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.rng.sampling.distribution;
018
019import org.apache.commons.rng.UniformRandomProvider;
020
021/**
022 * Sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson distribution</a>.
023 *
024 * <ul>
025 *  <li>
026 *   For small means, a Poisson process is simulated using uniform deviates, as described in
027 *   <blockquote>
028 *    Knuth (1969). <i>Seminumerical Algorithms</i>. The Art of Computer Programming,
029 *    Volume 2. Chapter 3.4.1.F.3 Important integer-valued distributions: The Poisson distribution.
030 *    Addison Wesley.
031 *   </blockquote>
032 *   The Poisson process (and hence, the returned value) is bounded by {@code 1000 * mean}.
033 *  </li>
034 * </ul>
035 *
036 * <p>This sampler is suitable for {@code mean < 40}.
037 * For large means, {@link LargeMeanPoissonSampler} should be used instead.</p>
038 *
039 * <p>Sampling uses {@link UniformRandomProvider#nextDouble()} and requires on average
040 * {@code mean + 1} deviates per sample.</p>
041 *
042 * @since 1.1
043 */
044public class SmallMeanPoissonSampler
045    implements SharedStateDiscreteSampler {
046    /**
047     * Pre-compute {@code Math.exp(-mean)}.
048     * Note: This is the probability of the Poisson sample {@code P(n=0)}.
049     */
050    private final double p0;
051    /** Pre-compute {@code 1000 * mean} as the upper limit of the sample. */
052    private final int limit;
053    /** Underlying source of randomness. */
054    private final UniformRandomProvider rng;
055
056    /**
057     * @param rng  Generator of uniformly distributed random numbers.
058     * @param mean Mean.
059     * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}
060     */
061    public SmallMeanPoissonSampler(UniformRandomProvider rng,
062                                   double mean) {
063        this.rng = rng;
064        if (mean <= 0) {
065            throw new IllegalArgumentException("mean is not strictly positive: " + mean);
066        }
067        p0 = Math.exp(-mean);
068        if (p0 > 0) {
069            // The returned sample is bounded by 1000 * mean
070            limit = (int) Math.ceil(1000 * mean);
071        } else {
072            // This excludes NaN values for the mean
073            throw new IllegalArgumentException("No p(x=0) probability for mean: " + mean);
074        }
075    }
076
077    /**
078     * @param rng Generator of uniformly distributed random numbers.
079     * @param source Source to copy.
080     */
081    private SmallMeanPoissonSampler(UniformRandomProvider rng,
082                                    SmallMeanPoissonSampler source) {
083        this.rng = rng;
084        p0 = source.p0;
085        limit = source.limit;
086    }
087
088    /** {@inheritDoc} */
089    @Override
090    public int sample() {
091        int n = 0;
092        double r = 1;
093
094        while (n < limit) {
095            r *= rng.nextDouble();
096            if (r >= p0) {
097                n++;
098            } else {
099                break;
100            }
101        }
102        return n;
103    }
104
105    /** {@inheritDoc} */
106    @Override
107    public String toString() {
108        return "Small Mean Poisson deviate [" + rng.toString() + "]";
109    }
110
111    /**
112     * {@inheritDoc}
113     *
114     * @since 1.3
115     */
116    @Override
117    public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) {
118        return new SmallMeanPoissonSampler(rng, this);
119    }
120
121    /**
122     * Creates a new sampler for the Poisson distribution.
123     *
124     * @param rng Generator of uniformly distributed random numbers.
125     * @param mean Mean of the distribution.
126     * @return the sampler
127     * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}.
128     * @since 1.3
129     */
130    public static SharedStateDiscreteSampler of(UniformRandomProvider rng,
131                                                double mean) {
132        return new SmallMeanPoissonSampler(rng, mean);
133    }
134}