The R Project SVN R

Rev

Rev 87974 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
574 ihaka 1
/*
2
 *  Mathlib : A C Library of Special Functions
90223 maechler 3
 *  Copyright (C) 2000-2026 The R Core Team
77694 maechler 4
 *  Copyright (C) 2005-2020 The R Foundation
574 ihaka 5
 *  Copyright (C) 1998 Ross Ihaka
6
 *
7
 *  This program is free software; you can redistribute it and/or modify
8
 *  it under the terms of the GNU General Public License as published by
9
 *  the Free Software Foundation; either version 2 of the License, or
10
 *  (at your option) any later version.
11
 *
12
 *  This program is distributed in the hope that it will be useful,
13
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 *  GNU General Public License for more details.
16
 *
42302 ripley 17
 *  You should have received a copy of the GNU General Public License
42310 ripley 18
 *  along with this program; if not, a copy is available at
68947 ripley 19
 *  https://www.R-project.org/Licenses/
574 ihaka 20
 *
21
 *  SYNOPSIS
22
 *
19500 hornik 23
 *    #include <Rmath.h>
574 ihaka 24
 *    double rhyper(double NR, double NB, double n);
25
 *
26
 *  DESCRIPTION
27
 *
28
 *    Random variates from the hypergeometric distribution.
29
 *    Returns the number of white balls drawn when kk balls
30
 *    are drawn at random from an urn containing nn1 white
31
 *    and nn2 black balls.
32
 *
33
 *  REFERENCE
34
 *
35
 *    V. Kachitvichyanukul and B. Schmeiser (1985).
36
 *    ``Computer generation of hypergeometric random variates,''
37
 *    Journal of Statistical Computation and Simulation 22, 127-145.
33718 maechler 38
 *
39
 *    The original algorithm had a bug -- R bug report PR#7314 --
40
 *    giving numbers slightly too small in case III h2pe
41
 *    where (m < 100 || ix <= 50) , see below.
574 ihaka 42
 */
43
 
8431 ripley 44
#include "nmath.h"
64655 ripley 45
#include "dpq.h"
70052 maechler 46
#include <limits.h>
574 ihaka 47
 
77694 maechler 48
// afc(i) :=  ln( i! )	[logarithm of the factorial i] = {R:} lgamma(i + 1) = {C:} lgammafn(i + 1)
574 ihaka 49
static double afc(int i)
50
{
70052 maechler 51
    // If (i > 7), use Stirling's approximation, otherwise use table lookup.
52
    const static double al[8] =
13434 maechler 53
    {
54
	0.0,/*ln(0!)=ln(1)*/
55
	0.0,/*ln(1!)=ln(1)*/
56
	0.69314718055994530941723212145817,/*ln(2) */
57
	1.79175946922805500081247735838070,/*ln(6) */
58
	3.17805383034794561964694160129705,/*ln(24)*/
59
	4.78749174278204599424770093452324,
60
	6.57925121201010099506017829290394,
61
	8.52516136106541430016553103634712
70052 maechler 62
	/* 10.60460290274525022841722740072165, approx. value below =
63
	   10.6046028788027; rel.error = 2.26 10^{-9}
64
 
65
	  FIXME: Use constants and if(n > ..) decisions from ./stirlerr.c
66
	  -----  will be even *faster* for n > 500 (or so)
67
	*/
13434 maechler 68
    };
69
 
1028 maechler 70
    if (i < 0) {
70052 maechler 71
	MATHLIB_WARNING(("rhyper.c: afc(i), i=%d < 0 -- SHOULD NOT HAPPEN!\n"), i);
72
	return -1; // unreached
574 ihaka 73
    }
70052 maechler 74
    if (i <= 7)
75
	return al[i];
76
    // else i >= 8 :
77
    double di = i, i2 = di*di;
78
    return (di + 0.5) * log(di) - di + M_LN_SQRT_2PI +
79
	(0.0833333333333333 - 0.00277777777777778 / i2) / di;
574 ihaka 80
}
81
 
