GNU Octave  8.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
randpoisson.cc
Go to the documentation of this file.
1 ////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright (C) 2006-2023 The Octave Project Developers
4 //
5 // See the file COPYRIGHT.md in the top-level directory of this
6 // distribution or <https://octave.org/copyright/>.
7 //
8 // This file is part of Octave.
9 //
10 // Octave is free software: you can redistribute it and/or modify it
11 // under the terms of the GNU General Public License as published by
12 // the Free Software Foundation, either version 3 of the License, or
13 // (at your option) any later version.
14 //
15 // Octave is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with Octave; see the file COPYING. If not, see
22 // <https://www.gnu.org/licenses/>.
23 //
24 ////////////////////////////////////////////////////////////////////////
25 
26 /* Original version written by Paul Kienzle distributed as free
27  software in the in the public domain. */
28 
29 #if defined (HAVE_CONFIG_H)
30 # include "config.h"
31 #endif
32 
33 #include <cmath>
34 #include <cstddef>
35 
36 #include "f77-fcn.h"
37 #include "lo-error.h"
38 #include "lo-ieee.h"
39 #include "randmtzig.h"
40 #include "randpoisson.h"
41 
43 
44 static double xlgamma (double x)
45 {
46  return std::lgamma (x);
47 }
48 
49 /* ---- pprsc.c from Stadloeber's winrand --- */
50 
51 /* flogfak(k) = ln(k!) */
52 static double flogfak (double k)
53 {
54 #define C0 9.18938533204672742e-01
55 #define C1 8.33333333333333333e-02
56 #define C3 -2.77777777777777778e-03
57 #define C5 7.93650793650793651e-04
58 #define C7 -5.95238095238095238e-04
59 
60  static double logfak[30L] =
61  {
62  0.00000000000000000, 0.00000000000000000, 0.69314718055994531,
63  1.79175946922805500, 3.17805383034794562, 4.78749174278204599,
64  6.57925121201010100, 8.52516136106541430, 10.60460290274525023,
65  12.80182748008146961, 15.10441257307551530, 17.50230784587388584,
66  19.98721449566188615, 22.55216385312342289, 25.19122118273868150,
67  27.89927138384089157, 30.67186010608067280, 33.50507345013688888,
68  36.39544520803305358, 39.33988418719949404, 42.33561646075348503,
69  45.38013889847690803, 48.47118135183522388, 51.60667556776437357,
70  54.78472939811231919, 58.00360522298051994, 61.26170176100200198,
71  64.55753862700633106, 67.88974313718153498, 71.25703896716800901
72  };
73 
74  double r, rr;
75 
76  if (k >= 30.0)
77  {
78  r = 1.0 / k;
79  rr = r * r;
80  return ((k + 0.5)*std::log (k) - k + C0
81  + r*(C1 + rr*(C3 + rr*(C5 + rr*C7))));
82  }
83  else
84  return (logfak[static_cast<int> (k)]);
85 }
86 
87 /******************************************************************
88  * *
89  * Poisson Distribution - Patchwork Rejection/Inversion *
90  * *
91  ******************************************************************
92  * *
93  * For parameter my < 10, Tabulated Inversion is applied. *
94  * For my >= 10, Patchwork Rejection is employed: *
95  * The area below the histogram function f(x) is rearranged in *
96  * its body by certain point reflections. Within a large center *
97  * interval variates are sampled efficiently by rejection from *
98  * uniform hats. Rectangular immediate acceptance regions speed *
99  * up the generation. The remaining tails are covered by *
100  * exponential functions. *
101  * *
102  ******************************************************************
103  * *
104  * FUNCTION : - pprsc samples a random number from the Poisson *
105  * distribution with parameter my > 0. *
106  * REFERENCE : - H. Zechner (1994): Efficient sampling from *
107  * continuous and discrete unimodal distributions, *
108  * Doctoral Dissertation, 156 pp., Technical *
109  * University Graz, Austria. *
110  * SUBPROGRAM : - drand(seed) ... (0,1)-Uniform generator with *
111  * unsigned long integer *seed. *
112  * *
113  * Implemented by H. Zechner, January 1994 *
114  * Revised by F. Niederl, July 1994 *
115  * *
116  ******************************************************************/
117 
118 static double f (double k, double l_nu, double c_pm)
119 {
120  return exp (k * l_nu - flogfak (k) - c_pm);
121 }
122 
123 static double pprsc (double my)
124 {
125  static double my_last = -1.0;
126  static double m, k2, k4, k1, k5;
127  static double dl, dr, r1, r2, r4, r5, ll, lr, l_my, c_pm,
128  f1, f2, f4, f5, p1, p2, p3, p4, p5, p6;
129  double Dk, X, Y;
130  double Ds, U, V, W;
131 
132  if (my != my_last)
133  {
134  /* set-up */
135  my_last = my;
136  /* approximate deviation of reflection points k2, k4 from my - 1/2 */
137  Ds = std::sqrt (my + 0.25);
138 
139  /* mode m, reflection points k2 and k4, and points k1 and k5, */
140  /* which delimit the centre region of h(x) */
141  m = std::floor (my);
142  k2 = ceil (my - 0.5 - Ds);
143  k4 = std::floor (my - 0.5 + Ds);
144  k1 = k2 + k2 - m + 1L;
145  k5 = k4 + k4 - m;
146 
147  /* range width of the critical left and right centre region */
148  dl = (k2 - k1);
149  dr = (k5 - k4);
150 
151  /* recurrence constants r(k)=p(k)/p(k-1) at k = k1, k2, k4+1, k5+1 */
152  r1 = my / k1;
153  r2 = my / k2;
154  r4 = my / (k4 + 1.0);
155  r5 = my / (k5 + 1.0);
156 
157  /* reciprocal values of the scale parameters of exp. tail envelope */
158  ll = std::log (r1); /* expon. tail left */
159  lr = -std::log (r5); /* expon. tail right*/
160 
161  /* Poisson constants, necessary for computing function values f(k) */
162  l_my = std::log (my);
163  c_pm = m * l_my - flogfak (m);
164 
165  /* function values f(k) = p(k)/p(m) at k = k2, k4, k1, k5 */
166  f2 = f (k2, l_my, c_pm);
167  f4 = f (k4, l_my, c_pm);
168  f1 = f (k1, l_my, c_pm);
169  f5 = f (k5, l_my, c_pm);
170 
171  /* area of the two centre and the two exponential tail regions */
172  /* area of the two immediate acceptance regions between k2, k4 */
173  p1 = f2 * (dl + 1.0); /* immed. left */
174  p2 = f2 * dl + p1; /* centre left */
175  p3 = f4 * (dr + 1.0) + p2; /* immed. right */
176  p4 = f4 * dr + p3; /* centre right */
177  p5 = f1 / ll + p4; /* exp. tail left */
178  p6 = f5 / lr + p5; /* exp. tail right*/
179  }
180 
181  for (;;)
182  {
183  /* generate uniform number U -- U(0, p6) */
184  /* case distinction corresponding to U */
185  if ((U = rand_uniform<double> () * p6) < p2)
186  {
187  /* centre left */
188 
189  /* immediate acceptance region
190  R2 = [k2, m) *[0, f2), X = k2, ... m -1 */
191  if ((V = U - p1) < 0.0) return (k2 + std::floor (U/f2));
192  /* immediate acceptance region
193  R1 = [k1, k2)*[0, f1), X = k1, ... k2-1 */
194  if ((W = V / dl) < f1 ) return (k1 + std::floor (V/f1));
195 
196  /* computation of candidate X < k2, and its counterpart Y > k2 */
197  /* either squeeze-acceptance of X or acceptance-rejection of Y */
198  Dk = std::floor (dl * rand_uniform<double> ()) + 1.0;
199  if (W <= f2 - Dk * (f2 - f2/r2))
200  {
201  /* quick accept of */
202  return (k2 - Dk); /* X = k2 - Dk */
203  }
204  if ((V = f2 + f2 - W) < 1.0)
205  {
206  /* quick reject of Y*/
207  Y = k2 + Dk;
208  if (V <= f2 + Dk * (1.0 - f2)/(dl + 1.0))
209  {
210  /* quick accept of */
211  return (Y); /* Y = k2 + Dk */
212  }
213  if (V <= f (Y, l_my, c_pm)) return (Y); /* final accept of Y*/
214  }
215  X = k2 - Dk;
216  }
217  else if (U < p4)
218  {
219  /* centre right */
220  /* immediate acceptance region
221  R3 = [m, k4+1)*[0, f4), X = m, ... k4 */
222  if ((V = U - p3) < 0.0) return (k4 - std::floor ((U - p2)/f4));
223  /* immediate acceptance region
224  R4 = [k4+1, k5+1)*[0, f5) */
225  if ((W = V / dr) < f5 ) return (k5 - std::floor (V/f5));
226 
227  /* computation of candidate X > k4, and its counterpart Y < k4 */
228  /* either squeeze-acceptance of X or acceptance-rejection of Y */
229  Dk = std::floor (dr * rand_uniform<double> ()) + 1.0;
230  if (W <= f4 - Dk * (f4 - f4*r4))
231  {
232  /* quick accept of */
233  return (k4 + Dk); /* X = k4 + Dk */
234  }
235  if ((V = f4 + f4 - W) < 1.0)
236  {
237  /* quick reject of Y*/
238  Y = k4 - Dk;
239  if (V <= f4 + Dk * (1.0 - f4)/ dr)
240  {
241  /* quick accept of */
242  return (Y); /* Y = k4 - Dk */
243  }
244  if (V <= f (Y, l_my, c_pm)) return (Y); /* final accept of Y*/
245  }
246  X = k4 + Dk;
247  }
248  else
249  {
250  W = rand_uniform<double> ();
251  if (U < p5)
252  {
253  /* expon. tail left */
254  Dk = std::floor (1.0 - std::log (W)/ll);
255  if ((X = k1 - Dk) < 0L) continue; /* 0 <= X <= k1 - 1 */
256  W *= (U - p4) * ll; /* W -- U(0, h(x)) */
257  if (W <= f1 - Dk * (f1 - f1/r1))
258  return (X); /* quick accept of X*/
259  }
260  else
261  {
262  /* expon. tail right*/
263  Dk = std::floor (1.0 - std::log (W)/lr);
264  X = k5 + Dk; /* X >= k5 + 1 */
265  W *= (U - p5) * lr; /* W -- U(0, h(x)) */
266  if (W <= f5 - Dk * (f5 - f5*r5))
267  return (X); /* quick accept of X*/
268  }
269  }
270 
271  /* acceptance-rejection test of candidate X from the original area */
272  /* test, whether W <= f(k), with W = U*h(x) and U -- U(0, 1)*/
273  /* log f(X) = (X - m)*log(my) - log X! + log m! */
274  if (std::log (W) <= X * l_my - flogfak (X) - c_pm) return (X);
275  }
276 }
277 /* ---- pprsc.c end ------ */
278 
279 /* The remainder of the file is by Paul Kienzle */
280 
281 /* Table size is predicated on the maximum value of lambda
282  * we want to store in the table, and the maximum value of
283  * returned by the uniform random number generator on [0,1).
284  * With lambda==10 and u_max = 1 - 1/(2^32+1), we
285  * have poisson_pdf(lambda,36) < 1-u_max. If instead our
286  * generator uses more bits of mantissa or returns a value
287  * in the range [0,1], then for lambda==10 we need a table
288  * size of 46 instead. For long doubles, the table size
289  * will need to be longer still. */
290 #define TABLESIZE 46
291 
292 /* Given uniform u, find x such that CDF(L,x)==u. Return x. */
293 
294 template <typename T>
295 static void
296 poisson_cdf_lookup (double lambda, T *p, std::size_t n)
297 {
298  double t[TABLESIZE];
299 
300  /* Precompute the table for the u up to and including 0.458.
301  * We will almost certainly need it. */
302  int intlambda = static_cast<int> (std::floor (lambda));
303  double P;
304  int tableidx;
305  std::size_t i = n;
306 
307  t[0] = P = exp (-lambda);
308  for (tableidx = 1; tableidx <= intlambda; tableidx++)
309  {
310  P = P*lambda/static_cast<double> (tableidx);
311  t[tableidx] = t[tableidx-1] + P;
312  }
313 
314  while (i-- > 0)
315  {
316  double u = rand_uniform<double> ();
317 
318  /* If u > 0.458 we know we can jump to floor(lambda) before
319  * comparing (this observation is based on Stadlober's winrand
320  * code). For lambda >= 1, this will be a win. Lambda < 1
321  * is already fast, so adding an extra comparison is not a
322  * problem. */
323  int k = (u > 0.458 ? intlambda : 0);
324 
325  /* We aren't using a for loop here because when we find the
326  * right k we want to jump to the next iteration of the
327  * outer loop, and the continue statement will only work for
328  * the inner loop. */
329  nextk:
330  if (u <= t[k])
331  {
332  p[i] = static_cast<T> (k);
333  continue;
334  }
335  if (++k < tableidx)
336  goto nextk;
337 
338  /* We only need high values of the table very rarely so we
339  * don't automatically compute the entire table. */
340  while (tableidx < TABLESIZE)
341  {
342  P = P*lambda/static_cast<double> (tableidx);
343  t[tableidx] = t[tableidx-1] + P;
344  /* Make sure we converge to 1.0 just in case u is uniform
345  * on [0,1] rather than [0,1). */
346  if (t[tableidx] == t[tableidx-1]) t[tableidx] = 1.0;
347  tableidx++;
348  if (u <= t[tableidx-1]) break;
349  }
350 
351  /* We are assuming that the table size is big enough here.
352  * This should be true even if rand_uniform is returning values in
353  * the range [0,1] rather than [0,1). */
354  p[i] = static_cast<T> (tableidx-1);
355  }
356 }
357 
358 /* From Press, et al., Numerical Recipes */
359 template <typename T>
360 static void
361 poisson_rejection (double lambda, T *p, std::size_t n)
362 {
363  double sq = std::sqrt (2.0*lambda);
364  double alxm = std::log (lambda);
365  double g = lambda*alxm - xlgamma (lambda+1.0);
366  std::size_t i;
367 
368  for (i = 0; i < n; i++)
369  {
370  double y, em, t;
371  do
372  {
373  do
374  {
375  y = tan (M_PI*rand_uniform<double> ());
376  em = sq * y + lambda;
377  }
378  while (em < 0.0);
379  em = std::floor (em);
380  t = 0.9*(1.0+y*y)* exp (em*alxm-flogfak (em)-g);
381  }
382  while (rand_uniform<double> () > t);
383  p[i] = em;
384  }
385 }
386 
387 /* The cutoff of L <= 1e8 in the following two functions before using
388  * the normal approximation is based on:
389  * > L=1e8; x=floor(linspace(0,2*L,1000));
390  * > max(abs(normal_pdf(x,L,L)-poisson_pdf(x,L)))
391  * ans = 1.1376e-28
392  * For L=1e7, the max is around 1e-9, which is within the step size of
393  * rand_uniform. For L>1e10 the pprsc function breaks down, as I saw
394  * from the histogram of a large sample, so 1e8 is both small enough
395  * and large enough. */
396 
397 /* Generate a set of poisson numbers with the same distribution */
398 template <typename T> void rand_poisson (T L_arg, octave_idx_type n, T *p)
399 {
400  double L = L_arg;
401  octave_idx_type i;
402  if (L < 0.0 || lo_ieee_isinf (L))
403  {
404  for (i=0; i<n; i++)
405  p[i] = numeric_limits<T>::NaN ();
406  }
407  else if (L <= 10.0)
408  {
409  poisson_cdf_lookup<T> (L, p, n);
410  }
411  else if (L <= 1e8)
412  {
413  for (i=0; i<n; i++)
414  p[i] = pprsc (L);
415  }
416  else
417  {
418  /* normal approximation: from Phys. Rev. D (1994) v50 p1284 */
419  const double sqrtL = std::sqrt (L);
420  for (i = 0; i < n; i++)
421  {
422  p[i] = std::floor (rand_normal<T> () * sqrtL + L + 0.5);
423  if (p[i] < 0.0)
424  p[i] = 0.0; /* will probably never happen */
425  }
426  }
427 }
428 
429 template void rand_poisson<double> (double, octave_idx_type, double *);
430 template void rand_poisson<float> (float, octave_idx_type, float *);
431 
432 /* Generate one poisson variate */
433 template <typename T> T rand_poisson (T L_arg)
434 {
435  double L = L_arg;
436  T ret;
437  if (L < 0.0) ret = numeric_limits<T>::NaN ();
438  else if (L <= 12.0)
439  {
440  /* From Press, et al. Numerical recipes */
441  double g = exp (-L);
442  int em = -1;
443  double t = 1.0;
444  do
445  {
446  ++em;
447  t *= rand_uniform<T> ();
448  }
449  while (t > g);
450  ret = em;
451  }
452  else if (L <= 1e8)
453  {
454  /* numerical recipes */
455  poisson_rejection<T> (L, &ret, 1);
456  }
457  else if (lo_ieee_isinf (L))
458  {
459  /* FIXME: R uses NaN, but the normal approximation suggests that
460  * limit should be Inf. Which is correct? */
461  ret = numeric_limits<T>::NaN ();
462  }
463  else
464  {
465  /* normal approximation: from Phys. Rev. D (1994) v50 p1284 */
466  ret = std::floor (rand_normal<T> () * std::sqrt (L) + L + 0.5);
467  if (ret < 0.0) ret = 0.0; /* will probably never happen */
468  }
469  return ret;
470 }
471 
472 template OCTAVE_API double rand_poisson<double> (double);
473 template OCTAVE_API float rand_poisson<float> (float);
474 
OCTAVE_END_NAMESPACE(octave)
#define NaN
Definition: Faddeeva.cc:261
OCTAVE_BEGIN_NAMESPACE(octave) static octave_value daspk_fcn
#define lo_ieee_isinf(x)
Definition: lo-ieee.h:108
F77_RET_T const F77_INT const F77_INT const F77_INT const F77_DBLE const F77_DBLE F77_INT F77_DBLE * V
std::complex< T > floor(const std::complex< T > &x)
Definition: lo-mappers.h:130
std::complex< T > ceil(const std::complex< T > &x)
Definition: lo-mappers.h:103
F77_RET_T const F77_DBLE * x
double lgamma(double x)
Definition: lo-specfun.h:336
#define OCTAVE_API
Definition: main.in.cc:55
T octave_idx_type m
Definition: mx-inlines.cc:773
octave_idx_type n
Definition: mx-inlines.cc:753
T * r
Definition: mx-inlines.cc:773
OCTAVE_API double rand_uniform< double >(void)
Definition: randmtzig.cc:431
static double pprsc(double my)
Definition: randpoisson.cc:123
static void poisson_cdf_lookup(double lambda, T *p, std::size_t n)
Definition: randpoisson.cc:296
#define TABLESIZE
Definition: randpoisson.cc:290
static double xlgamma(double x)
Definition: randpoisson.cc:44
static double f(double k, double l_nu, double c_pm)
Definition: randpoisson.cc:118
#define C5
#define C1
void rand_poisson(T L_arg, octave_idx_type n, T *p)
Definition: randpoisson.cc:398
#define C3
template void rand_poisson< double >(double, octave_idx_type, double *)
static double flogfak(double k)
Definition: randpoisson.cc:52
template void rand_poisson< float >(float, octave_idx_type, float *)
static void poisson_rejection(double lambda, T *p, std::size_t n)
Definition: randpoisson.cc:361
#define C0
#define C7