SmallMeanPoissonSampler.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.rng.sampling.distribution;

  18. import org.apache.commons.rng.UniformRandomProvider;

  19. /**
  20.  * Sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson distribution</a>.
  21.  *
  22.  * <ul>
  23.  *  <li>
  24.  *   For small means, a Poisson process is simulated using uniform deviates, as described in
  25.  *   <blockquote>
  26.  *    Knuth (1969). <i>Seminumerical Algorithms</i>. The Art of Computer Programming,
  27.  *    Volume 2. Chapter 3.4.1.F.3 Important integer-valued distributions: The Poisson distribution.
  28.  *    Addison Wesley.
  29.  *   </blockquote>
  30.  *   The Poisson process (and hence, the returned value) is bounded by {@code 1000 * mean}.
  31.  *  </li>
  32.  * </ul>
  33.  *
  34.  * <p>This sampler is suitable for {@code mean < 40}.
  35.  * For large means, {@link LargeMeanPoissonSampler} should be used instead.</p>
  36.  *
  37.  * <p>Sampling uses {@link UniformRandomProvider#nextDouble()} and requires on average
  38.  * {@code mean + 1} deviates per sample.</p>
  39.  *
  40.  * @since 1.1
  41.  */
  42. public class SmallMeanPoissonSampler
  43.     implements SharedStateDiscreteSampler {
  44.     /**
  45.      * Pre-compute {@code Math.exp(-mean)}.
  46.      * Note: This is the probability of the Poisson sample {@code P(n=0)}.
  47.      */
  48.     private final double p0;
  49.     /** Pre-compute {@code 1000 * mean} as the upper limit of the sample. */
  50.     private final int limit;
  51.     /** Underlying source of randomness. */
  52.     private final UniformRandomProvider rng;

  53.     /**
  54.      * Create an instance.
  55.      *
  56.      * @param rng  Generator of uniformly distributed random numbers.
  57.      * @param mean Mean.
  58.      * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}
  59.      */
  60.     public SmallMeanPoissonSampler(UniformRandomProvider rng,
  61.                                    double mean) {
  62.         this(rng, mean, computeP0(mean));
  63.     }

  64.     /**
  65.      * Instantiates a new small mean poisson sampler.
  66.      *
  67.      * @param rng  Generator of uniformly distributed random numbers.
  68.      * @param mean Mean.
  69.      * @param p0 {@code Math.exp(-mean)}.
  70.      */
  71.     private SmallMeanPoissonSampler(UniformRandomProvider rng,
  72.                                     double mean,
  73.                                     double p0) {
  74.         this.rng = rng;
  75.         this.p0 = p0;
  76.         // The returned sample is bounded by 1000 * mean
  77.         limit = (int) Math.ceil(1000 * mean);
  78.     }

  79.     /**
  80.      * @param rng Generator of uniformly distributed random numbers.
  81.      * @param source Source to copy.
  82.      */
  83.     private SmallMeanPoissonSampler(UniformRandomProvider rng,
  84.                                     SmallMeanPoissonSampler source) {
  85.         this.rng = rng;
  86.         p0 = source.p0;
  87.         limit = source.limit;
  88.     }

  89.     /** {@inheritDoc} */
  90.     @Override
  91.     public int sample() {
  92.         int n = 0;
  93.         double r = 1;

  94.         while (n < limit) {
  95.             r *= rng.nextDouble();
  96.             if (r >= p0) {
  97.                 n++;
  98.             } else {
  99.                 break;
  100.             }
  101.         }
  102.         return n;
  103.     }

  104.     /** {@inheritDoc} */
  105.     @Override
  106.     public String toString() {
  107.         return "Small Mean Poisson deviate [" + rng.toString() + "]";
  108.     }

  109.     /**
  110.      * {@inheritDoc}
  111.      *
  112.      * @since 1.3
  113.      */
  114.     @Override
  115.     public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) {
  116.         return new SmallMeanPoissonSampler(rng, this);
  117.     }

  118.     /**
  119.      * Creates a new sampler for the Poisson distribution.
  120.      *
  121.      * @param rng Generator of uniformly distributed random numbers.
  122.      * @param mean Mean of the distribution.
  123.      * @return the sampler
  124.      * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}.
  125.      * @since 1.3
  126.      */
  127.     public static SharedStateDiscreteSampler of(UniformRandomProvider rng,
  128.                                                 double mean) {
  129.         return new SmallMeanPoissonSampler(rng, mean);
  130.     }

  131.     /**
  132.      * Compute {@code Math.exp(-mean)}.
  133.      *
  134.      * <p>This method exists to raise an exception before invocation of the
  135.      * private constructor; this mitigates Finalizer attacks
  136.      * (see SpotBugs CT_CONSTRUCTOR_THROW).
  137.      *
  138.      * @param mean Mean.
  139.      * @return the mean
  140.      * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}
  141.      */
  142.     private static double computeP0(double mean) {
  143.         InternalUtils.requireStrictlyPositive(mean, "mean");
  144.         final double p0 = Math.exp(-mean);
  145.         if (p0 > 0) {
  146.             return p0;
  147.         }
  148.         // This excludes NaN values for the mean
  149.         throw new IllegalArgumentException("No p(x=0) probability for mean: " + mean);
  150.     }
  151. }