Debian Codegraph @

easel/esl_histogram.c

raw symbols SCIP
1 /* Collecting and displaying histograms.
2 *
3 * 1. Creating/destroying histograms and collecting data.
4 * 2. Declarations about the binned data before parameter fitting.
5 * 3. Routines for accessing data samples in a full histogram.
6 * 4. Setting expected counts
7 * 5. Output and display of binned data.
8 * 6. Test driver.
9 * 7. Examples.
10 */
11 #include <esl_config.h>
12
13 #include <stdlib.h>
14 #include <string.h>
15 #include <math.h>
16 #include <float.h>
17 #include <limits.h>
18
19 #include "easel.h"
20 #include "esl_stats.h"
21 #include "esl_vectorops.h"
22
23 #include "esl_histogram.h"
24
25 static int esl_histogram_sort(ESL_HISTOGRAM *h);
26
27
28 /*****************************************************************
29 * 1. Creating/destroying histograms and collecting data.
30 *****************************************************************/
31
32 /* Function: esl_histogram_Create()
33 * Synopsis: Create a new <ESL_HISTOGRAM>.
34 *
35 * Purpose: Creates and returns a new histogram object, initially
36 * allocated to count values $>$ <bmin> and $<=$ <bmax> into
37 * bins of width <w>. Thus, a total of <bmax>-<bmin>/<w> bins
38 * are initially created.
39 *
40 * The lower bound <bmin> and the width <w> permanently
41 * determine the offset and width of the binning, but not
42 * the range. For example, <esl_histogram_Create(-100,
43 * 100, 0.5)> would initialize the object to collect scores into
44 * 400 bins $[-100< x \leq -99.5],[-99.5 < x \leq
45 * -99.0]...[99.5 <x \leq 100.0]$. Aside from this, the
46 * range specified by the bounds <bmin> and <bmax> only
47 * needs to be an initial guess. The histogram object will
48 * reallocate itself dynamically as needed to accommodate
49 * scores that exceed current bounds.
50 *
51 * You can be sloppy about <bmax>; it does not have to
52 * exactly match a bin upper bound. The initial allocation
53 * is for all full-width bins with upper bounds $\leq
54 * bmax$.
55 *
56 * <esl_histogram_Create()> creates a simplified histogram
57 * object that collates only the "display" histogram. For
58 * a more complex object that also keeps the raw data samples,
59 * better suited for fitting distributions and goodness-of-fit
60 * testing, use <esl_histogram_CreateFull()>.
61 *
62 * There is currently no way to alter where the equals sign
63 * is, in setting the bin bounds: that is, you can't make bins
64 * that have <bmin> $\leq x$ and $x <$ <bmax>, alas.
65
66 *
67 * Args: bmin - caller guesses that minimum score will be > bmin
68 * bmax - caller guesses that max score will be <= bmax
69 * w - size of bins (1.0, for example)
70 *
71 * Returns: ptr to new <ESL_HISTOGRAM> object, which caller is responsible
72 * for free'ing with <esl_histogram_Destroy()>.
73 *
74 * Throws: <NULL> on allocation failure.
75 */
76 ESL_HISTOGRAM *
77 esl_histogram_Create(double bmin, double bmax, double w)
78 {
79 ESL_HISTOGRAM *h = NULL;
80 int status;
81 int i;
82
83 ESL_ALLOC(h, sizeof(ESL_HISTOGRAM));
84
85 h->xmin = DBL_MAX; /* xmin/xmax are the observed min/max */
86 h->xmax = -DBL_MAX;
87 h->n = 0;
88 h->obs = NULL; /* will get allocated below... */
89 h->bmin = bmin; /* bmin/bmax are the allocated bounds */
90 h->bmax = bmax;
91 h->nb = (int)((bmax-bmin)/w);
92 h->imin = h->nb;
93 h->imax = -1;
94 h->w = w;
95
96 h->x = NULL;
97 h->nalloc = 0;
98
99 h->phi = 0.;
100 h->cmin = h->imin; /* sentinel: no observed data yet */
101 h->z = 0;
102 h->Nc = 0;
103 h->No = 0;
104
105 h->expect = NULL; /* 'til a Set*() call */
106 h->emin = -1; /* sentinel: no expected counts yet */
107 h->tailbase = 0.; /* unused unless is_tailfit TRUE */
108 h->tailmass = 1.0; /* <= 1.0 if is_tailfit TRUE */
109
110 h->is_full = FALSE;
111 h->is_done = FALSE;
112 h->is_sorted = FALSE;
113 h->is_tailfit = FALSE;
114 h->is_rounded = FALSE;
115 h->dataset_is = COMPLETE;
116
117 ESL_ALLOC(h->obs, sizeof(uint64_t) * h->nb);
118 for (i = 0; i < h->nb; i++) h->obs[i] = 0;
119 return h;
120
121 ERROR:
122 esl_histogram_Destroy(h);
123 return NULL;
124 }
125
126 /* Function: esl_histogram_CreateFull()
127 * Synopsis: A <ESL_HISTOGRAM> to keep all data samples.
128 *
129 * Purpose: Alternative form of <esl_histogram_Create()> that
130 * creates a more complex histogram that will contain not just the
131 * display histogram, but also keeps track of all
132 * the raw sample values. Having a complete vector of raw
133 * samples improves distribution-fitting and goodness-of-fit
134 * tests, but will consume more memory.
135 */
136 ESL_HISTOGRAM *
137 esl_histogram_CreateFull(double bmin, double bmax, double w)
138 {
139 int status;
140 ESL_HISTOGRAM *h = esl_histogram_Create(bmin, bmax, w);
141 if (h == NULL) return NULL;
142
143 h->n = 0; /* make sure */
144 h->nalloc = 128; /* arbitrary initial allocation size */
145 ESL_ALLOC(h->x, sizeof(double) * h->nalloc);
146 h->is_full = TRUE;
147 return h;
148
149 ERROR:
150 esl_histogram_Destroy(h);
151 return NULL;
152 }
153
154
155 /* Function: esl_histogram_Destroy()
156 * Synopsis: Frees a <ESL_HISTOGRAM>.
157 *
158 * Purpose: Frees an <ESL_HISTOGRAM> object <h>.
159 */
160 void
161 esl_histogram_Destroy(ESL_HISTOGRAM *h)
162 {
163 if (h == NULL) return;
164 if (h->x != NULL) free(h->x);
165 if (h->obs != NULL) free(h->obs);
166 if (h->expect != NULL) free(h->expect);
167 free(h);
168 return;
169 }
170
171 /* Function: esl_histogram_Score2Bin()
172 * Synopsis: Given a real-valued <x>; calculate integer bin <b>
173 *
174 * Purpose: For a real-valued <x>, figure out what bin it would
175 * go into in the histogram <h>; return this value in
176 * <*ret_b>.
177 *
178 * Returns: <eslOK> on success.
179 *
180 * Throws: <eslERANGE> if bin <b> would exceed the range of
181 * an integer; for instance, if <x> isn't finite.
182 *
183 * Xref: J5/122. Replaces earlier macro implementation;
184 * we needed to range check <x> better.
185 */
186 int
187 esl_histogram_Score2Bin(ESL_HISTOGRAM *h, double x, int *ret_b)
188 {
189 int status;
190
191 if (! isfinite(x)) ESL_XEXCEPTION(eslERANGE, "value added to histogram is not finite");
192
193 x = ceil( ((x - h->bmin) / h->w) - 1.);
194
195 /* x is now the bin number as a double, which we will convert to
196 * int. Because x is a double (64-bit), we know all ints are exactly
197 * represented. Check for under/overflow before conversion.
198 */
199 if (x < (double) INT_MIN || x > (double) INT_MAX)
200 ESL_XEXCEPTION(eslERANGE, "value %f isn't going to fit in histogram", x);
201
202 *ret_b = (int) x;
203 return eslOK;
204
205 ERROR:
206 *ret_b = 0;
207 return status;
208 }
209
210
211 /* Function: esl_histogram_Add()
212 * Synopsis: Add a sample to the histogram.
213 *
214 * Purpose: Adds score <x> to a histogram <h>.
215 *
216 * The histogram will be automatically reallocated as
217 * needed if the score is smaller or larger than the
218 * current allocated bounds.
219 *
220 * Returns: <eslOK> on success.
221 *
222 * Throws: <eslEMEM> on reallocation failure.
223 *
224 * <eslERANGE> if <x> is beyond the reasonable range for
225 * the histogram to store -- either because it isn't finite,
226 * or because the histogram would need to allocate a number
227 * of bins that exceeds <INT_MAX>.
228 *
229 * Throws <eslEINVAL> for cases where something has been done
230 * to the histogram that requires it to be 'finished', and
231 * adding more data is prohibited; for example,
232 * if tail or censoring information has already been set.
233 * On either failure, initial state of <h> is preserved.
234 */
235 int
236 esl_histogram_Add(ESL_HISTOGRAM *h, double x)
237 {
238 int status;
239 void *tmp;
240 int b; /* what bin we're in */
241 int nnew; /* # of new bins created by a reallocation */
242 int bi;
243
244 /* Censoring info must only be set on a finished histogram;
245 * don't allow caller to add data after configuration has been declared
246 */
247 if (h->is_done)
248 ESL_EXCEPTION(eslEINVAL, "can't add more data to this histogram");
249
250 /* If we're a full histogram, check whether we need to reallocate
251 * the full data vector.
252 */
253 if (h->is_full && h->nalloc == h->n)
254 {
255 ESL_RALLOC(h->x, tmp, sizeof(double) * h->nalloc * 2);
256 h->nalloc *= 2;
257 }
258
259 /* Which bin will we want to put x into?
260 */
261 if ((status = esl_histogram_Score2Bin(h,x, &b)) != eslOK) return status;
262
263 /* Make sure we have that bin. Realloc as needed.
264 * If that reallocation succeeds, we can no longer fail;
265 * so we can change the state of h.
266 */
267 if (b < 0) /* Reallocate below? */
268 {
269 nnew = -b*2; /* overallocate by 2x */
270 if (nnew > INT_MAX - h->nb)
271 ESL_EXCEPTION(eslERANGE, "value %f requires unreasonable histogram bin number", x);
272 ESL_RALLOC(h->obs, tmp, sizeof(uint64_t) * (nnew+ h->nb));
273
274 memmove(h->obs+nnew, h->obs, sizeof(uint64_t) * h->nb);
275 h->nb += nnew;
276 b += nnew;
277 h->bmin -= nnew*h->w;
278 h->imin += nnew;
279 h->cmin += nnew;
280 if (h->imax > -1) h->imax += nnew;
281 for (bi = 0; bi < nnew; bi++) h->obs[bi] = 0;
282 }
283 else if (b >= h->nb) /* Reallocate above? */
284 {
285 nnew = (b-h->nb+1) * 2; /* 2x overalloc */
286 if (nnew > INT_MAX - h->nb)
287 ESL_EXCEPTION(eslERANGE, "value %f requires unreasonable histogram bin number", x);
288 ESL_RALLOC(h->obs, tmp, sizeof(uint64_t) * (nnew+ h->nb));
289 for (bi = h->nb; bi < h->nb+nnew; bi++) h->obs[bi] = 0;
290 if (h->imin == h->nb) { /* boundary condition of no data yet*/
291 h->imin+=nnew;
292 h->cmin+=nnew;
293 }
294 h->bmax += nnew*h->w;
295 h->nb += nnew;
296 }
297
298 /* If we're a full histogram, then we keep the raw x value,
299 * reallocating as needed.
300 */
301 if (h->is_full) h->x[h->n] = x;
302 h->is_sorted = FALSE; /* not any more! */
303
304 /* Bump the bin counter, and all the data sample counters.
305 */
306 h->obs[b]++;
307 h->n++;
308 h->Nc++;
309 h->No++;
310
311 if (b > h->imax) h->imax = b;
312 if (b < h->imin) { h->imin = b; h->cmin = b; }
313 if (x > h->xmax) h->xmax = x;
314 if (x < h->xmin) h->xmin = x;
315 return eslOK;
316
317 ERROR:
318 return status;
319 }
320
321
322 /* esl_histogram_sort()
323 *
324 * Purpose: Sort the raw scores in a full histogram, from smallest to
325 * largest. Has no effect on a normal histogram, or on a full
326 * histogram that is already sorted.
327 *
328 * Returns: <eslOK> on success.
329 * Upon return, <h->x[h->n-1]> is the high score, <h->x[0]> is the
330 * low score.
331 */
332 int
333 esl_histogram_sort(ESL_HISTOGRAM *h)
334 {
335 if (h->is_sorted) return eslOK; /* already sorted, don't do anything */
336 if (! h->is_full) return eslOK; /* nothing to sort */
337
338 esl_vec_DSortIncreasing(h->x, h->n);
339 h->is_sorted = TRUE;
340 return eslOK;
341 }
342
343 /*****************************************************************
344 * 2. Declarations about the binned data before parameter fitting
345 *****************************************************************/
346
347 /* Function: esl_histogram_DeclareCensoring()
348 * Synopsis: Collected data were left-censored.
349 *
350 * Purpose: Declare that the dataset collected in <h> is known to be a
351 * censored distribution, where <z> samples were unobserved because
352 * they had values $\leq$ some threshold <phi> ($\phi$).
353 *
354 * No more data can be added to the histogram with <_Add()>
355 * after censoring information has been set.
356 *
357 * This function is for "true" censored datasets, where
358 * the histogram truly contains no observed points
359 * $x \leq \phi$, and the number that were censored is known
360 * to be <z>.
361 *
362 * Returns: <eslOK> on success.
363 *
364 * Throws: <eslEINVAL> if you try to set <phi> to a value that is
365 * greater than the minimum <x> stored in the histogram.
366 */
367 int
368 esl_histogram_DeclareCensoring(ESL_HISTOGRAM *h, int z, double phi)
369 {
370 if (phi > h->xmin) ESL_EXCEPTION(eslEINVAL, "no uncensored x can be <= phi");
371
372 h->phi = phi;
373 h->cmin = h->imin;
374 h->z = z;
375 h->Nc = h->n + z;
376 h->No = h->n;
377 h->dataset_is = TRUE_CENSORED;
378 h->is_done = TRUE;
379 return eslOK;
380 }
381
382 /* Function: esl_histogram_DeclareRounding()
383 * Synopsis: Declare collected data were no more accurate than bins.
384 *
385 * Purpose: Declare that the data sample values in the histogram <h>
386 * are rounded off. Ideally, your bins in <h> should exactly
387 * match the rounding procedure. This raises a flag that
388 * binned parameter fitting routines will use when they set
389 * an origin, using the lower bound of the bin instead of
390 * the lowest raw value in the bin.
391 */
392 int
393 esl_histogram_DeclareRounding(ESL_HISTOGRAM *h)
394 {
395 h->is_rounded = TRUE;
396 return eslOK;
397 }
398
399
400 /* Function: esl_histogram_SetTail()
401 * Synopsis: Declare only tail $>$ some threshold is considered "observed".
402 *
403 * Purpose: Suggest a threshold <phi> to split a histogram <h>
404 * into "unobserved" data (values $\leq \phi$) and "observed"
405 * data (values $> \phi$).
406 *
407 * The suggested <phi> is revised downwards to a $\phi$ at the next
408 * bin lower bound, because operations on binned data in <h>
409 * need to know unambiguously whether all the data in a given bin
410 * will be counted as observed or unobserved.
411 *
412 * The probability mass that is in the resulting right tail
413 * is optionally returned in <ret_newmass>. You need to know
414 * this number if you're fitting a distribution solely to the
415 * tail (an exponential tail, for example).
416 *
417 * Any data point $x_i \leq \phi$ is then considered to be
418 * in a censored (unobserved) region for purposes of parameter
419 * fitting, calculating expected binned counts,
420 * and binned goodness-of-fit tests.
421 *
422 * No more data can be added to the histogram after
423 * censoring information has been set.
424 *
425 * This function defines a "virtual" left-censoring: the
426 * histogram actually contains complete data, but appropriate
427 * flags are set to demarcate the "observed" data in the right
428 * tail.
429 *
430 * Returns: <eslOK> on success.
431 *
432 * Throws: <eslERANGE> if <phi> is an unreasonable value that
433 * can't be converted to an integer bin value.
434 */
435 int
436 esl_histogram_SetTail(ESL_HISTOGRAM *h, double phi, double *ret_newmass)
437 {
438 int b;
439 int status;
440
441 /* Usually, put true phi at the next bin lower bound, but
442 * watch for a special case where phi is already exactly equal to a
443 * bin upper bound.
444 */
445 if ((status = esl_histogram_Score2Bin(h,phi, &(h->cmin))) != eslOK) return status;
446 if (phi == esl_histogram_Bin2UBound(h,h->cmin)) h->phi = phi;
447 else h->phi = esl_histogram_Bin2LBound(h, h->cmin);
448
449 h->z = 0;
450 for (b = h->imin; b < h->cmin; b++)
451 h->z += h->obs[b];
452 h->Nc = h->n; /* (redundant) */
453 h->No = h->n - h->z;
454 h->dataset_is = VIRTUAL_CENSORED;
455 h->is_done = TRUE;
456 if (ret_newmass != NULL) *ret_newmass = (double) h->No / (double) h->Nc;
457 return eslOK;
458 }
459
460 /* Function: esl_histogram_SetTailByMass()
461 * Synopsis: Declare only right tail mass is considered "observed".
462 *
463 * Purpose: Given a histogram <h> (with or without raw data samples),
464 * find a cutoff score that at least fraction <pmass> of the samples
465 * exceed. This threshold is stored internally in the histogram
466 * as <h->phi>. The number of "virtually censored" samples (to the
467 * left, with scores $\leq \phi$) is stored internally in <h->z>.
468 *
469 * The identified cutoff score must be a lower bound for some bin
470 * (bins can't be partially censored). The censored mass
471 * will thus usually be a bit greater than <pmass>, as the
472 * routine will find the highest satisfactory <h->phi>. The
473 * narrower the bin widths, the more accurately the routine
474 * will be able to satisfy the requested <frac>. The actual
475 * probability mass in the right tail is optionally returned
476 * in <ret_newmass>. You need to know this number if you're
477 * fitting a distribution solely to the tail (an exponential tail,
478 * for example). It is safe for <ret_newmass> to point at
479 * <pmass>, in which case the suggested <pmass> will be overwritten
480 * with the actual mass upon return.
481 *
482 * This function defines that the binned data will be
483 * fitted either as a tail, or as a (virtually) left-censored dataset.
484 *
485 * Returns: <eslOK> on success.
486 */
487 int
488 esl_histogram_SetTailByMass(ESL_HISTOGRAM *h, double pmass, double *ret_newmass)
489 {
490 int b;
491 uint64_t sum = 0;
492
493 for (b = h->imax; b >= h->imin; b--)
494 {
495 sum += h->obs[b];
496 if (sum >= (pmass * (double)h->n)) break;
497 }
498
499 h->phi = esl_histogram_Bin2LBound(h,b);
500 h->z = h->n - sum;
501 h->cmin = b;
502 h->Nc = h->n; /* (redundant) */
503 h->No = h->n - h->z;
504 h->dataset_is = VIRTUAL_CENSORED;
505 h->is_done = TRUE;
506 if (ret_newmass != NULL) *ret_newmass = (double) h->No / (double) h->Nc;
507 return eslOK;
508 }
509
510
511
512 /*****************************************************************
513 * 3. Routines for accessing data samples in a full histogram.
514 *****************************************************************/
515
516 /* Function: esl_histogram_GetRank()
517 * Synopsis: Retrieve n'th high score.
518 *
519 * Purpose: Retrieve the <rank>'th highest score from a
520 * full histogram <h>. <rank> is <1..n>, for
521 * <n> total samples in the histogram; return it through
522 * <ret_x>.
523 *
524 * If the raw scores aren't sorted, they are sorted
525 * first (an $N \log N$ operation).
526 *
527 * This can be called at any time, even during data
528 * collection, to see the current <rank>'th highest score.
529 *
530 * Returns: <eslOK> on success.
531 *
532 * Throws: <eslEINVAL> if the histogram is display-only,
533 * or if <rank> isn't in the range 1..n.
534 */
535 int
536 esl_histogram_GetRank(ESL_HISTOGRAM *h, int rank, double *ret_x)
537 {
538 if (! h->is_full)
539 ESL_EXCEPTION(eslEINVAL,
540 "esl_histogram_GetRank() needs a full histogram");
541 if (rank > h->n)
542 ESL_EXCEPTION(eslEINVAL,
543 "no such rank: not that many scores in the histogram");
544 if (rank < 1)
545 ESL_EXCEPTION(eslEINVAL, "histogram rank must be a value from 1..n");
546
547 esl_histogram_sort(h); /* make sure */
548 *ret_x = h->x[h->n - rank];
549 return eslOK;
550 }
551
552 /* Function: esl_histogram_GetData()
553 * Synopsis: Retrieve vector of all raw scores.
554 *
555 * Purpose: Retrieve the raw data values from the histogram <h>.
556 * Return them in the vector <ret_x>, and the number
557 * of values in <ret_n>. The values are indexed <[0..n-1]>,
558 * from smallest to largest (<x[n-1]> is the high score).
559 *
560 * <ret_x> is a pointer to internal memory in the histogram <h>.
561 * The histogram <h> is still responsible for that storage;
562 * its memory will be free'd when you call
563 * <esl_histogram_Destroy()>.
564 *
565 * You can only call this after you have finished collecting
566 * all the data. Subsequent calls to <esl_histogram_Add()>
567 * will fail.
568 *
569 * Internal note:
570 * The prohibition against adding more data (by raising
571 * the h->is_done flag) is because we're passing a pointer
572 * to internal data storage back to the caller. Subsequent
573 * calls to Add() will modify that memory -- in the worst case,
574 * if Add() has to reallocate that storage, completely invalidating
575 * the pointer that the caller has a copy of. We want to make
576 * sure that the <ret_x> pointer stays valid.
577 *
578 * Args: h - histogram to retrieve data values from
579 * ret_x - RETURN: pointer to the data samples, [0..n-1]
580 * ret_n - RETURN: number of data samples
581 *
582 * Returns: <eslOK> on success.
583 *
584 * Throws: <eslEINVAL> if the histogram <h> is not a full histogram.
585 */
586 int
587 esl_histogram_GetData(ESL_HISTOGRAM *h, double **ret_x, int *ret_n)
588 {
589 if (! h->is_full) ESL_EXCEPTION(eslEINVAL, "not a full histogram");
590 esl_histogram_sort(h);
591
592 *ret_x = h->x;
593 *ret_n = h->n;
594
595 h->is_done = TRUE;
596 return eslOK;
597 }
598
599
600 /* Function: esl_histogram_GetTail()
601 * Synopsis: Retrieve all raw scores above some threshold.
602 *
603 * Purpose: Given a full histogram <h>, retrieve all data values
604 * above the threshold <phi> in the right (high scoring)
605 * tail, as a ptr <ret_x> to an array of <ret_n> values
606 * indexed <[0..n-1]> from lowest to highest score.
607 * Optionally, it also returns the number of values in
608 * rest of the histogram in <ret_z>;
609 * this number is useful if you are going to fit
610 * the tail as a left-censored distribution.
611 *
612 * The test is strictly greater than <phi>, not greater
613 * than or equal to.
614 *
615 * <ret_x> is a pointer to internal memory in the histogram <h>.
616 * The histogram <h> is still responsible for that storage;
617 * its memory will be free'd when you call
618 * <esl_histogram_Destroy()>.
619 *
620 * You can only call this after you have finished collecting
621 * all the data. Subsequent calls to <esl_histogram_Add()>
622 * will fail.
623 *
624 * Args: h - histogram to retrieve the tail from
625 * phi - threshold: tail is all scores > phi
626 * ret_x - optRETURN: ptr to vector of data values [0..n-1]
627 * ret_n - optRETURN: number of data values in tail
628 * ret_z - optRETURN: number of data values not in tail.
629 *
630 * Returns: <eslOK> on success.
631 *
632 * Throws: <eslEINVAL> if the histogram is not a full histogram.
633 */
634 int
635 esl_histogram_GetTail(ESL_HISTOGRAM *h, double phi,
636 double **ret_x, int *ret_n, int *ret_z)
637 {
638 int hi, lo, mid;
639
640 if (! h->is_full) ESL_EXCEPTION(eslEINVAL, "not a full histogram");
641 esl_histogram_sort(h);
642
643 if (h->n == 0) mid = h->n; /* we'll return NULL, 0, n */
644 else if (h->x[0] > phi) mid = 0; /* we'll return x, n, 0 */
645 else if (h->x[h->n-1] <= phi) mid = h->n; /* we'll return NULL, 0, n */
646 else /* binary search, faster than a brute force scan */
647 {
648 lo = 0;
649 hi = h->n-1; /* know hi>0, because above took care of n=0 and n=1 cases */
650 while (1) {
651 mid = (lo + hi + 1) / 2; /* +1 makes mid round up, mid=0 impossible */
652 if (h->x[mid] <= phi) lo = mid; /* we're too far left */
653 else if (h->x[mid-1] > phi) hi = mid; /* we're too far right */
654 else break; /* ta-da! */
655 }
656 }
657
658 if (ret_x != NULL) *ret_x = h->x + mid;
659 if (ret_n != NULL) *ret_n = h->n - mid;
660 if (ret_z != NULL) *ret_z = mid;
661 h->is_done = TRUE;
662 return eslOK;
663 }
664
665
666 /* Function: esl_histogram_GetTailByMass()
667 * Synopsis: Retrieve all raw scores in right tail mass.
668 *
669 * Purpose: Given a full histogram <h>, retrieve the data values in
670 * the right (high scoring) tail, as a pointer <ret_x>
671 * to an array of <ret_n> values indexed <[0..n-1]> from
672 * lowest to highest score. The tail is defined by a
673 * given mass fraction threshold <pmass>; the mass in the returned
674 * tail is $\leq$ this threshold. <pmass> is a probability,
675 * so it must be $\geq 0$ and $\leq 1$.
676 *
677 * Optionally, the number of values in the rest of the
678 * histogram can be returned in <ret_z>. This is useful
679 * if you are going to fit the tail as a left-censored
680 * distribution.
681 *
682 * <ret_x> is a pointer to internal memory in <h>.
683 * The histogram <h> remains responsible for its storage,
684 * which will be free'd when you call <esl_histogram_Destroy()>.
685 * As a consequence, you can only call
686 * <esl_histogram_GetTailByMass()> after you have finished
687 * collecting data. Subsequent calls to <esl_histogram_Add()>
688 * will fail.
689 *
690 * Args: h - histogram to retrieve the tail from
691 * pmass - fractional mass threshold; tail contains <= pmass
692 * ret_x - optRETURN: ptr to vector of data values [0..n-1]
693 * ret_n - optRETURN: number of data values in tail x
694 * ret_z - optRETURN: number of data values not in tail
695 *
696 * Returns: <eslOK> on success.
697 *
698 * Throws: <eslEINVAL> if the histogram is not a full histogram,
699 * or <pmass> is not a probability.
700 */
701 int
702 esl_histogram_GetTailByMass(ESL_HISTOGRAM *h, double pmass,
703 double **ret_x, int *ret_n, int *ret_z)
704 {
705 uint64_t n;
706
707 if (! h->is_full)
708 ESL_EXCEPTION(eslEINVAL, "not a full histogram");
709 if (pmass < 0. || pmass > 1.)
710 ESL_EXCEPTION(eslEINVAL, "pmass not a probability");
711
712 esl_histogram_sort(h);
713
714 n = (uint64_t) ((double) h->n * pmass); /* rounds down, guaranteeing <= pmass */
715
716 if (ret_x != NULL) *ret_x = h->x + (h->n - n);
717 if (ret_n != NULL) *ret_n = n;
718 if (ret_z != NULL) *ret_z = h->n - n;
719 h->is_done = TRUE;
720 return eslOK;
721 }
722
723
724
725
726
727 /*****************************************************************
728 * 4. Setting expected counts
729 *****************************************************************/
730
731 /* Function: esl_histogram_SetExpect()
732 * Synopsis: Set expected counts for complete distribution.
733 *
734 * Purpose: Given a histogram <h> containing some number of empirically
735 * observed binned counts, and a pointer to a function <(*cdf)()>
736 * that describes the expected cumulative distribution function
737 * (CDF) for the complete data, conditional on some parameters
738 * <params>; calculate the expected counts in each bin of the
739 * histogram, and hold that information internally in the structure.
740 *
741 * The caller provides a function <(*cdf)()> that calculates
742 * the CDF via a generic interface, taking only two
743 * arguments: a quantile <x> and a void pointer to whatever
744 * parameters it needs, which it will cast and interpret.
745 * The <params> void pointer to the given parameters is
746 * just passed along to the generic <(*cdf)()> function. The
747 * caller will probably implement this <(*cdf)()> function as
748 * a wrapper around its real CDF function that takes
749 * explicit (non-void-pointer) arguments.
750 *
751 * Returns: <eslOK> on success.
752 *
753 * Throws: <eslEMEM> on allocation failure; state of <h> is preserved.
754 */
755 int
756 esl_histogram_SetExpect(ESL_HISTOGRAM *h,
757 double (*cdf)(double x, void *params), void *params)
758 {
759 int i;
760 double ai,bi; /* ai < x <= bi : lower,upper bounds in bin */
761 int status;
762
763 if (h->expect == NULL)
764 ESL_ALLOC(h->expect, sizeof(double) * h->nb);
765
766 for (i = 0; i < h->nb; i++)
767 {
768 ai = esl_histogram_Bin2LBound(h, i);
769 bi = esl_histogram_Bin2UBound(h, i);
770
771 h->expect[i] = h->Nc * ( (*cdf)(bi, params) - (*cdf)(ai, params) );
772
773 if (h->emin == -1 && h->expect[i] > 0.) h->emin = i;
774 }
775
776 h->is_done = TRUE;
777 return eslOK;
778
779 ERROR:
780 return status;
781 }
782
783 /* Function: esl_histogram_SetExpectedTail()
784 * Synopsis: Set expected counts for right tail.
785 *
786 * Purpose: Given a histogram <h>, and a pointer to a generic function
787 * <(*cdf)()> that describes the expected cumulative
788 * distribution function for the right (high-scoring) tail
789 * starting at <base_val> (all expected <x> $>$ <base_val>) and
790 * containing a fraction <pmass> of the complete data
791 * distribution (<pmass> $\geq 0$ and $\leq 1$);
792 * set the expected binned counts for all complete bins
793 * $\geq$ <base_val>.
794 *
795 * If <base_val> falls within a bin, that bin is considered
796 * to be incomplete, and the next higher bin is the starting
797 * point.
798 *
799 * Args: h - finished histogram
800 * base_val - threshold for the tail: all expected x > base_val
801 * pmass - fractional mass in the tail: 0 <= pmass <= 1
802 * cdf - generic-interface CDF function describing the tail
803 * params - void pointer to parameters for (*cdf)()
804 *
805 * Returns: <eslOK> on success.
806 *
807 * Throws: <eslEMEM> on memory allocation failure.
808 * <eslERANGE> if <base_val> isn't a reasonable value within
809 * the histogram (it converts to a bin value outside
810 * integer range).
811 */
812 int
813 esl_histogram_SetExpectedTail(ESL_HISTOGRAM *h, double base_val, double pmass,
814 double (*cdf)(double x, void *params),
815 void *params)
816 {
817 int status;
818 int b;
819 double ai, bi;
820
821 if (h->expect == NULL) ESL_ALLOC(h->expect, sizeof(double) * h->nb);
822
823 if ((status = esl_histogram_Score2Bin(h, base_val, &(h->emin))) != eslOK) return status;
824 h->emin += 1;
825 esl_vec_DSet(h->expect, h->emin, 0.);
826
827 for (b = h->emin; b < h->nb; b++)
828 {
829 ai = esl_histogram_Bin2LBound(h, b);
830 bi = esl_histogram_Bin2UBound(h, b);
831 h->expect[b] = pmass * (double) h->Nc *
832 ( (*cdf)(bi, params) - (*cdf)(ai, params) );
833 }
834
835 h->tailbase = base_val;
836 h->tailmass = pmass;
837 h->is_tailfit = TRUE;
838 h->is_done = TRUE;
839 return eslOK;
840
841 ERROR:
842 return status;
843 }
844
845
846
847
848 /*****************************************************************
849 * 5. Output and display of binned data.
850 *****************************************************************/
851
852 /* Function: esl_histogram_Write()
853 * Synopsis: Write a "pretty" ASCII histogram to a stream.
854 *
855 * Purpose: Print a "prettified" display histogram <h> to a file
856 * pointer <fp>. Deliberately a look-and-feel clone of
857 * Bill Pearson's excellent FASTA output.
858 *
859 * Also displays expected binned counts, if they've been
860 * set.
861 *
862 * Display will only work well if the bin width (w) is 0.1
863 * or more, because the score labels are only shown to one
864 * decimal point.
865 *
866 * Args: fp - open file to print to (stdout works)
867 * h - histogram to print
868 *
869 * Returns: <eslOK> on success.
870 *
871 * Throws: <eslEWRITE> on any system write error, such as a
872 * filled disk.
873 */
874 int
875 esl_histogram_Write(FILE *fp, ESL_HISTOGRAM *h)
876 {
877 int i;
878 double x;
879 uint64_t maxbar;
880 int imode;
881 uint64_t units;
882 int num;
883 char buffer[81]; /* output line buffer */
884 int pos; /* position in output line buffer */
885 uint64_t lowcount, highcount;
886 int ilowbound, ihighbound;
887 int nlines;
888 int emptybins = 3;
889
890
891 /* Find out how we'll scale the histogram. We have 58 characters to
892 * play with on a standard 80-column terminal display: leading "%6.1f
893 * %6d %6d|" occupies 21 chars. Save the peak position, we'll use
894 * it later.
895 */
896 maxbar = 0;
897 imode = 0;
898 for (i = 0; i < h->nb; i++)
899 if (h->obs[i] > maxbar)
900 {
901 maxbar = h->obs[i]; /* max height */
902 imode = i;
903 }
904
905 /* Truncate histogram display on both sides, ad hoc fashion.
906 * Start from the peak; then move out until we see <emptybins> empty bins,
907 * and stop.
908 */
909 for (num = 0, ihighbound = imode; ihighbound < h->imax; ihighbound++)
910 {
911 if (h->obs[ihighbound] > 0) { num = 0; continue; } /* reset */
912 if (++num == emptybins) { break; } /* stop */
913 }
914 for (num = 0, ilowbound = imode; ilowbound > h->imin; ilowbound--)
915 {
916 if (h->obs[ilowbound] > 0) { num = 0; continue; } /* reset */
917 if (++num == emptybins) { break; } /* stop */
918 }
919
920 /* collect counts outside of bounds */
921 for (lowcount = 0, i = h->imin; i < ilowbound; i++)
922 lowcount += h->obs[i];
923 for (highcount = 0, i = h->imax; i > ihighbound; i--)
924 highcount += h->obs[i];
925
926 /* maxbar might need to be raised now; then set our units */
927 if (lowcount > maxbar) maxbar = lowcount;
928 if (highcount > maxbar) maxbar = highcount;
929
930 if (maxbar > 0) units = ((maxbar-1)/ 58) + 1;
931 else units = 1; /* watch out for an empty histogram w/ no data points. */
932
933 /* Print the histogram header
934 */
935 if (fprintf(fp, "%6s %6s %6s (one = represents %llu sequences)\n",
936 "score", "obs", "exp", (unsigned long long) units) < 0)
937 ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
938 if (fprintf(fp, "%6s %6s %6s\n", "-----", "---", "---") < 0)
939 ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
940
941 /* Print the histogram itself */
942 buffer[80] = '\0';
943 buffer[79] = '\n';
944 nlines = 0; /* Count the # of lines we print, so we know if it ends up being zero */
945 for (i = h->imin; i <= h->imax; i++)
946 {
947 memset(buffer, ' ', 79 * sizeof(char));
948 x = i*h->w + h->bmin;
949
950 /* Deal with special cases at edges
951 */
952 if (i < ilowbound) continue;
953 else if (i > ihighbound) continue;
954 else if (i == ilowbound && i != h->imin)
955 {
956 snprintf(buffer, 81, "<%5.1f %6llu %6s|", x+h->w, (unsigned long long) lowcount, "-"); // 81 is the buffer[81] static alloc
957 if (lowcount > 0) {
958 num = 1+(lowcount-1) / units;
959 for (pos = 21; num > 0; num--) buffer[pos++] = '=';
960 }
961 if (fputs(buffer, fp) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
962 nlines++;
963 continue;
964 }
965 else if (i == ihighbound && i != h->imax)
966 {
967 snprintf(buffer, 81, ">%5.1f %6llu %6s|", x, (unsigned long long) highcount, "-");
968 if (highcount > 0) {
969 num = 1+(highcount-1) / units;
970 for (pos = 21; num > 0; num--) buffer[pos++] = '=';
971 }
972 if (fputs(buffer, fp) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
973 nlines++;
974 continue;
975 }
976
977 /* Deal with most cases
978 */
979 if (h->obs[i] < 1000000) /* displayable in 6 figures or less? */
980 {
981 if (h->expect != NULL)
982 snprintf(buffer, 81, "%6.1f %6llu %6d|", x, (unsigned long long) h->obs[i], (int) h->expect[i]);
983 else
984 snprintf(buffer, 81, "%6.1f %6llu %6s|", x, (unsigned long long) h->obs[i], "-");
985 }
986 else
987 {
988 if (h->expect != NULL)
989 snprintf(buffer, 81, "%6.1f %6.2e %6.2e|", x, (double) h->obs[i], h->expect[i]);
990 else
991 snprintf(buffer, 81, "%6.1f %6.2e %6s|", x, (double) h->obs[i], "-");
992 }
993 buffer[21] = ' '; /* sprintf writes a null char; replace it */
994
995 /* Mark the histogram bar for observed hits
996 */
997 if (h->obs[i] > 0) {
998 num = 1 + (h->obs[i]-1) / units;
999 for (pos = 21; num > 0; num--) buffer[pos++] = '=';
1000 }
1001
1002 /* Mark the theoretically expected value
1003 * (The test > 0. also suffices to remove any censored region.)
1004 */
1005 if (h->expect != NULL && h->expect[i] > 0.)
1006 {
1007 pos = 21 + (int)(h->expect[i]-1) / units;
1008 if (pos >= 78) pos = 78; /* be careful of buffer bounds */
1009 buffer[pos] = '*';
1010 }
1011
1012 /* Print the line
1013 */
1014 if (fputs(buffer, fp) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
1015 nlines++;
1016 }
1017
1018 if (nlines == 0 && fprintf(fp, "[histogram contained no data points]\n") < 0)
1019 ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
1020
1021 return eslOK;
1022 }
1023
1024 /* Function: esl_histogram_Plot()
1025 * Synopsis: Output a histogram in xmgrace XY format.
1026 *
1027 * Purpose: Print observed (and expected, if set) binned counts
1028 * in a histogram <h> to open file pointer <fp>
1029 * in xmgrace XY input file format.
1030 *
1031 * The number that's plotted on the X axis is the minimum
1032 * (starting) value of the bin's interval. The Y value is
1033 * the total number of counts in the interval (x,x+w] for bin
1034 * width w. In xmgrace, you want to set "right stairs" as
1035 * the line type in an XY plot.
1036 *
1037 * Returns: <eslOK> on success.
1038 *
1039 * Throws: <eslEWRITE> on any system write error.
1040 */
1041 int
1042 esl_histogram_Plot(FILE *fp, ESL_HISTOGRAM *h)
1043 {
1044 int imin, imax;
1045 int i;
1046 double x;
1047
1048 /* First data set is the observed histogram
1049 */
1050 for (i = h->imin; i <= h->imax; i++)
1051 {
1052 x = esl_histogram_Bin2LBound(h,i);
1053 if (fprintf(fp, "%f %llu\n", x, (unsigned long long) h->obs[i]) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram plot write failed");
1054 }
1055 x = esl_histogram_Bin2LBound(h,i); /* Print a trailing y=0, needed to make xmgrace display the last bar */
1056 if (fprintf(fp, "%f %d\n", x, 0) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram plot write failed");
1057 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram plot write failed");
1058
1059
1060 /* Second data set is the theoretical (expected) histogram
1061 */
1062 if (h->expect != NULL)
1063 {
1064 for (imin = 0; imin < h->nb; imin++)
1065 if (h->expect[imin] > 0.) break;
1066 for (imax = h->nb-1; imax >= 0; imax--)
1067 if (h->expect[imax] > 0.) break;
1068
1069 for (i = imin; i <= imax; i++)
1070 {
1071 x = esl_histogram_Bin2LBound(h,i);
1072 if (fprintf(fp, "%f %g\n", x, h->expect[i]) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram plot write failed");
1073 }
1074 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram plot write failed");
1075 }
1076 return eslOK;
1077 }
1078
1079 /* Function: esl_histogram_PlotSurvival()
1080 * Synopsis: Output $P(X>x)$ in xmgrace XY format.
1081 *
1082 * Purpose: Given a histogram <h>, output the observed (and
1083 * expected, if available) survival function $P(X>x)$
1084 * to file pointer <fp> in xmgrace XY input file format.
1085 *
1086 * One point is plotted per bin, so the narrower the
1087 * bin width, the more smooth and accurate the resulting
1088 * plots will be.
1089 *
1090 * As a special case, always plot the highest score with
1091 * survival probability 1/N, if it occurred in a bin with
1092 * other samples. This is to prevent a survival plot from
1093 * looking like it was artificially truncated.
1094 *
1095 * Returns: <eslOK> on success.
1096 *
1097 * Throws: <eslEWRITE> on any system write error.
1098 */
1099 int
1100 esl_histogram_PlotSurvival(FILE *fp, ESL_HISTOGRAM *h)
1101 {
1102 int i;
1103 uint64_t c = 0;
1104 double esum;
1105 double ai;
1106
1107 /* The observed binned counts:
1108 */
1109 if (h->obs[h->imax] > 1)
1110 if (fprintf(fp, "%f\t%g\n", h->xmax, 1.0 / (double) h->Nc) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram survival plot write failed");
1111 for (i = h->imax; i >= h->imin; i--)
1112 {
1113 if (h->obs[i] > 0) {
1114 c += h->obs[i];
1115 ai = esl_histogram_Bin2LBound(h, i);
1116 if (fprintf(fp, "%f\t%g\n", ai, (double) c / (double) h->Nc) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram survival plot write failed");
1117 }
1118 }
1119 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram survival plot write failed");
1120
1121 /* The expected binned counts:
1122 */
1123 if (h->expect != NULL)
1124 {
1125 esum = 0.;
1126 for (i = h->nb-1; i >= 0; i--)
1127 {
1128 if (h->expect[i] > 0.) {
1129 esum += h->expect[i]; /* some worry about 1+eps=1 problem here */
1130 ai = esl_histogram_Bin2LBound(h, i);
1131 if (fprintf(fp, "%f\t%g\n", ai, esum / (double) h->Nc) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram survival plot write failed");
1132 }
1133 }
1134 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram survival plot write failed");
1135 }
1136 return eslOK;
1137 }
1138
1139 /* Function: esl_histogram_PlotQQ()
1140 * Synopsis: Output a Q-Q plot in xmgrace XY format.
1141 *
1142 * Purpose: Given a histogram <h> containing an empirically observed
1143 * distribution, and a pointer to a function <(*invcdf)()>
1144 * for an expected inverse cumulative distribution
1145 * function conditional on some parameters <params>;
1146 * output a Q-Q plot in xmgrace XY format to file <fp>.
1147 *
1148 * Same domain limits as goodness-of-fit testing: output
1149 * is restricted to overlap between observed data (excluding
1150 * any censored data) and expected data (which may be limited
1151 * if only a tail was fit).
1152 *
1153 * Returns: <eslOK> on success.
1154 *
1155 * Throws: <eslEWRITE> on any system write error.
1156 */
1157 int
1158 esl_histogram_PlotQQ(FILE *fp, ESL_HISTOGRAM *h,
1159 double (*invcdf)(double x, void *params), void *params)
1160 {
1161 int i;
1162 double cdf;
1163 double bi;
1164 int bbase;
1165 uint64_t sum;
1166
1167 /* on censored data, start counting observed cdf at z, not 0
1168 */
1169 if (h->dataset_is == TRUE_CENSORED || h->dataset_is == VIRTUAL_CENSORED)
1170 sum = h->z;
1171 else
1172 sum = 0;
1173
1174 /* Determine smallest bin included in goodness of fit eval
1175 */
1176 bbase = h->cmin;
1177 if (h->is_tailfit && h->emin > bbase) bbase = h->emin;
1178 for (i = h->cmin; i < bbase; i++) sum += h->obs[i];
1179
1180 /* The q-q plot:
1181 */
1182 for (i = bbase; i < h->imax; i++) /* avoid last bin where upper cdf=1.0 */
1183 {
1184 sum += h->obs[i];
1185 cdf = (double) sum / (double) h->Nc;
1186
1187 if (h->is_tailfit) cdf = (cdf + h->tailmass - 1.) / (h->tailmass);
1188
1189 bi = esl_histogram_Bin2UBound(h, i);
1190 if (fprintf(fp, "%f\t%f\n", bi, (*invcdf)(cdf, params)) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram QQ plot write failed");
1191 }
1192 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram QQ plot write failed");
1193
1194 /* Plot a 45-degree expected QQ line:
1195 */
1196 bi = esl_histogram_Bin2LBound(h, bbase);
1197 if (fprintf(fp, "%f\t%f\n", bi, bi) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram QQ plot write failed");
1198 if (fprintf(fp, "%f\t%f\n", h->xmax, h->xmax) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram QQ plot write failed");
1199 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram QQ plot write failed");
1200
1201 return eslOK;
1202 }
1203
1204
1205
1206 /* Function: esl_histogram_Goodness()
1207 * Synopsis: Evaluate fit between observed, expected.
1208 *
1209 * Purpose: Given a histogram <h> with observed and expected counts,
1210 * where, for the expected counts, <nfitted> ($\geq 0$)
1211 * parameters were fitted (and thus should be subtracted
1212 * from the degrees of freedom);
1213 * Perform a G-test and/or a $\chi^2$ test for goodness of
1214 * fit between observed and expected, and optionally return
1215 * the number of bins the data were sorted into
1216 * (<ret_bins>), the G statistic and its probability (<ret_G> and
1217 * <ret_Gp>), and the $\chi^2$ statistic and its probability
1218 * (<ret_X2> and <ret_X2p>).
1219 *
1220 * If a goodness-of-fit probability is less than some threshold
1221 * (usually taken to be 0.01 or 0.05), that is considered to
1222 * be evidence that the observed data are unlikely to be consistent
1223 * with the tested distribution.
1224 *
1225 * The two tests should give similar
1226 * probabilities. However, both tests are sensitive to
1227 * arbitrary choices in how the data are binned, and
1228 * neither seems to be on an entirely sound theoretical
1229 * footing.
1230 *
1231 * On some datasets, pathological and/or very small, it may
1232 * be impossible to calculate goodness of fit
1233 * statistics. In this case, <eslENORESULT> is returned.
1234 *
1235 * Returns: <eslOK> on success.
1236 *
1237 * <eslENORESULT> if the data are such that goodness-of-fit
1238 * statistics can't be calculated, probably because there
1239 * just aren't many data points. On this error, <*ret_G>
1240 * and <*ret_X2> are 0.0, and <*ret_Gp> and <*ret_X2p> are
1241 * 1.0. (Because suppose n=1: then any fit to a single data
1242 * point is "perfect".)
1243 *
1244 * Throws: <eslEINVAL> if expected counts have not been set in
1245 * the histogram; <eslERANGE> or <eslENOHALT> on different internal
1246 * errors that can arise in calculating the probabilities;
1247 * <eslEMEM> on internal allocation failure.
1248 */
1249 int
1250 esl_histogram_Goodness(ESL_HISTOGRAM *h,
1251 int nfitted, int *ret_nbins,
1252 double *ret_G, double *ret_Gp,
1253 double *ret_X2, double *ret_X2p)
1254 {
1255 uint64_t *obs = NULL; /* observed in bin i, [0..nb-1] */
1256 double *exp = NULL; /* expected in bin i, [0..nb-1] */
1257 double *topx = NULL; /* all values in bin i <= topx[i] */
1258 int nb; /* # of re-bins */
1259 uint64_t minc; /* minimum target # of counts/bin */
1260 int i,b;
1261 double G, Gp;
1262 double X2, X2p;
1263 double tmp;
1264 int status;
1265 int bbase;
1266 uint64_t hmax;
1267 uint64_t nobs;
1268 double nexp;
1269
1270 if (h->expect == NULL) ESL_EXCEPTION(eslEINVAL, "no expected counts in that histogram");
1271
1272 /* Determine the smallest histogram bin included in
1273 * the goodness of fit evaluation.
1274 */
1275 bbase = h->cmin;
1276 if (h->is_tailfit && h->emin > bbase) bbase = h->emin;
1277
1278 /* How many observed total counts are in the evaluated range,
1279 * and what is the maximum in any given histogram bin?
1280 */
1281 nobs = 0;
1282 hmax = 0;
1283 for (i = bbase; i <= h->imax; i++)
1284 {
1285 nobs += h->obs[i];
1286 if (h->obs[i] > hmax) hmax = h->obs[i];
1287 }
1288 if (nobs == 0) { status = eslENORESULT; goto ERROR; }
1289
1290 /* Figure out how many eval bins we'd like to have, then allocate
1291 * for re-binning.
1292 * Number of bins for goodness-of-fit tests like G and X^2
1293 * is crucial but arbitrary, unfortunately. Some literature suggests
1294 * using 2*n^{0.4}, which gives:
1295 * n nbins #/bin
1296 * ----- ------ ------
1297 * 1000 31 32
1298 * 10000 79 127
1299 * 100000 200 500
1300 * 1000000 502 1992
1301 *
1302 * The most important thing seems to be to get the # of counts
1303 * in each bin to be roughly equal.
1304 */
1305 nb = 2* (int) pow((double) nobs, 0.4); /* "desired" nb. */
1306 minc = 1 + nobs / (2*nb); /* arbitrarily set min = 1/2 of the target # */
1307 ESL_ALLOC(obs, sizeof(uint64_t) * (nb*2+1)); /* final nb must be <= 2*nb+1 */
1308 ESL_ALLOC(exp, sizeof(double) * (nb*2+1));
1309 ESL_ALLOC(topx, sizeof(double) * (nb*2+1));
1310
1311 /* Determine the observed counts in each bin: that is, partition
1312 * the <sum> in the evaluated region.
1313 * Sweep left to right on the histogram bins,
1314 * collecting sum of counts, dropping the sum into the next re-bin
1315 * whenever we have more than <minc> counts.
1316 */
1317 nobs = 0;
1318 nexp = 0.;
1319 for (i = 0, b = bbase; b <= h->imax; b++)
1320 {
1321 nobs += h->obs[b];
1322 nexp += h->expect[b];
1323
1324 /* if we have enough counts, drop into bin i: */
1325 if (nobs >= minc && nexp >= minc) {
1326 ESL_DASSERT1( (i < (nb*2+1)) );
1327 obs[i] = nobs;
1328 exp[i] = nexp;
1329 topx[i] = esl_histogram_Bin2UBound(h,b);
1330 nobs = 0;
1331 nexp = 0.;
1332 i++;
1333 }
1334 }
1335 if (i == 0) { status = eslENORESULT; goto ERROR; }
1336 obs[i-1] += nobs; /* add the right tail to final bin */
1337 exp[i-1] += nexp;
1338 topx[i-1] = esl_histogram_Bin2UBound(h, h->imax);
1339 nb = i; /* nb is now actual # of bins, not target */
1340
1341 /* We have to have at least one degree of freedom, else
1342 * goodness-of-fit testing isn't defined (and moreover, will
1343 * fail numerically if we proceed)
1344 */
1345 if (nb-nfitted-1 <= 0) { status = eslENORESULT; goto ERROR; }
1346
1347 /* Calculate the X^2 statistic: \sum (obs_i - exp_i)^2 / exp_i */
1348 X2 = 0.;
1349 for (i = 0; i < nb; i++)
1350 {
1351 tmp = (double) obs[i] - exp[i];
1352 X2 += tmp*tmp / exp[i];
1353 }
1354 /* X^2 is distributed approximately chi^2. */
1355 if (X2 == 0.)
1356 X2p = 1.0;
1357 else if (X2 != eslINFINITY) {
1358 if ((status = esl_stats_ChiSquaredTest(nb-nfitted, X2, &X2p)) != eslOK) goto ERROR;
1359 }
1360 else
1361 X2p = 0.;
1362
1363 /* The G test assumes that #exp=#obs (the X^2 test didn't).
1364 * If that's not true, renormalize to make it so.
1365 * This normalization subtracts a degree of freedom.
1366 */
1367 nobs = 0;
1368 nexp = 0.;
1369 for (i = 0; i < nb; i++)
1370 {
1371 nobs += obs[i];
1372 nexp += exp[i];
1373 }
1374 for (i = 0; i < nb; i++)
1375 exp[i] = exp[i] * (double) nobs / nexp;
1376
1377 /* Calculate the G statistic: 2 * LLR */
1378 G = 0.;
1379 for (i = 0; i < nb; i++)
1380 G += (double) obs[i] * log ((double) obs[i] / exp[i]);
1381 G *= 2;
1382
1383 /* G is distributed approximately as \chi^2.
1384 * -1 is because total #obs=#exp
1385 */
1386 if (G == 0.)
1387 Gp = 1.0;
1388 else if (G != eslINFINITY)
1389 {
1390 if ((status = esl_stats_ChiSquaredTest(nb-nfitted-1, G, &Gp)) != eslOK) goto ERROR;
1391 }
1392 else Gp = 0.;
1393
1394 if (ret_nbins) *ret_nbins = nb;
1395 if (ret_G) *ret_G = G;
1396 if (ret_Gp) *ret_Gp = Gp;
1397 if (ret_X2) *ret_X2 = X2;
1398 if (ret_X2p) *ret_X2p = X2p;
1399 free(obs);
1400 free(exp);
1401 free(topx);
1402 return eslOK;
1403
1404 ERROR:
1405 if (ret_nbins) *ret_nbins = 0;
1406 if (ret_G) *ret_G = 0.;
1407 if (ret_Gp) *ret_Gp = 1.;
1408 if (ret_X2) *ret_X2 = 0.;
1409 if (ret_X2p) *ret_X2p = 1.;
1410 if (obs) free(obs);
1411 if (exp) free(exp);
1412 if (topx) free(topx);
1413 return status;
1414 }
1415
1416 /*****************************************************************
1417 * 6. Test driver.
1418 *****************************************************************/
1419 #ifdef eslHISTOGRAM_TESTDRIVE
1420 /* compile:
1421 * gcc -g -Wall -I. -L. -o test -DeslHISTOGRAM_TESTDRIVE esl_histogram.c -leasel -lm
1422 * run:
1423 * ./test -t1; ./test -t2; ./test -t3; ./test -t4; ./test -t5
1424 *
1425 * -t1 - complete data, fit to complete Gumbel\n\
1426 * -t2 - complete data, high scores fit as censored Gumbel\n\
1427 * -t3 - complete data, high scores fit to exponential tail\n\
1428 * -t4 - censored data, fit as censored Gumbel\n\
1429 * -t5 - complete data, binned, high scores fit to exponential tail\n\
1430 *
1431 * Some suggestions for manual testing:
1432 * ./test -t1 -j1 -v --surv test.xy; xmgrace test.xy
1433 * examine survivor plot fit, for -t1
1434 * do -t2 thru -t5 too
1435 *
1436 * ./test -t1 --j1 -v -qq test.xy; xmgrace test.xy
1437 * examine QQ plot fit, for -t1
1438 * do -t2 thru -t5 too
1439 *
1440 * ./test -t1 -v > foo
1441 * grep "^Estimated" foo | awk '{print $9}' | sort -g > test.xy
1442 * Look for straight line fit to G-test p values.
1443 * sub $9->$13 for chi-squared
1444 * sub Estimated -> Parametric for the parametric fits
1445 */
1446 #include <stdio.h>
1447 #include <stdlib.h>
1448
1449 #include "easel.h"
1450 #include "esl_stats.h"
1451 #include "esl_gumbel.h"
1452 #include "esl_exponential.h"
1453 #include "esl_random.h"
1454 #include "esl_getopts.h"
1455
1456
1457
1458 static ESL_OPTIONS options[] = {
1459 /* name type default env_var range toggles reqs incompat */
1460 { "-j", eslARG_INT, "100", NULL, "n>0", NULL, NULL, NULL, "number of trials", 0 },
1461 { "-m", eslARG_INT, "0", NULL, "n>=0", NULL, NULL, NULL, "number of test samples", 0 },
1462 { "-n", eslARG_INT, "10000", NULL, "n>0", NULL, NULL, NULL, "number of training samples", 0 },
1463 { "-t", eslARG_INT, "1", NULL, "1<=n<=5", NULL, NULL, NULL, "test type choice, 1-5", 0 },
1464 { "-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "be verbose?", 0 },
1465 { "--ascii", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "output ASCII histogram to <f>", 0 },
1466 { "--cmass", eslARG_REAL, "0.7", NULL, "0<=x<=1", NULL, NULL, NULL, "set virtual censoring mass to <x>", 0 },
1467 { "--lambda", eslARG_REAL, "0.8", NULL, "x>0", NULL, NULL, NULL, "set Gumbel lambda param to <x>", 0 },
1468 { "--mu", eslARG_REAL, "10.0", NULL, NULL, NULL, NULL, NULL, "set Gumbel mu param to <x>", 0 },
1469 { "--phi", eslARG_REAL, "10.0", NULL, NULL, NULL, NULL, NULL, "set censoring threshold to <x>", 0 },
1470 { "--plot", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "output histogram to xmgrace file <f>", 0 },
1471 { "--qq", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "output Q-Q goodness of fit to xmgrace file <f>", 0 },
1472 { "--surv", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "output survival plot to xmgrace file <f>", 0 },
1473 { "--tail", eslARG_REAL, "0.1", NULL, "0<=x<=1", NULL, NULL, NULL, "set tail mass for fitting to <x>", 0 },
1474 { 0,0,0,0,0,0,0,0,0,0 },
1475 };
1476
1477 static void
1478 binmacro_utest(void)
1479 {
1480 char *msg = "esl_histogram: binmacro unit test failure";
1481 ESL_HISTOGRAM *h = esl_histogram_Create(-100, 100, 1.0);
1482 double trialx[3] = { -42.42, 0, 42.42 };
1483 double x, ai, bi;
1484 int i,b;
1485
1486 /* test bin<->score conversion macros.
1487 */
1488 for (i = 0; i < 3; i++)
1489 {
1490 x = trialx[i];
1491 esl_histogram_Score2Bin(h, x, &b);
1492 ai = esl_histogram_Bin2LBound(h, b);
1493 bi = esl_histogram_Bin2UBound(h, b);
1494 if (x <= ai || x > bi) esl_fatal(msg);
1495 }
1496 esl_histogram_Destroy(h);
1497 return;
1498 }
1499
1500 static void
1501 valuerange_utest(void)
1502 {
1503 char *msg = "esl_histogram: value range unit test failure";
1504 ESL_HISTOGRAM *h = esl_histogram_Create(-100, 100, 1.0);
1505 int b;
1506
1507 esl_exception_SetHandler(&esl_nonfatal_handler);
1508
1509 if (esl_histogram_Score2Bin(h, eslINFINITY, &b) != eslERANGE) esl_fatal(msg);
1510 if (esl_histogram_Score2Bin(h, -eslINFINITY, &b) != eslERANGE) esl_fatal(msg);
1511 if (esl_histogram_Score2Bin(h, eslNaN, &b) != eslERANGE) esl_fatal(msg);
1512 if (esl_histogram_Score2Bin(h, 1e20, &b) != eslERANGE) esl_fatal(msg);
1513 if (esl_histogram_Score2Bin(h, -1e20, &b) != eslERANGE) esl_fatal(msg);
1514
1515 esl_exception_ResetDefaultHandler();
1516 esl_histogram_Destroy(h);
1517 return;
1518 }
1519
1520 int
1521 main(int argc, char **argv)
1522 {
1523 ESL_GETOPTS *go;
1524 ESL_RANDOMNESS *r;
1525 ESL_HISTOGRAM *h;
1526 ESL_HISTOGRAM *h1;
1527 double p[2]; /* parametric mu, lambda */
1528 double ep[2]; /* estimated mu, lambda */
1529 double avg_ep[2]; /* average estimated mu, lambda over many trials */
1530 int ntrials, trial;
1531 int ntrain, ntest;
1532 int test_type;
1533 enum { COLLECT_COMPLETE, COLLECT_CENSORED } cstrategy;
1534 enum { FIT_BINNED, FIT_SAMPLES } bstrategy;
1535 enum { FIT_COMPLETE, FIT_CENSORED, FIT_TAIL} fstrategy;
1536 double phi; /* censoring threshold */
1537 int z;
1538 double cmass;
1539 double tailmass, save_tailmass;
1540 int nfitted;
1541 int nbins;
1542 double G, Gp, X2, X2p, minGp, minX2p;
1543 int verbose;
1544 FILE *outfp;
1545 char *ascfile, *plotfile, *survfile, *qqfile;
1546 int i;
1547 double x;
1548 double *xv;
1549 int n;
1550
1551 go = esl_getopts_Create(options);
1552 esl_opt_ProcessCmdline(go, argc, argv);
1553 test_type = esl_opt_GetInteger(go, "-t");
1554 ntrials = esl_opt_GetInteger(go, "-j");
1555 ntrain = esl_opt_GetInteger(go, "-n");
1556 ntest = esl_opt_GetInteger(go, "-m");
1557 verbose = esl_opt_GetBoolean(go, "-v");
1558 cmass = esl_opt_GetReal (go, "--cmass");
1559 p[1] = esl_opt_GetReal (go, "--lambda");
1560 p[0] = esl_opt_GetReal (go, "--mu");
1561 phi = esl_opt_GetReal (go, "--phi");
1562 save_tailmass = esl_opt_GetReal (go, "--tail");
1563 ascfile = esl_opt_GetString (go, "--ascii");
1564 plotfile = esl_opt_GetString (go, "--plot");
1565 qqfile = esl_opt_GetString (go, "--qq");
1566 survfile = esl_opt_GetString (go, "--surv");
1567 esl_getopts_Destroy(go);
1568
1569 r = esl_randomness_Create(42);
1570 avg_ep[0] = 0.;
1571 avg_ep[1] = 0.;
1572 minGp = 1.;
1573 minX2p = 1.;
1574 tailmass = save_tailmass;
1575
1576 if (test_type == 1)
1577 {
1578 cstrategy = COLLECT_COMPLETE;
1579 bstrategy = FIT_SAMPLES;
1580 fstrategy = FIT_COMPLETE;
1581 }
1582 else if (test_type == 2)
1583 {
1584 cstrategy = COLLECT_COMPLETE;
1585 bstrategy = FIT_SAMPLES;
1586 fstrategy = FIT_CENSORED;
1587 }
1588 else if (test_type == 3)
1589 {
1590 cstrategy = COLLECT_COMPLETE;
1591 bstrategy = FIT_SAMPLES;
1592 fstrategy = FIT_TAIL;
1593 }
1594 else if (test_type == 4)
1595 {
1596 cstrategy = COLLECT_CENSORED;
1597 bstrategy = FIT_SAMPLES;
1598 fstrategy = FIT_CENSORED;
1599 }
1600 else if (test_type == 5)
1601 {
1602 cstrategy = COLLECT_COMPLETE;
1603 bstrategy = FIT_BINNED;
1604 fstrategy = FIT_TAIL;
1605 }
1606 else
1607 esl_fatal("no such test type");
1608
1609
1610 for (trial = 0; trial < ntrials; trial++)
1611 {
1612 /* Collection of the training data in <h>.
1613 * Data set can either be complete, true censored, or virtual censored.
1614 */
1615 h = esl_histogram_CreateFull(-100, 100, 0.1);
1616 z = 0;
1617 for (i = 0; i < ntrain; i++) {
1618 x = esl_gumbel_Sample(r, p[0], p[1]);
1619 if (cstrategy != COLLECT_CENSORED || x > phi)
1620 esl_histogram_Add(h, x);
1621 else
1622 z++;
1623 }
1624 if (cstrategy == COLLECT_CENSORED)
1625 esl_histogram_DeclareCensoring(h, z, phi);
1626
1627 /* Parameter fitting.
1628 * We test for four of twelve possible combinations of
1629 * collection strategy, binned vs. raw data, and complete,
1630 * censored, vs. tail fitting.
1631 * 1. complete Gumbel data, raw, fit to a Gumbel.
1632 * 2. complete Gumbel data, raw, tail fit as a censored Gumbel
1633 * 3. complete Gumbel data, raw, tail fit to an exponential tail
1634 * 4. censored Gumbel data, raw, censored fit to a Gumbel
1635 * 5 complete Gumbel data, binned, fit to an exponential tail.
1636 */
1637 if (cstrategy == COLLECT_COMPLETE &&
1638 bstrategy == FIT_SAMPLES &&
1639 fstrategy == FIT_COMPLETE)
1640 {
1641 esl_histogram_GetData(h, &xv, &n);
1642 if (esl_gumbel_FitComplete(xv, n, &(ep[0]), &ep[1]) != eslOK) esl_fatal("gumbel complete fit failed");
1643 }
1644 else if (cstrategy == COLLECT_COMPLETE &&
1645 bstrategy == FIT_SAMPLES &&
1646 fstrategy == FIT_CENSORED)
1647 {
1648 esl_histogram_GetTailByMass(h, cmass, &xv, &n, &z);
1649 if (esl_gumbel_FitCensored(xv, n, z, xv[0], &(ep[0]), &ep[1]) != eslOK) esl_fatal("gumbel censored fit failed");
1650 }
1651 else if (cstrategy == COLLECT_COMPLETE &&
1652 bstrategy == FIT_SAMPLES &&
1653 fstrategy == FIT_TAIL)
1654 {
1655 esl_histogram_GetTailByMass(h, tailmass, &xv, &n, &z);
1656 if (esl_exp_FitComplete(xv, n, &(ep[0]), &ep[1]) != eslOK) esl_fatal("exponential complete fit failed");
1657 }
1658 else if (cstrategy == COLLECT_CENSORED &&
1659 bstrategy == FIT_SAMPLES &&
1660 fstrategy == FIT_CENSORED)
1661 {
1662 esl_histogram_GetData(h, &xv, &n);
1663 if (esl_gumbel_FitCensored(xv, n, h->z, h->phi, &(ep[0]), &ep[1]) != eslOK) esl_fatal("gumbel censored fit failed");
1664 }
1665 else if (cstrategy == COLLECT_COMPLETE &&
1666 bstrategy == FIT_BINNED &&
1667 fstrategy == FIT_TAIL)
1668 {
1669 tailmass = save_tailmass; /* reset to original for each trial. */
1670 esl_histogram_SetTailByMass(h, tailmass, &tailmass);
1671 if (esl_exp_FitCompleteBinned(h, &(ep[0]), &ep[1]) != eslOK) esl_fatal("exponential binned complete fit failed");
1672 }
1673 else
1674 ESL_EXCEPTION(eslEINVAL, "not a scenario we currently test");
1675
1676 /* Keep track of average estimated mu, lambda
1677 * for automated testing purposes.
1678 */
1679 avg_ep[0] += ep[0] / (double) ntrials;
1680 avg_ep[1] += ep[1] / (double) ntrials;
1681
1682 /* Test data can either be the same as the training data,
1683 * or a new test set.
1684 */
1685 if (ntest > 0)
1686 {
1687 h1 = esl_histogram_CreateFull(-100.05, 100.05, 0.2);
1688 z = 0;
1689 for (i = 0; i < ntest; i++) {
1690 x = esl_gumbel_Sample(r, p[0], p[1]);
1691 if (cstrategy != COLLECT_CENSORED || x > phi)
1692 esl_histogram_Add(h1, x);
1693 else
1694 z++;
1695 }
1696 if (cstrategy == COLLECT_CENSORED)
1697 esl_histogram_DeclareCensoring(h, z, phi);
1698 }
1699 else h1 = h;
1700
1701
1702 /* Set expected binned counts in the test data, h1:
1703 */
1704 if (fstrategy == FIT_TAIL)
1705 esl_histogram_SetExpectedTail(h1, ep[0], tailmass,
1706 &esl_exp_generic_cdf, ep);
1707 else
1708 esl_histogram_SetExpect(h1, &esl_gumbel_generic_cdf, ep);
1709
1710
1711 /* Evaluate goodness-of-fit
1712 */
1713 nfitted = (ntest == 0)? 2 : 0;
1714 if (esl_histogram_Goodness(h1, nfitted, &nbins, &G, &Gp, &X2, &X2p) != eslOK)
1715 esl_fatal("esl_histogram unit testing: goodness-of-fit failed");
1716
1717 /* Track minimum goodness of fit probs, for automated testing
1718 */
1719 if (Gp < minGp) minGp = Gp;
1720 if (X2p < minX2p) minX2p = X2p;
1721
1722 if (verbose)
1723 printf("Estimated: %6.2f %6.4f nb %4d G %g\tGp %g\tX2 %g\tX2p %g\n",
1724 ep[0], ep[1], nbins, G, Gp, X2, X2p);
1725
1726 /* Output files, if requested.
1727 * (Best if ntrials=1. Will overwrite previous trials.)
1728 */
1729 if (ascfile != NULL)
1730 {
1731 outfp = fopen(ascfile, "w");
1732 esl_histogram_Write(outfp, h1);
1733 fclose(outfp);
1734 }
1735 if (plotfile != NULL)
1736 {
1737 outfp = fopen(plotfile, "w");
1738 esl_histogram_Plot(outfp, h1);
1739 fclose(outfp);
1740 }
1741 if (survfile != NULL)
1742 {
1743 outfp = fopen(survfile, "w");
1744 esl_histogram_PlotSurvival(outfp, h1);
1745 fclose(outfp);
1746 }
1747 if (qqfile != NULL)
1748 {
1749 outfp = fopen(qqfile, "w");
1750 if (fstrategy == FIT_TAIL)
1751 esl_histogram_PlotQQ(outfp, h1, &esl_exp_generic_invcdf, ep);
1752 else
1753 esl_histogram_PlotQQ(outfp, h1, &esl_gumbel_generic_invcdf, ep);
1754 fclose(outfp);
1755 }
1756
1757 esl_histogram_Destroy(h);
1758 if (ntest > 0) esl_histogram_Destroy(h1);
1759 }
1760
1761 /* Trap badness in an automated test.
1762 */
1763 if (fstrategy != FIT_TAIL && fabs(avg_ep[0] - p[0]) > 0.1)
1764 ESL_EXCEPTION(eslFAIL, "Something awry with Gumbel mu fit");
1765 if (fabs(avg_ep[1] - p[1]) > 0.1)
1766 ESL_EXCEPTION(eslFAIL, "Something awry with lambda fit");
1767 if (minGp < 1. / (1000. * ntrials))
1768 ESL_EXCEPTION(eslFAIL, "Something awry with G-test");
1769 if (minX2p < 1. / (1000. * ntrials))
1770 ESL_EXCEPTION(eslFAIL, "Something awry with chi squared test");
1771
1772 /* Smaller final tests
1773 */
1774 binmacro_utest();
1775 valuerange_utest();
1776
1777 esl_randomness_Destroy(r);
1778 return 0;
1779 }
1780 #endif /*eslHISTOGRAM_TESTDRIVE*/
1781
1782
1783
1784 /*****************************************************************
1785 * 7. Examples
1786 *****************************************************************/
1787
1788 /*****************************************************************
1789 * Five example main()'s for five use cases:
1790 * - complete data, fit to complete Gumbel
1791 * - complete data, high scores fit as censored Gumbel
1792 * - complete data, high scores fit to exponential tail
1793 * - censored data, fit as censored Gumbel
1794 * - complete data, binned, high scores fit to exponential tail
1795 *
1796 * (These same five cases are tested by ./test -t1 through ./test -t5.)
1797 *****************************************************************/
1798 /* Case 1. Complete data fit to complete Gumbel.
1799 * compile: gcc -I. -L. -o example -DeslHISTOGRAM_EXAMPLE esl_histogram.c -leasel -lm
1800 * run: ./example
1801 */
1802 #ifdef eslHISTOGRAM_EXAMPLE
1803 /*::cexcerpt::histogram_example::begin::*/
1804 #include "easel.h"
1805 #include "esl_random.h"
1806 #include "esl_histogram.h"
1807 #include "esl_gumbel.h"
1808
1809 int
1810 main(int argc, char **argv)
1811 {
1812 ESL_RANDOMNESS *r = esl_randomness_Create(0);
1813 ESL_HISTOGRAM *h = esl_histogram_CreateFull(-100, 100, 0.2);
1814 int nsamples = 10000;
1815 double mu = 10.0;
1816 double lambda = 0.8;
1817 double params[2];
1818 int i;
1819 double x;
1820 double *xv;
1821 int n;
1822 double G, Gp, X2, X2p;
1823
1824 for (i = 0; i < nsamples; i++) {
1825 x = esl_gumbel_Sample(r, mu, lambda);
1826 esl_histogram_Add(h, x);
1827 }
1828
1829 esl_histogram_GetData(h, &xv, &n);
1830 if (esl_gumbel_FitComplete(xv, n, &mu, &lambda) != eslOK)
1831 esl_fatal("gumbel complete data fit failed");
1832
1833 params[0] = mu;
1834 params[1] = lambda;
1835 esl_histogram_SetExpect(h, &esl_gumbel_generic_cdf, &params);
1836
1837 esl_histogram_Write(stdout, h);
1838 if (esl_histogram_Goodness(h, 0, NULL, &G, &Gp, &X2, &X2p) != eslOK)
1839 esl_fatal("goodness of fit testing failed");
1840
1841 printf("G = %f p = %f\n", G, Gp);
1842 printf("X^2 = %f p = %f\n", X2, X2p);
1843
1844 esl_histogram_Destroy(h);
1845 esl_randomness_Destroy(r);
1846 return 0;
1847 }
1848 /*::cexcerpt::histogram_example::end::*/
1849 #endif /*eslHISTOGRAM_EXAMPLE*/
1850
1851
1852
1853 /* Case 2. complete data, high scores fit as censored Gumbel
1854 * compile: gcc -I. -L. -o example -DeslHISTOGRAM_EXAMPLE2 esl_histogram.c -leasel -lm
1855 * run: ./example
1856 */
1857 #ifdef eslHISTOGRAM_EXAMPLE2
1858 /*::cexcerpt::histogram_example2::begin::*/
1859 #include "easel.h"
1860 #include "esl_random.h"
1861 #include "esl_histogram.h"
1862 #include "esl_gumbel.h"
1863
1864 int
1865 main(int argc, char **argv)
1866 {
1867 ESL_RANDOMNESS *r = esl_randomness_Create(0);
1868 ESL_HISTOGRAM *h = esl_histogram_CreateFull(-100, 100, 0.2);
1869 int nsamples = 10000;
1870 double mu = 10.0;
1871 double lambda = 0.8;
1872 double params[2];
1873 int i;
1874 double x;
1875 double *xv;
1876 int n, z;
1877 double G, Gp, X2, X2p;
1878
1879 for (i = 0; i < nsamples; i++) {
1880 x = esl_gumbel_Sample(r, mu, lambda);
1881 esl_histogram_Add(h, x);
1882 }
1883
1884 esl_histogram_GetTailByMass(h, 0.5, &xv, &n, &z); /* fit to right 50% */
1885 if (esl_gumbel_FitCensored(xv, n, z, xv[0], &mu, &lambda) != eslOK)
1886 esl_fatal("gumbel censored fit failed");
1887
1888 params[0] = mu;
1889 params[1] = lambda;
1890 esl_histogram_SetExpect(h, &esl_gumbel_generic_cdf, &params);
1891
1892 esl_histogram_Write(stdout, h);
1893 if (esl_histogram_Goodness(h, 0, NULL, &G, &Gp, &X2, &X2p) != eslOK)
1894 esl_fatal("goodness of fit testing failed");
1895
1896 printf("G = %f p = %f\n", G, Gp);
1897 printf("X^2 = %f p = %f\n", X2, X2p);
1898
1899 esl_histogram_Destroy(h);
1900 esl_randomness_Destroy(r);
1901 return 0;
1902 }
1903 /*::cexcerpt::histogram_example2::end::*/
1904 #endif /*eslHISTOGRAM_EXAMPLE2*/
1905
1906
1907 /* Case 3. complete data, high scores fit to exponential tail
1908 * compile: gcc -I. -L. -o example -DeslHISTOGRAM_EXAMPLE3 esl_histogram.c -leasel -lm
1909 * run: ./example
1910 */
1911 #ifdef eslHISTOGRAM_EXAMPLE3
1912 /*::cexcerpt::histogram_example3::begin::*/
1913 #include "easel.h"
1914 #include "esl_random.h"
1915 #include "esl_histogram.h"
1916 #include "esl_gumbel.h"
1917 #include "esl_exponential.h"
1918
1919 int
1920 main(int argc, char **argv)
1921 {
1922 ESL_RANDOMNESS *r = esl_randomness_Create(0);
1923 ESL_HISTOGRAM *h = esl_histogram_CreateFull(-100, 100, 0.2);
1924 int nsamples = 10000;
1925 double mu = 10.0;
1926 double lambda = 0.8;
1927 double params[2];
1928 int i;
1929 double x;
1930 double *xv;
1931 int n;
1932 double G, Gp, X2, X2p;
1933
1934 for (i = 0; i < nsamples; i++) {
1935 x = esl_gumbel_Sample(r, mu, lambda);
1936 esl_histogram_Add(h, x);
1937 }
1938
1939 esl_histogram_GetTailByMass(h, 0.1, &xv, &n, NULL); /* fit to 10% tail */
1940 esl_exp_FitComplete(xv, n, &mu, &lambda);
1941
1942 params[0] = mu;
1943 params[1] = lambda;
1944 esl_histogram_SetExpectedTail(h, mu, 0.1, &esl_exp_generic_cdf, &params);
1945
1946 esl_histogram_Write(stdout, h);
1947 if (esl_histogram_Goodness(h, 0, NULL, &G, &Gp, &X2, &X2p) != eslOK)
1948 esl_fatal("goodness of fit testing failed");
1949
1950 printf("G = %f p = %f\n", G, Gp);
1951 printf("X^2 = %f p = %f\n", X2, X2p);
1952
1953 esl_histogram_Destroy(h);
1954 esl_randomness_Destroy(r);
1955 return 0;
1956 }
1957 /*::cexcerpt::histogram_example3::end::*/
1958 #endif /*eslHISTOGRAM_EXAMPLE3*/
1959
1960 /* Case 4. censored data, high scores fit as a censored Gumbel tail
1961 * compile:
1962 gcc -I. -L. -o example -DeslHISTOGRAM_EXAMPLE4 esl_histogram.c -leasel -lm
1963 * run: ./example
1964 */
1965 #ifdef eslHISTOGRAM_EXAMPLE4
1966 /*::cexcerpt::histogram_example4::begin::*/
1967 #include "easel.h"
1968 #include "esl_random.h"
1969 #include "esl_histogram.h"
1970 #include "esl_gumbel.h"
1971
1972 int
1973 main(int argc, char **argv)
1974 {
1975 ESL_RANDOMNESS *r = esl_randomness_Create(0);
1976 ESL_HISTOGRAM *h = esl_histogram_CreateFull(-100, 100, 0.2);
1977 int nsamples = 10000;
1978 double mu = 10.0;
1979 double lambda = 0.8;
1980 double phi = 9.0;
1981 double params[2];
1982 int i;
1983 double x;
1984 double *xv;
1985 int n, z;
1986 double G, Gp, X2, X2p;
1987
1988 z = 0;
1989 for (i = 0; i < nsamples; i++) {
1990 x = esl_gumbel_Sample(r, mu, lambda);
1991 if (x > phi) esl_histogram_Add(h, x);
1992 else z++;
1993 }
1994
1995 esl_histogram_GetData(h, &xv, &n);
1996 if (esl_gumbel_FitCensored(xv, n, z, phi, &mu, &lambda) != eslOK)
1997 esl_fatal("gumbel censored fit failed");
1998
1999 params[0] = mu;
2000 params[1] = lambda;
2001 esl_histogram_SetExpect(h, &esl_gumbel_generic_cdf, &params);
2002
2003 esl_histogram_Write(stdout, h);
2004 if (esl_histogram_Goodness(h, 0, NULL, &G, &Gp, &X2, &X2p) != eslOK)
2005 esl_fatal("goodness of fit testing failed");
2006
2007 printf("G = %f p = %f\n", G, Gp);
2008 printf("X^2 = %f p = %f\n", X2, X2p);
2009
2010 esl_histogram_Destroy(h);
2011 esl_randomness_Destroy(r);
2012 return 0;
2013 }
2014 /*::cexcerpt::histogram_example4::end::*/
2015 #endif /*eslHISTOGRAM_EXAMPLE4*/
2016
2017 /* Case 5. complete data, binned high scores fit to exponential tail
2018 * compile:
2019 gcc -I. -L. -o example -DeslHISTOGRAM_EXAMPLE5 esl_histogram.c -leasel -lm
2020 * run: ./example
2021 */
2022 #ifdef eslHISTOGRAM_EXAMPLE5
2023 /*::cexcerpt::histogram_example5::begin::*/
2024 #include "easel.h"
2025 #include "esl_random.h"
2026 #include "esl_histogram.h"
2027 #include "esl_gumbel.h"
2028 #include "esl_exponential.h"
2029
2030 int
2031 main(int argc, char **argv)
2032 {
2033 ESL_RANDOMNESS *r = esl_randomness_Create(0);
2034 ESL_HISTOGRAM *h = esl_histogram_Create(-100, 100, 1.0);
2035 int nsamples = 10000;
2036 double mu = 10.0;
2037 double lambda = 0.8;
2038 double params[2];
2039 int i;
2040 double x;
2041 double actual_mass;
2042 double G, Gp, X2, X2p;
2043
2044 for (i = 0; i < nsamples; i++) {
2045 x = esl_gumbel_Sample(r, mu, lambda);
2046 x = ceil(x); /* crudely simulate an x of limited precision */
2047 esl_histogram_Add(h, x);
2048 }
2049
2050 esl_histogram_SetTailByMass(h, 0.1, &actual_mass);
2051 esl_histogram_DeclareRounding(h);
2052 if (esl_exp_FitCompleteBinned(h, &mu, &lambda) != eslOK)
2053 esl_fatal("exponential ML fitting failed");
2054
2055 params[0] = mu;
2056 params[1] = lambda;
2057 esl_histogram_SetExpectedTail(h, mu, actual_mass, &esl_exp_generic_cdf, &params);
2058
2059 esl_histogram_Write(stdout, h);
2060 if (esl_histogram_Goodness(h, 0, NULL, &G, &Gp, &X2, &X2p) != eslOK)
2061 esl_fatal("goodness of fit testing failed");
2062
2063 printf("G = %f p = %f\n", G, Gp);
2064 printf("X^2 = %f p = %f\n", X2, X2p);
2065
2066 esl_histogram_Destroy(h);
2067 esl_randomness_Destroy(r);
2068 return 0;
2069 }
2070 /*::cexcerpt::histogram_example5::end::*/
2071 #endif /*eslHISTOGRAM_EXAMPLE5*/
2072
2073
2074