Debian Codegraph @

easel/esl_gamma.c

raw symbols SCIP
1 /* Statistical routines for gamma distributions.
2 *
3 * Contents:
4 * 1. Routines for evaluating densities and distributions
5 * 2. Generic API routines: for general interface w/ histogram module
6 * 3. Dumping plots for files
7 * 4. Sampling
8 * 5. ML fitting to complete data
9 * 6. Unit tests
10 * 7. Test driver
11 * 8. Example
12 *
13 * Xref: STL10/65
14 *
15 * To do:
16 * - Fit*() functions should return eslEINVAL on n=0, eslENORESULT
17 * on failure due to small n. Compare esl_gumbel. xref J12/93.
18 * SRE, Wed Nov 27 11:18:19 2013
19 */
20 #include <esl_config.h>
21
22 #include <stdio.h>
23 #include <math.h>
24 #include <float.h>
25
26 #include "easel.h"
27 #include "esl_histogram.h"
28 #include "esl_random.h"
29 #include "esl_stats.h"
30
31 #include "esl_gamma.h"
32
33 static int tau_by_moments_binned(ESL_HISTOGRAM *g, double mu, double *ret_tau,
34 double *ret_mean, double *ret_logsum);
35 static double tau_function(double tau, double mean, double logsum);
36
37
38 /****************************************************************************
39 * 1. Routines for evaluating densities and distributions
40 ****************************************************************************/
41
42 /* Function: esl_gam_pdf()
43 *
44 * Purpose: Calculates the gamma PDF $P(X=x)$ given value <x>,
45 * location parameter <mu>, scale parameter <lambda>, and shape
46 * parameter <tau>.
47 */
48 double
49 esl_gam_pdf(double x, double mu, double lambda, double tau)
50 {
51 double y = lambda * (x - mu);
52 double gamtau;
53 double val;
54
55 if (y < 0.) return 0.;
56
57 esl_stats_LogGamma(tau, &gamtau);
58 val = ((tau*log(lambda) + (tau-1.)*log(x-mu)) - gamtau) - y;
59 return exp(val);
60 }
61
62 /* Function: esl_gam_logpdf()
63 *
64 * Purpose: Calculates log of the probability density function
65 * for the gamma, $\log P(X=x)$, given value <x>,
66 * location parameter <mu>, scale parameter <lambda>, and
67 * shape parameter <tau>.
68 */
69 double
70 esl_gam_logpdf(double x, double mu, double lambda, double tau)
71 {
72 double y = lambda * (x - mu);
73 double gamtau;
74 double val;
75
76 if (x < 0.) return -eslINFINITY;
77
78 esl_stats_LogGamma(tau, &gamtau);
79 val = ((tau*log(lambda) + (tau-1.)*log(x-mu)) - gamtau) - y;
80 return val;
81 }
82
83 /* Function: esl_gam_cdf()
84 *
85 * Purpose: Calculates the cumulative distribution function
86 * for the gamma, $P(X \leq x)$, given value <x>,
87 * location parameter <mu>, scale parameter <lambda>, and
88 * shape parameter <tau>.
89 *
90 * (For $\mu=0$, $\lambda = 1$, this is the
91 * incomplete Gamma function $P(\tau,x)$.)
92 */
93 double
94 esl_gam_cdf(double x, double mu, double lambda, double tau)
95 {
96 double y = lambda * (x - mu);
97 double val;
98
99 if (y <= 0.) return 0.;
100
101 esl_stats_IncompleteGamma(tau, y, &val, NULL);
102 return val;
103 }
104
105 /* Function: esl_gam_logcdf()
106 *
107 * Purpose: Calculates the log of the cumulative distribution function
108 * for the gamma, $\log P(X \leq x)$, given value <x>, location
109 * parameter <mu>, scale parameter <lambda>, and shape
110 * parameter <tau>.
111 */
112 double
113 esl_gam_logcdf(double x, double mu, double lambda, double tau)
114 {
115 double y = lambda * (x - mu);
116 double val;
117
118 if (y <= 0.) return -eslINFINITY;
119
120 esl_stats_IncompleteGamma(tau, y, &val, NULL);
121 return log(val);
122 }
123
124 /* Function: esl_gam_surv()
125 *
126 * Purpose: Calculates the survival function for the gamma, $P(X > x)$,
127 * given value <x>, location parameter <mu>, scale parameter
128 * <lambda>, and shape parameter <tau>.
129 */
130 double
131 esl_gam_surv(double x, double mu, double lambda, double tau)
132 {
133 double y = lambda * (x - mu);
134 double val;
135
136 if (y <= 0.) return 1.0;
137
138 esl_stats_IncompleteGamma(tau, y, NULL, &val);
139 return val;
140 }
141
142
143 /* Function: esl_gam_logsurv()
144 *
145 * Purpose: Calculates the log of the survival function for the gamma,
146 * $\log P(X > x)$, given value <x>, location parameter <mu>,
147 * scale parameter <lambda>, and shape parameter <tau>.
148 *
149 * Relies on <esl_stats_IncompleteGamma()>, which has limited
150 * dynamic range. Any result of < -700 or so will be -infinity.
151 * To fix this, we need a log version of <esl_stats_IncompleteGamma()>.
152 */
153 double
154 esl_gam_logsurv(double x, double mu, double lambda, double tau)
155 {
156 double y = lambda * (x - mu);
157 double val;
158
159 if (y <= 0.) return 0.;
160
161 esl_stats_IncompleteGamma(tau, y, NULL, &val);
162 return log(val);
163 }
164
165
166 /* Function: esl_gam_invcdf()
167 *
168 * Purpose: Calculates the inverse CDF for a gamma with location
169 * parameter <mu>, scale parameter <lambda> and shape
170 * parameter <tau>, returning the value <x> at which the
171 * CDF is <p>.
172 *
173 * This inverse CDF is solved by a computationally expensive,
174 * brute force bisection search on the CDF of <x>.
175 */
176 double
177 esl_gam_invcdf(double p, double mu, double lambda, double tau)
178 {
179 double x1, x2, xm; /* low, high guesses at x */
180 double f2, fm;
181 double tol = 1e-6;
182
183 x1 = 0.;
184 x2 = tau / lambda;
185 do { /* bracket */
186 x2 = x2*2.;
187 f2 = esl_gam_cdf(x2, mu, lambda, tau);
188 } while (f2 < p);
189
190 do { /* bisection */
191 xm = (x1+x2)/ 2.;
192 fm = esl_gam_cdf(xm, mu, lambda, tau);
193
194 if (fm > p) x2 = xm;
195 else if (fm < p) x1 = xm;
196 else return xm; /* unlikely exact fm==p */
197 } while ( (x2-x1)/(x1+x2) > tol);
198
199 xm = (x1+x2)/2.;
200 return xm;
201 }
202 /*-------------------- end densities & distributions ------------------------*/
203
204
205
206
207 /****************************************************************************
208 * 2. Generic API routines: for general interface w/ histogram module
209 ****************************************************************************/
210
211 /* Function: esl_gam_generic_pdf()
212 *
213 * Purpose: Generic-API wrapper around <esl_gam_pdf()>, taking
214 * a void ptr to a double array containing $\mu$, $\lambda$,
215 * $\tau$ parameters.
216 */
217 double
218 esl_gam_generic_pdf(double x, void *params)
219 {
220 double *p = (double *) params;
221 return esl_gam_pdf(x, p[0], p[1], p[2]);
222 }
223
224
225 /* Function: esl_gam_generic_cdf()
226 *
227 * Purpose: Generic-API wrapper around <esl_gam_cdf()>, taking
228 * a void ptr to a double array containing $\mu$, $\lambda$,
229 * $\tau$ parameters.
230 */
231 double
232 esl_gam_generic_cdf(double x, void *params)
233 {
234 double *p = (double *) params;
235 return esl_gam_cdf(x, p[0], p[1], p[2]);
236 }
237
238
239 /* Function: esl_gam_generic_surv()
240 *
241 * Purpose: Generic-API wrapper around <esl_gam_surv()>, taking
242 * a void ptr to a double array containing $\mu$, $\lambda$,
243 * $\tau$ parameters.
244 */
245 double
246 esl_gam_generic_surv(double x, void *params)
247 {
248 double *p = (double *) params;
249 return esl_gam_surv(x, p[0], p[1], p[2]);
250 }
251
252
253 /* Function: esl_gam_generic_invcdf()
254 *
255 * Purpose: Generic-API wrapper around <esl_gam_invcdf()>, taking
256 * a void ptr to a double array containing $\mu$, $\lambda$,
257 * $\tau$ parameters.
258 */
259 double
260 esl_gam_generic_invcdf(double x, void *params)
261 {
262 double *p = (double *) params;
263 return esl_gam_invcdf(x, p[0], p[1], p[2]);
264 }
265 /*------------------------ end generic API ---------------------------------*/
266
267
268
269 /****************************************************************************
270 * 3. Dumping plots for files
271 ****************************************************************************/
272
273 /* Function: esl_gam_Plot()
274 *
275 * Purpose: Plot some gamma distribution function <func> (for instance,
276 * <esl_gam_pdf()>) for parameters <mu>, <lambda>, and <tau>, for
277 * a range of values x from <xmin> to <xmax> in steps of <xstep>;
278 * output to an open stream <fp> in xmgrace XY input format.
279 *
280 * Returns: <eslOK> on success.
281 *
282 * Throws: <eslEWRITE> on any system write error, such as a filled disk.
283 */
284 int
285 esl_gam_Plot(FILE *fp, double mu, double lambda, double tau,
286 double (*func)(double x, double mu, double lambda, double tau),
287 double xmin, double xmax, double xstep)
288 {
289 double x;
290 for (x = xmin; x <= xmax; x += xstep)
291 if (fprintf(fp, "%f\t%g\n", x, (*func)(x, mu, lambda, tau)) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "gamma plot write failed");
292 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "gamma plot write failed");
293 return eslOK;
294 }
295 /*-------------------- end plot dumping routines ---------------------------*/
296
297
298 /****************************************************************************
299 * 4. Sampling
300 ****************************************************************************/
301 /* Function: esl_gam_Sample()
302 *
303 * Purpose: Sample a gamma-distributed random variate.
304 */
305 double
306 esl_gam_Sample(ESL_RANDOMNESS *r, double mu, double lambda, double tau)
307 {
308 double x;
309
310 do {
311 x = esl_rnd_Gamma(r, tau);
312 x = mu + x / lambda; // a roundoff error of 1 + \epsilon = 1 is possible here
313 } while (x == mu); // ... so avoid it.
314 return x;
315 }
316 /*--------------------------- end sampling ---------------------------------*/
317
318
319
320 /****************************************************************************
321 * 5. ML fitting to complete data
322 ****************************************************************************/
323
324 /* gam_sufficient_stats()
325 *
326 * The mean \frac{\sum_i x_i}{n} and the mean of the logs \frac{\sum_i
327 * log(x_i)}{n} are all we need for calculating the NLL for the gamma,
328 * and its first and second derivatives.
329 *
330 * Throws <eslEINVAL> if any of the x[i] are < \mu.
331 */
332 static int
333 gam_sufficient_stats(double *x, int n, double mu, double *ret_xbar, double *ret_logxbar)
334 {
335 double xbar = 0.;
336 double logxbar = 0.;
337 int i;
338 int status;
339
340 for (i = 0; i < n; i++) // this is naive summation, which is numerically unstable for large sums;
341 { // ... double precision should be enough; see esl_vec_DSum() for Kahan compensated summation if you need more
342 if (x[i] - mu < 0) ESL_XEXCEPTION(eslEINVAL, "x[i] < mu in esl_gamma::gamma_sufficient_stats()");
343 xbar += x[i] - mu;
344 logxbar += (x[i] - mu == 0.0) ? -36. : log(x[i] - mu); // -36. is ~ log(DBL_EPSILON); safeguard against roundoff to 0
345 }
346 *ret_xbar = xbar / n;
347 *ret_logxbar = logxbar / n;
348 return eslOK;
349
350 ERROR:
351 *ret_xbar = -eslINFINITY;
352 *ret_logxbar = -eslINFINITY;
353 return status;
354 }
355
356 /* gam_nll()
357 *
358 * This is the one-parameter (tau only) form of the average NLL per
359 * sample; the objective function for the generalized Newton, obtained
360 * by substituting \lambda = \tau / xbar. See esl_gamma.md notes.
361 *
362 * The NLL can be negative! The gamma is a continuous probability
363 * distribution.
364 *
365 * Throws <eslERANGE> if tau < 0.
366 */
367 static int
368 gam_nll(double xbar, double logxbar, double tau, double *ret_nll)
369 {
370 double logp = 0.;
371 double loggamtau;
372 int status;
373
374 if ((status = esl_stats_LogGamma(tau, &loggamtau)) != eslOK) goto ERROR;
375 logp = tau * log(tau) - tau * log(xbar) - loggamtau + (tau - 1.0) * logxbar - tau;
376 *ret_nll = -logp;
377 return eslOK;
378
379 ERROR:
380 *ret_nll = eslINFINITY;
381 return status;
382 }
383
384
385 /* gam_fitting_engine()
386 *
387 * Implements generalized Newton optimization algorithm
388 * [Minka00,Minka02]; given precalculated means <xbar> and <logxbar>
389 * and known <mu>, obtain ML estimates of the lambda and tau
390 * parameters and return them in <*ret_lambda>, <*ret_tau>.
391 *
392 * Throws <eslENOHALT> if it fails to converge; <*ret_lambda>
393 * and <*ret_tau> are 0.0.
394 * Throws <eslERANGE> if we try to evaluate a bad <tau> value, which
395 * I think can only happen on some sort of internal coding error.
396 */
397 static int
398 gam_fitting_engine(double xbar, double logxbar, double mu, double *ret_lambda, double *ret_tau)
399 {
400 int max_iterations = 100;
401 int iter = 0;
402 double fx = eslINFINITY;
403 double psi, trigamma;
404 double tau, old_tau;
405 double old_fx;
406 int status;
407
408 tau = 0.5 / (log(xbar) - logxbar); // initial rough estimate for tau, combining Stirling approx for log Gamma(x) with f'(nll)=0
409 do
410 {
411 old_fx = fx;
412 old_tau = tau;
413
414 /* Update tau using generalized Newton, based on fitting g(\tau) = a + b \tau + c \log \tau around current \tau */
415 if (( status = esl_stats_Psi(tau, &psi)) != eslOK) goto ERROR;
416 if (( status = esl_stats_Trigamma(tau, &trigamma)) != eslOK) goto ERROR;
417 tau = 1.0 / (1.0/tau + (logxbar - log(xbar) + log(tau) - psi) / ( tau - tau * tau * trigamma));
418 if (( status = gam_nll(xbar, logxbar, tau, &fx)) != eslOK) goto ERROR;
419 iter++;
420 }
421 while ( iter < max_iterations &&
422 (esl_DCompare(old_tau, tau, 1e-6, 1e-6) != eslOK ||
423 esl_DCompare(old_fx, fx, 1e-6, 1e-6) != eslOK) );
424 if (iter == max_iterations) ESL_XEXCEPTION(eslENOHALT, "generalized Newton failed to converge in ML Gamma fitting");
425
426 *ret_lambda = tau / xbar;
427 *ret_tau = tau;
428 return eslOK;
429
430 ERROR:
431 *ret_lambda = -eslINFINITY;
432 *ret_tau = -eslINFINITY;
433 return status;
434 }
435
436
437
438 /* Function: esl_gam_FitComplete()
439 *
440 * Purpose: Given complete data consisting of <n> samples <x[0]..x[n-1]>,
441 * and a known location parameter <mu>, determine and return
442 * maximum likelihood parameters <ret_lambda> and <ret_tau>.
443 *
444 * Args: x - complete gamma-distributed data [0..n-1]
445 * n - number of samples in <x>
446 * mu - known location parameter
447 * ret_lambda - RETURN: ML estimate of lambda
448 * ret_tau - RETURN: ML estimate of tau
449 *
450 * Returns: <eslOK> on success.
451 *
452 * Throws: <eslENOHALT> if convergence fails;
453 * <eslEINVAL> if data cannot be gamma distributed (some <x[i] < mu>).
454 * (<eslERANGE> is also code-possible, but theory-impossible.)
455 */
456 int
457 esl_gam_FitComplete(double *x, int n, double mu, double *ret_lambda, double *ret_tau)
458 {
459 double xbar;
460 double logxbar;
461 double lambda, tau;
462 int status;
463
464 if ((status = gam_sufficient_stats(x, n, mu, &xbar, &logxbar)) != eslOK) goto ERROR;
465 if ((status = gam_fitting_engine(xbar, logxbar, mu, &lambda, &tau)) != eslOK) goto ERROR;
466
467 *ret_lambda = lambda;
468 *ret_tau = tau;
469 return eslOK;
470
471 ERROR:
472 *ret_lambda = -eslINFINITY;
473 *ret_tau = -eslINFINITY;
474 return status;
475 }
476
477
478 /* Function: esl_gam_FitCountHistogram()
479 * Synopsis: Fit a gamma distribution to $c_i$ counts
480 * Incept: SRE, Mon 13 Jun 2022
481 *
482 * Purpose: Given counts <c_i> for <i=0..n>, with <c[0]=0>,
483 * fit a gamma approximation to this histogram.
484 *
485 * Counts are doubles, not integers; this allows us to use
486 * weighted counts, and it also allows the total number of
487 * counts to range up to ~9e15 (the maximum exact integer
488 * representation in a double, 2^53).
489 *
490 * Args: c - observed counts c[1..n]; c[0]=0; other c[i>0] >= 0
491 * n - maximum i in c[i]
492 * ret_lamnda - RETURN: estimated mu
493 * ret_tau - RETURN: estimated sigma
494 *
495 * Returns: <eslOK> on success
496 *
497 * Throws: <eslEINVAL> for problems like c[0] != 0, c[i] < 0, or zero total counts.
498 * <eslENOHALT> if generalized Newton optimization fails to converge (very unlikely)
499 * <eslERANGE> is code-possible, theory-impossible
500 */
501 int
502 esl_gam_FitCountHistogram(double *ct, int n, double mu, double *ret_lambda, double *ret_tau)
503 {
504 double xbar = 0.; // \bar{x}; mean x value
505 double logxbar = 0.; // \overline{\log x}; mean of log x
506 double ntot = 0.;
507 int mu_i = lround(mu);
508 double v;
509 int i;
510 int status;
511
512 if (ceil(mu) != mu) ESL_XEXCEPTION(eslEINVAL, "esl_gam_FitCountHistogram assumes mu is an exact integer representation (e.g. 0.0)");
513 for (i = 0; i <= mu_i; i++)
514 if (ct[i] != 0.) ESL_XEXCEPTION(eslEINVAL, "esl_gam_FitCountHistogram assumes all ct[i] for i <= mu are 0.0");
515
516 for (i = mu_i+1; i <= n; i++)
517 if (ct[i] > 0.)
518 {
519 v = (double) i - mu;
520 xbar += ct[i] * v;
521 logxbar += ct[i] * log(v);
522 ntot += ct[i];
523 }
524 else if (ct[i] < 0.) ESL_XEXCEPTION(eslEINVAL, "count ct[%d] < 0", i);
525 if (ntot <= 0.) ESL_XEXCEPTION(eslEINVAL, "count histogram ct[] has no counts");
526 xbar /= ntot;
527 logxbar /= ntot;
528
529 return gam_fitting_engine(xbar, logxbar, mu, ret_lambda, ret_tau);
530
531 ERROR:
532 *ret_lambda = -eslINFINITY;
533 *ret_tau = -eslINFINITY;
534 return status;
535 }
536
537
538
539
540 /* Function: esl_gam_FitCompleteBinned()
541 *
542 * Purpose: Fit a complete gamma distribution to the observed
543 * binned data in a histogram <g>, where each
544 * bin i holds some number of observed samples x with values from
545 * lower bound l to upper bound u (that is, $l < x \leq u$);
546 * determine and return maximum likelihood estimates for the
547 * parameters $\mu, \lambda, \tau$ and
548 * return them in <*ret_mu>, <*ret_lambda>, <*ret_tau>.
549 *
550 * Unlike the <esl_exp_FitCompleteBinned()> case where the
551 * ML fit optimizes $\sum_i n_i \log P(a_i \leq x < b_i)$
552 * where $a_i \leq b_i$ are the bounds of bin i with
553 * occupancy $n_i$, here we take the approximation that
554 * $c_i = a_i + 0.5*(b_i-a_i)$ and optimize $\log P(a_i
555 * \leq x < b_i) \simeq \log(w) + \log P(x=c_i)$.
556 *
557 * Since $b_i-a_i = w$ is fixed, optimizing the above
558 * becomes equivalent to optimizing $\sum_i n_i * log P(x=c_i)$.
559 *
560 * The optimization is then equivalent to the non-binned case,
561 * but subsituting in averages such as $\sum_i x(i)$ by
562 * $\sum_i n_i*c_i i$, and so forth.
563 *
564 * If the binned data in <g> were set to focus on
565 * a tail by virtual censoring, the "complete" gamma is
566 * fitted to this tail. The caller then also needs to
567 * remember what fraction of the probability mass was in this
568 * tail.
569 *
570 * Args: g - histogram
571 * ret_mu - RETURN: given by the histogram
572 * ret_lambda - RETURN: ML estimate of lambda
573 * ret_tau - RETURN: ML estimate of tau
574 *
575 * Returns: <eslOK> on success.
576 *
577 * Throws: <eslENOHALT> if bracketing or bisection fails;
578 * <eslEINVAL> if data cannot be gamma distributed (some <x[i] < mu>,
579 * or zero variance in x).
580 *
581 * Returns: <eslOK> on success.
582 *
583 * Throws: <eslEINVAL> if dataset is true-censored.
584 *
585 * Note: This is an older implementation than FitComplete(). Here we
586 * use rootfinding to find tau. FitComplete() uses
587 * generalized Newton optimization [Minka00,Minka02], which
588 * is much more efficient (and way cooler).
589 */
590 int
591 esl_gam_FitCompleteBinned(ESL_HISTOGRAM *g, double *ret_mu, double *ret_lambda, double *ret_tau)
592 {
593 double mu = 0.;
594 double mean, logsum;
595 int i;
596 double c, fc;
597 double a, fa;
598 double b, fb;
599 double tol = 1e-6;
600 int maxit = 100;
601 int status;
602
603 if (g->dataset_is == COMPLETE)
604 {
605 if (g->is_rounded) mu = esl_histogram_Bin2LBound(g, g->imin);
606 else mu = g->xmin;
607 }
608 else if (g->dataset_is == VIRTUAL_CENSORED) /* i.e., we'll fit to tail */
609 mu = g->phi;
610 else if (g->dataset_is == TRUE_CENSORED)
611 ESL_EXCEPTION(eslEINVAL, "can't fit true censored dataset");
612
613 if ((status = tau_by_moments_binned(g, mu, &c, &mean, &logsum) != eslOK)) goto ERROR;
614 a = b = c;
615 if (c == 1.0) {
616 *ret_mu = mu;
617 *ret_lambda = c / mean;
618 *ret_tau = c;
619 return eslOK;
620 }
621 fc = tau_function(c, mean, logsum);
622
623 /* Rootfinding, 1.: bracketing the root with points a,b.
624 */
625 if (fc > 0.) /* fx>0 means tau is too small, search right */
626 {
627 for (i = 0; i < maxit; i++) /* max iterations */
628 {
629 b = a * 2.;
630 fb = tau_function(b, mean, logsum);
631
632 if (fb < 0.) break; /* a,b now bracket */
633 a = b; /* else fb>0, so b is a better left bracket than a */
634 }
635 if (i == maxit) ESL_XEXCEPTION(eslENOHALT, "failed to bracket");
636 }
637 else if (fc < 0.) /* fx<0 means tau is too large, search left */
638 {
639 for (i = 0; i < maxit; i++)
640 {
641 a = b/2.;
642 fa = tau_function(a, mean, logsum);
643 if (fa > 0.) break; /* a,b now bracket */
644 b = a; /* else fa<0, so a is a better right bracket than b */
645 }
646 if (i == maxit) ESL_XEXCEPTION(eslENOHALT, "failed to bracket");
647 }
648
649 /* Rootfinding, 2.: Bisection search.
650 * We have the root in interval (a,b).
651 */
652 for (i = 0; i < maxit; i++)
653 {
654 c = (a+b)/2.; /* bisection */
655 fc = tau_function(c, mean, logsum);
656
657 if (fc > 0.) a = c;
658 else if (fc < 0.) b = c;
659 else break; /* unlikely event that we nail it */
660
661 if ((b-a) <= tol) {
662 c = (a+b)/2.;
663 break;
664 }
665 }
666 if (i == maxit) ESL_XEXCEPTION(eslENOHALT, "bisection search failed");
667
668 *ret_mu = mu;
669 *ret_lambda = (mean > 0.)? c / mean : 0.0;
670 *ret_tau = c;
671 return eslOK;
672
673 ERROR:
674 *ret_mu = 0.;
675 *ret_lambda = 0.;
676 *ret_tau = 0.;
677 return status;
678 }
679
680 /* tau_function()
681 *
682 * This is the rootfinding equation for tau...
683 * \ref{eqn:gamma_tau_root} in the documentation.
684 * mean is 1/N \sum (x_i - \mu)
685 * logsum is 1/N \sum \log (x_i - \mu)
686 * These are both independent of tau, and dependent
687 * on all data points, so we require the caller to
688 * precalculate them for us.
689 *
690 * This is a decreasing function of tau:
691 * the return value is > 0 when tau is too small,
692 * and < 0 when tau is too large.
693 */
694 static double
695 tau_function(double tau, double mean, double logsum)
696 {
697 double psitau;
698
699 esl_stats_Psi(tau, &psitau);
700 return ( ((log(tau) - psitau) - log(mean)) + logsum );
701 }
702
703 /* tau_by_moments_binned()
704 *
705 * Obtain an initial estimate for tau by matching moments. Also
706 * returns mean and logsum, which we need for ML fitting. To obtain a
707 * lambda estimate, use lambda = tau / mean.
708 *
709 * note: the whole method relies on the property log(sum) >= logsum;
710 * which works if all points are valid, that is positive;
711 * log(0) = -inf is not a valid point,
712 * and the inequality (Jensen's inequality) does not hold.
713 */
714 static int
715 tau_by_moments_binned(ESL_HISTOGRAM *g, double mu, double *ret_tau, double *ret_mean, double *ret_logsum)
716 {
717 int i;
718 double ai, bi, ci;
719 double sum, mean, var, logsum;
720 double tol = 1e-6;
721
722 sum = mean = var = logsum = 0.;
723 for (i = g->cmin+1; i <= g->imax; i++) /* for each occupied bin */
724 {
725 if (g->obs[i] == 0) continue;
726 ai = esl_histogram_Bin2LBound(g,i);
727 bi = esl_histogram_Bin2UBound(g,i);
728 ci = ai + 0.5 * (bi-ai);
729
730 if (ci < mu) ESL_EXCEPTION(eslEINVAL, "No point can be < mu in gamma data");
731 sum += (double)g->obs[i];
732 mean += (double)g->obs[i] * (ci-mu); /* mean is temporarily just the sum */
733 logsum += (ci>mu)? (double)g->obs[i] * log(ci-mu):0.0;
734 var += (double)g->obs[i] * (ci-mu) * (ci-mu); /* var is temporarily the sum of squares */
735 }
736
737 var = (sum > 1.)? (var - mean*mean/sum) / (sum-1.) : 0.0; /* now var is the variance */
738 mean /= (sum > 0.)? sum : 1.; /* and now mean is the mean */
739 logsum /= (sum > 0.)? sum : 1.;
740
741 if (ret_tau != NULL) *ret_tau = (var < tol || mean == 0.)? 1. : mean * mean / var;
742 if (ret_mean != NULL) *ret_mean = mean;
743 if (ret_logsum != NULL) *ret_logsum = logsum;
744 return eslOK;
745 }
746
747 /****************************************************************************
748 * 6. Unit tests
749 ****************************************************************************/
750 #ifdef eslGAMMA_TESTDRIVE
751
752 /* utest_FitComplete()
753 *
754 * This test fails stochastically, because it generates a random data
755 * sample from random choices of lambda and tau. So we run it with a
756 * fixed RNG seed in production code (<allow_badluck> is normally
757 * FALSE).
758 *
759 * The 0.5 lower limit is set for the random params because if you let
760 * \tau get small, you get very peaky distributions at the origin, and
761 * numerical error in fitting them [SRE:H13/23].
762 */
763 static void
764 utest_FitComplete(ESL_RANDOMNESS *rng, int allow_badluck)
765 {
766 char msg[] = "esl_gamma::FitComplete unit test failed";
767 double *x = NULL;
768 int n = 1000000;
769 double mu = 10.0; // don't use 0., in case I've idiotically assumed mu=0 somewhere
770 double lambda, tau; // don't randomly initialize these until *after* the allow_badluck RNG reinit
771 double lambda_e, tau_e; // new fit
772 double xbar, logxbar;
773 double nll, nll_e;
774 int i;
775 int status;
776
777 if (! allow_badluck) esl_randomness_Init(rng, 42);
778
779 lambda = 0.5 + esl_rnd_UniformPositive(rng) * 9.5; // (0.5,10.0)
780 tau = 0.5 + esl_rnd_UniformPositive(rng) * 9.5;
781
782 ESL_ALLOC(x, sizeof(double) * n);
783 for (i = 0; i < n; i++)
784 x[i] = esl_gam_Sample(rng, mu, lambda, tau);
785
786 if ((status = gam_sufficient_stats(x, n, mu, &xbar, &logxbar)) != eslOK) esl_fatal(msg);
787 if ((status = esl_gam_FitComplete(x, n, mu, &lambda_e, &tau_e)) != eslOK) esl_fatal(msg);
788 if ((status = gam_nll(xbar, logxbar, tau, &nll)) != eslOK) esl_fatal(msg);
789 if ((status = gam_nll(xbar, logxbar, tau_e, &nll_e)) != eslOK) esl_fatal(msg);
790
791 #if 0
792 printf("true mu = %f\n", mu);
793 printf("true lambda = %f\n", lambda);
794 printf("true tau = %f\n", tau);
795 printf("sample mean = %f\n", xbar);
796 printf("nll at true = %f\n", nll);
797 printf("fit lambda = %f\n", lambda_e);
798 printf("fit tau = %f\n", tau_e);
799 printf("nll at fit = %f\n", nll_e);
800 printf("lambda error = %f rel %f abs\n", (lambda_e-lambda)/lambda, lambda_e-lambda);
801 printf("tau error = %f rel %f abs\n", (tau_e-tau)/tau, tau_e-tau);
802 printf("nll diff = %f\n", nll - nll_e); // this difference should be nonnegative; nll_e <= nll.
803 #endif
804
805 if ( esl_DCompare(lambda, lambda_e, 1e-2, 1e-2) != eslOK) esl_fatal(msg);
806 if ( esl_DCompare(tau, tau_e, 1e-2, 1e-2) != eslOK) esl_fatal(msg);
807 if ( nll < nll_e) esl_fatal(msg); // it's a convex optimization.
808
809 free(x);
810 return;
811
812 ERROR:
813 esl_fatal(msg);
814 }
815
816 /* utest_FitCountHistogram()
817 *
818 * (This test has no stochastic failures; should always succeed.)
819 */
820 static void
821 utest_FitCountHistogram(void)
822 {
823 char msg[] = "esl_gamma::FitCountHistogram unit test failed";
824 double lambda = 0.0053; // an arbitrary lambda
825 double tau = 1.9; // ... and an arbitrary tau
826 double mu = 10.;
827 int mu_i = lround(mu);
828 int maxL = 100000;
829 int totn = 10000000;
830 double *ct = NULL;
831 double lambda_e, tau_e;
832 int i;
833 int status;
834
835 ESL_ALLOC(ct, sizeof(double) * (maxL+1));
836 for (i = 0; i <= mu_i; i++) ct[i] = 0.;
837 for (i = mu_i+1; i <= maxL; i++)
838 ct[i] = totn * esl_gam_pdf((double) i, mu, lambda, tau);
839
840 if (( status = esl_gam_FitCountHistogram(ct, maxL, mu, &lambda_e, &tau_e)) != eslOK) esl_fatal(msg);
841
842 if ( esl_DCompare(lambda, lambda_e, 1e-3, 1e-3) != eslOK) esl_fatal(msg);
843 if ( esl_DCompare(tau, tau_e, 1e-3, 1e-3) != eslOK) esl_fatal(msg);
844
845 free(ct);
846 return;
847
848 ERROR:
849 esl_fatal(msg);
850 }
851
852 #endif //eslGAMMA_TESTDRIVE
853
854 /****************************************************************************
855 * 6. Test driver
856 ****************************************************************************/
857 #ifdef eslGAMMA_TESTDRIVE
858
859 #include "esl_getopts.h"
860
861 static ESL_OPTIONS options[] = {
862 /* name type default env range toggles reqs incomp help docgroup*/
863 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
864 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
865 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "allow bad luck (stochastic failures)", 0 },
866 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
867 };
868 static char usage[] = "[-options]";
869 static char banner[] = "test driver for lognormal module";
870
871 int
872 main(int argc, char **argv)
873 {
874 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
875 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
876 int allow_badluck = esl_opt_GetBoolean(go, "-x"); // if a utest can fail just by chance, let it, instead of suppressing
877
878 fprintf(stderr, "## %s\n", argv[0]);
879 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
880
881 utest_FitCountHistogram();
882
883 /* tests that can stochastically fail go last, because they default to reinit'ing RNG w/ fixed seed */
884 utest_FitComplete(rng, allow_badluck);
885
886 fprintf(stderr, "# status = ok\n");
887
888 esl_randomness_Destroy(rng);
889 esl_getopts_Destroy(go);
890 return eslOK;
891 }
892 #endif //eslGAMMA_TESTDRIVE
893
894 /****************************************************************************
895 * Example main()
896 ****************************************************************************/
897 #ifdef eslGAMMA_EXAMPLE
898 /*::cexcerpt::gam_example::begin::*/
899 #include <stdio.h>
900 #include "easel.h"
901 #include "esl_random.h"
902 #include "esl_histogram.h"
903 #include "esl_gamma.h"
904
905 int
906 main(int argc, char **argv)
907 {
908 double mu = -5.0;
909 double lambda = 2.0;
910 double tau = 0.7;
911 ESL_HISTOGRAM *h = esl_histogram_CreateFull(mu, 100., 0.1);
912 ESL_RANDOMNESS *r = esl_randomness_Create(0);
913 int n = 10000;
914 double elam, etau;
915 int i;
916 double x;
917 double *data;
918 int ndata;
919
920 /* Take <n> gamma-distributed random samples. */
921 for (i = 0; i < n; i++)
922 {
923 x = esl_gam_Sample(r, mu, lambda, tau);
924 esl_histogram_Add(h, x);
925 }
926 esl_histogram_GetData(h, &data, &ndata);
927
928 /* Plot the empirical (sampled) and expected survivals */
929 esl_histogram_PlotSurvival(stdout, h);
930 esl_gam_Plot(stdout, mu, lambda, tau,
931 &esl_gam_surv, h->xmin, h->xmax, 0.1);
932
933 /* ML fit to complete data, and plot fitted survival curve */
934 esl_gam_FitComplete(data, ndata, mu, &elam, &etau);
935 esl_gam_Plot(stdout, mu, elam, etau,
936 &esl_gam_surv, h->xmin, h->xmax, 0.1);
937
938 esl_randomness_Destroy(r);
939 esl_histogram_Destroy(h);
940 return 0;
941 }
942 /*::cexcerpt::gam_example::end::*/
943 #endif /*eslGAMMA_EXAMPLE*/
944
945