View Javadoc
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  
18  package org.apache.commons.rng.sampling.distribution;
19  
20  import org.apache.commons.rng.UniformRandomProvider;
21  import org.apache.commons.rng.sampling.SharedStateSampler;
22  
23  /**
24   * Functions used by some of the samplers.
25   * This class is not part of the public API, as it would be
26   * better to group these utilities in a dedicated component.
27   */
28  final class InternalUtils { // Class is package-private on purpose; do not make it public.
29      /** All long-representable factorials. */
30      private static final long[] FACTORIALS = new long[] {
31          1L,                1L,                  2L,
32          6L,                24L,                 120L,
33          720L,              5040L,               40320L,
34          362880L,           3628800L,            39916800L,
35          479001600L,        6227020800L,         87178291200L,
36          1307674368000L,    20922789888000L,     355687428096000L,
37          6402373705728000L, 121645100408832000L, 2432902008176640000L };
38  
39      /** The first array index with a non-zero log factorial. */
40      private static final int BEGIN_LOG_FACTORIALS = 2;
41  
42      /** Utility class. */
43      private InternalUtils() {}
44  
45      /**
46       * @param n Argument.
47       * @return {@code n!}
48       * @throws IndexOutOfBoundsException if the result is too large to be represented
49       * by a {@code long} (i.e. if {@code n > 20}), or {@code n} is negative.
50       */
51      public static long factorial(int n)  {
52          return FACTORIALS[n];
53      }
54  
55      /**
56       * Validate the probabilities sum to a finite positive number.
57       *
58       * @param probabilities the probabilities
59       * @return the sum
60       * @throws IllegalArgumentException if {@code probabilities} is null or empty, a
61       * probability is negative, infinite or {@code NaN}, or the sum of all
62       * probabilities is not strictly positive.
63       */
64      public static double validateProbabilities(double[] probabilities) {
65          if (probabilities == null || probabilities.length == 0) {
66              throw new IllegalArgumentException("Probabilities must not be empty.");
67          }
68  
69          double sumProb = 0;
70          for (final double prob : probabilities) {
71              validateProbability(prob);
72              sumProb += prob;
73          }
74  
75          if (Double.isInfinite(sumProb) || sumProb <= 0) {
76              throw new IllegalArgumentException("Invalid sum of probabilities: " + sumProb);
77          }
78          return sumProb;
79      }
80  
81      /**
82       * Validate the probability is a finite positive number.
83       *
84       * @param probability Probability.
85       * @throws IllegalArgumentException if {@code probability} is negative, infinite or {@code NaN}.
86       */
87      public static void validateProbability(double probability) {
88          if (probability < 0 ||
89              Double.isInfinite(probability) ||
90              Double.isNaN(probability)) {
91              throw new IllegalArgumentException("Invalid probability: " +
92                                                 probability);
93          }
94      }
95  
96      /**
97       * Create a new instance of the given sampler using
98       * {@link SharedStateSampler#withUniformRandomProvider(UniformRandomProvider)}.
99       *
100      * @param sampler Source sampler.
101      * @param rng Generator of uniformly distributed random numbers.
102      * @return the new sampler
103      * @throws UnsupportedOperationException if the underlying sampler is not a
104      * {@link SharedStateSampler} or does not return a {@link NormalizedGaussianSampler} when
105      * sharing state.
106      */
107     static NormalizedGaussianSampler newNormalizedGaussianSampler(
108             NormalizedGaussianSampler sampler,
109             UniformRandomProvider rng) {
110         if (!(sampler instanceof SharedStateSampler<?>)) {
111             throw new UnsupportedOperationException("The underlying sampler cannot share state");
112         }
113         final Object newSampler = ((SharedStateSampler<?>) sampler).withUniformRandomProvider(rng);
114         if (!(newSampler instanceof NormalizedGaussianSampler)) {
115             throw new UnsupportedOperationException(
116                 "The underlying sampler did not create a normalized Gaussian sampler");
117         }
118         return (NormalizedGaussianSampler) newSampler;
119     }
120 
121     /**
122      * Class for computing the natural logarithm of the factorial of {@code n}.
123      * It allows to allocate a cache of precomputed values.
124      * In case of cache miss, computation is performed by a call to
125      * {@link InternalGamma#logGamma(double)}.
126      */
127     public static final class FactorialLog {
128         /**
129          * Precomputed values of the function:
130          * {@code LOG_FACTORIALS[i] = log(i!)}.
131          */
132         private final double[] logFactorials;
133 
134         /**
135          * Creates an instance, reusing the already computed values if available.
136          *
137          * @param numValues Number of values of the function to compute.
138          * @param cache Existing cache.
139          * @throws NegativeArraySizeException if {@code numValues < 0}.
140          */
141         private FactorialLog(int numValues,
142                              double[] cache) {
143             logFactorials = new double[numValues];
144 
145             int endCopy;
146             if (cache != null && cache.length > BEGIN_LOG_FACTORIALS) {
147                 // Copy available values.
148                 endCopy = Math.min(cache.length, numValues);
149                 System.arraycopy(cache, BEGIN_LOG_FACTORIALS, logFactorials, BEGIN_LOG_FACTORIALS,
150                     endCopy - BEGIN_LOG_FACTORIALS);
151             } else {
152                 // All values to be computed
153                 endCopy = BEGIN_LOG_FACTORIALS;
154             }
155 
156             // Compute remaining values.
157             for (int i = endCopy; i < numValues; i++) {
158                 if (i < FACTORIALS.length) {
159                     logFactorials[i] = Math.log(FACTORIALS[i]);
160                 } else {
161                     logFactorials[i] = logFactorials[i - 1] + Math.log(i);
162                 }
163             }
164         }
165 
166         /**
167          * Creates an instance with no precomputed values.
168          *
169          * @return an instance with no precomputed values.
170          */
171         public static FactorialLog create() {
172             return new FactorialLog(0, null);
173         }
174 
175         /**
176          * Creates an instance with the specified cache size.
177          *
178          * @param cacheSize Number of precomputed values of the function.
179          * @return a new instance where {@code cacheSize} values have been
180          * precomputed.
181          * @throws IllegalArgumentException if {@code n < 0}.
182          */
183         public FactorialLog withCache(final int cacheSize) {
184             return new FactorialLog(cacheSize, logFactorials);
185         }
186 
187         /**
188          * Computes {@code log(n!)}.
189          *
190          * @param n Argument.
191          * @return {@code log(n!)}.
192          * @throws IndexOutOfBoundsException if {@code numValues < 0}.
193          */
194         public double value(final int n) {
195             // Use cache of precomputed values.
196             if (n < logFactorials.length) {
197                 return logFactorials[n];
198             }
199 
200             // Use cache of precomputed factorial values.
201             if (n < FACTORIALS.length) {
202                 return Math.log(FACTORIALS[n]);
203             }
204 
205             // Delegate.
206             return InternalGamma.logGamma(n + 1.0);
207         }
208     }
209 }