Debian Codegraph @

easel/esl_gev.c

raw symbols SCIP
1 /* Statistical routines for generalized extreme value (GEV) distributions.
2 *
3 * Contents:
4 * 1. Evaluating densities and distributions
5 * 2. Generic API routines: for general interface w/ histogram module
6 * 3. Dumping plots to files
7 * 4. Sampling
8 * 5. ML fitting to complete or censored data
9 * 6. Stats driver
10 * 7. Example
11 *
12 * Xref:
13 * STL9/118, 2005/0712-easel-gev-impl. Verified against evd package in R.
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:07 2013
19 *
20 *****************************************************************
21 * GEV distribution
22 * G(x) = exp{ -[1 + \alpha \lambda(x - \mu)]^{-1/\alpha} }
23 * where:
24 * \mu = location parameter
25 * \lambda = scale parameter (\lambda = 1/\sigma, in [Coles01] notation)
26 * \alpha = shape parameter (\alpha = \xi, in [Coles01] notation)
27 *
28 * lim_{\alpha -> 0} is a type I EVD (Gumbel)
29 * \alpha > 0 is a Type II EVD (Frechet)
30 * \alpha < 0 is a Type III EVD (Weibull)
31 *
32 * Reference:
33 * [Coles01]
34 * S. Coles, An Introduction to Statistical Modeling of Extreme Values,
35 * Springer, 2001.
36 */
37 #include <esl_config.h>
38
39 #include <stdio.h>
40 #include <math.h>
41 #include <float.h>
42
43 #include "easel.h"
44 #include "esl_minimizer.h"
45 #include "esl_random.h"
46 #include "esl_stats.h"
47
48 #include "esl_gev.h"
49
50
51
52 /****************************************************************************
53 * 1. Evaluating densities and distributions
54 ****************************************************************************/
55
56 /* Function: esl_gev_pdf()
57 *
58 * Purpose: Calculates the probability density function for the
59 * generalized extreme value distribution, $P(X=x)$, given
60 * quantile <x> and GEV location, scale, shape parameters
61 * <mu>, <lambda>, <alpha>.
62 */
63 double
64 esl_gev_pdf(double x, double mu, double lambda, double alpha)
65 {
66 double y = lambda * (x-mu);
67 double ya1 = 1. + alpha * y;
68 double lya1;
69
70 /* Special case: if alpha is tiny, approximate by a Gumbel */
71 if (fabs(y*alpha) < 1e-12) return (lambda * exp(-y - exp(-y)));
72
73 /* Else, use GEV; but use log/exp to avoid a pow() call,
74 * as that's almost 2x faster (on my machine anyway).
75 */
76 if (ya1 <= 0) return 0.;
77 lya1 = log(ya1);
78 return (lambda * exp(-(1.+ 1./alpha)*lya1 - exp(-lya1/alpha)));
79 }
80
81 /* Function: esl_gev_logpdf()
82 *
83 * Purpose: Calculates the log probability density function for the
84 * generalized extreme value distribution, $\log P(X=x)$,
85 * given quantile <x> and GEV location, scale, shape
86 * parameters <mu>, <lambda>, <alpha>.
87 */
88 double
89 esl_gev_logpdf(double x, double mu, double lambda, double alpha)
90 {
91 double y = lambda *(x-mu);
92 double ya1 = 1. + alpha*y;
93 double lya1;
94
95 /* Special case: if alpha is tiny, approx by a Gumbel */
96 if (fabs(y*alpha) < 1e-12) return ((log(lambda) - y) - exp(-y));
97
98 /* It's important not to return NaN for this domain error;
99 * minimizer relies on being able to compare logL's for any parameter,
100 * and you can't compare NaN to anything.
101 */
102 if (ya1 <= 0) return -eslINFINITY;
103
104 lya1 = log(ya1);
105 return ( (log(lambda) - (1.+1./alpha)*lya1) - exp(-lya1/alpha));
106 }
107
108
109 /* Function: esl_gev_cdf()
110 *
111 * Purpose: Calculates the cumulative distribution function for the
112 * generalized extreme value distribution, $P(X \leq x)$,
113 * given quantile <x> and GEV location, scale, shape
114 * parameters <mu>, <lambda>, <alpha>.
115 */
116 double
117 esl_gev_cdf(double x, double mu, double lambda, double alpha)
118 {
119 double y = lambda *(x-mu);
120 double ya1 = 1. + alpha*y;
121 double lya1;
122
123 /* Special case: if alpha is tiny, approx by a Gumbel */
124 if (fabs(y*alpha) < 1e-12) return (exp(-exp(-y)));
125
126 if (ya1 <= 0) {
127 if (x < mu) return 0.0; /* the frechet case */
128 else return 1.0; /* the weibull case */
129 }
130 lya1 = log(ya1);
131 return (exp(-exp(-lya1/alpha)));
132 }
133
134
135
136 /* Function: esl_gev_logcdf()
137 *
138 * Purpose: Calculates the log of the cumulative distribution function for a
139 * generalized extreme value distribution, $\log P(X \leq x)$,
140 * given quantile <x> and GEV location, scale, shape
141 * parameters <mu>, <lambda>, <alpha>.
142 */
143 double
144 esl_gev_logcdf(double x, double mu, double lambda, double alpha)
145 {
146 double y = lambda *(x-mu);
147 double ya1 = 1. + alpha*y;
148 double lya1;
149
150 /* Special case: if alpha is tiny, approx by a Gumbel */
151 if (fabs(y*alpha) < 1e-12) return (-exp(-y));
152
153 if (ya1 <= 0) {
154 if (x < mu) return -eslINFINITY; /* Frechet */
155 else return 0.0; /* Weibull */
156 }
157
158 lya1 = log(ya1);
159 return (-exp(-lya1/alpha));
160 }
161
162
163 /* Function: esl_gev_surv()
164 *
165 * Purpose: Calculates the survivor function, $P(X>x)$ (that is, 1-cdf),
166 * the right tail's probability mass, given quantile <x> and
167 * GEV location, scale, shape parameters <mu>, <lambda>, <alpha>.
168 */
169 double
170 esl_gev_surv(double x, double mu, double lambda, double alpha)
171 {
172 double y = lambda *(x-mu);
173 double ya1 = 1. + alpha*y;
174 double lya1;
175
176 /* Special case: for tiny alpha, use Gumbel (xref esl_gumbel.c) */
177 if (fabs(y*alpha) < 1e-12)
178 return ((y > -0.5*log(DBL_EPSILON)) ? exp(-y) : (1 - exp(-exp(-y))));
179
180 if (ya1 <= 0) {
181 if (x < mu) return 1.0; /* the frechet case */
182 else return 0.0; /* the weibull case */
183 }
184 lya1 = log(ya1)/alpha;
185 return ((lya1 > -0.5*log(DBL_EPSILON)) ? exp(-lya1) : (1 - exp(-exp(-lya1))));
186 }
187
188
189 /* Function: esl_gev_logsurv()
190 *
191 * Purpose: Calculates the log survivor function $\log P(X>x)$ for a
192 * generalized extreme value distribution (that is,
193 * $\log (1 - \mbox{cdf})$, the log of the right tail's probability
194 * mass), given quantile <x> and GEV location, scale, shape
195 * parameters <mu>, <lambda>, <alpha>.
196 */
197 double
198 esl_gev_logsurv(double x, double mu, double lambda, double alpha)
199 {
200 double y = lambda *(x-mu);
201 double ya1 = 1. + alpha*y;
202 double lya1;
203
204 /* Special case: for tiny alpha, use Gumbel (xref esl_gumbel.c) */
205 if (fabs(y*alpha) < 1e-12)
206 {
207 if (y > -0.5 * log(DBL_EPSILON)) return (-y);
208 else if (y < -2.9) return (-exp(-exp(-y)));
209 else return (log(1-exp(-exp(-y))));
210 }
211
212 /* See esl_gumbel.c for analysis of the crossovers in
213 * the three cases (small, large, and ok lya1)
214 */
215 if (ya1 <= 0) {
216 if (x < mu) return 1.0; /* Frechet case */
217 else return -eslINFINITY; /* Weibull case */
218 }
219
220 lya1 = log(ya1)/alpha;
221 if (lya1 > -0.5 * log(DBL_EPSILON)) return (-lya1);
222 else if (lya1 < -2.9) return (-exp(-exp(-lya1)));
223 else return (log(1-exp(-exp(-lya1))));
224 }
225
226 /* Function: esl_gev_invcdf()
227 *
228 * Purpose: Calculates the inverse CDF of the GEV: given a probability
229 * <p> ($0 < p < 1$), returns the quantile <x> which would
230 * give <p> as its CDF, for a generalized extreme value
231 * distribution with parameters <mu>, <lambda>, and <alpha>.
232 */
233 double
234 esl_gev_invcdf(double p, double mu, double lambda, double alpha)
235 {
236 /* failover to Gumbel sample, for tiny alpha */
237 if (fabs(alpha) < 1e-12) return (mu - log(-1. * log(p)) / lambda);
238
239 return mu + (exp(-alpha*log(-log(p))) - 1.) / (alpha * lambda) ;
240 }
241 /*-------------------- end densities & distributions ------------------------*/
242
243
244
245 /*****************************************************************
246 * 2. Generic API routines: for general interface w/ histogram module
247 *****************************************************************/
248
249 /* Function: esl_gev_generic_pdf()
250 *
251 * Purpose: Generic-API version of PDF.
252 */
253 double
254 esl_gev_generic_pdf(double x, void *params)
255 {
256 double *p = (double *) params;
257 return esl_gev_pdf(x, p[0], p[1], p[2]);
258 }
259
260 /* Function: esl_gev_generic_cdf()
261 *
262 * Purpose: Generic-API version of CDF.
263 */
264 double
265 esl_gev_generic_cdf(double x, void *params)
266 {
267 double *p = (double *) params;
268 return esl_gev_cdf(x, p[0], p[1], p[2]);
269 }
270
271 /* Function: esl_gev_generic_surv()
272 *
273 * Purpose: Generic-API version of survival function.
274 */
275 double
276 esl_gev_generic_surv(double x, void *params)
277 {
278 double *p = (double *) params;
279 return esl_gev_surv(x, p[0], p[1], p[2]);
280 }
281
282 /* Function: esl_gev_generic_invcdf()
283 *
284 * Purpose: Generic-API version of inverse CDF.
285 */
286 double
287 esl_gev_generic_invcdf(double p, void *params)
288 {
289 double *v = (double *) params;
290 return esl_gev_invcdf(p, v[0], v[1], v[2]);
291 }
292 /*------------------------- end of generic API --------------------------*/
293
294
295
296 /****************************************************************************
297 * 3. Dumping plots to files
298 ****************************************************************************/
299
300 /* Function: esl_gev_Plot()
301 *
302 * Purpose: Plot some GEV function <func> (for instance,
303 * <esl_gev_pdf()>) for parameters <mu> and <lambda>, for
304 * a range of quantiles x from <xmin> to <xmax> in steps of <xstep>;
305 * output to an open stream <fp> in xmgrace XY input format.
306 *
307 * Returns: <eslOK> on success.
308 *
309 * Throws: <eslEWRITE> on any system write error, such as filled disk.
310 */
311 int
312 esl_gev_Plot(FILE *fp, double mu, double lambda, double alpha,
313 double (*func)(double x, double mu, double lambda, double alpha),
314 double xmin, double xmax, double xstep)
315 {
316 double x;
317 for (x = xmin; x <= xmax; x += xstep)
318 if (fprintf(fp, "%f\t%g\n", x, (*func)(x, mu, lambda, alpha)) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "gev plot write failed");
319 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "gev plot write failed");
320 return eslOK;
321 }
322 /*-------------------- end plot dumping routines ---------------------------*/
323
324
325
326
327 /****************************************************************************
328 * 4. Sampling
329 ****************************************************************************/
330 /* Function: esl_gev_Sample()
331 *
332 * Purpose: Sample a GEV-distributed random variate,
333 * by the transformation method.
334 */
335 double
336 esl_gev_Sample(ESL_RANDOMNESS *r, double mu, double lambda, double alpha)
337 {
338 double p;
339 p = esl_rnd_UniformPositive(r);
340 return esl_gev_invcdf(p, mu, lambda, alpha);
341 }
342 /*--------------------------- end sampling ---------------------------------*/
343
344
345
346
347 /****************************************************************************
348 * 5. ML fitting to complete or censored data
349 ****************************************************************************/
350
351 /* Easel's conjugate gradient descent code allows a single void ptr to
352 * point to any necessary fixed data, so we put everything into one
353 * structure:
354 */
355 struct gev_data {
356 double *x; /* data: n observed samples */
357 int n; /* number of observed samples */
358
359 int is_censored; /* TRUE if a censored, not complete dataset */
360 double phi; /* censoring/truncation threshold: obs x_i > phi */
361 int z; /* # of censored samples */
362 };
363
364 /* gev_func():
365 * Returns the neg log likelihood of a complete or censored GEV data sample;
366 * in the API of the conjugate gradient descent optimizer in esl_minimizer.
367 */
368 static double
369 gev_func(double *p, int nparam, void *dptr)
370 {
371 double mu, w, lambda, alpha;
372 struct gev_data *data;
373 double logL;
374 int i;
375
376 /* Unpack what the optimizer gave us.
377 */
378 mu = p[0];
379 w = p[1]; /* w is a c.o.v. to allow unconstrained opt of lambda>0 */
380 lambda = exp(w);
381 alpha = p[2];
382 data = (struct gev_data *) dptr;
383
384 logL = 0.;
385 for (i = 0; i < data->n; i++)
386 logL += esl_gev_logpdf(data->x[i], mu, lambda, alpha);
387
388 if (data->is_censored)
389 logL += data->z * esl_gev_logcdf(data->phi, mu, lambda, alpha);
390
391 return -logL; /* goal: minimize NLL */
392 }
393
394 /* gev_gradient()
395 * Computes the gradient of the negative log likelihood of a complete
396 * or censored GEV sample; in the API of the CG optimizer.
397 */
398 static void
399 gev_gradient(double *p, int nparam, void *dptr, double *dp)
400 {
401 double mu, w, lambda, alpha;
402 struct gev_data *data;
403 double *x;
404 int i;
405 double dmu, dw, dalpha;
406 double y, ay, ay1, lay1;
407
408 /* Unpack what the optimizer gave us */
409 mu = p[0];
410 w = p[1]; /* w is a c.o.v. to allow unconstrained opt of lambda>0 */
411 lambda = exp(w);
412 alpha = p[2];
413 data = (struct gev_data *) dptr;
414 x = data->x;
415
416 dmu = 0.;
417 dw = data->n; /* d/dw, term1 */
418 dalpha = 0.;
419
420 for (i = 0; i < data->n; i++)
421 {
422 y = lambda * (x[i]-mu);
423 ay = alpha*y;
424 ay1 = 1+ay; /* 1+ay=1, for ay < DBL_EPSILON */
425 lay1 = log(ay1);
426
427 /* d/dmu, term1. (will become 1, for small alpha.) */
428 dmu += (alpha+1) / ay1;
429
430 /* d/dmu, term2. For tiny ay, use log(1+x) ~ x to simplify. */
431 if (fabs(ay) < 1e-12) dmu -= exp(-y);
432 else dmu -= exp(-(1+1/alpha) * lay1);
433
434 /* d/dw, term2. converges to -y, for small alpha. */
435 dw -= y*(1+alpha) / ay1;
436
437 /* d/dw, term2. For tiny ay, use log(1+x) ~ x to simplify. */
438 if (fabs(ay) < 1e-12) dw += y*exp(-y);
439 else dw += y*exp(-(1+1/alpha) * lay1);
440
441 /* d/dalpha, term1
442 */
443 dalpha -= (1 + 1/alpha) * y/ay1;
444
445 /* d/dalpha, terms 2,3,4: for tiny ay, simplify.
446 * d/dalpha will go to +/-inf for alpha ~ 0, so watch out.
447 */
448 if (fabs(ay) < 1e-12) {
449 dalpha += y/alpha;
450 dalpha += y*exp(-y) / (alpha*ay1);
451 dalpha -= y*exp(-y) / alpha;
452 } else {
453 dalpha += lay1 / (alpha*alpha);
454 dalpha += y * exp(-lay1/alpha) / (alpha*ay1);
455 dalpha -= lay1 * exp(-lay1/alpha) / (alpha*alpha);
456 }
457 }
458 dmu *= lambda;
459
460 /* Add the terms that come from the censored data gradient,
461 * if it's a censored dataset.
462 */
463 if (data->is_censored)
464 {
465 y = lambda * (data->phi - mu);
466 ay = alpha * y;
467 ay1 = 1 + ay;
468 lay1 = log(ay1);
469
470 if (fabs(ay) < 1e-12)
471 { /* special case of small alpha, converging towards Gumbel */
472 dmu -= data->z * lambda * exp(-y) / ay1;
473 dw += data->z * y * exp(-y) / ay1;
474 dalpha -= data->z * exp(-y) * y/alpha * ay/ay1;
475 }
476 else
477 { /* normal case */
478 dmu -= data->z * lambda * exp(-lay1/alpha) / ay1;
479 dw += data->z * y * exp(-lay1/alpha) / ay1;
480 dalpha -= data->z * exp(-lay1/alpha) *
481 (lay1/(alpha*alpha) - y/(alpha*ay1));
482 }
483 }
484
485 /* Return the negative gradient, because we're minimizing NLL,
486 * not maximizing LL.
487 */
488 dp[0] = -dmu;
489 dp[1] = -dw;
490 dp[2] = -dalpha;
491 return;
492 }
493
494 /* fitting_engine()
495 * Fitting code shared by the FitComplete() and FitCensored() API.
496 *
497 * The fitting_engine(), in turn, is just an adaptor wrapped around
498 * the conjugate gradient descent minimizer.
499 */
500 static int
501 fitting_engine(struct gev_data *data,
502 double *ret_mu, double *ret_lambda, double *ret_alpha)
503 {
504 ESL_MIN_CFG *cfg = NULL; /* customization of the optimizer */
505 double p[3]; /* parameter vector */
506 double mean, variance;
507 double mu, lambda, alpha; /* initial param guesses */
508 double fx; /* f(x) at minimum; currently unused */
509 int status;
510
511 /* Make an initial guess.
512 * (very good guess for complete data; merely sufficient for censored)
513 */
514 esl_stats_DMean(data->x, data->n, &mean, &variance);
515 lambda = eslCONST_PI / sqrt(6.*variance);
516 mu = mean - 0.57722/lambda;
517 alpha = 0.0001;
518
519 p[0] = mu;
520 p[1] = log(lambda); /* c.o.v. from lambda to w */
521 p[2] = alpha;
522
523 /* customize the CG optimizer */
524 cfg = esl_min_cfg_Create(3);
525 cfg->cg_rtol = 1e-6;
526 /* max initial step sizes: keeps bracketing from exploding */
527 cfg->u[0] = 1.0;
528 cfg->u[1] = fabs(log(0.02));
529 cfg->u[2] = 0.02;
530
531 /* pass problem to the optimizer
532 */
533 status = esl_min_ConjugateGradientDescent(cfg, p, 3,
534 &gev_func, &gev_gradient, (void *)data,
535 &fx, NULL);
536
537 esl_min_cfg_Destroy(cfg);
538 *ret_mu = p[0];
539 *ret_lambda = exp(p[1]);
540 *ret_alpha = p[2];
541 return status;
542 }
543
544
545 /* Function: esl_gev_FitComplete()
546 *
547 * Purpose: Given an array of <n> GEV-distributed samples <x[0]..x[n-1>,
548 * return maximum likelihood parameters <ret_mu>,
549 * <ret_lambda>, and <ret_alpha>.
550 *
551 * Uses a conjugate gradient descent algorithm that
552 * can be computationally intensive. A typical problem
553 * involving 10,000-100,000 points may take a second
554 * to solve.
555 *
556 * Note: Just a wrapper: sets up the problem for fitting_engine().
557 *
558 * Args: x - complete GEV-distributed data [0..n-1]
559 * n - number of samples in <x>
560 * ret_mu - RETURN: maximum likelihood estimate of mu
561 * ret_lambda - RETURN: maximum likelihood estimate of lambda
562 * ret_alpha - RETURN: maximum likelihood estimate of alpha
563 *
564 * Returns: <eslOK> on success.
565 *
566 * Throws: <eslENOHALT> if the fit doesn't converge.
567 *
568 * Xref: STL9/118-120.
569 */
570 int
571 esl_gev_FitComplete(double *x, int n,
572 double *ret_mu, double *ret_lambda, double *ret_alpha)
573 {
574 struct gev_data data;
575
576 data.x = x;
577 data.n = n;
578 data.is_censored = FALSE;
579 data.phi = -DBL_MAX;
580 data.z = 0;
581
582 return (fitting_engine(&data, ret_mu, ret_lambda, ret_alpha));
583 }
584
585 /* Function: esl_gev_FitCensored()
586 *
587 * Purpose: Given a left-censored array of <n> GEV-distributed samples
588 * <x[0]..x[n-1>, the number of censored samples <z>, and
589 * the censoring value <phi> (where all $x_i > \phi$ and
590 * all $z$ censored samples are $\leq \phi$);
591 * return maximum likelihood parameters <ret_mu>,
592 * <ret_lambda>, and <ret_alpha>.
593 *
594 * Args: x - censored GEV-distributed data [0..n-1], all > phi
595 * n - number of samples in <x>
596 * z - number of censored samples, all <= phi
597 * phi - censoring threshold
598 * ret_mu - RETURN: maximum likelihood estimate of mu
599 * ret_lambda - RETURN: maximum likelihood estimate of lambda
600 * ret_alpha - RETURN: maximum likelihood estimate of alpha
601 *
602 * Note: Just a wrapper: sets up the problem for fitting_engine().
603 *
604 * Returns: <eslOK> on success.
605 *
606 * Throws: <eslENOHALT> if the fit doesn't converge.
607 *
608 * Xref: STL9/133
609 */
610 int
611 esl_gev_FitCensored(double *x, int n, int z, double phi,
612 double *ret_mu, double *ret_lambda, double *ret_alpha)
613 {
614 struct gev_data data;
615
616 data.x = x;
617 data.n = n;
618 data.is_censored = TRUE;
619 data.phi = phi;
620 data.z = z;
621
622 return (fitting_engine(&data, ret_mu, ret_lambda, ret_alpha));
623 }
624 /*--------------------------- end fitting ----------------------------------*/
625
626
627
628
629
630 /****************************************************************************
631 * 6. Stats driver
632 ****************************************************************************/
633 #ifdef eslGEV_STATS
634 #include <stdio.h>
635 #include <math.h>
636 #include "easel.h"
637 #include "esl_random.h"
638 #include "esl_minimizer.h"
639 #include "esl_gev.h"
640
641 #define MAX_STATS_TESTS 10
642 static void stats_sample(FILE *fp);
643 static int stats_fittest(FILE *fp, int ntrials, int n, double mu,
644 double lambda, double alpha);
645 int
646 main(int argc, char **argv)
647 {
648 FILE *fp;
649 double mu = 0.0;
650 double lambda = 1.0;
651 double xmin = -20.;
652 double xmax = 60.;
653 double xstep = 0.1;
654 double x,z;
655 int do_test[MAX_STATS_TESTS+1];
656 int i;
657
658 for (i = 0; i <= MAX_STATS_TESTS; i++) do_test[i] = 0;
659 for (i = 1; i < argc; i++)
660 do_test[atoi(argv[i])] = 1;
661
662 /* stats.1: xmgrace xy file w/ densities for Gumbel, Frechet, Weibull */
663 if (do_test[1]) {
664 if ((fp = fopen("stats.1", "w")) == NULL) abort();
665 for (x = xmin; x <= xmax; x+= xstep)
666 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_pdf(x, mu, lambda, 0.0));
667 fprintf(fp, "&\n");
668 for (x = xmin; x <= xmax; x+= xstep)
669 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_pdf(x, mu, lambda, 0.1));
670 fprintf(fp, "&\n");
671 for (x = xmin; x <= xmax; x+= xstep)
672 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_pdf(x, mu, lambda, -0.1));
673 fprintf(fp, "&\n");
674 fclose(fp);
675 }
676
677 /* stats.2: xmgrace xy file w/ log densities for Gumbel, Frechet, Weibull */
678 if (do_test[2]) {
679 if ((fp = fopen("stats.2", "w")) == NULL) abort();
680 for (x = xmin; x <= xmax; x+= xstep) {
681 z = esl_gev_logpdf(x, mu, lambda, 0.0);
682 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
683 }
684 fprintf(fp, "&\n");
685 for (x = xmin; x <= xmax; x+= xstep) {
686 z = esl_gev_logpdf(x, mu, lambda, 0.1);
687 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
688 }
689 fprintf(fp, "&\n");
690 for (x = xmin; x <= xmax; x+= xstep) {
691 z = esl_gev_logpdf(x, mu, lambda, -0.1);
692 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
693 }
694 fprintf(fp, "&\n");
695 fclose(fp);
696 }
697
698 /* stats.3: xmgrace xy file w/ CDF for Gumbel, Frechet, Weibull */
699 if (do_test[3]) {
700 if ((fp = fopen("stats.3", "w")) == NULL) abort();
701 for (x = xmin; x <= xmax; x+= xstep)
702 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_cdf(x, mu, lambda, 0.0));
703 fprintf(fp, "&\n");
704 for (x = xmin; x <= xmax; x+= xstep)
705 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_cdf(x, mu, lambda, 0.6));
706 fprintf(fp, "&\n");
707 for (x = xmin; x <= xmax; x+= xstep)
708 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_cdf(x, mu, lambda, -0.6));
709 fprintf(fp, "&\n");
710 fclose(fp);
711 }
712
713 /* stats.4: xmgrace xy file w/ logCDF for Gumbel, Frechet, Weibull */
714 if (do_test[4]) {
715 if ((fp = fopen("stats.4", "w")) == NULL) abort();
716 for (x = xmin; x <= xmax; x+= xstep) {
717 z = esl_gev_logcdf(x, mu, lambda, 0.0);
718 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
719 }
720 fprintf(fp, "&\n");
721 for (x = xmin; x <= xmax; x+= xstep) {
722 z = esl_gev_logcdf(x, mu, lambda, 0.2);
723 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
724 }
725 fprintf(fp, "&\n");
726 for (x = xmin; x <= xmax; x+= xstep) {
727 z = esl_gev_logcdf(x, mu, lambda, -0.2);
728 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
729 }
730 fprintf(fp, "&\n");
731 fclose(fp);
732 }
733
734 /* stats.5: xmgrace xy file w/ surv for Gumbel, Frechet, Weibull */
735 if (do_test[5]) {
736 if ((fp = fopen("stats.5", "w")) == NULL) abort();
737 for (x = xmin; x <= xmax; x+= xstep)
738 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_surv(x, mu, lambda, 0.0));
739 fprintf(fp, "&\n");
740 for (x = xmin; x <= xmax; x+= xstep)
741 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_surv(x, mu, lambda, 0.6));
742 fprintf(fp, "&\n");
743 for (x = xmin; x <= xmax; x+= xstep)
744 fprintf(fp, "%.1f %9.7f\n", x, esl_gev_surv(x, mu, lambda, -0.6));
745 fprintf(fp, "&\n");
746 fclose(fp);
747 }
748
749 /* stats.6: xmgrace xy file w/ logsurv for Gumbel, Frechet, Weibull */
750 if (do_test[6]) {
751 if ((fp = fopen("stats.6", "w")) == NULL) abort();
752 for (x = xmin; x <= xmax; x+= xstep) {
753 z = esl_gev_logsurv(x, mu, lambda, 0.0);
754 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
755 }
756 fprintf(fp, "&\n");
757 for (x = xmin; x <= xmax; x+= xstep) {
758 z = esl_gev_logsurv(x, mu, lambda, 0.2);
759 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
760 }
761 fprintf(fp, "&\n");
762 for (x = xmin; x <= xmax; x+= xstep) {
763 z = esl_gev_logsurv(x, mu, lambda, -0.2);
764 if (finite(z)) fprintf(fp, "%.1f %9.7f\n", x, z);
765 }
766 fprintf(fp, "&\n");
767 fclose(fp);
768 }
769
770 /* stats.7. R input file of 10,000 random GEV samples.
771 */
772 if (do_test[7]) {
773 if ((fp = fopen("stats.7", "w")) == NULL) abort();
774 stats_sample(fp);
775 fclose(fp);
776 }
777
778 /* stats.8. Test 500 fits of the Frechet.
779 */
780 if (do_test[8]) {
781 if ((fp = fopen("stats.8", "w")) == NULL) abort();
782 stats_fittest(fp, 500, 10000, mu, lambda, 0.2);
783 fclose(fp);
784 }
785
786 /* stats.9. Test 500 fits of the near-Gumbel
787 */
788 if (do_test[9]) {
789 if ((fp = fopen("stats.9", "w")) == NULL) abort();
790 stats_fittest(fp, 500, 10000, mu, lambda, 0.00001);
791 fclose(fp);
792 }
793
794 /* stats.10. Test 500 fits of the Weibull
795 */
796 if (do_test[10]) {
797 if ((fp = fopen("stats.10", "w")) == NULL) abort();
798 stats_fittest(fp, 500, 10000, mu, lambda, -0.2);
799 fclose(fp);
800 }
801 return 0;
802 }
803
804 /* stats_sample()
805 * Creates an R input table containing 10,000 random samples
806 * each in columns labeled "gumbel", "frechet", "weibull".
807 * To process in R (remember that R uses 1/lambda for scale):
808 library(ismev)
809 library(evd)
810 z=read.table("stats.7")
811 x1 <- sort(z$gumbel, decreasing=T)
812 x2 <- sort(z$frechet, decreasing=T)
813 x3 <- sort(z$weibull, decreasing=T)
814 q1 <- qgumbel(ppoints(10000), -20., 1./0.4)
815 q2 <- qgev(ppoints(10000), -20., 1./0.4, 0.2)
816 q3 <- qgev(ppoints(10000), -20., 1./0.4, -0.2)
817 xax<- seq(-40,40,by=0.1)
818 a1 <- dgumbel(xax, -20, 1/0.4)
819 a2 <- dgev(xax, -20, 1/0.4, 0.2)
820 a3 <- dgev(xax, -20, 1/0.4, -0.2)
821 qqplot(x1,q1); abline(0,1)
822 qqplot(x2,q2); abline(0,1)
823 qqplot(x3,q3); abline(0,1)
824 plot(density(x1,bw=0.2)); lines(xax,a1)
825 plot(density(x2,bw=0.2)); lines(xax,a2)
826 plot(density(x3,bw=0.2)); lines(xax,a3)
827 */
828 static void
829 stats_sample(FILE *fp)
830 {
831 ESL_RANDOMNESS *r;
832 double mu = -20.;
833 double lambda = 0.4;
834 int n = 10000;
835 double a,b,c;
836 int i;
837
838 r = esl_randomness_Create(42);
839 fprintf(fp, " gumbel \t frechet\t weibull\n");
840 for (i = 1; i <= n; i++)
841 {
842 a = esl_gev_Sample(r, mu, lambda, 0.0);
843 b = esl_gev_Sample(r, mu, lambda, 0.2);
844 c = esl_gev_Sample(r, mu, lambda, -0.2);
845 fprintf(fp, "%d\t%8.4f\t%8.4f\t%8.4f\n", i, a,b,c);
846 }
847 esl_randomness_Destroy(r);
848 }
849
850 /* stats_fittest()
851 * Samples <n> numbers from a GEV w/ parameters <mu>, <lambda>, <alpha>;
852 * then fits to a GEV and print info about how good the fit is.
853 *
854 * Repeat this <ntrials> times.
855 *
856 * For each trial, outputs a line to <fp>:
857 * <trial> <nll> <est_nll> <est_mu> <mu %error> <est_lambda> <%err>\
858 * <est_alpha> <%err> <est E-val at parametric E=1>
859 *
860 * Each sampled set is done with the random number generator seeded to
861 * the trial number. This should make each set reproducible and
862 * identical to the sets used to test R's fitting.
863 *
864 * xref STL9/191; xref 2005/0718-weibull-debugging
865 */
866 static int
867 stats_fittest(FILE *fp, int ntrials, int n, double mu, double lambda, double alpha)
868 {
869 ESL_RANDOMNESS *r = NULL;
870 double *x = NULL;
871 int i;
872 int trial;
873 double est_mu, est_lambda, est_alpha;
874 double z;
875 double nll, est_nll;
876 int status;
877
878 ESL_ALLOC(x, sizeof(double) * n);
879 for (trial = 1; trial <= ntrials; trial++)
880 {
881 r = esl_randomness_Create(trial);
882 nll = 0.;
883 for (i = 0; i < n; i++)
884 {
885 x[i] = esl_gev_Sample(r, mu, lambda, alpha);
886 nll -= esl_gev_logpdf(x[i], mu, lambda, alpha);
887 }
888 esl_randomness_Destroy(r);
889
890 esl_gev_FitComplete(x, n, &est_mu, &est_lambda, &est_alpha);
891
892 est_nll = 0.;
893 for (i = 0; i < n; i++)
894 est_nll -= esl_gev_logpdf(x[i], est_mu, est_lambda, est_alpha);
895
896 z = mu + (exp(-alpha*log(1/(double)n)) - 1 ) / (alpha*lambda);/* x at E=1*/
897 z = (double) n * esl_gev_surv(z, est_mu, est_lambda, est_alpha); /* E at x */
898
899 printf("%4d %10.2f %10.2f %8.3f %8.3f %8.5f %8.3f %8.5f %8.3f %6.4f\n",
900 trial, nll, est_nll,
901 est_mu, 100* fabs((est_mu-mu)/mu),
902 est_lambda, 100* fabs((est_lambda-lambda)/lambda),
903 est_alpha, 100* fabs((est_alpha-alpha)/alpha),
904 z);
905 }
906 free(x);
907 return eslOK;
908
909 ERROR:
910 return status;
911 }
912 #endif /*eslGEV_STATS*/
913
914
915 /*****************************************************************
916 * 7. Example
917 *****************************************************************/
918 #ifdef eslGEV_EXAMPLE
919 /*::cexcerpt::gev_example::begin::*/
920 #include <stdio.h>
921 #include "easel.h"
922 #include "esl_random.h"
923 #include "esl_minimizer.h"
924 #include "esl_gev.h"
925
926 int
927 main(int argc, char **argv)
928 {
929 double est_mu, est_lambda, est_alpha;
930 double z;
931 int i;
932 int n = 10000; /* simulate 10,000 samples */
933 double mu = -20.0; /* with mu = -20 */
934 double lambda = 0.4; /* and lambda = 0.4 */
935 double alpha = 0.1; /* and alpha = 0.1 */
936 double min = 9999.;
937 double max = -9999.;
938 double *x = malloc(sizeof(double) * n);
939 ESL_RANDOMNESS *r = esl_randomness_Create(0);;
940
941 for (i = 0; i < n; i++) /* generate the 10,000 samples */
942 {
943 x[i] = esl_gev_Sample(r, mu, lambda, alpha);
944 if (x[i] < min) min = x[i];
945 if (x[i] > max) max = x[i];
946 }
947
948 z = esl_gev_surv(max, mu, lambda, alpha); /* right tail p~1e-4 >= max */
949 printf("max = %6.1f P(>max) = %g E=%6.3f\n", max, z, z*(double)n);
950 z = esl_gev_cdf(min, mu, lambda, alpha); /* left tail p~1e-4 < min */
951 printf("min = %6.1f P(<=min) = %g E=%6.3f\n", min, z, z*(double)n);
952
953 esl_gev_FitComplete(x, n, &est_mu, &est_lambda, &est_alpha);
954
955 printf("Parametric mu = %6.1f. Estimated mu = %6.2f. Difference = %.1f%%.\n",
956 mu, est_mu, 100. * fabs((est_mu - mu) / mu));
957 printf("Parametric lambda = %6.2f. Estimated lambda = %6.2f. Difference = %.1f%%.\n",
958 lambda, est_lambda, 100. * fabs((est_lambda - lambda) /lambda));
959 printf("Parametric alpha = %6.4f. Estimated alpha = %6.4f. Difference = %.1f%%.\n",
960 alpha, est_alpha, 100. * fabs((est_alpha - alpha) /alpha));
961
962 free(x);
963 esl_randomness_Destroy(r);
964 return 0;
965 }
966 /*::cexcerpt::gev_example::end::*/
967 #endif /*eslGEV_EXAMPLE*/
968