Debian Codegraph @

easel/esl_lognormal.c

raw symbols SCIP
1 /* Statistical routines for lognormal distributions
2 *
3 * Contents:
4 * 1. Evaluating lognormal densities and distributions
5 * 2. Sampling
6 * 3. Fitting
7 * 4. Unit tests
8 * 5. Test driver
9 */
10
11 #include "easel.h"
12 #include "esl_random.h"
13 #include "esl_lognormal.h"
14
15 /*****************************************************************
16 * 1. Evaluating lognormal densities and distributions
17 *****************************************************************/
18
19 double
20 esl_lognormal_pdf(double x, double mu, double sigma)
21 {
22 double z;
23
24 ESL_DASSERT1(( x >= 0. ));
25 if (x == 0.) return 0.;
26
27 z = (log(x) - mu) / sigma;
28 return exp(-z*z*0.5) / (x * sigma * sqrt(2.*eslCONST_PI));
29 }
30
31 double
32 esl_lognormal_logpdf(double x, double mu, double sigma)
33 {
34 double z;
35
36 ESL_DASSERT1(( x >= 0. ));
37 if (x == 0.) return -eslINFINITY;
38
39 z = (log(x) - mu) / sigma;
40 return -log(x * sigma) - 0.5 * log(2 * eslCONST_PI) - 0.5*z*z;
41 }
42
43 /*****************************************************************
44 * 2. Sampling
45 *****************************************************************/
46
47 /* Function: esl_lognormal_Sample()
48 * Synopsis: Sample a lognormal-distributed variate
49 *
50 * Purpose: Given $\mu > 0$ and $\sigma > 0$ parameters,
51 * return a lognormal-distributed random variate
52 * $x > 0$.
53 */
54 double
55 esl_lognormal_Sample(ESL_RANDOMNESS *rng, double mu, double sigma)
56 {
57 ESL_DASSERT1(( mu > 0. && sigma > 0. ));
58 double u = esl_rnd_Gaussian(rng, 0., 1.); // standard N(0;1) normal variate
59 return exp(mu + sigma*u);
60 }
61
62 /*****************************************************************
63 * 3. Fitting
64 *****************************************************************/
65
66 int
67 esl_lognormal_FitComplete(double *x, int n, double *ret_mu, double *ret_sigma)
68 {
69 int i;
70 double y,t,c,z;
71 double mu = 0.;
72 double sigma = 0.;
73
74 // Kahan compensated summation for \mu = \sum_i log(x_i)
75 c = 0.;
76 for (i = 0; i < n; i++) {
77 y = log(x[i]) - c;
78 t = mu + y;
79 c = (t-mu)-y;
80 mu = t;
81 }
82 mu /= n; // now mu = mean of log(x): 1/n \sum_i log(x_i)
83
84 // Second pass: Kahan summation for \sigma^2 = 1/(n-1) \sum_i (log(x_i) - \mu)^2
85 c = 0.;
86 for (i = 0; i < n; i++) {
87 z = log(x[i]) - mu;
88 y = (z*z) - c;
89 t = sigma + y;
90 c = (t-sigma) - y;
91 sigma = t;
92 }
93 sigma = sqrt(sigma / (n-1));
94
95 *ret_mu = mu;
96 *ret_sigma = sigma;
97 return eslOK;
98 }
99
100
101 /* Function: esl_lognormal_FitCountHistogram()
102 * Synopsis: Fit a lognormal approximation to $c_i$ counts
103 * Incept: SRE, Mon 06 Jun 2022
104 *
105 * Purpose: Given counts <c_i> for <i=0..n>, with <c[0]=0>,
106 * fit a lognormal approximation to this histogram.
107 *
108 * Counts are doubles, not integers; this allows us to use
109 * weighted counts, and it also allows the total number of
110 * counts to range up to ~9e15 (the maximum exact integer
111 * representation in a double, 2^53).
112 *
113 * Args: c - observed counts c[1..n]; c[0]=0; other c[i>0] >= 0
114 * n - maximum i in c[i]
115 * ret_mu - RETURN: estimated mu
116 * ret_sigma - RETURN: estimated sigma
117 *
118 * Returns: <eslOK> on success
119 *
120 * Throws: <eslEINVAL> for problems like c[0] != 0, c[i] < 0, or zero total counts.
121 */
122 int
123 esl_lognormal_FitCountHistogram(double *c, int n, double *ret_mu, double *ret_sigma)
124 {
125 double mu = 0.;
126 double sigma = 0.;
127 double ntot = 0;
128 double z;
129 int i;
130 int status;
131
132 if (c[0] != 0.) ESL_XEXCEPTION(eslEINVAL, "you want c[0]=0.0 in esl_lognormal_FitCountHistogram()");
133
134 /* First pass: calculate \mu = 1/ntot \sum_i c_i log(i) */
135 for (i = 1; i <= n; i++)
136 if (c[i] > 0.) {
137 mu += c[i] * log((double) i);
138 ntot += c[i];
139 }
140 else if (c[i] < 0.) ESL_XEXCEPTION(eslEINVAL, "count c[%d] < 0", i);
141 if (ntot <= 0.) ESL_XEXCEPTION(eslEINVAL, "count histogram c[] has no counts");
142 mu /= ntot;
143
144 // Second pass: \sigma^2 = 1/(ntot-1) \sum_i c_i (log(i) - \mu)^2
145 for (i = 1; i <= n; i++)
146 if (c[i] > 0.) {
147 z = log((double) i) - mu;
148 sigma += c[i]*z*z;
149 }
150 sigma = sqrt( sigma / (ntot-1));
151
152 *ret_mu = mu;
153 *ret_sigma = sigma;
154 return eslOK;
155
156 ERROR:
157 *ret_mu = -eslINFINITY;
158 *ret_sigma = -eslINFINITY;
159 return status;
160 }
161
162
163 /*****************************************************************
164 * 4. Unit tests
165 *****************************************************************/
166 #ifdef eslLOGNORMAL_TESTDRIVE
167
168 /* utest_FitComplete()
169 *
170 * In theory, this test could fail stochastically, so we run it
171 * with a fixed RNG seed in production code (<allow_badluck> is
172 * normally FALSE). I didn't observe any failures in 10k runs.
173 */
174 static void
175 utest_FitComplete(ESL_RANDOMNESS *rng, int allow_badluck)
176 {
177 char msg[] = "esl_lognormal::FitCountHistogram unit test failed";
178 double mu = 4.8;
179 double sigma = 0.7;
180 double *x = NULL;
181 int n = 1000000;
182 double est_mu, est_sigma;
183 int i;
184 int status;
185
186 if (! allow_badluck) esl_randomness_Init(rng, 42);
187
188 ESL_ALLOC(x, sizeof(double) * n);
189 for (i = 0; i < n; i++)
190 x[i] = esl_lognormal_Sample(rng, mu, sigma);
191
192 if ((status = esl_lognormal_FitComplete(x, n, &est_mu, &est_sigma)) != eslOK) esl_fatal(msg);
193 if ( esl_DCompare(mu, est_mu, 1e-3, 1e-3) != eslOK) esl_fatal(msg);
194 if ( esl_DCompare(sigma, est_sigma, 1e-3, 1e-3) != eslOK) esl_fatal(msg);
195
196 free(x);
197 return;
198
199 ERROR:
200 esl_fatal(msg);
201 }
202
203 /* utest_FitCountHistogram()
204 */
205 static void
206 utest_FitCountHistogram(void)
207 {
208 char msg[] = "esl_lognormal::FitCountHistogram unit test failed";
209 double mu = 4.8;
210 double sigma = 0.7;
211 int maxL = 100000;
212 int totn = 10000000;
213 double *c;
214 int i;
215 double est_mu, est_sigma;
216 int status;
217
218 ESL_ALLOC(c, sizeof(double) * (maxL+1));
219 c[0] = 0.;
220 for (i = 1; i <= maxL; i++)
221 c[i] = totn * esl_lognormal_pdf((double) i, mu, sigma);
222
223 if (( status = esl_lognormal_FitCountHistogram(c, maxL, &est_mu, &est_sigma)) != eslOK) esl_fatal(msg);
224 if ( esl_DCompare(mu, est_mu, 1e-4, 1e-4) != eslOK) esl_fatal(msg);
225 if ( esl_DCompare(sigma, est_sigma, 1e-4, 1e-4) != eslOK) esl_fatal(msg);
226
227 free(c);
228 return;
229
230 ERROR:
231 esl_fatal(msg);
232 }
233 #endif // eslLOGNORMAL_TESTDRIVE
234
235 /*****************************************************************
236 * 5. Test driver
237 *****************************************************************/
238 // gcc -o esl_lognormal_utest -g -Wall -I ~/src/easel -L ~/src/easel -DeslLOGNORMAL_TESTDRIVE esl_lognormal.c -leasel -lm
239
240 #ifdef eslLOGNORMAL_TESTDRIVE
241
242 #include "esl_getopts.h"
243
244 static ESL_OPTIONS options[] = {
245 /* name type default env range toggles reqs incomp help docgroup*/
246 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
247 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
248 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "allow bad luck (stochastic failures)", 0 },
249 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
250 };
251 static char usage[] = "[-options]";
252 static char banner[] = "test driver for lognormal module";
253
254 int
255 main(int argc, char **argv)
256 {
257 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
258 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
259 int allow_badluck = esl_opt_GetBoolean(go, "-x"); // if a utest can fail just by chance, let it, instead of suppressing
260
261 fprintf(stderr, "## %s\n", argv[0]);
262 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
263
264 utest_FitCountHistogram();
265
266 /* tests that can stochastically fail go last, because they default to reinit'ing RNG w/ fixed seed */
267 utest_FitComplete(rng, allow_badluck);
268
269
270 fprintf(stderr, "# status = ok\n");
271
272 esl_randomness_Destroy(rng);
273 esl_getopts_Destroy(go);
274 return eslOK;
275 }
276 #endif // eslLOGNORMAL_TESTDRIVE
277
278