70052 maechler 82
//     rhyper(NR, NB, n) -- NR 'red', NB 'blue', n drawn, how many are 'red'
574 ihaka 83
double rhyper(double nn1in, double nn2in, double kkin)
84
{
85
    /* check parameter validity */
86
 
7671 maechler 87
    if(!R_FINITE(nn1in) || !R_FINITE(nn2in) || !R_FINITE(kkin))
77685 maechler 88
	ML_WARN_return_NAN;
574 ihaka 89
 
70052 maechler 90
    nn1in = R_forceint(nn1in);
91
    nn2in = R_forceint(nn2in);
92
    kkin  = R_forceint(kkin);
90223 maechler 93
    double N = nn1in + nn2in;
574 ihaka 94
 
70052 maechler 95
    if (nn1in < 0 || nn2in < 0 || kkin < 0 || kkin > nn1in + nn2in)
77685 maechler 96
	ML_WARN_return_NAN;
90223 maechler 97
    if (N > INT_MAX || kkin >= INT_MAX) {
70052 maechler 98
	/* large n -- evade integer overflow (and inappropriate algorithms)
99
	   -------- */
87974 maechler 100
#ifdef DEBUG_rhyper
101
	REprintf("rhyper(nn1=%.0f, nn2=%.0f, kk=%.0f): 'large n' case\n", nn1in, nn2in, kkin);
102
#endif
70052 maechler 103
        // FIXME: Much faster to give rbinom() approx when appropriate; -> see Kuensch(1989)
104
	// Johnson, Kotz,.. p.258 (top) mention the *four* different binomial approximations
105
	if(kkin == 1.) { // Bernoulli
106
	    return rbinom(kkin, nn1in / (nn1in + nn2in));
107
	}
108
	// Slow, but safe: return  F^{-1}(U)  where F(.) = phyper(.) and  U ~ U[0,1]
77694 maechler 109
	return qhyper(unif_rand(), nn1in, nn2in, kkin,
87946 ripley 110
		      /*lower_tail =*/ false, /*log_p = */ false);
111
	// lower_tail=false: a thinko, is still "correct" as equiv. to  U <--> 1-U
70052 maechler 112
    }
7671 maechler 113
 
87974 maechler 114
    int
115
	nn1 = (int)nn1in,
116
	nn2 = (int)nn2in,
117
	kk  = (int)kkin;
118
 
119
    /* These should become 'thread_local globals' : */
120
    static int ks = -1, n1s = -1, n2s = -1;
121
    static int m, minjx, maxjx;
122
    static int k, n1, n2; // <- not allowing larger integer par
123
 
124
    bool setup1, setup2;
574 ihaka 125
    /* if new parameter values, initialize */
77694 maechler 126
    if (nn1 != n1s || nn2 != n2s) { // n1 | n2 is changed: setup all
87946 ripley 127
	setup1 = true;	setup2 = true;
77694 maechler 128
    } else if (kk != ks) { // n1 & n2 are unchanged: setup 'k' only
87946 ripley 129
	setup1 = false;	setup2 = true;
77694 maechler 130
    } else { // all three unchanged ==> no setup
87946 ripley 131
	setup1 = false;	setup2 = false;
574 ihaka 132
    }
77694 maechler 133
    if (setup1) { // n1 & n2
134
	n1s = nn1; n2s = nn2; // save
574 ihaka 135
	if (nn1 <= nn2) {
77694 maechler 136
	    n1 = nn1; n2 = nn2;
137
	} else { // nn2 < nn1
138
	    n1 = nn2; n2 = nn1;
574 ihaka 139
	}
77694 maechler 140
	// now have n1 <= n2
574 ihaka 141
    }
77694 maechler 142
    if (setup2) { // k
143
	ks = kk; // save
77879 ripley 144
	if ((double)kk + kk >= N) { // this could overflow
77694 maechler 145
	    k = (int)(N - kk);
574 ihaka 146
	} else {
147
	    k = kk;
148
	}
87974 maechler 149
	// now have  k < N/2 = (n1+n2)/2
574 ihaka 150
    }
151
    if (setup1 || setup2) {
77694 maechler 152
	m = (int) ((k + 1.) * (n1 + 1.) / (N + 2.)); // m := floor(adjusted mean E[.])
574 ihaka 153
	minjx = imax2(0, k - n2);
154
	maxjx = imin2(n1, k);
70052 maechler 155
#ifdef DEBUG_rhyper
77694 maechler 156
	REprintf("rhyper(n1=%d, n2=%d, k=%d), setup: floor(a.mean)=: m = %d, [min,maxjx]= [%d,%d]\n",
70052 maechler 157
		 nn1, nn2, kk, m, minjx, maxjx);
158
#endif
574 ihaka 159
    }
87974 maechler 160
#ifdef DEBUG_rhyper
161
    else
162
	REprintf("rhyper(n1=%d, n2=%d, k=%d); setup UNchanged\n", nn1, nn2, kk);
163
#endif
574 ihaka 164
 
87974 maechler 165
    // generate random variate --- Three basic cases ---------------------------
166
 
167
    int ix; // return value (coerced to double at the very end) .. FIXME?? what if overflows
168
 
4562 pd 169
    if (minjx == maxjx) { /* I: degenerate distribution ---------------- */
70052 maechler 170
#ifdef DEBUG_rhyper
77694 maechler 171
	REprintf("rhyper(), branch I (degenerate): ix := maxjx = %d\n", maxjx);
70052 maechler 172
#endif
574 ihaka 173
	ix = maxjx;
70052 maechler 174
	goto L_finis; // return appropriate variate
1362 maechler 175
 
68749 maechler 176
    } else if (m - minjx < 10) { // II: (Scaled) algorithm HIN (inverse transformation) ----
177
	const static double scale = 1e25; // scaling factor against (early) underflow
178
	const static double con = 57.5646273248511421;
87974 maechler 179
	          // 25*log(10) = log(scale) { <==> exp(con) == scale }
180
	static double w,
181
	    lw; // = log(w);  w = exp(lw) * scale = exp(lw + log(scale)) = exp(lw + con)
574 ihaka 182
	if (setup1 || setup2) {
87974 maechler 183
	    // NB:  n1 <= n2  here
574 ihaka 184
	    if (k < n2) {
68749 maechler 185
		lw = afc(n2) + afc(n1 + n2 - k) - afc(n2 - k) - afc(n1 + n2);
574 ihaka 186
	    } else {
68749 maechler 187
		lw = afc(n1) + afc(     k     ) - afc(k - n2) - afc(n1 + n2);
574 ihaka 188
	    }
68749 maechler 189
	    w = exp(lw + con);
574 ihaka 190
	}
87974 maechler 191
 
70052 maechler 192
#ifdef DEBUG_rhyper
87974 maechler 193
	REprintf("  branch II; w = %g %s\n", w,
194
		 (w > 0) ? "> 0" : "= 0 <==> Underflow __NOT GOOD__");
70052 maechler 195
#endif
87974 maechler 196
	if(w <= 0.)
197
	    MATHLIB_ERROR(_("w = %g <= 0: Underflow in rhyper()  SHOULD NOT HAPPEN!"), w);
198
	// FIXME: MM has code "rhyper.c+M3" for switching to log space if w == 0
199
 
200
	double p, u;
574 ihaka 201
      L10:
202
	p = w;
203
	ix = minjx;
7725 ripley 204
	u = unif_rand() * scale;
70052 maechler 205
#ifdef DEBUG_rhyper
206
	REprintf("  _new_ u = %g\n", u);
207
#endif
68749 maechler 208
	while (u > p) {
13434 maechler 209
	    u -= p;
68749 maechler 210
	    p *= ((double) n1 - ix) * (k - ix);
13434 maechler 211
	    ix++;
574 ihaka 212
	    p = p / ix / (n2 - k + ix);
70052 maechler 213
#ifdef DEBUG_rhyper
214
	    REprintf("       ix=%3d, u=%11g, p=%20.14g (u-p=%g)\n", ix, u, p, u-p);
215
#endif
574 ihaka 216
	    if (ix > maxjx)
217
		goto L10;
70052 maechler 218
	    // FIXME  if(p == 0.)  we also "have lost"  => goto L10
574 ihaka 219
	}
77694 maechler 220
 
68749 maechler 221
    } else { /* III : H2PE Algorithm --------------------------------------- */
574 ihaka 222
 
87974 maechler 223
	static double a, xl, xr, lamdl, lamdr, p1, p2, p3;
574 ihaka 224
	if (setup1 || setup2) {
87974 maechler 225
	    double
226
		s = sqrt((N - k) * k * n1 * n2 / (N - 1) / N / N),
574 ihaka 227
 
87974 maechler 228
		/* remark: d is defined in reference without int. */
229
		/* the truncation centers the cell boundaries at 0.5 */
230
		d = (int) (1.5 * s) + .5;
574 ihaka 231
	    xl = m - d + .5;
232
	    xr = m + d + .5;
13434 maechler 233
	    a = afc(m) + afc(n1 - m) + afc(k - m) + afc(n2 - k + m);
87974 maechler 234
	    double
235
		kl = exp(a - afc((int) (xl)) - afc((int) (n1 - xl))
236
			 - afc((int) (k - xl))
237
			 - afc((int) (n2 - k + xl))),
238
		kr = exp(a - afc((int) (xr - 1))
239
			 - afc((int) (n1 - xr + 1))
240
			 - afc((int) (k - xr + 1))
241
			 - afc((int) (n2 - k + xr - 1)));
13434 maechler 242
	    lamdl = -log(xl * (n2 - k + xl) / (n1 - xl + 1) / (k - xl + 1));
243
	    lamdr = -log((n1 - xr + 1) * (k - xr + 1) / xr / (n2 - k + xr));
574 ihaka 244
	    p1 = d + d;
245
	    p2 = p1 + kl / lamdl;
246
	    p3 = p2 + kr / lamdr;
87974 maechler 247
#ifdef DEBUG_rhyper
248
	    REprintf("rhyper(), branch III {accept/reject}: (xl,xr)= (%g,%g); lamdl,r = (%g,%g)\n",
249
		     xl, xr, lamdl, lamdr);
250
	    REprintf(" --------> (p1,p2,p3) = (%g,%g,%g)\n", p1,p2,p3);
574 ihaka 251
	}
87974 maechler 252
	else
253
	    REprintf("rhyper(), branch III {accept/reject}: NO setup needed; lamdl,r = (%g,%g)\n",
254
		     lamdl, lamdr);
255
#else
256
        }
70052 maechler 257
#endif
87974 maechler 258
 
259
	/* acceptance/rejection test */
260
	bool reject = true;
261
        int n_uv = 0;
262
    do { // L30: -------------- acceptance / rejection : loop while reject=true -------------
263
	double
264
	    u = unif_rand() * p3,
265
	    v = unif_rand();
70052 maechler 266
	n_uv++;
267
	if(n_uv >= 10000) {
77694 maechler 268
	    REprintf("rhyper(*, n1=%d, n2=%d, k=%d): branch III: giving up after %d rejections\n",
269
		     nn1, nn2, kk, n_uv);
77685 maechler 270
	    ML_WARN_return_NAN;
70052 maechler 271
        }
272
#ifdef DEBUG_rhyper
77694 maechler 273
	REprintf(" ... L30 [%d]: new (u=%g, v ~ U[0,1]=%g): ", n_uv, u,v);
70052 maechler 274
#endif
275
 
4562 pd 276
	if (u < p1) {		/* rectangular region */
59170 ripley 277
	    ix = (int) (xl + u);
87974 maechler 278
#ifdef DEBUG_rhyper
279
	    REprintf(" rectangular: ix=%d\n", ix);
280
#endif
4562 pd 281
	} else if (u <= p2) {	/* left tail */
59170 ripley 282
	    ix = (int) (xl + log(v) / lamdl);
87974 maechler 283
#ifdef DEBUG_rhyper
284
	    REprintf(" left tail: ix=%d %s", ix, (ix < minjx)? "< minjx (=> L30)\n" : ">= minjx;");
285
#endif
574 ihaka 286
	    if (ix < minjx)
87974 maechler 287
		continue; // goto L30
574 ihaka 288
	    v = v * (u - p1) * lamdl;
4562 pd 289
	} else {		/* right tail */
59170 ripley 290
	    ix = (int) (xr - log(v) / lamdr);
87974 maechler 291
#ifdef DEBUG_rhyper
292
	    REprintf(" right tail: ix=%d %s", ix, (ix > maxjx)? "> maxjx (=> L30)\n" : "< maxjx;");
293
#endif
574 ihaka 294
	    if (ix > maxjx)
87974 maechler 295
		continue; // goto L30
574 ihaka 296
	    v = v * (u - p2) * lamdr;
297
	}
87974 maechler 298
#ifdef DEBUG_rhyper
299
	if(u >= p1) REprintf(" new v = %g\n", v);
300
#endif
574 ihaka 301
 
302
	if (m < 100 || ix <= 50) {
303
	    /* explicit evaluation */
33718 maechler 304
	    /* The original algorithm (and TOMS 668) have
305
		   f = f * i * (n2 - k + i) / (n1 - i) / (k - i);
306
	       in the (m > ix) case, but the definition of the
307
	       recurrence relation on p134 shows that the +1 is
308
	       needed. */
70052 maechler 309
	    double f = 1.0;
574 ihaka 310
	    if (m < ix) {
87974 maechler 311
		for (int i = m + 1; i <= ix; i++)
13434 maechler 312
		    f = f * (n1 - i + 1) * (k - i + 1) / (n2 - k + i) / i;
574 ihaka 313
	    } else if (m > ix) {
87974 maechler 314
		for (int i = ix + 1; i <= m; i++)
33687 tlumley 315
		    f = f * i * (n2 - k + i) / (n1 - i + 1) / (k - i + 1);
574 ihaka 316
	    }
87974 maechler 317
#ifdef DEBUG_rhyper
318
	    REprintf(" small m or ix: f = %g\n", f);
319
#endif
574 ihaka 320
	    if (v <= f) {
87946 ripley 321
		reject = false;
574 ihaka 322
	    }
323
	} else {
70052 maechler 324
 
325
	    const static double deltal = 0.0078;
326
	    const static double deltau = 0.0034;
327
 
328
#ifdef DEBUG_rhyper
329
	    REprintf(" ... accept/reject 'large' case v=%g\n", v);
330
#endif
574 ihaka 331
	    /* squeeze using upper and lower bounds */
87974 maechler 332
	    double
333
		y = ix,
334
		y1 = y + 1.0,
335
		ym = y - m,
336
		yn = n1 - y + 1.0,
337
		yk = k  - y + 1.0,
338
		nk = n2 - k + y1,
339
		r = -ym / y1,
340
		s =  ym / yn,
341
		t =  ym / yk,
342
		e = -ym / nk,
343
		g = yn * yk / (y1 * nk) - 1.0,
344
		dg = (g < 0.0) ? 1. + g : 1.,
345
		gu = g * (1.0 + g * (-0.5 + g / 3.0)),
346
		gl = gu - .25 * (g * g * g * g) / dg,
347
		xm = m + 0.5,
348
		xn = n1 - m + 0.5,
349
		xk = k - m + 0.5,
350
		nm = n2 - k + xm,
351
		ub = y * gu - m * gl + deltau
574 ihaka 352
		+ xm * r * (1. + r * (-0.5 + r / 3.0))
353
		+ xn * s * (1. + s * (-0.5 + s / 3.0))
354
		+ xk * t * (1. + t * (-0.5 + t / 3.0))
355
		+ nm * e * (1. + e * (-0.5 + e / 3.0));
356
	    /* test against upper bound */
87974 maechler 357
	    double alv = log(v);
574 ihaka 358
	    if (alv > ub) {
87946 ripley 359
		reject = true;
574 ihaka 360
	    } else {
87974 maechler 361
		/* test against lower bound */
362
		double dr = xm * (r * r * r * r);
363
		if (r < 0.)
13434 maechler 364
		    dr /= (1.0 + r);
87974 maechler 365
		double ds = xn * (s * s * s * s);
574 ihaka 366
		if (s < 0.0)
13434 maechler 367
		    ds /= (1.0 + s);
87974 maechler 368
		double dt = xk * (t * t * t * t);
574 ihaka 369
		if (t < 0.0)
13434 maechler 370
		    dt /= (1.0 + t);
87974 maechler 371
		double de = nm * (e * e * e * e);
574 ihaka 372
		if (e < 0.0)
13434 maechler 373
		    de /= (1.0 + e);
574 ihaka 374
		if (alv < ub - 0.25 * (dr + ds + dt + de)
375
		    + (y + m) * (gl - gu) - deltal) {
87946 ripley 376
		    reject = false;
33718 maechler 377
		}
13434 maechler 378
		else {
379
		    /* * Stirling's formula to machine accuracy
574 ihaka 380
		     */
381
		    if (alv <= (a - afc(ix) - afc(n1 - ix)
382
				- afc(k - ix) - afc(n2 - k + ix))) {
87946 ripley 383
			reject = false;
574 ihaka 384
		    } else {
87946 ripley 385
			reject = true;
574 ihaka 386
		    }
387
		}
388
	    }
87974 maechler 389
	} // end{ III "large" }
574 ihaka 390
 
87974 maechler 391
    } while (reject);
392
 
77694 maechler 393
    } // end{branch III}
70052 maechler 394
 
574 ihaka 395
 
77694 maechler 396
L_finis:  /* return appropriate variate */
397
 
398
#ifdef DEBUG_rhyper
399
    REprintf(" L_finis: ix = %d, then", ix);
400
#endif
77879 ripley 401
    if ((double)kk + kk >= N) {
574 ihaka 402
	if (nn1 > nn2) {
403
	    ix = kk - nn2 + ix;
404
	} else {
405
	    ix = nn1 - ix;
406
	}
77694 maechler 407
    } else if (nn1 > nn2) {
408
	ix = kk - ix;
574 ihaka 409
    }
77694 maechler 410
#ifdef DEBUG_rhyper
411
    REprintf(" %d\n", ix);
412
#endif
574 ihaka 413
    return ix;
414
}