Debian Codegraph @

easel/esl_stats.c

raw symbols SCIP
1 /* Foundation and miscellenea for the statistics modules.
2 *
3 * Contents:
4 * 1. Summary statistics (means, variances)
5 * 2. Special functions
6 * 3. Standard statistical tests
7 * 4. Data fitting.
8 * 5. Unit tests.
9 * 6. Test driver.
10 * 7. Examples.
11 * - driver for linear regression
12 * - driver for G-test
13 */
14 #include <esl_config.h>
15
16 #include <math.h>
17
18 #include "easel.h"
19 #include "esl_stats.h"
20
21
22 /*****************************************************************
23 * 1. Summary statistics calculations (means, variances)
24 *****************************************************************/
25
26 /* Function: esl_stats_DMean()
27 * Synopsis: Calculates mean and $\sigma^2$ for samples $x_i$.
28 *
29 * Purpose: Calculates the sample mean and $s^2$, the unbiased
30 * estimator of the population variance, for a
31 * sample of <n> numbers <x[0]..x[n-1]>, and optionally
32 * returns either or both through <ret_mean> and
33 * <ret_var>.
34 *
35 * <esl_stats_FMean()> and <esl_stats_IMean()> do the same,
36 * for float and integer vectors.
37 *
38 * Args: x - samples x[0]..x[n-1]
39 * n - number of samples
40 * opt_mean - optRETURN: sample mean
41 * opt_var - optRETURN: sample variance
42 *
43 * Returns: <eslOK> on success.
44 */
45 int
46 esl_stats_DMean(const double *x, int n, double *opt_mean, double *opt_var)
47 {
48 double sum = 0.;
49 double sqsum = 0.;
50 int i;
51
52 for (i = 0; i < n; i++)
53 {
54 sum += x[i];
55 sqsum += x[i]*x[i];
56 }
57 if (opt_mean != NULL) *opt_mean = sum / (double) n;
58 if (opt_var != NULL) *opt_var = (n > 1 ? fabs((sqsum - sum*sum/(double)n) / ((double)n-1)) : 0.); // fabs() avoids -epsilon result for zero variance.
59 return eslOK;
60 }
61 int
62 esl_stats_FMean(const float *x, int n, double *opt_mean, double *opt_var)
63 {
64 double sum = 0.;
65 double sqsum = 0.;
66 int i;
67
68 for (i = 0; i < n; i++)
69 {
70 sum += x[i];
71 sqsum += x[i]*x[i];
72 }
73 if (opt_mean != NULL) *opt_mean = sum / (double) n;
74 if (opt_var != NULL) *opt_var = (n > 1 ? fabs((sqsum - sum*sum/(double)n) / ((double)n-1)) : 0.); // fabs() avoids -epsilon result for zero variance.
75 return eslOK;
76 }
77 int
78 esl_stats_IMean(const int *x, int n, double *opt_mean, double *opt_var)
79 {
80 double sum = 0.;
81 double sqsum = 0.;
82 int i;
83
84 for (i = 0; i < n; i++)
85 {
86 sum += x[i];
87 sqsum += x[i]*x[i];
88 }
89 if (opt_mean != NULL) *opt_mean = sum / (double) n;
90 if (opt_var != NULL) *opt_var = (n > 1 ? fabs((sqsum - sum*sum/(double)n) / ((double)n-1)) : 0.); // fabs() avoids -epsilon result for zero variance.
91 return eslOK;
92 }
93 /*--------------- end, summary statistics -----------------------*/
94
95
96
97 /*****************************************************************
98 * 2. Special functions.
99 *****************************************************************/
100
101 /* Function: esl_stats_LogGamma()
102 * Synopsis: Calculates $\log \Gamma(x)$.
103 *
104 * Purpose: Returns natural log of $\Gamma(x)$, for $x > 0$.
105 *
106 * Credit: Adapted from a public domain implementation in the
107 * NCBI core math library. Thanks to John Spouge and
108 * the NCBI. (According to NCBI, that's Dr. John
109 * "Gammas Galore" Spouge to you, pal.)
110 *
111 * Args: x : argument, x > 0.0
112 * ret_answer : RETURN: the answer
113 *
114 * Returns: Put the answer in <ret_answer>; returns <eslOK>.
115 *
116 * Throws: <eslERANGE> if $x <= 0$.
117 */
118 int
119 esl_stats_LogGamma(double x, double *ret_answer)
120 {
121 int i;
122 double xx, tx;
123 double tmp, value;
124 static double cof[11] = {
125 4.694580336184385e+04,
126 -1.560605207784446e+05,
127 2.065049568014106e+05,
128 -1.388934775095388e+05,
129 5.031796415085709e+04,
130 -9.601592329182778e+03,
131 8.785855930895250e+02,
132 -3.155153906098611e+01,
133 2.908143421162229e-01,
134 -2.319827630494973e-04,
135 1.251639670050933e-10
136 };
137
138 /* Protect against invalid x<=0 */
139 if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_LogGamma()");
140
141 xx = x - 1.0;
142 tx = tmp = xx + 11.0;
143 value = 1.0;
144 for (i = 10; i >= 0; i--) /* sum least significant terms first */
145 {
146 value += cof[i] / tmp;
147 tmp -= 1.0;
148 }
149 value = log(value);
150 tx += 0.5;
151 value += 0.918938533 + (xx+0.5)*log(tx) - tx;
152 *ret_answer = value;
153 return eslOK;
154 }
155
156
157 /* Function: esl_stats_Psi()
158 * Synopsis: Calculates $\Psi(x)$ (the digamma function).
159 *
160 * Purpose: Computes $\Psi(x)$ (the "digamma" function), the
161 * derivative of $\log \Gamma(x)$ for $x > 0$:
162 * $d/dx \log \Gamma(x) = \frac{\Gamma'(x)}{\Gamma(x)} = \Psi(x)$.
163 *
164 * Implements J.M. Bernardo's "Algorithm AS 103", J Royal
165 * Stat. Soc. C (Appl. Stat.) 25:315-317 (1976).
166 *
167 * Throws: <eslERANGE> if x <= 0
168 */
169 int
170 esl_stats_Psi(double x, double *ret_answer)
171 {
172 double psi = 0.;
173 double x2;
174
175 if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_Psi()");
176 else if (x <= 1e-5) { *ret_answer = -eslCONST_EULER - 1./x; return eslOK; } // For small x < S, Psi(x) ~= -0.5772 - 1/x + O(x), we're done.
177
178 /* For medium x, use Psi(1+x) = \Psi(x) + 1/x to c.o.v. x,
179 * big enough for Stirling approximation to work...
180 */
181 while (x < 8.5) // This is bound C, which Bernardo sets to 8.5.
182 {
183 psi -= 1./x;
184 x += 1.;
185 }
186
187 /* For large X, use Stirling approximation */
188 x2 = 1./x; psi += log(x) - 0.5 * x2;
189 x2 = x2*x2; psi += (-1./12.)*x2 + (1./120.)*x2*x2 - (1./252.)*x2*x2*x2;
190
191 *ret_answer = psi; // Bernardo chose S,C bounds so rel error < 1e-10.
192 return eslOK;
193 }
194
195
196 /* Function: esl_stats_Trigamma()
197 * Synopsis: Compute $Psi'(x)$ (the trigamma function)
198 * Incept: SRE, Wed 18 May 2022
199 *
200 * Purpose: Computes $\Psi'(x)$, the "trigamma" function, the second
201 * derivative of $\log \Gamma(x)$, for $x > 0$. Needed in
202 * maximum likelihood fitting of Gamma distributions.
203 *
204 * Implements "Algorithm AS 121": B.E. Schneider, J. Royal
205 * Stat. Soc. C (Appl. Stat.), 27:97-99 (1978).
206 *
207 * Throws: <eslERANGE> if x <= 0.
208 */
209 int
210 esl_stats_Trigamma(double x, double *ret_answer)
211 {
212 double trigam = 0.;
213 double y;
214
215 if (x <= 0.) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_Trigamma()");
216 else if (x <= 1.0e-4) { *ret_answer = 1.0 / (x*x); return eslOK; } // approximation for small value case x <= A; Schneider (1978) justifies the A=1e-4 choice
217
218 while (x < 5.0) // B=5.0 is also a choice justified by Schneider (1978).
219 { // For x >= B, we go straight on to a series approximation for large x
220 trigam += 1. / (x*x); // For A < x < B, here we use the relation Psi'(x+1) = \Psi(x) - 1/x^2 to get Psi'(x) as a constant + Psi'(z) with z=x+i >= B
221 x += 1.;
222 }
223
224 y = 1.0 / (x*x);
225 trigam += 0.5 * y + (1. + y*((1./6.) + y*((1./30.)+ y*((1./42.)+ y*(1./30.))))) / x; // This is the series approximation, for large x >= B.
226 // Schneider chose A,B so rel error of approximations is < 1e-8.
227 *ret_answer = trigam;
228 return eslOK;
229 }
230
231 /* Function: esl_stats_IncompleteGamma()
232 * Synopsis: Calculates the incomplete Gamma function.
233 *
234 * Purpose: Returns $P(a,x)$ and $Q(a,x)$ where:
235 *
236 * \begin{eqnarray*}
237 * P(a,x) & = & \frac{1}{\Gamma(a)} \int_{0}^{x} t^{a-1} e^{-t} dt \\
238 * & = & \frac{\gamma(a,x)}{\Gamma(a)} \\
239 * Q(a,x) & = & \frac{1}{\Gamma(a)} \int_{x}^{\infty} t^{a-1} e^{-t} dt\\
240 * & = & 1 - P(a,x) \\
241 * \end{eqnarray*}
242 *
243 * $P(a,x)$ is the CDF of a gamma density with $\lambda = 1$,
244 * and $Q(a,x)$ is the survival function.
245 *
246 * For $x \simeq 0$, $P(a,x) \simeq 0$ and $Q(a,x) \simeq 1$; and
247 * $P(a,x)$ is less prone to roundoff error.
248 *
249 * The opposite is the case for large $x >> a$, where
250 * $P(a,x) \simeq 1$ and $Q(a,x) \simeq 0$; there, $Q(a,x)$ is
251 * less prone to roundoff error.
252 *
253 * Method: Based on ideas from Numerical Recipes in C, Press et al.,
254 * Cambridge University Press, 1988.
255 *
256 * Args: a - for instance, degrees of freedom / 2 [a > 0]
257 * x - for instance, chi-squared statistic / 2 [x >= 0]
258 * ret_pax - RETURN: P(a,x)
259 * ret_qax - RETURN: Q(a,x)
260 *
261 * Return: <eslOK> on success.
262 *
263 * Throws: <eslERANGE> if <a> or <x> is out of accepted range.
264 * <eslENOHALT> if approximation fails to converge.
265 */
266 int
267 esl_stats_IncompleteGamma(double a, double x, double *ret_pax, double *ret_qax)
268 {
269 int iter; /* iteration counter */
270 double pax; /* P(a,x) */
271 double qax; /* Q(a,x) */
272 int status;
273
274 if (a <= 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): a must be > 0");
275 if (x < 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): x must be >= 0");
276
277 /* For x > a + 1 the following gives rapid convergence;
278 * calculate Q(a,x) = \frac{\Gamma(a,x)}{\Gamma(a)},
279 * using a continued fraction development for \Gamma(a,x).
280 */
281 if (x > a+1)
282 {
283 double oldp; /* previous value of p */
284 double nu0, nu1; /* numerators for continued fraction calc */
285 double de0, de1; /* denominators for continued fraction calc */
286
287 nu0 = 0.; /* A_0 = 0 */
288 de0 = 1.; /* B_0 = 1 */
289 nu1 = 1.; /* A_1 = 1 */
290 de1 = x; /* B_1 = x */
291
292 oldp = nu1;
293 for (iter = 1; iter < 100; iter++)
294 {
295 /* Continued fraction development:
296 * set A_j = b_j A_j-1 + a_j A_j-2
297 * B_j = b_j B_j-1 + a_j B_j-2
298 * We start with A_2, B_2.
299 */
300 /* j = even: a_j = iter-a, b_j = 1 */
301 /* A,B_j-2 are in nu0, de0; A,B_j-1 are in nu1,de1 */
302 nu0 = nu1 + ((double)iter - a) * nu0;
303 de0 = de1 + ((double)iter - a) * de0;
304 /* j = odd: a_j = iter, b_j = x */
305 /* A,B_j-2 are in nu1, de1; A,B_j-1 in nu0,de0 */
306 nu1 = x * nu0 + (double) iter * nu1;
307 de1 = x * de0 + (double) iter * de1;
308 /* rescale */
309 if (de1 != 0.)
310 {
311 nu0 /= de1;
312 de0 /= de1;
313 nu1 /= de1;
314 de1 = 1.;
315 }
316 /* check for convergence */
317 if (fabs((nu1-oldp)/nu1) < 1.e-7)
318 {
319 if ((status = esl_stats_LogGamma(a, &qax)) != eslOK) return status;
320 qax = nu1 * exp(a * log(x) - x - qax);
321
322 if (ret_pax != NULL) *ret_pax = 1 - qax;
323 if (ret_qax != NULL) *ret_qax = qax;
324 return eslOK;
325 }
326
327 oldp = nu1;
328 }
329 ESL_EXCEPTION(eslENOHALT,
330 "esl_stats_IncompleteGamma(): fraction failed to converge");
331 }
332 else /* x <= a+1 */
333 {
334 double p; /* current sum */
335 double val; /* current value used in sum */
336
337 /* For x <= a+1 we use a convergent series instead:
338 * P(a,x) = \frac{\gamma(a,x)}{\Gamma(a)},
339 * where
340 * \gamma(a,x) = e^{-x}x^a \sum_{n=0}{\infty} \frac{\Gamma{a}}{\Gamma{a+1+n}} x^n
341 * which looks appalling but the sum is in fact rearrangeable to
342 * a simple series without the \Gamma functions:
343 * = \frac{1}{a} + \frac{x}{a(a+1)} + \frac{x^2}{a(a+1)(a+2)} ...
344 * and it's obvious that this should converge nicely for x <= a+1.
345 */
346 p = val = 1. / a;
347 for (iter = 1; iter < 10000; iter++)
348 {
349 val *= x / (a+(double)iter);
350 p += val;
351
352 if (fabs(val/p) < 1.e-7)
353 {
354 if ((status = esl_stats_LogGamma(a, &pax)) != eslOK) return status;
355 pax = p * exp(a * log(x) - x - pax);
356
357 if (ret_pax != NULL) *ret_pax = pax;
358 if (ret_qax != NULL) *ret_qax = 1. - pax;
359 return eslOK;
360 }
361 }
362 ESL_EXCEPTION(eslENOHALT,
363 "esl_stats_IncompleteGamma(): series failed to converge");
364 }
365 /*NOTREACHED*/
366 return eslOK;
367 }
368
369
370 /* Function: esl_stats_erfc()
371 * Synopsis: Complementary error function.
372 *
373 * Purpose: Calculate and return the complementary error function,
374 * erfc(x).
375 *
376 * erfc(x) is mandated by the ANSI C99 standard but that
377 * doesn't mean it's available on supposedly modern systems
378 * (looking at you here, Microsoft).
379 *
380 * Used for cumulative distribution function calculations
381 * for the normal (Gaussian) distribution. See <esl_normal>
382 * module.
383 *
384 * erfc(-inf) = 2.0
385 * erfc(0) = 1.0
386 * erfc(inf) = 0.0
387 * erfc(NaN) = NaN
388 *
389 * Args: x : any real-numbered value -inf..inf
390 *
391 * Returns: erfc(x)
392 *
393 * Throws: (no abnormal error conditions)
394 *
395 * Source:
396 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
397 * Developed at SunPro, a Sun Microsystems, Inc. business.
398 * Permission to use, copy, modify, and distribute this software is
399 * freely granted, provided that this notice is preserved.
400 * [as posted by eggcrook at stackexchange.com, 21 Dec 2012]
401 *
402 * Removed arcane incantations for runtime detection of endianness,
403 * and for treating IEEE754 doubles as two adjacent uint32_t;
404 * replaced with ANSI-compliant macros and compile-time detection
405 * of endianness. [Apr 2015]
406 */
407 double
408 esl_stats_erfc(double x)
409 {
410 static const double erx = 8.45062911510467529297e-01; /* 0x3FEB0AC1, 0x60000000 */
411 /*
412 * Coefficients for approximation to erf on [0,0.84375]
413 */
414 static const double pp0 = 1.28379167095512558561e-01; /* 0x3FC06EBA, 0x8214DB68 */
415 static const double pp1 = -3.25042107247001499370e-01; /* 0xBFD4CD7D, 0x691CB913 */
416 static const double pp2 = -2.84817495755985104766e-02; /* 0xBF9D2A51, 0xDBD7194F */
417 static const double pp3 = -5.77027029648944159157e-03; /* 0xBF77A291, 0x236668E4 */
418 static const double pp4 = -2.37630166566501626084e-05; /* 0xBEF8EAD6, 0x120016AC */
419 static const double qq1 = 3.97917223959155352819e-01; /* 0x3FD97779, 0xCDDADC09 */
420 static const double qq2 = 6.50222499887672944485e-02; /* 0x3FB0A54C, 0x5536CEBA */
421 static const double qq3 = 5.08130628187576562776e-03; /* 0x3F74D022, 0xC4D36B0F */
422 static const double qq4 = 1.32494738004321644526e-04; /* 0x3F215DC9, 0x221C1A10 */
423 static const double qq5 = -3.96022827877536812320e-06; /* 0xBED09C43, 0x42A26120 */
424 /*
425 * Coefficients for approximation to erf in [0.84375,1.25]
426 */
427 static const double pa0 = -2.36211856075265944077e-03; /* 0xBF6359B8, 0xBEF77538 */
428 static const double pa1 = 4.14856118683748331666e-01; /* 0x3FDA8D00, 0xAD92B34D */
429 static const double pa2 = -3.72207876035701323847e-01; /* 0xBFD7D240, 0xFBB8C3F1 */
430 static const double pa3 = 3.18346619901161753674e-01; /* 0x3FD45FCA, 0x805120E4 */
431 static const double pa4 = -1.10894694282396677476e-01; /* 0xBFBC6398, 0x3D3E28EC */
432 static const double pa5 = 3.54783043256182359371e-02; /* 0x3FA22A36, 0x599795EB */
433 static const double pa6 = -2.16637559486879084300e-03; /* 0xBF61BF38, 0x0A96073F */
434 static const double qa1 = 1.06420880400844228286e-01; /* 0x3FBB3E66, 0x18EEE323 */
435 static const double qa2 = 5.40397917702171048937e-01; /* 0x3FE14AF0, 0x92EB6F33 */
436 static const double qa3 = 7.18286544141962662868e-02; /* 0x3FB2635C, 0xD99FE9A7 */
437 static const double qa4 = 1.26171219808761642112e-01; /* 0x3FC02660, 0xE763351F */
438 static const double qa5 = 1.36370839120290507362e-02; /* 0x3F8BEDC2, 0x6B51DD1C */
439 static const double qa6 = 1.19844998467991074170e-02; /* 0x3F888B54, 0x5735151D */
440 /*
441 * Coefficients for approximation to erfc in [1.25,1/0.35]
442 */
443 static const double ra0 = -9.86494403484714822705e-03; /* 0xBF843412, 0x600D6435 */
444 static const double ra1 = -6.93858572707181764372e-01; /* 0xBFE63416, 0xE4BA7360 */
445 static const double ra2 = -1.05586262253232909814e+01; /* 0xC0251E04, 0x41B0E726 */
446 static const double ra3 = -6.23753324503260060396e+01; /* 0xC04F300A, 0xE4CBA38D */
447 static const double ra4 = -1.62396669462573470355e+02; /* 0xC0644CB1, 0x84282266 */
448 static const double ra5 = -1.84605092906711035994e+02; /* 0xC067135C, 0xEBCCABB2 */
449 static const double ra6 = -8.12874355063065934246e+01; /* 0xC0545265, 0x57E4D2F2 */
450 static const double ra7 = -9.81432934416914548592e+00; /* 0xC023A0EF, 0xC69AC25C */
451 static const double sa1 = 1.96512716674392571292e+01; /* 0x4033A6B9, 0xBD707687 */
452 static const double sa2 = 1.37657754143519042600e+02; /* 0x4061350C, 0x526AE721 */
453 static const double sa3 = 4.34565877475229228821e+02; /* 0x407B290D, 0xD58A1A71 */
454 static const double sa4 = 6.45387271733267880336e+02; /* 0x40842B19, 0x21EC2868 */
455 static const double sa5 = 4.29008140027567833386e+02; /* 0x407AD021, 0x57700314 */
456 static const double sa6 = 1.08635005541779435134e+02; /* 0x405B28A3, 0xEE48AE2C */
457 static const double sa7 = 6.57024977031928170135e+00; /* 0x401A47EF, 0x8E484A93 */
458 static const double sa8 = -6.04244152148580987438e-02; /* 0xBFAEEFF2, 0xEE749A62 */
459 /*
460 * Coefficients for approximation to erfc in [1/0.35,28]
461 */
462 static const double rb0 = -9.86494292470009928597e-03; /* 0xBF843412, 0x39E86F4A */
463 static const double rb1 = -7.99283237680523006574e-01; /* 0xBFE993BA, 0x70C285DE */
464 static const double rb2 = -1.77579549177547519889e+01; /* 0xC031C209, 0x555F995A */
465 static const double rb3 = -1.60636384855821916062e+02; /* 0xC064145D, 0x43C5ED98 */
466 static const double rb4 = -6.37566443368389627722e+02; /* 0xC083EC88, 0x1375F228 */
467 static const double rb5 = -1.02509513161107724954e+03; /* 0xC0900461, 0x6A2E5992 */
468 static const double rb6 = -4.83519191608651397019e+02; /* 0xC07E384E, 0x9BDC383F */
469 static const double sb1 = 3.03380607434824582924e+01; /* 0x403E568B, 0x261D5190 */
470 static const double sb2 = 3.25792512996573918826e+02; /* 0x40745CAE, 0x221B9F0A */
471 static const double sb3 = 1.53672958608443695994e+03; /* 0x409802EB, 0x189D5118 */
472 static const double sb4 = 3.19985821950859553908e+03; /* 0x40A8FFB7, 0x688C246A */
473 static const double sb5 = 2.55305040643316442583e+03; /* 0x40A3F219, 0xCEDF3BE6 */
474 static const double sb6 = 4.74528541206955367215e+02; /* 0x407DA874, 0xE79FE763 */
475 static const double sb7 = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */
476
477 int hx,ix;
478 double R,S,P,Q,s,y,z,r;
479
480 ESL_GET_HIGHWORD(hx, x); // SRE: replaced original Sun incantation here.
481 ix = hx & 0x7fffffff;
482 if (ix>=0x7ff00000) /* erfc(nan)=nan; erfc(+-inf)=0,2 */
483 return (double)(((unsigned)hx>>31)<<1)+1.0/x;
484
485 if (ix < 0x3feb0000) /* |x|<0.84375 */
486 {
487 if (ix < 0x3c700000) return 1.0-x; /* |x|<2**-56 */
488 z = x*x;
489 r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
490 s = 1.0+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
491 y = r/s;
492 if (hx < 0x3fd00000) /* x<1/4 */
493 {
494 return 1.0-(x+x*y);
495 }
496 else
497 {
498 r = x*y;
499 r += (x-0.5);
500 return 0.5 - r ;
501 }
502 }
503
504 if (ix < 0x3ff40000) /* 0.84375 <= |x| < 1.25 */
505 {
506 s = fabs(x)-1.0;
507 P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
508 Q = 1.0+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
509 if (hx>=0)
510 {
511 z = 1.0-erx;
512 return z - P/Q;
513 }
514 else
515 {
516 z = erx+P/Q;
517 return 1.0+z;
518 }
519 }
520
521 if (ix < 0x403c0000) /* |x|<28 */
522 {
523 x = fabs(x);
524 s = 1.0/(x*x);
525 if (ix< 0x4006DB6D) /* |x| < 1/.35 ~ 2.857143*/
526 {
527 R = ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));
528 S = 1.0+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));
529 }
530 else /* |x| >= 1/.35 ~ 2.857143 */
531 {
532 if (hx < 0 && ix >= 0x40180000) return 2.0; /* x < -6 */
533 R = rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));
534 S = 1.0+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));
535 }
536 z = x;
537 ESL_SET_LOWWORD(z, 0); // SRE: replaced original Sun incantation here.
538 r = exp(-z*z-0.5625) * exp((z-x)*(z+x)+R/S);
539
540 if (hx>0) return r/x;
541 else return 2.0-r/x;
542 }
543 else
544 {
545 if (hx>0) return 0.;
546 else return 2.0;
547 }
548 }
549 /*----------------- end, special functions ----------------------*/
550
551
552 /*****************************************************************
553 * 3. Standard statistical tests.
554 *****************************************************************/
555
556 /* Function: esl_stats_GTest()
557 * Synopsis: Calculates a G-test on 2 vs. 1 binomials.
558 *
559 * Purpose: In experiment a, we've drawn <ca> successes in <na> total
560 * trials; in experiment b, we've drawn <cb> successes in
561 * <nb> total trials. Are the counts different enough to
562 * conclude that the two experiments are different? The
563 * null hypothesis is that the successes in both experiments
564 * were drawn from the same binomial distribution with
565 * per-trial probability $p$. The tested hypothesis is that
566 * experiments a,b have different binomial probabilities
567 * $p_a,p_b$. The G-test is a log-likelihood-ratio statistic,
568 * assuming maximum likelihood values for $p,p_a,p_b$.
569 * $2G$ is distributed approximately as $X^2(1)$,
570 * %"X" is "Chi"
571 * which we use to calculate a P-value for the G statistic.
572 *
573 * Args: ca - number of positives in experiment a
574 * na - total number in experiment a
575 * cb - number of positives in experiment b
576 * nb - total number in experiment b
577 * ret_G - RETURN: G statistic, a log likelihood ratio, in nats
578 * ret_P - RETURN: P-value for the G-statistic
579 *
580 * Returns: <eslOK> on success.
581 *
582 * Throws: (no abnormal error conditions)
583 *
584 * Xref: Archive1999/0906-sagescore/sagescore.c
585 */
586 int
587 esl_stats_GTest(int ca, int na, int cb, int nb, double *ret_G, double *ret_P)
588 {
589 double a,b,c,d,n;
590 double G = 0.;
591
592 a = (double) ca;
593 b = (double) (na - ca);
594 c = (double) cb;
595 d = (double) (nb - cb);
596 n = (double) na+nb;
597
598 /* Yes, the calculation here is correct; algebraic
599 * rearrangement of the log-likelihood-ratio with
600 * p_a = ca/na, p_b = cb/nb, and p = (ca+cb)/(na+nb).
601 * Guard against 0 probabilities; assume 0 log 0 => 0.
602 */
603 if (a > 0.) G = a * log(a);
604 if (b > 0.) G += b * log(b);
605 if (c > 0.) G += c * log(c);
606 if (d > 0.) G += d * log(d);
607 if (n > 0.) G += n * log(n);
608 if (a+b > 0.) G -= (a+b) * log(a+b);
609 if (c+d > 0.) G -= (c+d) * log(c+d);
610 if (a+c > 0.) G -= (a+c) * log(a+c);
611 if (b+d > 0.) G -= (b+d) * log(b+d);
612
613 *ret_G = G;
614 return esl_stats_IncompleteGamma( 0.5, G, NULL, ret_P);
615 }
616
617
618 /* Function: esl_stats_ChiSquaredTest()
619 * Synopsis: Calculates a $\chi^2$ P-value.
620 * Incept: SRE, Tue Jul 19 11:39:32 2005 [St. Louis]
621 *
622 * Purpose: Calculate the probability that a chi-squared statistic
623 * with <v> degrees of freedom would exceed the observed
624 * chi-squared value <x>; return it in <ret_answer>. If
625 * this probability is less than some small threshold (say,
626 * 0.05 or 0.01), then we may reject the hypothesis we're
627 * testing.
628 *
629 * Args: v - degrees of freedom
630 * x - observed chi-squared value
631 * ret_answer - RETURN: P(\chi^2 > x)
632 *
633 * Returns: <eslOK> on success.
634 *
635 * Throws: <eslERANGE> if <v> or <x> are out of valid range.
636 * <eslENOHALT> if iterative calculation fails.
637 */
638 int
639 esl_stats_ChiSquaredTest(int v, double x, double *ret_answer)
640 {
641 return esl_stats_IncompleteGamma((double)v/2., x/2., NULL, ret_answer);
642 }
643 /*----------------- end, statistical tests ---------------------*/
644
645
646
647 /*****************************************************************
648 * 4. Data fitting.
649 *****************************************************************/
650
651 /* Function: esl_stats_LinearRegression()
652 * Synopsis: Fit data to a straight line.
653 * Incept: SRE, Sat May 26 11:33:46 2007 [Janelia]
654 *
655 * Purpose: Fit <n> points <x[i]>, <y[i]> to a straight line
656 * $y = a + bx$ by linear regression.
657 *
658 * The $x_i$ are taken to be known, and the $y_i$ are taken
659 * to be observed quantities associated with a sampling
660 * error $\sigma_i$. If known, the standard deviations
661 * $\sigma_i$ for $y_i$ are provided in the <sigma> array.
662 * If they are unknown, pass <sigma = NULL>, and the
663 * routine will proceed with the assumption that $\sigma_i
664 * = 1$ for all $i$.
665 *
666 * The maximum likelihood estimates for $a$ and $b$ are
667 * optionally returned in <opt_a> and <opt_b>.
668 *
669 * The estimated standard deviations of $a$ and $b$ and
670 * their estimated covariance are optionally returned in
671 * <opt_sigma_a>, <opt_sigma_b>, and <opt_cov_ab>.
672 *
673 * The Pearson correlation coefficient is optionally
674 * returned in <opt_cc>.
675 *
676 * The $\chi^2$ P-value for the regression fit is
677 * optionally returned in <opt_Q>. This P-value may only be
678 * obtained when the $\sigma_i$ are known. If <sigma> is
679 * passed as <NULL> and <opt_Q> is requested, <*opt_Q> is
680 * set to 1.0.
681 *
682 * This routine follows the description and algorithm in
683 * \citep[pp.661-666]{Press93}.
684 *
685 * <n> must be greater than 2; at least two x[i] must
686 * differ; and if <sigma> is provided, all <sigma[i]> must
687 * be $>0$. If any of these conditions isn't met, the
688 * routine throws <eslEINVAL>.
689 *
690 * Args: x - x[0..n-1]
691 * y - y[0..n-1]
692 * sigma - sample error in observed y_i
693 * n - number of data points
694 * opt_a - optRETURN: intercept estimate
695 * opt_b - optRETURN: slope estimate
696 * opt_sigma_a - optRETURN: error in estimate of a
697 * opt_sigma_b - optRETURN: error in estimate of b
698 * opt_cov_ab - optRETURN: covariance of a,b estimates
699 * opt_cc - optRETURN: Pearson correlation coefficient for x,y
700 * opt_Q - optRETURN: X^2 P-value for linear fit
701 *
702 * Returns: <eslOK> on success.
703 *
704 * Throws: <eslEMEM> on allocation error;
705 * <eslEINVAL> if a contract condition isn't met;
706 * <eslENORESULT> if the chi-squared test fails.
707 * In these cases, all optional return values are set to 0.
708 */
709 int
710 esl_stats_LinearRegression(const double *x, const double *y, const double *sigma, int n,
711 double *opt_a, double *opt_b,
712 double *opt_sigma_a, double *opt_sigma_b, double *opt_cov_ab,
713 double *opt_cc, double *opt_Q)
714 {
715 int status;
716 double *t = NULL;
717 double S, Sx, Sy, Stt;
718 double Sxy, Sxx, Syy;
719 double a, b, sigma_a, sigma_b, cov_ab, cc, X2, Q;
720 double xdev, ydev;
721 double tmp;
722 int i;
723
724 /* Contract checks. */
725 if (n <= 2) ESL_XEXCEPTION(eslEINVAL, "n must be > 2 for linear regression fitting");
726 if (sigma != NULL)
727 for (i = 0; i < n; i++) if (sigma[i] <= 0.) ESL_XEXCEPTION(eslEINVAL, "sigma[%d] <= 0", i);
728 status = eslEINVAL;
729 for (i = 0; i < n; i++) if (x[i] != 0.) { status = eslOK; break; }
730 if (status != eslOK) ESL_XEXCEPTION(eslEINVAL, "all x[i] are 0.");
731
732 /* Allocations */
733 ESL_ALLOC(t, sizeof(double) * n);
734
735 /* S = \sum_{i=1}{n} \frac{1}{\sigma_i^2}. (S > 0.) */
736 if (sigma != NULL) { for (S = 0., i = 0; i < n; i++) S += 1./ (sigma[i] * sigma[i]); }
737 else S = (double) n;
738
739 /* S_x = \sum_{i=1}{n} \frac{x[i]}{ \sigma_i^2} (Sx real.) */
740 for (Sx = 0., i = 0; i < n; i++) {
741 if (sigma == NULL) Sx += x[i];
742 else Sx += x[i] / (sigma[i] * sigma[i]);
743 }
744
745 /* S_y = \sum_{i=1}{n} \frac{y[i]}{\sigma_i^2} (Sy real.) */
746 for (Sy = 0., i = 0; i < n; i++) {
747 if (sigma == NULL) Sy += y[i];
748 else Sy += y[i] / (sigma[i] * sigma[i]);
749 }
750
751 /* t_i = \frac{1}{\sigma_i} \left( x_i - \frac{S_x}{S} \right) (t_i real) */
752 for (i = 0; i < n; i++) {
753 t[i] = x[i] - Sx/S;
754 if (sigma != NULL) t[i] /= sigma[i];
755 }
756
757 /* S_{tt} = \sum_{i=1}^n t_i^2 (if at least one x is != 0, Stt > 0) */
758 for (Stt = 0., i = 0; i < n; i++) { Stt += t[i] * t[i]; }
759
760 /* b = \frac{1}{S_{tt}} \sum_{i=1}^{N} \frac{t_i y_i}{\sigma_i} */
761 for (b = 0., i = 0; i < n; i++) {
762 if (sigma != NULL) { b += t[i]*y[i] / sigma[i]; }
763 else { b += t[i]*y[i]; }
764 }
765 b /= Stt;
766
767 /* a = \frac{ S_y - S_x b } {S} */
768 a = (Sy - Sx * b) / S;
769
770 /* \sigma_a^2 = \frac{1}{S} \left( 1 + \frac{ S_x^2 }{S S_{tt}} \right) */
771 sigma_a = sqrt ((1. + (Sx*Sx) / (S*Stt)) / S);
772
773 /* \sigma_b = \frac{1}{S_{tt}} */
774 sigma_b = sqrt (1. / Stt);
775
776 /* Cov(a,b) = - \frac{S_x}{S S_{tt}} */
777 cov_ab = -Sx / (S * Stt);
778
779 /* Pearson correlation coefficient */
780 Sxy = Sxx = Syy = 0.;
781 for (i = 0; i < n; i++) {
782 if (sigma != NULL) {
783 xdev = (x[i] / (sigma[i] * sigma[i])) - (Sx / n);
784 ydev = (y[i] / (sigma[i] * sigma[i])) - (Sy / n);
785 } else {
786 xdev = x[i] - (Sx / n);
787 ydev = y[i] - (Sy / n);
788 }
789 Sxy += xdev * ydev;
790 Sxx += xdev * xdev;
791 Syy += ydev * ydev;
792 }
793 cc = Sxy / (sqrt(Sxx) * sqrt(Syy));
794
795 /* \chi^2 */
796 for (X2 = 0., i = 0; i < n; i++) {
797 tmp = y[i] - a - b*x[i];
798 if (sigma != NULL) tmp /= sigma[i];
799 X2 += tmp*tmp;
800 }
801
802 /* We can calculate a goodness of fit if we know the \sigma_i */
803 if (sigma != NULL) {
804 if (esl_stats_ChiSquaredTest(n-2, X2, &Q) != eslOK) { status = eslENORESULT; goto ERROR; }
805 } else Q = 1.0;
806
807 /* If we didn't use \sigma_i, adjust the sigmas for a,b */
808 if (sigma == NULL) {
809 tmp = sqrt(X2 / (double)(n-2));
810 sigma_a *= tmp;
811 sigma_b *= tmp;
812 }
813
814 /* Done. Set up for normal return.
815 */
816 free(t);
817 if (opt_a != NULL) *opt_a = a;
818 if (opt_b != NULL) *opt_b = b;
819 if (opt_sigma_a != NULL) *opt_sigma_a = sigma_a;
820 if (opt_sigma_b != NULL) *opt_sigma_b = sigma_b;
821 if (opt_cov_ab != NULL) *opt_cov_ab = cov_ab;
822 if (opt_cc != NULL) *opt_cc = cc;
823 if (opt_Q != NULL) *opt_Q = Q;
824 return eslOK;
825
826 ERROR:
827 if (t != NULL) free(t);
828 if (opt_a != NULL) *opt_a = 0.;
829 if (opt_b != NULL) *opt_b = 0.;
830 if (opt_sigma_a != NULL) *opt_sigma_a = 0.;
831 if (opt_sigma_b != NULL) *opt_sigma_b = 0.;
832 if (opt_cov_ab != NULL) *opt_cov_ab = 0.;
833 if (opt_cc != NULL) *opt_cc = 0.;
834 if (opt_Q != NULL) *opt_Q = 0.;
835 return status;
836 }
837 /*------------------- end, data fitting -------------------------*/
838
839
840
841 /*****************************************************************
842 * 5. Unit tests.
843 *****************************************************************/
844 #ifdef eslSTATS_TESTDRIVE
845 #include "esl_random.h"
846 #include "esl_stopwatch.h"
847 #ifdef HAVE_LIBGSL
848 #include <gsl/gsl_sf_gamma.h>
849 #endif
850
851
852 static void
853 utest_DMean(ESL_RANDOMNESS *rng)
854 {
855 char msg[] = "esl_stats:: DMean unit test failed";
856 double x[10000];
857 int n = 10000;
858 int i;
859 double mean, var;
860
861 for (i = 0; i < n; i++) x[i] = esl_random(rng);
862 esl_stats_DMean(x, n, &mean, &var);
863 if (esl_DCompare(0.5, mean, 0., 0.01) != eslOK) esl_fatal(msg); // mean of U(0,1) = 0.5
864 if (esl_DCompare(1./12., var, 0., 0.01) != eslOK) esl_fatal(msg); // var of U(0,1) = 1/12
865
866 /* pathological case 1: all x[i] equal. */
867 for (i = 1; i < n; i++) x[i] = x[0];
868 esl_stats_DMean(x, n, &mean, &var);
869 if (esl_DCompare(x[0], mean, 0., 1e-5) != eslOK) esl_fatal(msg);
870 if (esl_DCompare(0.0, var, 0., 1e-5) != eslOK) esl_fatal(msg); // zero variance
871
872 /* pathological case 2: n=1 */
873 esl_stats_DMean(x, 1, &mean, &var);
874 if (esl_DCompare(x[0], mean, 0., 1e-5) != eslOK) esl_fatal(msg);
875 if (esl_DCompare(0.0, var, 0., 1e-5) != eslOK) esl_fatal(msg); // zero variance
876 }
877
878 static void
879 utest_FMean(ESL_RANDOMNESS *rng)
880 {
881 char msg[] = "esl_stats:: FMean unit test failed";
882 float x[10000];
883 int n = 10000;
884 int i;
885 double mean, var;
886
887 for (i = 0; i < n; i++) x[i] = esl_random(rng);
888 esl_stats_FMean(x, n, &mean, &var); // mean, var are in doubles
889 if (esl_DCompare(0.5, mean, 0., 0.01) != eslOK) esl_fatal(msg); // mean of U(0,1) = 0.5
890 if (esl_DCompare(1./12., var, 0., 0.01) != eslOK) esl_fatal(msg); // var of U(0,1) = 1/12
891
892 /* pathological case 1: all x[i] equal. */
893 for (i = 1; i < n; i++) x[i] = x[0];
894 esl_stats_FMean(x, n, &mean, &var);
895 if (esl_DCompare(x[0], mean, 0., 1e-5) != eslOK) esl_fatal(msg);
896 if (esl_DCompare(0.0, var, 0., 1e-5) != eslOK) esl_fatal(msg); // zero variance
897
898 /* pathological case 2: n=1 */
899 esl_stats_FMean(x, 1, &mean, &var);
900 if (esl_DCompare(x[0], mean, 0., 1e-5) != eslOK) esl_fatal(msg);
901 if (esl_DCompare(0.0, var, 0., 1e-5) != eslOK) esl_fatal(msg); // zero variance
902 }
903
904 static void
905 utest_IMean(ESL_RANDOMNESS *rng)
906 {
907 char msg[] = "esl_stats:: IMean unit test failed";
908 int x[10000];
909 int n = 10000;
910 int i;
911 double mean, var;
912 double mean0,var0;
913
914 for (i = 0; i < n; i++) x[i] = esl_rnd_Roll(rng, 101); // U(0,100)
915 mean0 = 100./2.; // mean of discrete U(a,b) = (a+b)/2
916 var0 = (101.0*101.0-1.)/12.; // variance of discrete U(a,b) = ((b-a+1)^2 -1)/12
917 esl_stats_IMean(x, n, &mean, &var); // mean, var are in doubles
918 if (esl_DCompare(mean0, mean, 0.02, 0.02) != eslOK) esl_fatal(msg);
919 if (esl_DCompare(var0, var, 0.02, 0.02) != eslOK) esl_fatal(msg);
920
921 /* pathological case 1: all x[i] equal. */
922 for (i = 1; i < n; i++) x[i] = x[0];
923 esl_stats_IMean(x, n, &mean, &var);
924 mean0 = (double) x[0];
925 var0 = 0.;
926 if (esl_DCompare(mean0, mean, 0., 1e-5) != eslOK) esl_fatal(msg);
927 if (esl_DCompare(var0, var, 0., 1e-5) != eslOK) esl_fatal(msg); // zero variance
928
929 /* pathological case 2: n=1 */
930 esl_stats_IMean(x, 1, &mean, &var);
931 if (esl_DCompare(mean0, mean, 0., 1e-5) != eslOK) esl_fatal(msg);
932 if (esl_DCompare(var0, var, 0., 1e-5) != eslOK) esl_fatal(msg); // zero variance
933 }
934
935
936
937 /* Macros for treating IEEE754 double as two uint32_t halves, with
938 * compile-time handling of endianness; see esl_stats.h.
939 */
940 static void
941 utest_doublesplitting(ESL_RANDOMNESS *rng)
942 {
943 char msg[] = "esl_stats:: doublesplitting unit test failed";
944 uint32_t ix0, ix1;
945 double x;
946 double x2;
947 int iteration; // iteration 0 uses x = 2; iteration 1 uses random x = [0,1).
948
949 for (iteration = 0; iteration < 2; iteration++)
950 {
951 x = (iteration == 0 ? 2.0 : esl_random(rng));
952 ESL_GET_WORDS(ix0, ix1, x);
953 ESL_SET_WORDS(x2, ix0, ix1);
954 if (x2 != x) esl_fatal(msg);
955
956 ESL_GET_HIGHWORD(ix0, x);
957 ESL_SET_HIGHWORD(x2, ix0);
958 if (x2 != x) esl_fatal(msg);
959
960 ESL_GET_LOWWORD(ix0, x);
961 ESL_SET_LOWWORD(x2, ix0);
962 if (iteration == 0 && ix0 != 0) esl_fatal(msg);
963 if (x2 != x) esl_fatal(msg);
964 }
965 }
966
967 /* The LogGamma() function is rate-limiting in hmmbuild, because it is
968 * used so heavily in mixture Dirichlet calculations.
969 * ./configure --with-gsl; [compile test driver]
970 * ./stats_utest -v
971 * runs a comparison of time/precision against GSL.
972 * SRE, Sat May 23 10:04:41 2009, on home Mac:
973 * LogGamma = 1.29u / N=1e8 = 13 nsec/call
974 * gsl_sf_lngamma = 1.43u / N=1e8 = 14 nsec/call
975 */
976 static void
977 utest_LogGamma(ESL_RANDOMNESS *r, int N, int be_verbose)
978 {
979 char *msg = "esl_stats_LogGamma() unit test failed";
980 ESL_STOPWATCH *w = esl_stopwatch_Create();
981 double *x = malloc(sizeof(double) * N);
982 double *lg = malloc(sizeof(double) * N);
983 double *lg2 = malloc(sizeof(double) * N);
984 int i;
985
986 for (i = 0; i < N; i++)
987 x[i] = esl_random(r) * 100.;
988
989 esl_stopwatch_Start(w);
990 for (i = 0; i < N; i++)
991 if (esl_stats_LogGamma(x[i], &(lg[i])) != eslOK) esl_fatal(msg);
992 esl_stopwatch_Stop(w);
993
994 if (be_verbose) esl_stopwatch_Display(stdout, w, "esl_stats_LogGamma() timing: ");
995
996 #ifdef HAVE_LIBGSL
997 esl_stopwatch_Start(w);
998 for (i = 0; i < N; i++) lg2[i] = gsl_sf_lngamma(x[i]);
999 esl_stopwatch_Stop(w);
1000
1001 if (be_verbose) esl_stopwatch_Display(stdout, w, "gsl_sf_lngamma() timing: ");
1002
1003 for (i = 0; i < N; i++)
1004 if (esl_DCompare_old(lg[i], lg2[i], 1e-2) != eslOK) esl_fatal(msg);
1005 #endif
1006
1007 free(lg2);
1008 free(lg);
1009 free(x);
1010 esl_stopwatch_Destroy(w);
1011 }
1012
1013 static void
1014 utest_psi(ESL_RANDOMNESS *rng)
1015 {
1016 char msg[] = "esl_stats:: psi unit test failed";
1017 int ntrials = 5; // number of random x's to check
1018 int regime; // distribute our checks into all three regimes for esl_stats_Psi()'s approximations
1019 double x, psi_slow, psi, n; // those three regimes are 0 < x <= 1e-5; 1e-5 < x < 8.5; x >= 8.5
1020
1021 while (ntrials--)
1022 {
1023 regime = esl_rnd_Roll(rng, 3); // x <= S, S < x < C, x >= C regimes for esl_stats_Psi(); for
1024 if (regime == 0) x = 1.0e-5 * esl_rnd_UniformPositive(rng); // (0,1e-5); only rarely tests < 1e-6, won't test 1e-5 exactly, but fine
1025 else if (regime == 1) x = 8.5 * esl_rnd_UniformPositive(rng); // (0,8.5); rarely this'll be < 1e-4 but that's fine
1026 else x = 8.5 + 91.5*esl_random(rng); // [8.5,100)
1027
1028 // Check against (slowly converging) series approximations eqn(3) and eqn(2) combined, from Bernardo (1976)
1029 // The esl_stats_Psi() function already uses eqn(2) for x<=1e-5, so it's sort of pointless to test x<=1e-5, but whatever, it's not nothing to check
1030 psi_slow = -eslCONST_EULER - 1./x;
1031 for (n = 1.; n < 500000.; n += 1.) psi_slow += x / (n*(n+x));
1032
1033 if (esl_stats_Psi(x, &psi) != eslOK) esl_fatal(msg);
1034 if (esl_DCompare(psi, psi_slow, 1e-4, 1e-4)) esl_fatal(msg);
1035 }
1036 }
1037
1038 static void
1039 utest_trigamma(ESL_RANDOMNESS *rng)
1040 {
1041 char msg[] = "esl_stats:: trigamma unit test failed";
1042 int ntrials = 5; // number of random x's to check
1043 int regime; // distribute our checks into all three regimes of esl_stats_Trigamma()'s approximations
1044 double x, trigam_slow, trigam, i; // those regimes are 0 < x <= 1e-4, 1e-4 < x < 5.0, x >= 5.0
1045
1046 while (ntrials--)
1047 {
1048 regime = esl_rnd_Roll(rng, 3); // x <= A, A < x < B, x >= B regimes for esl_stats_Trigamma()
1049 if (regime == 0) x = 1.0e-4 * esl_rnd_UniformPositive(rng); // (0,1e-4); only rarely tests < 1e-5, won't test 1e-4 exactly, but fine
1050 else if (regime == 1) x = 5.0 * esl_rnd_UniformPositive(rng); // (0,5); rarely this'll be < 1e-4 but that's fine
1051 else x = 5.0 + 95.*esl_random(rng); // [5,100)
1052 if (x <= 0. || x >= 100.) esl_fatal(msg); // this would probably mean a failure in the ranges of esl_random functions above
1053
1054 // This is series approximation eqn(2) from Schneider (1978),
1055 // and boy he's not kidding that it's slowly converging
1056 trigam_slow = 0.;
1057 for (i = 0.; i < 1000000.; i += 1.0) trigam_slow += 1./((x+i)*(x+i));
1058
1059 if (esl_stats_Trigamma(x, &trigam) != eslOK) esl_fatal(msg);
1060 if (esl_DCompare(trigam, trigam_slow, 1e-4, 1e-4)) esl_fatal(msg);
1061 }
1062 }
1063
1064 /* The test of esl_stats_LinearRegression() is a statistical test,
1065 * so we can't be too aggressive about testing results.
1066 *
1067 * Args:
1068 * r - a source of randomness
1069 * use_sigma - TRUE to pass sigma to the regression fit.
1070 * be_verbose - TRUE to print results (manual, not automated test mode)
1071 */
1072 static void
1073 utest_LinearRegression(ESL_RANDOMNESS *r, int use_sigma, int be_verbose)
1074 {
1075 char msg[] = "linear regression unit test failed";
1076 double a = -3.;
1077 double b = 1.;
1078 int n = 100;
1079 double xori = -20.;
1080 double xstep = 1.0;
1081 double setsigma = 1.0; /* sigma on all points */
1082 int i;
1083 double *x = NULL;
1084 double *y = NULL;
1085 double *sigma = NULL;
1086 double ae, be, siga, sigb, cov_ab, cc, Q;
1087
1088 if ((x = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
1089 if ((y = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
1090 if ((sigma = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
1091
1092 /* Simulate some linear data */
1093 for (i = 0; i < n; i++)
1094 {
1095 sigma[i] = setsigma;
1096 x[i] = xori + i*xstep;
1097 y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);
1098 }
1099
1100 if (use_sigma) {
1101 if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);
1102 } else {
1103 if (esl_stats_LinearRegression(x, y, NULL, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);
1104 }
1105
1106 if (be_verbose) {
1107 printf("Linear regression test:\n");
1108 printf("estimated intercept a = %8.4f [true = %8.4f]\n", ae, a);
1109 printf("estimated slope b = %8.4f [true = %8.4f]\n", be, b);
1110 printf("estimated sigma on a = %8.4f\n", siga);
1111 printf("estimated sigma on b = %8.4f\n", sigb);
1112 printf("estimated cov(a,b) = %8.4f\n", cov_ab);
1113 printf("correlation coeff = %8.4f\n", cc);
1114 printf("P-value = %8.4f\n", Q);
1115 }
1116
1117 /* The following tests are statistical.
1118 */
1119 if ( fabs(ae-a) > 2*siga ) esl_fatal(msg);
1120 if ( fabs(be-b) > 2*sigb ) esl_fatal(msg);
1121 if ( cc < 0.95) esl_fatal(msg);
1122 if (use_sigma) {
1123 if (Q < 0.001) esl_fatal(msg);
1124 } else {
1125 if (Q != 1.0) esl_fatal(msg);
1126 }
1127
1128 free(x);
1129 free(y);
1130 free(sigma);
1131 }
1132
1133 static void
1134 utest_erfc(ESL_RANDOMNESS *rng, int be_verbose)
1135 {
1136 char msg[] = "esl_stats:: erfc unit test failed";
1137 double x;
1138 double result;
1139 int i;
1140
1141 if (be_verbose) {
1142 printf("#--------------------------\n");
1143 printf("# erfc unit testing...\n");
1144 }
1145
1146 result = esl_stats_erfc( eslNaN);
1147 if (! isnan(result)) esl_fatal(msg);
1148 if (esl_stats_erfc(-eslINFINITY) != 2.0) esl_fatal(msg);
1149 if (esl_stats_erfc( 0.0) != 1.0) esl_fatal(msg);
1150 if (esl_stats_erfc( eslINFINITY) != 0.0) esl_fatal(msg);
1151
1152 for (i = 0; i < 42; i++)
1153 {
1154 x = esl_random(rng) * 10. - 5.;
1155 result = esl_stats_erfc(x);
1156 if (!isfinite(result)) esl_fatal(msg);
1157 #ifdef HAVE_ERFC
1158 if (esl_DCompare_old(result, erfc(x), 1e-6) != eslOK) esl_fatal(msg);
1159 if (be_verbose)
1160 printf("%15f %15f %15f\n", x, result, erfc(x));
1161 #endif
1162 }
1163
1164 if (be_verbose)
1165 printf("#--------------------------\n");
1166 return;
1167 }
1168
1169 #endif /*eslSTATS_TESTDRIVE*/
1170 /*-------------------- end of unit tests ------------------------*/
1171
1172
1173
1174
1175 /*****************************************************************
1176 * 6. Test driver.
1177 *****************************************************************/
1178 #ifdef eslSTATS_TESTDRIVE
1179 /* gcc -g -Wall -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lm
1180 * gcc -DHAVE_LIBGSL -O2 -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lgsl -lm
1181 */
1182 #include <stdio.h>
1183 #include "easel.h"
1184 #include "esl_getopts.h"
1185 #include "esl_random.h"
1186 #include "esl_stats.h"
1187
1188 static ESL_OPTIONS options[] = {
1189 /* name type default env range togs reqs incomp help docgrp */
1190 {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
1191 {"-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
1192 {"-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "verbose: show verbose output", 0},
1193 {"-N", eslARG_INT,"10000000", NULL, NULL, NULL, NULL, NULL, "number of trials in LogGamma test", 0},
1194 { 0,0,0,0,0,0,0,0,0,0},
1195 };
1196 static char usage[] = "[-options]";
1197 static char banner[] = "test driver for stats special functions";
1198
1199 int
1200 main(int argc, char **argv)
1201 {
1202 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1203 ESL_RANDOMNESS *r = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1204 int be_verbose = esl_opt_GetBoolean(go, "-v");
1205 int N = esl_opt_GetInteger(go, "-N");
1206
1207 if (be_verbose) printf("seed = %" PRIu32 "\n", esl_randomness_GetSeed(r));
1208
1209 utest_DMean(r);
1210 utest_FMean(r);
1211 utest_IMean(r);
1212 utest_doublesplitting(r);
1213 utest_erfc(r, be_verbose);
1214 utest_LogGamma(r, N, be_verbose);
1215 utest_psi(r);
1216 utest_trigamma(r);
1217 utest_LinearRegression(r, TRUE, be_verbose);
1218 utest_LinearRegression(r, FALSE, be_verbose);
1219
1220 esl_getopts_Destroy(go);
1221 esl_randomness_Destroy(r);
1222 exit(0);
1223 }
1224 #endif /*eslSTATS_TESTDRIVE*/
1225 /*------------------- end of test driver ------------------------*/
1226
1227
1228
1229
1230 /*****************************************************************
1231 * 7. Examples.
1232 *****************************************************************/
1233
1234 /* Compile: gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm
1235 * or gcc -g -Wall -o example -I. -L. -DeslSTATS_EXAMPLE esl_stats.c -leasel -lm
1236 */
1237 #ifdef eslSTATS_EXAMPLE
1238 /*::cexcerpt::stats_example::begin::*/
1239 /* gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm */
1240 #include <stdio.h>
1241 #include "easel.h"
1242 #include "esl_random.h"
1243 #include "esl_stats.h"
1244
1245 int main(void)
1246 {
1247 ESL_RANDOMNESS *r = esl_randomness_Create(0);
1248 double a = -3.;
1249 double b = 1.;
1250 double xori = -20.;
1251 double xstep = 1.0;
1252 double setsigma = 1.0; /* sigma on all points */
1253 int n = 100;
1254 double *x = malloc(sizeof(double) * n);
1255 double *y = malloc(sizeof(double) * n);
1256 double *sigma = malloc(sizeof(double) * n);
1257 int i;
1258 double ae, be, siga, sigb, cov_ab, cc, Q;
1259
1260 /* Simulate some linear data, with Gaussian noise added to y_i */
1261 for (i = 0; i < n; i++) {
1262 sigma[i] = setsigma;
1263 x[i] = xori + i*xstep;
1264 y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);
1265 }
1266
1267 if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK)
1268 esl_fatal("linear regression failed");
1269
1270 printf("estimated intercept a = %8.4f [true = %8.4f]\n", ae, a);
1271 printf("estimated slope b = %8.4f [true = %8.4f]\n", be, b);
1272 printf("estimated sigma on a = %8.4f\n", siga);
1273 printf("estimated sigma on b = %8.4f\n", sigb);
1274 printf("estimated cov(a,b) = %8.4f\n", cov_ab);
1275 printf("correlation coeff = %8.4f\n", cc);
1276 printf("P-value = %8.4f\n", Q);
1277
1278 free(x); free(y); free(sigma);
1279 esl_randomness_Destroy(r);
1280 exit(0);
1281 }
1282 /*::cexcerpt::stats_example::end::*/
1283 #endif /* eslSTATS_EXAMPLE */
1284
1285
1286 #ifdef eslSTATS_EXAMPLE2
1287
1288 #include <stdlib.h>
1289
1290 #include "easel.h"
1291 #include "esl_getopts.h"
1292 #include "esl_stats.h"
1293
1294 static ESL_OPTIONS options[] = {
1295 /* name type default env range toggles reqs incomp help docgroup*/
1296 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1297 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1298 };
1299 static char usage[] = "[-options] <ca> <na> <cb> <nb>";
1300 static char banner[] = "example from the stats module: using a G-test";
1301
1302 int
1303 main(int argc, char **argv)
1304 {
1305 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 4, argc, argv, banner, usage);
1306 int ca = strtol(esl_opt_GetArg(go, 1), NULL, 10);
1307 int na = strtol(esl_opt_GetArg(go, 2), NULL, 10);
1308 int cb = strtol(esl_opt_GetArg(go, 3), NULL, 10);
1309 int nb = strtol(esl_opt_GetArg(go, 4), NULL, 10);
1310 double G, P;
1311 int status;
1312
1313 if (ca > na || cb > nb) esl_fatal("argument order wrong? expect ca, na, cb, nb for ca/na, cb/nb");
1314
1315 if ( (status = esl_stats_GTest(ca, na, cb, nb, &G, &P)) != eslOK) esl_fatal("G-test failed?");
1316 printf("%-10.3g %12.2f\n", P, G);
1317 exit(0);
1318 }
1319 #endif /* eslSTATS_EXAMPLE2 */
1320 /*--------------------- end of examples -------------------------*/
1321