-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.f90
1673 lines (1364 loc) · 44.2 KB
/
random.f90
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
module random
! A module for random number generation from the following distributions:
!
! Distribution function/subroutine name
!
! Normal (Gaussian) random_normal
! Gamma random_gamma
! Chi-squared random_chisq
! Exponential random_exponential
! Weibull random_Weibull
! Beta random_beta
! t random_t
! Multivariate normal random_mvnorm
! Generalized inverse Gaussian random_inv_gauss
! Poisson random_Poisson
! Binomial random_binomial1 *
! random_binomial2 *
! Negative binomial random_neg_binomial
! von Mises random_von_Mises
! Cauchy random_Cauchy
!
! Generate a random ordering of the integers 1 .. N
! random_order
! Initialize (seed) the uniform random number generator for ANY compiler
! seed_random_number
! Lognormal - see note below.
! ** Two functions are provided for the binomial distribution.
! if the parameter values remain constant, it is recommended that the
! first function is used (random_binomial1). if one or both of the
! parameters change, use the second function (random_binomial2).
! The compilers own random number generator, subroutine RANdoM_NUMBER(r),
! is used to provide a source of uniformly distributed random numbers.
! N.B. At this stage, only one random number is generated at each call to
! one of the functions above.
! The module uses the following functions which are included here:
! bin_prob to calculate a single binomial probability
! lngamma to calculate the logarithm to base e of the gamma function
! Some of the code is adapted from Dagpunar's book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
!
! In most of Dagpunar's routines, there is a test to see whether the value
! of one or two floating-point parameters has changed since the last call.
! These tests have been replaced by using a logical variable FIRST.
! This should be set to .TRUE. on the first call using new values of the
! parameters, and .FALSE. if the parameter values are the same as for the
! previous call.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Lognormal distribution
! if X has a lognormal distribution, then log(X) is normally distributed.
! Here the logarithm is the natural logarithm, that is to base e, sometimes
! denoted as ln. To generate random variates from this distribution, generate
! a random deviate from the normal distribution with mean and variance equal
! to the mean and variance of the logarithms of X, then take its exponential.
! Relationship between the mean & variance of log(X) and the mean & variance
! of X, when X has a lognormal distribution.
! Let m = mean of log(X), and s^2 = variance of log(X)
! Then
! mean of X = exp(m + 0.5s^2)
! variance of X = (mean(X))^2.[exp(s^2) - 1]
! In the reverse direction (rarely used)
! variance of log(X) = log[1 + var(X)/(mean(X))^2]
! mean of log(X) = log(mean(X) - 0.5var(log(X))
! N.B. The above formulae relate to population parameters; they will only be
! approximate if applied to sample values.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Version 1.13, 2 October 2000
! Changes from version 1.01
! 1. The random_order, random_Poisson & random_binomial routines have been
! replaced with more efficient routines.
! 2. A routine, seed_random_number, has been added to seed the uniform random
! number generator. This requires input of the required number of seeds
! for the particular compiler from a specified I/O unit such as a keyboard.
! 3. Made compatible with Lahey's ELF90.
! 4. Marsaglia & Tsang algorithm used for random_gamma when shape parameter > 1.
! 5. intent for array f corrected in random_mvnorm.
! Author: Alan Miller
! e-mail: amiller @ bigpond.net.au
implicit none
public :: dp,random_normal,random_exponential,random_laplace,lngamma,pi, &
seed_random_number,random_order,random_cauchy,random_binomial1, &
random_binomial2,random_neg_binomial,random_von_mises,random_poisson, &
random_inv_gauss,random_weibull,random_beta,random_mvnorm,random_chisq, &
random_t,random_normal_vec_inline,random_beta_vec,random_shuffle, &
random_seed_init
real, private :: zero = 0.0, half = 0.5, one = 1.0, two = 2.0, &
vsmall = tiny(1.0), vlarge = huge(1.0)
private :: integral
integer, parameter :: dp = selected_real_kind(12, 60)
real(kind=dp), parameter :: pi = 3.141592653589793D0
interface random_laplace
module procedure random_laplace_scalar,random_laplace_vec
end interface
interface random_normal
module procedure random_normal_scalar,random_normal_vec,random_normal_mat
end interface
contains
!
function random_laplace_scalar() result(yy)
real(kind=dp) :: yy
real(kind=dp) :: xran
call random_number(xran)
yy = random_exponential()*merge(-1,1,xran>0.5_dp)
end function random_laplace_scalar
!
function random_laplace_vec(n,standard) result(yy)
integer, intent(in) :: n
logical, intent(in), optional :: standard
real(kind=dp) :: yy(n)
real(kind=dp) :: xran
integer :: i
do i=1,n
call random_number(xran)
yy(i) = random_exponential()*merge(-1,1,xran>0.5_dp)
end do
if (present(standard)) then
if (standard) yy = yy / sqrt(2.0_dp)
end if
end function random_laplace_vec
!
function random_normal_mat(n1, n2) result(mat)
! return an n1-by-n2 matrix of random normal variates
integer, intent(in) :: n1, n2
real(kind=dp) :: mat(n1, n2)
integer :: i1, i2
do i2=1,n2
do i1=1,n1
mat(i1,i2) = random_normal_scalar()
end do
end do
end function random_normal_mat
!
function random_normal_vec(n) result(vec)
! return n random normal variates
integer, intent(in) :: n
real(kind=dp) :: vec(n)
integer :: i
do i=1,n
vec(i) = random_normal_scalar()
end do
end function random_normal_vec
!
function random_normal_scalar() result(fn_val)
! Adapted from the following Fortran 77 code
! ALGORITHM 712, COLLECTED ALGORITHMS FROM ACM.
! THIS WORK PUBLISHED IN TRANSACTIONS ON MATHEMATICAL SOFTWARE,
! VOL. 18, NO. 4, DECEMBER, 1992, PP. 434-435.
! The function random_normal() returns a normally distributed pseudo-random
! number with zero mean and unit variance.
! The algorithm uses the ratio of uniforms method of A.J. kinderman
! and J.F. Monahan augmented with quadratic bounding curves.
real :: fn_val
! Local variables
real, parameter :: s = 0.449871, t = -0.386595, a = 0.19600, b = 0.25472, &
r1 = 0.27597, r2 = 0.27846
real :: u, v, x, y, q
! Generate P = (u,v) uniform in rectangle enclosing acceptance region
do
call random_number(u)
call random_number(v)
v = 1.7156 * (v - half)
! Evaluate the quadratic form
x = u - s
y = abs(v) - t
q = x**2 + y*(a*y - b*x)
! Accept P if inside inner ellipse
if (q < r1) exit
! Reject P if outside outer ellipse
if (q > r2) cycle
! Reject P if outside acceptance region
if (v**2 < -4.0*log(u)*u**2) exit
end do
! Return ratio of P's coordinates as the normal deviate
fn_val = v/u
end function random_normal_scalar
!
function random_normal_vec_inline(n) result(fn_val)
! Adapted from the following Fortran 77 code
! ALGORITHM 712, COLLECTED ALGORITHMS FROM ACM.
! THIS WORK PUBLISHED IN TRANSACTIONS ON MATHEMATICAL SOFTWARE,
! VOL. 18, NO. 4, DECEMBER, 1992, PP. 434-435.
! The function random_normal() returns a normally distributed pseudo-random
! number with zero mean and unit variance.
! The algorithm uses the ratio of uniforms method of A.J. kinderman
! and J.F. Monahan augmented with quadratic bounding curves.
integer, intent(in) :: n
real :: fn_val(n)
! Local variables
real, parameter :: s = 0.449871, t = -0.386595, a = 0.19600, b = 0.25472, &
r1 = 0.27597, r2 = 0.27846
real :: u, v, x, y, q
integer :: i
! Generate P = (u,v) uniform in rectangle enclosing acceptance region
do i=1,n
do
call random_number(u)
call random_number(v)
v = 1.7156 * (v - half)
! Evaluate the quadratic form
x = u - s
y = abs(v) - t
q = x**2 + y*(a*y - b*x)
! Accept P if inside inner ellipse
if (q < r1) exit
! Reject P if outside outer ellipse
if (q > r2) cycle
! Reject P if outside acceptance region
if (v**2 < -4.0*log(u)*u**2) exit
end do
! Return ratio of P's coordinates as the normal deviate
fn_val(i) = v/u
end do
end function random_normal_vec_inline
!
function random_gamma(s, first) result(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! function GENERATES A RANdoM GAMMA VARIATE.
! callS EITHER random_gamma1 (S > 1.0)
! OR random_exponential (S = 1.0)
! OR random_gamma2 (S < 1.0).
! S = SHAPE parameter OF DISTRIBUTION (0 < real).
real, intent(IN) :: s
logical, intent(IN) :: first
real :: fn_val
if (s <= zero) then
write(*, *) 'SHAPE parameter VALUE MUST BE POSITIVE'
stop
end if
if (s > one) then
fn_val = random_gamma1(s, first)
ELSE if (s < one) then
fn_val = random_gamma2(s, first)
ELSE
fn_val = random_exponential()
end if
return
end function random_gamma
function random_gamma1(s, first) result(fn_val)
! Uses the algorithm in
! Marsaglia, G. and Tsang, W.W. (2000) `A simple method for generating
! gamma variables', Trans. om Math. Software (TOMS), vol.26(3), pp.363-372.
! Generates a random gamma deviate for shape parameter s >= 1.
real, intent(IN) :: s
logical, intent(IN) :: first
real :: fn_val
! Local variables
real, save :: c, d
real :: u, v, x
if (first) then
d = s - one/3.
c = one/SQRT(9.0*d)
end if
! Start of main loop
do
! Generate v = (1+cx)^3 where x is random normal; repeat if v <= 0.
do
x = random_normal()
v = (one + c*x)**3
if (v > zero) exit
end do
! Generate uniform variable U
call random_number(u)
if (u < one - 0.0331*x**4) then
fn_val = d*v
exit
ELSE if (log(u) < half*x**2 + d*(one - v + log(v))) then
fn_val = d*v
exit
end if
end do
return
end function random_gamma1
function random_gamma2(s, first) result(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! function GENERATES A RANdoM VARIATE IN [0,INFINITY) FROM
! A GAMMA DISTRIBUTION WITH DENSITY PROPORTIONAL TO
! GAMMA2**(S-1) * exp(-GAMMA2),
! USING A SWITCHING METHOD.
! S = SHAPE parameter OF DISTRIBUTION
! (real < 1.0)
real, intent(IN) :: s
logical, intent(IN) :: first
real :: fn_val
! Local variables
real :: r, x, w
real, save :: a, p, c, uf, vr, d
if (s <= zero .OR. s >= one) then
write(*, *) 'SHAPE parameter VALUE OUTSIDE PERMITTED RANGE'
stop
end if
if (first) then ! Initialization, if necessary
a = one - s
p = a/(a + s*exp(-a))
if (s < vsmall) then
write(*, *) 'SHAPE parameter VALUE TOO SMALL'
stop
end if
c = one/s
uf = p*(vsmall/a)**s
vr = one - vsmall
d = a*log(a)
end if
do
call random_number(r)
if (r >= vr) then
cycle
ELSE if (r > p) then
x = a - log((one - r)/(one - p))
w = a*log(x)-d
ELSE if (r > uf) then
x = a*(r/p)**c
w = x
ELSE
fn_val = zero
return
end if
call random_number(r)
if (one-r <= w .AND. r > zero) then
if (r*(w + one) >= one) cycle
if (-log(r) <= w) cycle
end if
exit
end do
fn_val = x
return
end function random_gamma2
function random_chisq(ndf, first) result(fn_val)
! Generates a random variate from the chi-squared distribution with
! ndf degrees of freedom
integer, intent(IN) :: ndf
logical, intent(IN) :: first
real :: fn_val
fn_val = two * random_gamma(half*ndf, first)
return
end function random_chisq
function random_exponential() result(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! function GENERATES A RANdoM VARIATE IN [0,INFINITY) FROM
! A NEGATIVE expONENTIAL DlSTRIBUTION WlTH DENSITY PROPORTIONAL
! TO exp(-random_exponential), USING INVERSION.
real :: fn_val
! Local variable
real :: r
do
call random_number(r)
if (r > zero) exit
end do
fn_val = -log(r)
return
end function random_exponential
function random_Weibull(a) result(fn_val)
! Generates a random variate from the Weibull distribution with
! probability density:
! a
! a-1 -x
! f(x) = a.x e
real, intent(IN) :: a
real :: fn_val
! For speed, there is no checking that a is not zero or very small.
fn_val = random_exponential() ** (one/a)
return
end function random_Weibull
!
function random_beta_vec(n,aa,bb) result(fn_val)
integer , intent(in) :: n
real(kind=dp), intent(IN) :: aa, bb
real(kind=dp) :: fn_val(n)
integer :: i
if (n < 1) return
fn_val(1) = random_beta(aa,bb,first=.true.)
do i=2,n
fn_val(i) = random_beta(aa,bb,first=.false.)
end do
end function random_beta_vec
!
function random_beta(aa, bb, first) result(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! function GENERATES A RANdoM VARIATE IN [0,1]
! FROM A BETA DISTRIBUTION WITH DENSITY
! PROPORTIONAL TO BETA**(AA-1) * (1-BETA)**(BB-1).
! USING CHENG'S log logISTIC METHOD.
! AA = SHAPE parameter FROM DISTRIBUTION (0 < real)
! BB = SHAPE parameter FROM DISTRIBUTION (0 < real)
real(kind=dp), intent(IN) :: aa, bb
logical, intent(IN) :: first
real(kind=dp) :: fn_val
! Local variables
real(kind=dp), parameter :: aln4 = 1.3862944_dp
real(kind=dp) :: a, b, g, r, s, x, y, z
real(kind=dp), save :: d, f, h, t, c
logical, save :: swap
if (aa <= zero .OR. bb <= zero) then
write(*, *) 'IMPERMISSIBLE SHAPE parameter VALUE(S)'
stop
end if
if (first) then ! Initialization, if necessary
a = aa
b = bb
swap = b > a
if (swap) then
g = b
b = a
a = g
end if
d = a/b
f = a+b
if (b > one) then
h = SQRT((two*a*b - f)/(f - two))
t = one
ELSE
h = b
t = one/(one + (a/(vlarge*b))**b)
end if
c = a+h
end if
do
call random_number(r)
call random_number(x)
s = r*r*x
if (r < vsmall .OR. s <= zero) cycle
if (r < t) then
x = log(r/(one - r))/h
y = d*exp(x)
z = c*x + f*log((one + d)/(one + y)) - aln4
if (s - one > z) then
if (s - s*z > one) cycle
if (log(s) > z) cycle
end if
fn_val = y/(one + y)
ELSE
if (4.0_dp*s > (one + one/d)**f) cycle
fn_val = one
end if
exit
end do
if (swap) fn_val = one - fn_val
end function random_beta
function random_t(m) result(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! function GENERATES A RANdoM VARIATE FROM A
! T DISTRIBUTION USING kindERMAN AND MONAHAN'S RATIO METHOD.
! M = DEGREES OF FREEdoM OF DISTRIBUTION
! (1 <= 1NTEGER)
integer, intent(IN) :: m
real :: fn_val
! Local variables
real, save :: s, c, a, f, g
real :: r, x, v
real, parameter :: three = 3.0, four = 4.0, quart = 0.25, &
five = 5.0, sixteen = 16.0
integer :: mm = 0
if (m < 1) then
write(*, *) 'IMPERMISSIBLE DEGREES OF FREEdoM'
stop
end if
if (m /= mm) then ! Initialization, if necessary
s = m
c = -quart*(s + one)
a = four/(one + one/s)**c
f = sixteen/a
if (m > 1) then
g = s - one
g = ((s + one)/g)**c*SQRT((s+s)/g)
ELSE
g = one
end if
mm = m
end if
do
call random_number(r)
if (r <= zero) cycle
call random_number(v)
x = (two*v - one)*g/r
v = x*x
if (v > five - a*r) then
if (m >= 1 .AND. r*(v + three) > f) cycle
if (r > (one + v/s)**c) cycle
end if
exit
end do
fn_val = x
return
end function random_t
subroutine random_mvnorm(n, h, d, f, first, x, ier)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! N.B. An extra argument, ier, has been added to Dagpunar's routine
! subroutine GENERATES AN N VARIATE RANdoM NORMAL
! VECTOR USING A CHOLESKY DECOMPOSITION.
! ARGUMENTS:
! N = NUMBER OF VARIATES IN VECTOR
! (INput,integer >= 1)
! H(J) = J'TH ELEMENT OF VECTOR OF MEANS
! (INput,real)
! X(J) = J'TH ELEMENT OF DELIVERED VECTOR
! (OUTput,real)
!
! D(J*(J-1)/2+I) = (I,J)'TH ELEMENT OF VARIANCE MATRIX (J> = I)
! (INput,real)
! F((J-1)*(2*N-J)/2+I) = (I,J)'TH ELEMENT OF LOWER TRIANGULAR
! DECOMPOSITION OF VARIANCE MATRIX (J <= I)
! (OUTput,real)
! FIRST = .TRUE. if THIS IS THE FIRST call OF THE ROUTINE
! OR if THE DISTRIBUTION HAS CHANGED SINCE THE LAST call OF THE ROUTINE.
! OTHERWISE SET TO .FALSE.
! (INput,logical)
! ier = 1 if the input covariance matrix is not +ve definite
! = 0 otherwise
integer, intent(IN) :: n
real, intent(IN) :: h(:), d(:) ! d(n*(n+1)/2)
real, intent(IN OUT) :: f(:) ! f(n*(n+1)/2)
real, intent(OUT) :: x(:)
logical, intent(IN) :: first
integer, intent(OUT) :: ier
! Local variables
integer :: j, i, m
real :: y, v
integer, save :: n2
if (n < 1) then
write(*, *) 'SIZE OF VECTOR IS NON POSITIVE'
stop
end if
ier = 0
if (first) then ! Initialization, if necessary
n2 = 2*n
if (d(1) < zero) then
ier = 1
return
end if
f(1) = SQRT(d(1))
y = one/f(1)
do j = 2,n
f(j) = d(1+j*(j-1)/2) * y
end do
do i = 2,n
v = d(i*(i-1)/2+i)
do m = 1,i-1
v = v - f((m-1)*(n2-m)/2+i)**2
end do
if (v < zero) then
ier = 1
return
end if
v = SQRT(v)
y = one/v
f((i-1)*(n2-i)/2+i) = v
do j = i+1,n
v = d(j*(j-1)/2+i)
do m = 1,i-1
v = v - f((m-1)*(n2-m)/2+i)*f((m-1)*(n2-m)/2 + j)
end do ! m = 1,i-1
f((i-1)*(n2-i)/2 + j) = v*y
end do ! j = i+1,n
end do ! i = 2,n
end if
x(1:n) = h(1:n)
do j = 1,n
y = random_normal()
do i = j,n
x(i) = x(i) + f((j-1)*(n2-j)/2 + i) * y
end do ! i = j,n
end do ! j = 1,n
return
end subroutine random_mvnorm
function random_inv_gauss(h, b, first) result(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! function GENERATES A RANdoM VARIATE IN [0,INFINITY] FROM
! A REparameterISED GENERALISED INVERSE GAUSSIAN (GIG) DISTRIBUTION
! WITH DENSITY PROPORTIONAL TO GIG**(H-1) * exp(-0.5*B*(GIG+1/GIG))
! USING A RATIO METHOD.
! H = parameter OF DISTRIBUTION (0 <= real)
! B = parameter OF DISTRIBUTION (0 < real)
real, intent(IN) :: h, b
logical, intent(IN) :: first
real :: fn_val
! Local variables
real :: ym, xm, r, w, r1, r2, x
real, save :: a, c, d, e
real, parameter :: quart = 0.25
if (h < zero .OR. b <= zero) then
write(*, *) 'IMPERMISSIBLE DISTRIBUTION parameter VALUES'
stop
end if
if (first) then ! Initialization, if necessary
if (h > quart*b*SQRT(vlarge)) then
write(*, *) 'THE RATIO H:B IS TOO SMALL'
stop
end if
e = b*b
d = h + one
ym = (-d + SQRT(d*d + e))/b
if (ym < vsmall) then
write(*, *) 'THE VALUE OF B IS TOO SMALL'
stop
end if
d = h - one
xm = (d + SQRT(d*d + e))/b
d = half*d
e = -quart*b
r = xm + one/xm
w = xm*ym
a = w**(-half*h) * SQRT(xm/ym) * exp(-e*(r - ym - one/ym))
if (a < vsmall) then
write(*, *) 'THE VALUE OF H IS TOO LARGE'
stop
end if
c = -d*log(xm) - e*r
end if
do
call random_number(r1)
if (r1 <= zero) cycle
call random_number(r2)
x = a*r2/r1
if (x <= zero) cycle
if (log(r1) < d*log(x) + e*(x + one/x) + c) exit
end do
fn_val = x
return
end function random_inv_gauss
function random_Poisson(mu, first) result(ival)
!**********************************************************************
! Translated to Fortran 90 by Alan Miller from:
! RANLIB
!
! Library of Fortran Routines for Random Number Generation
!
! Compiled and Written by:
!
! Barry W. Brown
! James Lovato
!
! Department of Biomathematics, Box 237
! The University of Texas, M.D. Anderson Cancer Center
! 1515 Holcombe Boulevard
! Houston, TX 77030
!
! This work was supported by grant CA-16672 from the National Cancer Institute.
! GENerate POIsson random deviate
! function
! Generates a single random deviate from a Poisson distribution with mean mu.
! Arguments
! mu --> The mean of the Poisson distribution from which
! a random deviate is to be generated.
! real mu
! Method
! For details see:
! Ahrens, J.H. and Dieter, U.
! Computer Generation of Poisson Deviates
! From Modified Normal Distributions.
! ACM Trans. Math. Software, 8, 2
! (June 1982),163-179
! TABLES: COEFFICIENTS A0-A7 FOR STEP F. FACTORIALS FACT
! COEFFICIENTS A(K) - FOR PX = FK*V*V*SUM(A(K)*V**K)-DEL
! SEPARATION OF CASES A AND B
! .. Scalar Arguments ..
real, intent(IN) :: mu
logical, intent(IN) :: first
integer :: ival
! ..
! .. Local Scalars ..
real :: b1, b2, c, c0, c1, c2, c3, del, difmuk, e, fk, fx, fy, g, &
omega, px, py, t, u, v, x, xx
real, save :: s, d, p, q, p0
integer :: j, k, kflag
logical, save :: full_init
integer, save :: l, m
! ..
! .. Local Arrays ..
real, save :: pp(35)
! ..
! .. Data statements ..
real, parameter :: a0 = -.5, a1 = .3333333, a2 = -.2500068, a3 = .2000118, &
a4 = -.1661269, a5 = .1421878, a6 = -.1384794, &
a7 = .1250060
real, parameter :: fact(10) = (/ 1., 1., 2., 6., 24., 120., 720., 5040., &
40320., 362880. /)
! ..
! .. Executable Statements ..
if (mu > 10.0) then
! C A S E A. (RECALCULATION OF S, D, L if MU HAS CHANGED)
if (first) then
s = SQRT(mu)
d = 6.0*mu*mu
! THE POISSON PROBABILITIES PK EXCEED THE DISCRETE NORMAL
! PROBABILITIES FK WHENEVER K >= M(MU). L=ifIX(MU-1.1484)
! IS AN UPPER BOUND TO M(MU) FOR ALL MU >= 10 .
l = mu - 1.1484
full_init = .false.
end if
! STEP N. NORMAL SAMPLE - random_normal() FOR STANDARD NORMAL DEVIATE
g = mu + s*random_normal()
if (g > 0.0) then
ival = g
! STEP I. IMMEDIATE ACCEPTANCE if ival IS LARGE ENOUGH
if (ival>=l) return
! STEP S. SQUEEZE ACCEPTANCE - SAMPLE U
fk = ival
difmuk = mu - fk
call random_number(u)
if (d*u >= difmuk*difmuk*difmuk) return
end if
! STEP P. PREPARATIONS FOR STEPS Q AND H.
! (RECALCULATIONS OF parameterS if NECESSARY)
! .3989423=(2*PI)**(-.5) .416667E-1=1./24. .1428571=1./7.
! THE QUANTITIES B1, B2, C3, C2, C1, C0 ARE FOR THE HERMITE
! APPROXIMATIONS TO THE DISCRETE NORMAL PROBABILITIES FK.
! C=.1069/MU GUARANTEES MAJORIZATION BY THE 'HAT'-function.
if (.NOT. full_init) then
omega = .3989423/s
b1 = .4166667E-1/mu
b2 = .3*b1*b1
c3 = .1428571*b1*b2
c2 = b2 - 15.*c3
c1 = b1 - 6.*b2 + 45.*c3
c0 = 1. - b1 + 3.*b2 - 15.*c3
c = .1069/mu
full_init = .true.
end if
if (g < 0.0) GO TO 50
! 'subroutine' F IS callED (KFLAG=0 FOR CORRECT return)
kflag = 0
GO TO 70
! STEP Q. QUOTIENT ACCEPTANCE (RARE CASE)
40 if (fy-u*fy <= py*exp(px-fx)) return
! STEP E. expONENTIAL SAMPLE - random_exponential() FOR STANDARD expONENTIAL
! DEVIATE E AND SAMPLE T FROM THE LAPLACE 'HAT'
! (if T <= -.6744 then PK < FK FOR ALL MU >= 10.)
50 e = random_exponential()
call random_number(u)
u = u + u - one
t = 1.8 + SIGN(e, u)
if (t <= (-.6744)) GO TO 50
ival = mu + s*t
fk = ival
difmuk = mu - fk
! 'subroutine' F IS callED (KFLAG=1 FOR CORRECT return)
kflag = 1
GO TO 70
! STEP H. HAT ACCEPTANCE (E IS REPEATED ON REJECTION)
60 if (c*abs(u) > py*exp(px+e) - fy*exp(fx+e)) GO TO 50
return
! STEP F. 'subroutine' F. CALCULATION OF PX, PY, FX, FY.
! CASE ival < 10 USES FACTORIALS FROM TABLE FACT
70 if (ival>=10) GO TO 80
px = -mu
py = mu**ival/fact(ival+1)
GO TO 110
! CASE ival >= 10 USES POLYNOMIAL APPROXIMATION
! A0-A7 FOR ACCURACY WHEN ADVISABLE
! .8333333E-1=1./12. .3989423=(2*PI)**(-.5)
80 del = .8333333E-1/fk
del = del - 4.8*del*del*del
v = difmuk/fk
if (abs(v)>0.25) then
px = fk*log(one + v) - difmuk - del
ELSE
px = fk*v*v* (((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v+a0) - del
end if
py = .3989423/SQRT(fk)
110 x = (half - difmuk)/s
xx = x*x
fx = -half*xx
fy = omega* (((c3*xx + c2)*xx + c1)*xx + c0)
if (kflag <= 0) GO TO 40
GO TO 60
!---------------------------------------------------------------------------
! C A S E B. mu < 10
! START NEW TABLE AND CALCULATE P0 if NECESSARY
ELSE
if (first) then
m = MAX(1, INT(mu))
l = 0
p = exp(-mu)
q = p
p0 = p
end if
! STEP U. UNifORM SAMPLE FOR INVERSION METHOD
do
call random_number(u)
ival = 0
if (u <= p0) return
! STEP T. TABLE COMPARISON UNTIL THE end PP(L) OF THE
! PP-TABLE OF CUMULATIVE POISSON PROBABILITIES
! (0.458=PP(9) FOR MU=10)
if (l == 0) GO TO 150
j = 1
if (u > 0.458) j = MIN(l, m)
do k = j, l
if (u <= pp(k)) GO TO 180
end do
if (l == 35) cycle
! STEP C. CREATION OF NEW POISSON PROBABILITIES P
! AND THEIR CUMULATIVES Q=PP(K)
150 l = l + 1
do k = l, 35
p = p*mu / k
q = q + p
pp(k) = q
if (u <= q) GO TO 170