-
Notifications
You must be signed in to change notification settings - Fork 2
/
MbRandom.cpp
1752 lines (1549 loc) · 43.1 KB
/
MbRandom.cpp
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
/*!
* \file
* This file contains the implementation of MbRandom, a
* class that deals with random variables.
*
* \brief Implementation of MbRandom class
*
* MrBayes version 4.0 beta
*
* (c) Copyright 2005.
* \version 4.0 beta
* \date Last modified: $Date: 2006/09/11 17:29:51 $
* \author John Huelsenbeck (1)
* \author Bret Larget (2)
* \author Paul van der Mark (3)
* \author Fredrik Ronquist (3)
* \author Donald Simon (4)
* \author (authors listed in alphabetical order)
* (1) Department of Integrative Biology, University of California, Berkeley
* (2) Departments of Botany and of Statistics, University of Wisconsin - Madison
* (3) School of Computational Science, Florida State University
* (4) Department of Mathematics/Computer Science, Duquesne University
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License (the file gpl.txt included with this
* distribution or http://www.gnu.org/licenses/gpl.txt for more
* details.
*
* $Id: MbRandom.cpp,v 1.3 2006/09/11 17:29:51 paulvdm Exp $
*/
#include <cmath>
#include <ctime>
#include <iostream>
#include <cassert>
#include <cstdio>
#include "MbRandom.h"
#include "MbVector.h"
using namespace std;
#pragma mark Constructors
/*!
* Constructor for MbRandom class. This constructor does not take
* any parameters and initializes the seed using the current
* system time.
*
* \brief Constructor for MbRandom, initializing seed with system time.
* \param Takes no parameter.
* \return Returns no value.
* \throws Does not throw an error.
*/
MbRandom::MbRandom(void) {
setSeed();
initializedFacTable = false;
availableNormalRv = false;
}
/*!
* Constructor for MbRandom class. This constructor takes as a
* parameter a long integer with the user-supplied seed for the
* random number generator.
*
* \brief Constructor for MbRandom, initializing seed with a user-supplied long integer.
* \param x is a long integer with the user-supplied random number seed.
* \return Returns no value.
* \throws Does not throw an error.
*/
MbRandom::MbRandom(seedType x) {
setSeed(x, 0);
initializedFacTable = false;
availableNormalRv = false;
}
#pragma mark Chi-Square Distribution
/*!
* This function generates a chi square distributed random variable.
*
* \brief Chi-square random variable.
* \param v is the degrees of freedom parameter of the chi-square distribution.
* \return Returns a chi-square distributed random variable.
* \throws Does not throw an error.
*/
double MbRandom::chiSquareRv(double v) {
/* Cast the degrees of freedom parameter as an integer. We will see
if there is a decimal remainder later. */
int n = (int)(v);
double x2;
if ( (double)(n) == v && n <= 100 )
{
/* If the degrees of freedom is an integer and less than 100, we
generate our chi-square random variable by generating v
standard normal random variables, squaring each, and taking the
sum of the squared random variables. */
x2 = 0.0;
for (int i=0; i<n; i++)
{
double x = normalRv();
x2 += x * x;
}
}
else
{
/* Otherwise, we use the relationship of the chi-square to a gamma
(it is a special case of the gamma) to generate the chi-square
random variable. */
x2 = gammaRv(v/2.0, 0.5);
}
return x2;
}
/*!
* This function calculates the probability density
* for a chi-square distributed random variable.
*
* \brief Chi-square probability density.
* \param v is the degrees of freedom parameter of the chi-square.
* \param x is the chi-square random variable.
* \return Returns the probability density.
* \throws Does not throw an error.
*/
double MbRandom::chiSquarePdf(double v, double x) {
double pdf;
if ( x < 0.0 )
{
pdf = 0.0;
}
else
{
double b = v / 2.0;
pdf = exp ( -0.5 * x ) * pow ( x, ( b - 1.0 ) ) / ( pow ( 2.0, b ) * gamma ( b ) );
}
return pdf;
}
/*!
* This function calculates the cumulative probability
* for a chi-square distributed random variable.
*
* \brief Chi-square cumulative probability.
* \param v is the degrees of freedom parameter of the chi-square.
* \param x is the chi-square random variable.
* \return Returns the cumulative probability.
* \throws Does not throw an error.
*/
double MbRandom::chiSquareCdf(double v, double x) {
return gammaCdf( v / 2.0, 0.5, x );
}
/*!
* This function calculates the natural log of the probability density
* for a chi-square distributed random variable.
*
* \brief Natural log of chi-square probability density.
* \param v is the degrees of freedom parameter of the chi-square.
* \param x is the chi-square random variable.
* \return Returns the natural log of the probability density.
* \throws Does not throw an error.
*/
double MbRandom::lnChiSquarePdf(double v, double x) {
double b = v / 2.0;
return ( -(b * log(2.0) + lnGamma(b)) - b + (b - 1.0) * log(x) );
}
/*!
* This function calculates the quantile of a chi square distribution with v
* degrees of freedom.
*
* \brief Quantile of a chi square distribution.
* \param v is the degrees of freedom of the chi square.
* \param prob is the probability up to the quantile.
* \return Returns quantile value (or -1 if in error).
* \throws Does not throw an error.
*/
double MbRandom::chiSquareQuantile(double prob, double v) {
double e = 0.5e-6, aa = 0.6931471805, p = prob, g,
xx, c, ch, a = 0.0, q = 0.0, p1 = 0.0, p2 = 0.0, t = 0.0,
x = 0.0, b = 0.0, s1, s2, s3, s4, s5, s6;
if (p < 0.000002 || p > 0.999998 || v <= 0.0)
return (-1.0);
g = lnGamma(v/2.0);
xx = v/2.0;
c = xx - 1.0;
if (v >= -1.24*log(p))
goto l1;
ch = pow((p*xx*exp(g+xx*aa)), 1.0/xx);
if (ch-e < 0)
return (ch);
goto l4;
l1:
if (v > 0.32)
goto l3;
ch = 0.4;
a = log(1.0-p);
l2:
q = ch;
p1 = 1.0+ch*(4.67+ch);
p2 = ch*(6.73+ch*(6.66+ch));
t = -0.5+(4.67+2.0*ch)/p1 - (6.73+ch*(13.32+3.0*ch))/p2;
ch -= (1.0-exp(a+g+0.5*ch+c*aa)*p2/p1)/t;
if (fabs(q/ch-1.0)-0.01 <= 0.0)
goto l4;
else
goto l2;
l3:
x = pointNormal (p);
p1 = 0.222222/v;
ch = v*pow((x*sqrt(p1)+1.0-p1), 3.0);
if (ch > 2.2*v+6.0)
ch = -2.0*(log(1.0-p)-c*log(0.5*ch)+g);
l4:
q = ch;
p1 = 0.5*ch;
if ((t = incompleteGamma (p1, xx, g)) < 0.0)
{
printf ("\nerr IncompleteGamma");
return (-1.0);
}
p2 = p-t;
t = p2*exp(xx*aa+g+p1-c*log(ch));
b = t/ch;
a = 0.5*t-b*c;
s1 = (210.0+a*(140.0+a*(105.0+a*(84.0+a*(70.0+60.0*a))))) / 420.0;
s2 = (420.0+a*(735.0+a*(966.0+a*(1141.0+1278.0*a))))/2520.0;
s3 = (210.0+a*(462.0+a*(707.0+932.0*a)))/2520.0;
s4 = (252.0+a*(672.0+1182.0*a)+c*(294.0+a*(889.0+1740.0*a)))/5040.0;
s5 = (84.0+264.0*a+c*(175.0+606.0*a))/2520.0;
s6 = (120.0+c*(346.0+127.0*c))/5040.0;
ch += t*(1+0.5*t*s1-b*c*(s1-b*(s2-b*(s3-b*(s4-b*(s5-b*s6))))));
if (fabs(q/ch-1.0) > e)
goto l4;
return (ch);
}
#pragma mark Gamma Distribution
/*!
* This function generates a gamma-distributed random variable.
*
* \brief Gamma random variable.
* \param a is the shape parameter of the gamma.
* \param b is the scale parameter of the gamma.
* \return Returns a gamma-distributed random variable.
* \throws Does not throw an error.
*/
double MbRandom::gammaRv(double a, double b) {
return (rndGamma(a) / b);
}
/*!
* This function calculates the probability density
* for a gamma-distributed random variable.
*
* \brief Gamma probability density.
* \param a is the shape parameter of the gamma.
* \param b is the scale parameter of the gamma.
* \param x is the gamma random variable.
* \return Returns the probability density.
* \throws Does not throw an error.
*/
double MbRandom::gammaPdf(double a, double b, double x) {
return (pow(b, a) / gamma(a)) * pow(x, a - 1.0) * exp(-x * b);
}
/*!
* This function calculates the cumulative probability
* for a gamma-distributed random variable.
*
* \brief Gamma cumulative probability.
* \param a is the shape parameter of the gamma.
* \param b is the scale parameter of the gamma.
* \param x is the gamma random variable.
* \return Returns the cumulative probability.
* \throws Does not throw an error.
*/
double MbRandom::gammaCdf(double a, double b, double x) {
return incompleteGamma(b*x, a, lnGamma(a));
}
/*!
* This function calculates the natural log of the probability density
* for a gamma-distributed random variable.
*
* \brief Natural log of gamma probability density.
* \param a is the shape parameter of the gamma.
* \param b is the scale parameter of the gamma.
* \param x is the gamma random variable.
* \return Returns the natural log of the probability density.
* \throws Does not throw an error.
*/
double MbRandom::lnGammaPdf(double a, double b, double x) {
return a * log(b) - lnGamma(a) + (a - 1.0) * log(x) - x * b;
}
/*!
* This function calculates the average or median values of the
* categories for a discretized gamma distribution. The gamma is
* broken into K categories, with each category having equal
* probability. The mean or meadian value for each category is
* then calculated.
*
* \brief Calculates the mean/median values for a discretized gamma.
* \param catRate a pointer to a vector of doubles containing the nCats mean/median values.
* \param a the shape parameter of the gamma distribution.
* \param b the scale parameter of the gamma distribution.
* \param nCats the number of discrete categories.
* \param When true, the median of the category is calculated. Otherwise
the mean is used.
* \return Does not return a value.
* \throws Does not throw an error.
*/
void MbRandom::discretizeGamma(MbVector<double> &catRate, double a, double b, int nCats, bool median) {
double factor = a / b * nCats;
if (median)
{
/* the median value for each category is used to represent all of the values
in that category */
double interval = 1.0 / (2.0 * nCats);
for (int i=0; i<nCats; i++)
catRate[i] = chiSquareQuantile((i * 2.0 + 1.0) * interval, 2.0 * a) / (2.0 * b);
double t = 0.0;
for (int i=0; i<nCats; i++)
t += catRate[i];
for (int i=0; i<nCats; i++)
catRate[i] *= factor / t;
}
else
{
/* the mean value for each category is used to represent all of the values
in that category */
/* calculate the points in the gamma distribution */
for (int i=0; i<nCats-1; i++)
catRate[i] = chiSquareQuantile((i + 1.0) / nCats, 2.0 * a) / (2.0 * b);
/* calculate the cumulative values */
double lnGammaValue = lnGamma(a + 1.0);
for (int i=0; i<nCats-1; i++)
catRate[i] = incompleteGamma(catRate[i] * b, a + 1.0, lnGammaValue);
catRate[nCats-1] = 1.0;
/* calculate the relative values and rescale */
for (int i=nCats-1; i>0; i--)
{
catRate[i] -= catRate[i-1];
catRate[i] *= factor;
}
catRate[0] *= factor;
}
}
#pragma mark Log Normal Distribution
/*!
* This function returns the quantile of a normal probability
* distribution.
*
* \brief Natural quantile.
* \param mu is the mean parameter of the normal.
* \param sigma is the variance parameter of the normal.
* \param p is the probability up to the quantile.
* \return Returns the quantile.
* \throws Does not throw an error.
*/
double MbRandom::logNormalQuantile(double mu, double sigma, double p) {
return exp( normalQuantile(mu, sigma, p) );
}
/*!
* This function calculates the cumulative probability
* for a normally-distributed random variable.
*
* \brief Normal cumulative probability.
* \param mu is the mean parameter of the normal.
* \param sigma is the variance parameter of the normal.
* \param x is the normal random variable.
* \return Returns the cumulative probability.
* \see Adams, A. G. 1969. Areas under the normal curve. Cojputer J. 12:197-198.
* \throws Does not throw an error.
*/
double MbRandom::normalCdf(double mu, double sigma, double x) {
double cdf;
double q;
double z = (x - mu) / sigma;
/* |X| <= 1.28 */
if ( fabs(z) <= 1.28 )
{
double a1 = 0.398942280444;
double a2 = 0.399903438504;
double a3 = 5.75885480458;
double a4 = 29.8213557808;
double a5 = 2.62433121679;
double a6 = 48.6959930692;
double a7 = 5.92885724438;
double y = 0.5 * z * z;
q = 0.5 - fabs(z) * ( a1 - a2 * y / ( y + a3 - a4 / ( y + a5 + a6 / ( y + a7 ) ) ) );
}
else if ( fabs(z) <= 12.7 )
{
double b0 = 0.398942280385;
double b1 = 3.8052E-08;
double b2 = 1.00000615302;
double b3 = 3.98064794E-04;
double b4 = 1.98615381364;
double b5 = 0.151679116635;
double b6 = 5.29330324926;
double b7 = 4.8385912808;
double b8 = 15.1508972451;
double b9 = 0.742380924027;
double b10 = 30.789933034;
double b11 = 3.99019417011;
double y = 0.5 * z * z;
q = exp(-y) * b0 / (fabs(z) - b1 + b2 / (fabs(z) + b3 + b4 / (fabs(z) - b5 + b6 / (fabs(z) + b7 - b8 / (fabs(z) + b9 + b10 / (fabs(z) + b11))))));
}
else
{
q = 0.0;
}
if ( z < 0.0 )
{
/* negative x */
cdf = q;
}
else
{
/* positive x */
cdf = 1.0 - q;
}
return cdf;
}
/*!
* This function returns the quantile of a normal probability
* distribution.
*
* \brief Natural quantile.
* \param mu is the mean parameter of the normal.
* \param sigma is the variance parameter of the normal.
* \param p is the probability up to the quantile.
* \return Returns the quantile.
* \throws Does not throw an error.
*/
double MbRandom::normalQuantile(double mu, double sigma, double p) {
double z = pointNormal(p);
double x = z * sigma + mu;
return x;
}
#pragma mark Uniform Distribution
/*!
* This function generates a uniformly-distributed random variable on the interval [0,1).
* It is a version of the Marsaglia Multi-Carry.
*
* Taken from:
* Mathlib : A C Library of Special Functions
* Copyright (C) 2000, 2003 The R Development Core Team
*
* This random generator has a period of 2^60, which ensures it has the maximum
* period of 2^32 for unsigned ints (32 bit ints).
*
* \brief Uniform[0,1) random variable.
* \return Returns a uniformly-distributed random variable on the interval [0,1).
* \throws Does not throw an error.
* \see http://stat.fsu.edu/~geo/diehard.html
*/
double MbRandom::uniformRv(void) {
// Returns a pseudo-random number between 0 and 1.
double u = 0.0; // TAH: if I1 == 395220642 && I2 == 1045444223, this returns 0, so I put this check in...
while(u == 0.0){
I1 = 36969 * (I1 & 0177777) + (I1 >> 16);
I2 = 18000 * (I2 & 0177777) + (I2 >> 16);
u = ((I1 << 16)^(I2 & 0177777)) * 2.328306437080797e-10; /*!< in [0,1) */
}
return u;
}
/*!
* This function calculates the cumulative probability
* for a uniform(0,1) random variable.
*
* \brief Uniform(0,1) cumulative probability.
* \param x is the uniform random variable.
* \return Returns the cumulative probability.
* \throws Does not throw an error.
*/
double MbRandom::uniformCdf(double x) {
if ( x < 0.0 )
return 0.0;
else if ( x > 1.0 )
return 1.0;
else
return x;
}
/*!
* This function generates a discrete and uniformly-distributed random
* variable on the interval (a,b).
*
* \brief Discrete uniform(a,b) random variable.
* \param a is the lower bound on the uniform.
* \param b is the upper bound on the uniform.
* \return Returns a discrete and uniformly-distributed random variable
* on the interval (a,b).
* \throws Does not throw an error.
*/
int MbRandom::discreteUniformRv(int a, int b) {
return (int)((b-a+1) * uniformRv()) + a;
}
#pragma mark Beta Distribution
/*!
* This function generates a Beta-distributed random variable.
*
* \brief Beta random variable.
* \param a parameter of the Beta.
* \param b parameter of the Beta.
* \return Returns the random variable.
* \throws Does not throw an error.
*/
double MbRandom::betaRv(double a, double b) {
double z0 = rndGamma( a );
double z1 = rndGamma( b );
double sum = z0 + z1;
double x = z0 / sum;
/*double mu = ( a - 1.0 ) / ( a + b - 2.0 );
double stdev = 0.5 / sqrt( a + b - 2.0 );
double x;
for (;;)
{
double y = normalRv();
x = mu + stdev * y;
if ( x < 0.0 || 1.0 < x )
continue;
double u = uniformRv();
double test = (a - 1.0) * log(x / (a - 1.0)) + (b - 1.0) * log((1.0 - x) / (b - 1.0)) + (a + b - 2.0) * log(a + b - 2.0) + 0.5 * y * y;
if ( log (u) <= test )
break;
}*/
return x;
}
/*!
* This function returns the probability density for a
* Beta-distributed random variable.
*
* \brief Beta probability density.
* \param a parameter of the Beta.
* \param b parameter of the Beta.
* \return Returns the probability density.
* \throws Does not throw an error.
*/
double MbRandom::betaPdf(double a, double b, double x) {
double pdf;
if ( x < 0.0 || 1.0 < x )
pdf = 0.0;
else
pdf = pow(x, (a - 1.0)) * pow((1.0 - x), (b - 1.0)) / beta(a, b);
return pdf;
}
/*!
* This function returns the natural log of the probability density
* for a Beta-distributed random variable.
*
* \brief Beta log probability density.
* \param a parameter of the Beta.
* \param b parameter of the Beta.
* \return Returns the natural log of the probability density.
* \throws Does not throw an error.
*/
double MbRandom::lnBetaPdf(double a, double b, double x) {
return ( (lnGamma(a + b) - lnGamma(a) - lnGamma(b)) + (a - 1.0) * log(x) + (b - 1.0) * log(1.0 - x) );
}
/*!
* This function returns the cumulative probability for a
* Beta-distributed random variable.
*
* \brief Beta cumulative probability.
* \param a parameter of the Beta.
* \param b parameter of the Beta.
* \return Returns the cumulative probability.
* \throws Does not throw an error.
*/
double MbRandom::betaCdf(double a, double b, double x) {
double cdf;
if ( x <= 0.0 )
cdf = 0.0;
else if ( x <= 1.0 )
cdf = incompleteBeta(a, b, x);
else
cdf = 1.0;
return cdf;
}
/*!
* This function returns the quantile for a
* Beta-distributed random variable.
*
* \brief Beta quantile.
* \param a parameter of the Beta.
* \param b parameter of the Beta.
* \param p is the probability up to the quantile.
* \return Returns the quantile.
* \throws Does not throw an error.
*/
double MbRandom::betaQuantile(double a, double b, double p) {
# define MAXK 20
double bcoeff;
double error = 0.0001;
double errapp = 0.01;
int j;
/* estimate the solution */
double x = a / ( a + b );
double xOld = 0.0;
int loopCnt = 2;
double d[MAXK * (MAXK-1)];
while ( errapp <= fabs ( ( x - xOld ) / x ) && loopCnt != 0 )
{
xOld = x;
loopCnt--;
/* cdfX = PROB { BETA(A,B) <= X }
q = ( cdf - cdfX ) / pdfX */
double cdfX = betaCdf(a, b, x);
double pdfX = betaPdf(a, b, x);
double q = (p - cdfX) / pdfX;
/* D(N,K) = C(N,K) * Q**(N+K-1) / (N-1)! */
double t = 1.0 - x;
double s1 = q * ( b - 1.0 ) / t;
double s2 = q * ( 1.0 - a ) / x;
d[2-1+0*MAXK] = s1 + s2;
double tail = d[2-1+0*MAXK] * q / 2.0;
x = x + q + tail;
int k = 3;
while ( error < fabs ( tail / x ) && k <= MAXK )
{
/* find D(2,K-2) */
s1 = q * ((double)(k) - 2.0) * s1 / t;
s2 = q * (2.0 - (double)(k)) * s2 / x;
d[2-1+(k-2)*MAXK] = s1 + s2;
/* find D(3,K-3), D(4,K-4), D(5,K-5), ... , D(K-1,1) */
for (int i=3; i<=k-1; i++)
{
double sum2 = d[2-1+0*MAXK] * d[i-2+(k-i)*MAXK];
bcoeff = 1.0;
for ( j = 1; j <= k - i; j++ )
{
bcoeff = ( bcoeff * ( double ) ( k - i - j + 1 ) ) / ( double ) ( j );
sum2 = sum2 + bcoeff * d[2-1+j*MAXK] * d[i-2+(k-i-j)*MAXK];
}
d[i-1+(k-i)*MAXK] = sum2 + d[i-2+(k-i+1)*MAXK] / (double)(i - 1);
}
/* compute D(K,0) and use it to expand the series */
d[k-1+0*MAXK] = d[2-1+0*MAXK] * d[k-2+0*MAXK] + d[k-2+1*MAXK] / (double)(k - 1);
tail = d[k-1+0*MAXK] * q / (double)(k);
x += tail;
/* check for divergence */
if ( x <= 0.0 || 1.0 <= x )
{
cout << "Error in betaQuantile: The series has diverged" << endl;
x = -1.0;
return x;
}
k++;
}
}
return x;
# undef MAXK
}
#pragma mark Dirichlet Distribution
/*!
* This function generates a Dirichlet-distributed random variable.
*
* \brief Dirichlet random variable.
* \param *a is a pointer to a vector of doubles containing the parameters of the Dirichlet.
* \param n is an integer with the number of Dirichlet prameters.
* \param *z is a pointer to a vector of doubles containing the Dirichlet random variable.
* \return Does not return a value (the random variable is initialized in the parameter z).
* \throws Does not throw an error.
*/
void MbRandom::dirichletRv(const MbVector<double> &a, MbVector<double> &z) {
int n = a.size();
double sum = 0.0;
for(int i=0; i<n; i++)
{
/* z[i] = rndGamma(a[i]) / 1.0; */
z[i] = rndGamma(a[i]);
sum += z[i];
}
for(int i=0; i<n; i++)
z[i] /= sum;
}
/*!
* This function calculates the probability density
* for a Dirichlet-distributed random variable.
*
* \brief Dirichlet probability density.
* \param *a is a pointer to a vector of doubles containing the Dirichlet parameters.
* \param *z is a pointer to a vector of doubles containing the random variables.
* \param n is the number of Dirichlet parameters/random variables.
* \return Returns the probability density.
* \throws Throws an MbException::ERROR.
*/
double MbRandom::dirichletPdf(const MbVector<double> &a, const MbVector<double> &z) {
int n = a.size();
double zSum = 0.0;
for (int i=0; i<n; i++)
zSum += z[i];
double tol = 0.0001;
if ( tol < fabs( zSum - 1.0 ) )
{
cout << "Fatal error in dirichletPdf" << endl;
exit(1);
//ui->error("Fatal error in dirichletPdf");
//throw(MbException(MbException::ERROR));
}
double aSum = 0.0;
for (int i=0; i<n; i++)
aSum += a[i];
double aProd = 1.0;
for (int i=0; i<n; i++)
aProd *= gamma(a[i]);
double pdf = gamma(aSum) / aProd;
for (int i=0; i<n; i++)
pdf = pdf * pow( z[i], a[i] - 1.0 );
return pdf;
}
/*!
* This function calculates the natural log of the probability density
* for a Dirichlet-distributed random variable.
*
* \brief Natural log of Dirichlet probability density.
* \param *a is a pointer to a vector of doubles containing the Dirichlet parameters.
* \param *z is a pointer to a vector of doubles containing the random variables.
* \param n is the number of Dirichlet parameters/random variables.
* \return Returns the natural log of the probability density.
* \throws Does not throw an error.
*/
double MbRandom::lnDirichletPdf(const MbVector<double> &a, const MbVector<double> &z) {
int n = a.size(); //!< we assume that a and z have the same size
double alpha0 = 0.0;
for (int i=0; i<n; i++)
alpha0 += a[i];
double lnP = lnGamma(alpha0);
for (int i=0; i<n; i++)
lnP -= lnGamma(a[i]);
for (int i=0; i<n; i++)
lnP += (a[i] - 1.0) * log(z[i]);
return lnP;
}
#pragma mark Poisson Distribution
/*!
* This function generates a Poisson-distributed random
* variable with parameter lambda.
*
* \brief Poisson(lambda) random variable.
* \param lambda the rate parameter of the Poisson.
* \return This function returns a Poisson-distributed integer.
* \throws Does not throw an error.
*/
int MbRandom::poissonRv(double lambda) {
if (lambda < 17.0)
{
if (lambda < 1.0e-6)
{
if (lambda == 0.0)
return 0;
if (lambda < 0.0)
{
/* there should be an error here */
cout << "Parameter negative in poisson function" << endl;
}
/* For extremely small lambda we calculate the probabilities of x = 1
and x = 2 (ignoring higher x). The reason for using this
method is to prevent numerical inaccuracies in other methods. */
return poissonLow(lambda);
}
else
{
/* use the inversion method */
return poissonInver(lambda);
}
}
else
{
if (lambda > 2.0e9)
{
/* there should be an error here */
cout << "Parameter too big in poisson function" <<endl;
}
/* use the ratio-of-uniforms method */
return poissonRatioUniforms(lambda);
}
}
/*!
* This function calculates the cumulative probability for a
* Poisson distribution.
*
* \brief Poisson cumulative probability.
* \param lambda is the rate parameter of the Poisson.
* \param x is the value of the random variable.
* \return Returns the cumulative probability.
* \throws Does not throw an error.
*/
double MbRandom::poissonCdf(double lambda, int x) {
if ( x < 0 )
return 0.0;
double next = exp(-lambda);
double cdf = next;
for (int i=1; i<=x; i++)
{
double last = next;
next = last * lambda / (double)i;
cdf += next;
}
return cdf;
}
/*!
* This function calculates the beta function.
*
* \brief Beta function.
* \param a is an argument.
* \param b is an argument.
* \return Returns the value of the beta function.
* \throws Does not throw an error.
*/
double MbRandom::beta(double a, double b) {
return ( exp(lnGamma(a) + lnGamma(b) - lnGamma(a + b)) );
}
/*!
* This function calculates the gamma function for real x.
*
* \brief Gamma function.
* \param x is the argument.
* \return Returns the value of the gamma function.
* \throws Does not throw an error.
*/
double MbRandom::gamma(double x) {
double c[7] = { -1.910444077728E-03,
8.4171387781295E-04,
-5.952379913043012E-04,
7.93650793500350248E-04,
-2.777777777777681622553E-03,
8.333333333333333331554247E-02,
5.7083835261E-03 };
double fact;
int i;
int n;
double p[8] = { -1.71618513886549492533811,
2.47656508055759199108314E+01,
-3.79804256470945635097577E+02,
6.29331155312818442661052E+02,
8.66966202790413211295064E+02,
-3.14512729688483675254357E+04,
-3.61444134186911729807069E+04,
6.64561438202405440627855E+04 };
bool parity;
double q[8] = { -3.08402300119738975254353E+01,
3.15350626979604161529144E+02,
-1.01515636749021914166146E+03,
-3.10777167157231109440444E+03,
2.25381184209801510330112E+04,
4.75584627752788110767815E+03,
-1.34659959864969306392456E+05,
-1.15132259675553483497211E+05 };
double sqrtpi = 0.9189385332046727417803297;
double sum2;
double value;
double xbig = 35.040;
double xden;
double xminin = 1.18E-38;
double xnum;
double y;
double y1;
double ysq;
double z;
parity = false;
fact = 1.0;
n = 0;
y = x;
if ( y <= 0.0 )
{
/* argument negative */
y = -x;
y1 = ( double ) ( ( int ) ( y ) );
value = y - y1;
if ( value != 0.0 )
{
if ( y1 != ( double ) ( ( int ) ( y1 * 0.5 ) ) * 2.0 )
parity = true;
fact = -PI / sin(PI * value);
y = y + 1.0;
}
else
{
//value = d_huge ( );
value = HUGE_VAL;
return value;
}
}
if ( y < mbEpsilon() )
{
/* argument < EPS */
if ( xminin <= y )
{
value = 1.0 / y;
}
else