1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
/* randist/hyperg.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
/* The hypergeometric distribution has the form,
prob(k) = choose(n1,t) choose(n2, t-k) / choose(n1+n2,t)
where choose(a,b) = a!/(b!(a-b)!)
n1 + n2 is the total population (tagged plus untagged)
n1 is the tagged population
t is the number of samples taken (without replacement)
k is the number of tagged samples found
*/
unsigned int
gsl_ran_hypergeometric (const gsl_rng * r, unsigned int n1, unsigned int n2,
unsigned int t)
{
const unsigned int n = n1 + n2;
unsigned int i = 0;
unsigned int a = n1;
unsigned int b = n1 + n2;
unsigned int k = 0;
if (t > n)
{
t = n ;
}
if (t < n / 2)
{
for (i = 0 ; i < t ; i++)
{
double u = gsl_rng_uniform(r) ;
if (b * u < a)
{
k++ ;
if (k == n1)
return k ;
a-- ;
}
b-- ;
}
return k;
}
else
{
for (i = 0 ; i < n - t ; i++)
{
double u = gsl_rng_uniform(r) ;
if (b * u < a)
{
k++ ;
if (k == n1)
return n1 - k ;
a-- ;
}
b-- ;
}
return n1 - k;
}
}
double
gsl_ran_hypergeometric_pdf (const unsigned int k,
const unsigned int n1,
const unsigned int n2,
unsigned int t)
{
if (t > n1 + n2)
{
t = n1 + n2 ;
}
if (k > n1 || k > t)
{
return 0 ;
}
else if (t > n2 && k + n2 < t )
{
return 0 ;
}
else
{
double p;
double c1 = gsl_sf_lnchoose(n1,k);
double c2 = gsl_sf_lnchoose(n2,t-k);
double c3 = gsl_sf_lnchoose(n1+n2,t);
p = exp(c1 + c2 - c3) ;
return p;
}
}
|