-
Notifications
You must be signed in to change notification settings - Fork 27
/
esl_histogram.c
2074 lines (1853 loc) · 69 KB
/
esl_histogram.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Collecting and displaying histograms.
*
* 1. Creating/destroying histograms and collecting data.
* 2. Declarations about the binned data before parameter fitting.
* 3. Routines for accessing data samples in a full histogram.
* 4. Setting expected counts
* 5. Output and display of binned data.
* 6. Test driver.
* 7. Examples.
*/
#include <esl_config.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include "easel.h"
#include "esl_stats.h"
#include "esl_vectorops.h"
#include "esl_histogram.h"
static int esl_histogram_sort(ESL_HISTOGRAM *h);
/*****************************************************************
* 1. Creating/destroying histograms and collecting data.
*****************************************************************/
/* Function: esl_histogram_Create()
* Synopsis: Create a new <ESL_HISTOGRAM>.
*
* Purpose: Creates and returns a new histogram object, initially
* allocated to count values $>$ <bmin> and $<=$ <bmax> into
* bins of width <w>. Thus, a total of <bmax>-<bmin>/<w> bins
* are initially created.
*
* The lower bound <bmin> and the width <w> permanently
* determine the offset and width of the binning, but not
* the range. For example, <esl_histogram_Create(-100,
* 100, 0.5)> would initialize the object to collect scores into
* 400 bins $[-100< x \leq -99.5],[-99.5 < x \leq
* -99.0]...[99.5 <x \leq 100.0]$. Aside from this, the
* range specified by the bounds <bmin> and <bmax> only
* needs to be an initial guess. The histogram object will
* reallocate itself dynamically as needed to accommodate
* scores that exceed current bounds.
*
* You can be sloppy about <bmax>; it does not have to
* exactly match a bin upper bound. The initial allocation
* is for all full-width bins with upper bounds $\leq
* bmax$.
*
* <esl_histogram_Create()> creates a simplified histogram
* object that collates only the "display" histogram. For
* a more complex object that also keeps the raw data samples,
* better suited for fitting distributions and goodness-of-fit
* testing, use <esl_histogram_CreateFull()>.
*
* There is currently no way to alter where the equals sign
* is, in setting the bin bounds: that is, you can't make bins
* that have <bmin> $\leq x$ and $x <$ <bmax>, alas.
*
* Args: bmin - caller guesses that minimum score will be > bmin
* bmax - caller guesses that max score will be <= bmax
* w - size of bins (1.0, for example)
*
* Returns: ptr to new <ESL_HISTOGRAM> object, which caller is responsible
* for free'ing with <esl_histogram_Destroy()>.
*
* Throws: <NULL> on allocation failure.
*/
ESL_HISTOGRAM *
esl_histogram_Create(double bmin, double bmax, double w)
{
ESL_HISTOGRAM *h = NULL;
int status;
int i;
ESL_ALLOC(h, sizeof(ESL_HISTOGRAM));
h->xmin = DBL_MAX; /* xmin/xmax are the observed min/max */
h->xmax = -DBL_MAX;
h->n = 0;
h->obs = NULL; /* will get allocated below... */
h->bmin = bmin; /* bmin/bmax are the allocated bounds */
h->bmax = bmax;
h->nb = (int)((bmax-bmin)/w);
h->imin = h->nb;
h->imax = -1;
h->w = w;
h->x = NULL;
h->nalloc = 0;
h->phi = 0.;
h->cmin = h->imin; /* sentinel: no observed data yet */
h->z = 0;
h->Nc = 0;
h->No = 0;
h->expect = NULL; /* 'til a Set*() call */
h->emin = -1; /* sentinel: no expected counts yet */
h->tailbase = 0.; /* unused unless is_tailfit TRUE */
h->tailmass = 1.0; /* <= 1.0 if is_tailfit TRUE */
h->is_full = FALSE;
h->is_done = FALSE;
h->is_sorted = FALSE;
h->is_tailfit = FALSE;
h->is_rounded = FALSE;
h->dataset_is = COMPLETE;
ESL_ALLOC(h->obs, sizeof(uint64_t) * h->nb);
for (i = 0; i < h->nb; i++) h->obs[i] = 0;
return h;
ERROR:
esl_histogram_Destroy(h);
return NULL;
}
/* Function: esl_histogram_CreateFull()
* Synopsis: A <ESL_HISTOGRAM> to keep all data samples.
*
* Purpose: Alternative form of <esl_histogram_Create()> that
* creates a more complex histogram that will contain not just the
* display histogram, but also keeps track of all
* the raw sample values. Having a complete vector of raw
* samples improves distribution-fitting and goodness-of-fit
* tests, but will consume more memory.
*/
ESL_HISTOGRAM *
esl_histogram_CreateFull(double bmin, double bmax, double w)
{
int status;
ESL_HISTOGRAM *h = esl_histogram_Create(bmin, bmax, w);
if (h == NULL) return NULL;
h->n = 0; /* make sure */
h->nalloc = 128; /* arbitrary initial allocation size */
ESL_ALLOC(h->x, sizeof(double) * h->nalloc);
h->is_full = TRUE;
return h;
ERROR:
esl_histogram_Destroy(h);
return NULL;
}
/* Function: esl_histogram_Destroy()
* Synopsis: Frees a <ESL_HISTOGRAM>.
*
* Purpose: Frees an <ESL_HISTOGRAM> object <h>.
*/
void
esl_histogram_Destroy(ESL_HISTOGRAM *h)
{
if (h == NULL) return;
if (h->x != NULL) free(h->x);
if (h->obs != NULL) free(h->obs);
if (h->expect != NULL) free(h->expect);
free(h);
return;
}
/* Function: esl_histogram_Score2Bin()
* Synopsis: Given a real-valued <x>; calculate integer bin <b>
*
* Purpose: For a real-valued <x>, figure out what bin it would
* go into in the histogram <h>; return this value in
* <*ret_b>.
*
* Returns: <eslOK> on success.
*
* Throws: <eslERANGE> if bin <b> would exceed the range of
* an integer; for instance, if <x> isn't finite.
*
* Xref: J5/122. Replaces earlier macro implementation;
* we needed to range check <x> better.
*/
int
esl_histogram_Score2Bin(ESL_HISTOGRAM *h, double x, int *ret_b)
{
int status;
if (! isfinite(x)) ESL_XEXCEPTION(eslERANGE, "value added to histogram is not finite");
x = ceil( ((x - h->bmin) / h->w) - 1.);
/* x is now the bin number as a double, which we will convert to
* int. Because x is a double (64-bit), we know all ints are exactly
* represented. Check for under/overflow before conversion.
*/
if (x < (double) INT_MIN || x > (double) INT_MAX)
ESL_XEXCEPTION(eslERANGE, "value %f isn't going to fit in histogram", x);
*ret_b = (int) x;
return eslOK;
ERROR:
*ret_b = 0;
return status;
}
/* Function: esl_histogram_Add()
* Synopsis: Add a sample to the histogram.
*
* Purpose: Adds score <x> to a histogram <h>.
*
* The histogram will be automatically reallocated as
* needed if the score is smaller or larger than the
* current allocated bounds.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on reallocation failure.
*
* <eslERANGE> if <x> is beyond the reasonable range for
* the histogram to store -- either because it isn't finite,
* or because the histogram would need to allocate a number
* of bins that exceeds <INT_MAX>.
*
* Throws <eslEINVAL> for cases where something has been done
* to the histogram that requires it to be 'finished', and
* adding more data is prohibited; for example,
* if tail or censoring information has already been set.
* On either failure, initial state of <h> is preserved.
*/
int
esl_histogram_Add(ESL_HISTOGRAM *h, double x)
{
int status;
void *tmp;
int b; /* what bin we're in */
int nnew; /* # of new bins created by a reallocation */
int bi;
/* Censoring info must only be set on a finished histogram;
* don't allow caller to add data after configuration has been declared
*/
if (h->is_done)
ESL_EXCEPTION(eslEINVAL, "can't add more data to this histogram");
/* If we're a full histogram, check whether we need to reallocate
* the full data vector.
*/
if (h->is_full && h->nalloc == h->n)
{
ESL_RALLOC(h->x, tmp, sizeof(double) * h->nalloc * 2);
h->nalloc *= 2;
}
/* Which bin will we want to put x into?
*/
if ((status = esl_histogram_Score2Bin(h,x, &b)) != eslOK) return status;
/* Make sure we have that bin. Realloc as needed.
* If that reallocation succeeds, we can no longer fail;
* so we can change the state of h.
*/
if (b < 0) /* Reallocate below? */
{
nnew = -b*2; /* overallocate by 2x */
if (nnew > INT_MAX - h->nb)
ESL_EXCEPTION(eslERANGE, "value %f requires unreasonable histogram bin number", x);
ESL_RALLOC(h->obs, tmp, sizeof(uint64_t) * (nnew+ h->nb));
memmove(h->obs+nnew, h->obs, sizeof(uint64_t) * h->nb);
h->nb += nnew;
b += nnew;
h->bmin -= nnew*h->w;
h->imin += nnew;
h->cmin += nnew;
if (h->imax > -1) h->imax += nnew;
for (bi = 0; bi < nnew; bi++) h->obs[bi] = 0;
}
else if (b >= h->nb) /* Reallocate above? */
{
nnew = (b-h->nb+1) * 2; /* 2x overalloc */
if (nnew > INT_MAX - h->nb)
ESL_EXCEPTION(eslERANGE, "value %f requires unreasonable histogram bin number", x);
ESL_RALLOC(h->obs, tmp, sizeof(uint64_t) * (nnew+ h->nb));
for (bi = h->nb; bi < h->nb+nnew; bi++) h->obs[bi] = 0;
if (h->imin == h->nb) { /* boundary condition of no data yet*/
h->imin+=nnew;
h->cmin+=nnew;
}
h->bmax += nnew*h->w;
h->nb += nnew;
}
/* If we're a full histogram, then we keep the raw x value,
* reallocating as needed.
*/
if (h->is_full) h->x[h->n] = x;
h->is_sorted = FALSE; /* not any more! */
/* Bump the bin counter, and all the data sample counters.
*/
h->obs[b]++;
h->n++;
h->Nc++;
h->No++;
if (b > h->imax) h->imax = b;
if (b < h->imin) { h->imin = b; h->cmin = b; }
if (x > h->xmax) h->xmax = x;
if (x < h->xmin) h->xmin = x;
return eslOK;
ERROR:
return status;
}
/* esl_histogram_sort()
*
* Purpose: Sort the raw scores in a full histogram, from smallest to
* largest. Has no effect on a normal histogram, or on a full
* histogram that is already sorted.
*
* Returns: <eslOK> on success.
* Upon return, <h->x[h->n-1]> is the high score, <h->x[0]> is the
* low score.
*/
int
esl_histogram_sort(ESL_HISTOGRAM *h)
{
if (h->is_sorted) return eslOK; /* already sorted, don't do anything */
if (! h->is_full) return eslOK; /* nothing to sort */
esl_vec_DSortIncreasing(h->x, h->n);
h->is_sorted = TRUE;
return eslOK;
}
/*****************************************************************
* 2. Declarations about the binned data before parameter fitting
*****************************************************************/
/* Function: esl_histogram_DeclareCensoring()
* Synopsis: Collected data were left-censored.
*
* Purpose: Declare that the dataset collected in <h> is known to be a
* censored distribution, where <z> samples were unobserved because
* they had values $\leq$ some threshold <phi> ($\phi$).
*
* No more data can be added to the histogram with <_Add()>
* after censoring information has been set.
*
* This function is for "true" censored datasets, where
* the histogram truly contains no observed points
* $x \leq \phi$, and the number that were censored is known
* to be <z>.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if you try to set <phi> to a value that is
* greater than the minimum <x> stored in the histogram.
*/
int
esl_histogram_DeclareCensoring(ESL_HISTOGRAM *h, int z, double phi)
{
if (phi > h->xmin) ESL_EXCEPTION(eslEINVAL, "no uncensored x can be <= phi");
h->phi = phi;
h->cmin = h->imin;
h->z = z;
h->Nc = h->n + z;
h->No = h->n;
h->dataset_is = TRUE_CENSORED;
h->is_done = TRUE;
return eslOK;
}
/* Function: esl_histogram_DeclareRounding()
* Synopsis: Declare collected data were no more accurate than bins.
*
* Purpose: Declare that the data sample values in the histogram <h>
* are rounded off. Ideally, your bins in <h> should exactly
* match the rounding procedure. This raises a flag that
* binned parameter fitting routines will use when they set
* an origin, using the lower bound of the bin instead of
* the lowest raw value in the bin.
*/
int
esl_histogram_DeclareRounding(ESL_HISTOGRAM *h)
{
h->is_rounded = TRUE;
return eslOK;
}
/* Function: esl_histogram_SetTail()
* Synopsis: Declare only tail $>$ some threshold is considered "observed".
*
* Purpose: Suggest a threshold <phi> to split a histogram <h>
* into "unobserved" data (values $\leq \phi$) and "observed"
* data (values $> \phi$).
*
* The suggested <phi> is revised downwards to a $\phi$ at the next
* bin lower bound, because operations on binned data in <h>
* need to know unambiguously whether all the data in a given bin
* will be counted as observed or unobserved.
*
* The probability mass that is in the resulting right tail
* is optionally returned in <ret_newmass>. You need to know
* this number if you're fitting a distribution solely to the
* tail (an exponential tail, for example).
*
* Any data point $x_i \leq \phi$ is then considered to be
* in a censored (unobserved) region for purposes of parameter
* fitting, calculating expected binned counts,
* and binned goodness-of-fit tests.
*
* No more data can be added to the histogram after
* censoring information has been set.
*
* This function defines a "virtual" left-censoring: the
* histogram actually contains complete data, but appropriate
* flags are set to demarcate the "observed" data in the right
* tail.
*
* Returns: <eslOK> on success.
*
* Throws: <eslERANGE> if <phi> is an unreasonable value that
* can't be converted to an integer bin value.
*/
int
esl_histogram_SetTail(ESL_HISTOGRAM *h, double phi, double *ret_newmass)
{
int b;
int status;
/* Usually, put true phi at the next bin lower bound, but
* watch for a special case where phi is already exactly equal to a
* bin upper bound.
*/
if ((status = esl_histogram_Score2Bin(h,phi, &(h->cmin))) != eslOK) return status;
if (phi == esl_histogram_Bin2UBound(h,h->cmin)) h->phi = phi;
else h->phi = esl_histogram_Bin2LBound(h, h->cmin);
h->z = 0;
for (b = h->imin; b < h->cmin; b++)
h->z += h->obs[b];
h->Nc = h->n; /* (redundant) */
h->No = h->n - h->z;
h->dataset_is = VIRTUAL_CENSORED;
h->is_done = TRUE;
if (ret_newmass != NULL) *ret_newmass = (double) h->No / (double) h->Nc;
return eslOK;
}
/* Function: esl_histogram_SetTailByMass()
* Synopsis: Declare only right tail mass is considered "observed".
*
* Purpose: Given a histogram <h> (with or without raw data samples),
* find a cutoff score that at least fraction <pmass> of the samples
* exceed. This threshold is stored internally in the histogram
* as <h->phi>. The number of "virtually censored" samples (to the
* left, with scores $\leq \phi$) is stored internally in <h->z>.
*
* The identified cutoff score must be a lower bound for some bin
* (bins can't be partially censored). The censored mass
* will thus usually be a bit greater than <pmass>, as the
* routine will find the highest satisfactory <h->phi>. The
* narrower the bin widths, the more accurately the routine
* will be able to satisfy the requested <frac>. The actual
* probability mass in the right tail is optionally returned
* in <ret_newmass>. You need to know this number if you're
* fitting a distribution solely to the tail (an exponential tail,
* for example). It is safe for <ret_newmass> to point at
* <pmass>, in which case the suggested <pmass> will be overwritten
* with the actual mass upon return.
*
* This function defines that the binned data will be
* fitted either as a tail, or as a (virtually) left-censored dataset.
*
* Returns: <eslOK> on success.
*/
int
esl_histogram_SetTailByMass(ESL_HISTOGRAM *h, double pmass, double *ret_newmass)
{
int b;
uint64_t sum = 0;
for (b = h->imax; b >= h->imin; b--)
{
sum += h->obs[b];
if (sum >= (pmass * (double)h->n)) break;
}
h->phi = esl_histogram_Bin2LBound(h,b);
h->z = h->n - sum;
h->cmin = b;
h->Nc = h->n; /* (redundant) */
h->No = h->n - h->z;
h->dataset_is = VIRTUAL_CENSORED;
h->is_done = TRUE;
if (ret_newmass != NULL) *ret_newmass = (double) h->No / (double) h->Nc;
return eslOK;
}
/*****************************************************************
* 3. Routines for accessing data samples in a full histogram.
*****************************************************************/
/* Function: esl_histogram_GetRank()
* Synopsis: Retrieve n'th high score.
*
* Purpose: Retrieve the <rank>'th highest score from a
* full histogram <h>. <rank> is <1..n>, for
* <n> total samples in the histogram; return it through
* <ret_x>.
*
* If the raw scores aren't sorted, they are sorted
* first (an $N \log N$ operation).
*
* This can be called at any time, even during data
* collection, to see the current <rank>'th highest score.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if the histogram is display-only,
* or if <rank> isn't in the range 1..n.
*/
int
esl_histogram_GetRank(ESL_HISTOGRAM *h, int rank, double *ret_x)
{
if (! h->is_full)
ESL_EXCEPTION(eslEINVAL,
"esl_histogram_GetRank() needs a full histogram");
if (rank > h->n)
ESL_EXCEPTION(eslEINVAL,
"no such rank: not that many scores in the histogram");
if (rank < 1)
ESL_EXCEPTION(eslEINVAL, "histogram rank must be a value from 1..n");
esl_histogram_sort(h); /* make sure */
*ret_x = h->x[h->n - rank];
return eslOK;
}
/* Function: esl_histogram_GetData()
* Synopsis: Retrieve vector of all raw scores.
*
* Purpose: Retrieve the raw data values from the histogram <h>.
* Return them in the vector <ret_x>, and the number
* of values in <ret_n>. The values are indexed <[0..n-1]>,
* from smallest to largest (<x[n-1]> is the high score).
*
* <ret_x> is a pointer to internal memory in the histogram <h>.
* The histogram <h> is still responsible for that storage;
* its memory will be free'd when you call
* <esl_histogram_Destroy()>.
*
* You can only call this after you have finished collecting
* all the data. Subsequent calls to <esl_histogram_Add()>
* will fail.
*
* Internal note:
* The prohibition against adding more data (by raising
* the h->is_done flag) is because we're passing a pointer
* to internal data storage back to the caller. Subsequent
* calls to Add() will modify that memory -- in the worst case,
* if Add() has to reallocate that storage, completely invalidating
* the pointer that the caller has a copy of. We want to make
* sure that the <ret_x> pointer stays valid.
*
* Args: h - histogram to retrieve data values from
* ret_x - RETURN: pointer to the data samples, [0..n-1]
* ret_n - RETURN: number of data samples
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if the histogram <h> is not a full histogram.
*/
int
esl_histogram_GetData(ESL_HISTOGRAM *h, double **ret_x, int *ret_n)
{
if (! h->is_full) ESL_EXCEPTION(eslEINVAL, "not a full histogram");
esl_histogram_sort(h);
*ret_x = h->x;
*ret_n = h->n;
h->is_done = TRUE;
return eslOK;
}
/* Function: esl_histogram_GetTail()
* Synopsis: Retrieve all raw scores above some threshold.
*
* Purpose: Given a full histogram <h>, retrieve all data values
* above the threshold <phi> in the right (high scoring)
* tail, as a ptr <ret_x> to an array of <ret_n> values
* indexed <[0..n-1]> from lowest to highest score.
* Optionally, it also returns the number of values in
* rest of the histogram in <ret_z>;
* this number is useful if you are going to fit
* the tail as a left-censored distribution.
*
* The test is strictly greater than <phi>, not greater
* than or equal to.
*
* <ret_x> is a pointer to internal memory in the histogram <h>.
* The histogram <h> is still responsible for that storage;
* its memory will be free'd when you call
* <esl_histogram_Destroy()>.
*
* You can only call this after you have finished collecting
* all the data. Subsequent calls to <esl_histogram_Add()>
* will fail.
*
* Args: h - histogram to retrieve the tail from
* phi - threshold: tail is all scores > phi
* ret_x - optRETURN: ptr to vector of data values [0..n-1]
* ret_n - optRETURN: number of data values in tail
* ret_z - optRETURN: number of data values not in tail.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if the histogram is not a full histogram.
*/
int
esl_histogram_GetTail(ESL_HISTOGRAM *h, double phi,
double **ret_x, int *ret_n, int *ret_z)
{
int hi, lo, mid;
if (! h->is_full) ESL_EXCEPTION(eslEINVAL, "not a full histogram");
esl_histogram_sort(h);
if (h->n == 0) mid = h->n; /* we'll return NULL, 0, n */
else if (h->x[0] > phi) mid = 0; /* we'll return x, n, 0 */
else if (h->x[h->n-1] <= phi) mid = h->n; /* we'll return NULL, 0, n */
else /* binary search, faster than a brute force scan */
{
lo = 0;
hi = h->n-1; /* know hi>0, because above took care of n=0 and n=1 cases */
while (1) {
mid = (lo + hi + 1) / 2; /* +1 makes mid round up, mid=0 impossible */
if (h->x[mid] <= phi) lo = mid; /* we're too far left */
else if (h->x[mid-1] > phi) hi = mid; /* we're too far right */
else break; /* ta-da! */
}
}
if (ret_x != NULL) *ret_x = h->x + mid;
if (ret_n != NULL) *ret_n = h->n - mid;
if (ret_z != NULL) *ret_z = mid;
h->is_done = TRUE;
return eslOK;
}
/* Function: esl_histogram_GetTailByMass()
* Synopsis: Retrieve all raw scores in right tail mass.
*
* Purpose: Given a full histogram <h>, retrieve the data values in
* the right (high scoring) tail, as a pointer <ret_x>
* to an array of <ret_n> values indexed <[0..n-1]> from
* lowest to highest score. The tail is defined by a
* given mass fraction threshold <pmass>; the mass in the returned
* tail is $\leq$ this threshold. <pmass> is a probability,
* so it must be $\geq 0$ and $\leq 1$.
*
* Optionally, the number of values in the rest of the
* histogram can be returned in <ret_z>. This is useful
* if you are going to fit the tail as a left-censored
* distribution.
*
* <ret_x> is a pointer to internal memory in <h>.
* The histogram <h> remains responsible for its storage,
* which will be free'd when you call <esl_histogram_Destroy()>.
* As a consequence, you can only call
* <esl_histogram_GetTailByMass()> after you have finished
* collecting data. Subsequent calls to <esl_histogram_Add()>
* will fail.
*
* Args: h - histogram to retrieve the tail from
* pmass - fractional mass threshold; tail contains <= pmass
* ret_x - optRETURN: ptr to vector of data values [0..n-1]
* ret_n - optRETURN: number of data values in tail x
* ret_z - optRETURN: number of data values not in tail
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if the histogram is not a full histogram,
* or <pmass> is not a probability.
*/
int
esl_histogram_GetTailByMass(ESL_HISTOGRAM *h, double pmass,
double **ret_x, int *ret_n, int *ret_z)
{
uint64_t n;
if (! h->is_full)
ESL_EXCEPTION(eslEINVAL, "not a full histogram");
if (pmass < 0. || pmass > 1.)
ESL_EXCEPTION(eslEINVAL, "pmass not a probability");
esl_histogram_sort(h);
n = (uint64_t) ((double) h->n * pmass); /* rounds down, guaranteeing <= pmass */
if (ret_x != NULL) *ret_x = h->x + (h->n - n);
if (ret_n != NULL) *ret_n = n;
if (ret_z != NULL) *ret_z = h->n - n;
h->is_done = TRUE;
return eslOK;
}
/*****************************************************************
* 4. Setting expected counts
*****************************************************************/
/* Function: esl_histogram_SetExpect()
* Synopsis: Set expected counts for complete distribution.
*
* Purpose: Given a histogram <h> containing some number of empirically
* observed binned counts, and a pointer to a function <(*cdf)()>
* that describes the expected cumulative distribution function
* (CDF) for the complete data, conditional on some parameters
* <params>; calculate the expected counts in each bin of the
* histogram, and hold that information internally in the structure.
*
* The caller provides a function <(*cdf)()> that calculates
* the CDF via a generic interface, taking only two
* arguments: a quantile <x> and a void pointer to whatever
* parameters it needs, which it will cast and interpret.
* The <params> void pointer to the given parameters is
* just passed along to the generic <(*cdf)()> function. The
* caller will probably implement this <(*cdf)()> function as
* a wrapper around its real CDF function that takes
* explicit (non-void-pointer) arguments.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation failure; state of <h> is preserved.
*/
int
esl_histogram_SetExpect(ESL_HISTOGRAM *h,
double (*cdf)(double x, void *params), void *params)
{
int i;
double ai,bi; /* ai < x <= bi : lower,upper bounds in bin */
int status;
if (h->expect == NULL)
ESL_ALLOC(h->expect, sizeof(double) * h->nb);
for (i = 0; i < h->nb; i++)
{
ai = esl_histogram_Bin2LBound(h, i);
bi = esl_histogram_Bin2UBound(h, i);
h->expect[i] = h->Nc * ( (*cdf)(bi, params) - (*cdf)(ai, params) );
if (h->emin == -1 && h->expect[i] > 0.) h->emin = i;
}
h->is_done = TRUE;
return eslOK;
ERROR:
return status;
}
/* Function: esl_histogram_SetExpectedTail()
* Synopsis: Set expected counts for right tail.
*
* Purpose: Given a histogram <h>, and a pointer to a generic function
* <(*cdf)()> that describes the expected cumulative
* distribution function for the right (high-scoring) tail
* starting at <base_val> (all expected <x> $>$ <base_val>) and
* containing a fraction <pmass> of the complete data
* distribution (<pmass> $\geq 0$ and $\leq 1$);
* set the expected binned counts for all complete bins
* $\geq$ <base_val>.
*
* If <base_val> falls within a bin, that bin is considered
* to be incomplete, and the next higher bin is the starting
* point.
*
* Args: h - finished histogram
* base_val - threshold for the tail: all expected x > base_val
* pmass - fractional mass in the tail: 0 <= pmass <= 1
* cdf - generic-interface CDF function describing the tail
* params - void pointer to parameters for (*cdf)()
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on memory allocation failure.
* <eslERANGE> if <base_val> isn't a reasonable value within
* the histogram (it converts to a bin value outside
* integer range).
*/
int
esl_histogram_SetExpectedTail(ESL_HISTOGRAM *h, double base_val, double pmass,
double (*cdf)(double x, void *params),
void *params)
{
int status;
int b;
double ai, bi;
if (h->expect == NULL) ESL_ALLOC(h->expect, sizeof(double) * h->nb);
if ((status = esl_histogram_Score2Bin(h, base_val, &(h->emin))) != eslOK) return status;
h->emin += 1;
esl_vec_DSet(h->expect, h->emin, 0.);
for (b = h->emin; b < h->nb; b++)
{
ai = esl_histogram_Bin2LBound(h, b);
bi = esl_histogram_Bin2UBound(h, b);
h->expect[b] = pmass * (double) h->Nc *
( (*cdf)(bi, params) - (*cdf)(ai, params) );
}
h->tailbase = base_val;
h->tailmass = pmass;
h->is_tailfit = TRUE;
h->is_done = TRUE;
return eslOK;
ERROR:
return status;
}
/*****************************************************************
* 5. Output and display of binned data.
*****************************************************************/
/* Function: esl_histogram_Write()
* Synopsis: Write a "pretty" ASCII histogram to a stream.
*
* Purpose: Print a "prettified" display histogram <h> to a file
* pointer <fp>. Deliberately a look-and-feel clone of
* Bill Pearson's excellent FASTA output.
*
* Also displays expected binned counts, if they've been
* set.
*
* Display will only work well if the bin width (w) is 0.1
* or more, because the score labels are only shown to one
* decimal point.
*
* Args: fp - open file to print to (stdout works)
* h - histogram to print
*
* Returns: <eslOK> on success.
*
* Throws: <eslEWRITE> on any system write error, such as a
* filled disk.
*/
int
esl_histogram_Write(FILE *fp, ESL_HISTOGRAM *h)
{
int i;
double x;
uint64_t maxbar;
int imode;
uint64_t units;
int num;
char buffer[81]; /* output line buffer */
int pos; /* position in output line buffer */
uint64_t lowcount, highcount;
int ilowbound, ihighbound;
int nlines;
int emptybins = 3;
/* Find out how we'll scale the histogram. We have 58 characters to
* play with on a standard 80-column terminal display: leading "%6.1f
* %6d %6d|" occupies 21 chars. Save the peak position, we'll use
* it later.
*/
maxbar = 0;
imode = 0;
for (i = 0; i < h->nb; i++)
if (h->obs[i] > maxbar)
{
maxbar = h->obs[i]; /* max height */
imode = i;
}
/* Truncate histogram display on both sides, ad hoc fashion.
* Start from the peak; then move out until we see <emptybins> empty bins,
* and stop.
*/
for (num = 0, ihighbound = imode; ihighbound < h->imax; ihighbound++)
{
if (h->obs[ihighbound] > 0) { num = 0; continue; } /* reset */
if (++num == emptybins) { break; } /* stop */
}
for (num = 0, ilowbound = imode; ilowbound > h->imin; ilowbound--)
{
if (h->obs[ilowbound] > 0) { num = 0; continue; } /* reset */
if (++num == emptybins) { break; } /* stop */
}
/* collect counts outside of bounds */
for (lowcount = 0, i = h->imin; i < ilowbound; i++)
lowcount += h->obs[i];
for (highcount = 0, i = h->imax; i > ihighbound; i--)
highcount += h->obs[i];
/* maxbar might need to be raised now; then set our units */
if (lowcount > maxbar) maxbar = lowcount;
if (highcount > maxbar) maxbar = highcount;
if (maxbar > 0) units = ((maxbar-1)/ 58) + 1;
else units = 1; /* watch out for an empty histogram w/ no data points. */
/* Print the histogram header
*/
if (fprintf(fp, "%6s %6s %6s (one = represents %llu sequences)\n",
"score", "obs", "exp", (unsigned long long) units) < 0)
ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
if (fprintf(fp, "%6s %6s %6s\n", "-----", "---", "---") < 0)
ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
/* Print the histogram itself */
buffer[80] = '\0';
buffer[79] = '\n';
nlines = 0; /* Count the # of lines we print, so we know if it ends up being zero */
for (i = h->imin; i <= h->imax; i++)
{
memset(buffer, ' ', 79 * sizeof(char));
x = i*h->w + h->bmin;
/* Deal with special cases at edges
*/
if (i < ilowbound) continue;
else if (i > ihighbound) continue;
else if (i == ilowbound && i != h->imin)
{
snprintf(buffer, 81, "<%5.1f %6llu %6s|", x+h->w, (unsigned long long) lowcount, "-"); // 81 is the buffer[81] static alloc
if (lowcount > 0) {
num = 1+(lowcount-1) / units;
for (pos = 21; num > 0; num--) buffer[pos++] = '=';
}
if (fputs(buffer, fp) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
nlines++;
continue;
}
else if (i == ihighbound && i != h->imax)
{
snprintf(buffer, 81, ">%5.1f %6llu %6s|", x, (unsigned long long) highcount, "-");
if (highcount > 0) {
num = 1+(highcount-1) / units;
for (pos = 21; num > 0; num--) buffer[pos++] = '=';
}
if (fputs(buffer, fp) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "histogram write failed");
nlines++;
continue;
}
/* Deal with most cases
*/
if (h->obs[i] < 1000000) /* displayable in 6 figures or less? */
{
if (h->expect != NULL)
snprintf(buffer, 81, "%6.1f %6llu %6d|", x, (unsigned long long) h->obs[i], (int) h->expect[i]);
else
snprintf(buffer, 81, "%6.1f %6llu %6s|", x, (unsigned long long) h->obs[i], "-");
}
else
{
if (h->expect != NULL)
snprintf(buffer, 81, "%6.1f %6.2e %6.2e|", x, (double) h->obs[i], h->expect[i]);
else
snprintf(buffer, 81, "%6.1f %6.2e %6s|", x, (double) h->obs[i], "-");
}
buffer[21] = ' '; /* sprintf writes a null char; replace it */
/* Mark the histogram bar for observed hits
*/
if (h->obs[i] > 0) {
num = 1 + (h->obs[i]-1) / units;
for (pos = 21; num > 0; num--) buffer[pos++] = '=';
}