-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoolkit.f90
1894 lines (1589 loc) · 64.4 KB
/
toolkit.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
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! toolkit.f90, a toolkit for fortran90 programming
! Borja Petit, © 2021
!
! general purpose:
! - grid: generate a grid for a continuous varibale
! - interpolation: interpolate a value over a grid, returning position and distance
! - interpolate: linearly interpolate a value over an n-dimensional grid, with n <= 6
! - timing: returns the number of seconds since 00:00h of the 1st day of the month [robust to parelalization]
! - multiplo: returns 1 if an integer is a multiple of another user-provided integer
! - iseven: returns 1 if a user-provided integer is even
!
! statistics:
! - varmean: returns the average of a variable, allowing for weigths
! - varstd: returns the standard deviation of a variable, allowing for weigths
! - correlation: returns the correlation of two variables, allowing for weigths
! - percentile: returns the i-th percentile of a variables, allowing for weigths
! - ols: returns the ols coefficients of a 1-var or 2-var regression, allowing for weigths
! - fit2poli: fits a 2nd order polynomianl to a variable, allowing for weigths
! - tachen: returns the transition matrix for a discretized ar(1) process
! - randomnormal: returns a random draw for a nomal distribution
! - cdfn: retutns the cdf of a nomabl distribution
! - beta_noncentral_cdf: returns the cdf from a beta distribution
!
! linear algebra:
! - vect: transform a matrix of dimension (n x m) into a vector of n·m rows
! - cumsum: returns the vector with cummulative sum of a vector (as matlab's cumsum function)
! - diag: returns the main diagonal of a matrix
! - transmat: returns the transpose of a square matrix
! - inverse: returns the invesrse of a sqaured matrix
!
! optimization (with and without states/fixed parameters)
! - simplex: simplex algorithm
! - lmmin: levenberg–marquardt algorithm
! - golden: golden search algorithm
! - brent: brent method
!
! it also includes some other functions/subroutines used for optimization:
! - broyden: updates a jacobian matrix using the broyden's method
! - normalize: transform a bounded variable into an unbounded one [for optimizaton]
! - denormalize: transform a undonded variable into an counded one [for optimizaton]
!
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
module toolkit
implicit none
integer , parameter :: dp = kind(1.0d00)
real(dp) , parameter :: zero = dble(0.00000000000000)
real(dp) , parameter :: half = dble(0.50000000000000)
real(dp) , parameter :: one = dble(1.00000000000000)
real(dp) , parameter :: two = dble(2.00000000000000)
real(dp) , parameter :: cien = dble(100.000000000000)
real(dp) , parameter :: mil = dble(1000.00000000000)
real(dp) , parameter :: tolvl = dble(0.00000000010000)
interface interpolate
module procedure interpolate1d,interpolate2d,interpolate3d,interpolate4d,interpolate5d,interpolate6d
end interface interpolate
interface vect
module procedure vectorize_int_2d,vectorize_int_3d,vectorize_int_4d,vectorize_int_5d,&
vectorize_dp_2d,vectorize_dp_3d,vectorize_dp_4d,vectorize_dp_5d
end interface vect
interface randomnormal
module procedure randomnormal_scalar,randomnormal_vec
end interface randomnormal
interface error
module procedure error_0,error_1
end interface error
interface num2text
module procedure int2text,real2text
end interface num2text
contains
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! general propuse functions and subroutines
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! ----------------------------------------------------------------------------
! this function creates a grid betwee "maxv" and "minv" with a curvature of "s"
! - if s>1: more grids points around "maxv"
! - if s<1: more grids points around "minv"
function grid(maxv,minv,n,s) result(v)
implicit none
integer :: i,n
real(dp) , optional :: s
real(dp) :: maxv,minv,grid0(n),v(n),ss,xmin,xmax
v(:) = zero ; ss = one ; if (present(s)) ss = s
xmin = min(maxv,minv)
xmax = max(maxv,minv)
if (ss.le.zero) call error(' errror in grid: spacing parameter is nonpositive')
if (ss.gt.zero) forall (i=1:n) grid0(i) = dble(i-1)/dble(n-1)
if (ss.gt.zero) forall (i=1:n) v(i) = (grid0(i)**ss)*(xmax-xmin) + minv
return
end function grid
! ----------------------------------------------------------------------------
! this subroutine finds the closest point in a given grid and return its
! position and the relative distance
subroutine interpolation(pos,wth,xnow,xgrid,outof)
implicit none
integer :: j,n,ofs
real(dp), intent(in) :: xnow,xgrid(:)
real(dp), intent(out) :: wth
integer , intent(out) :: pos
integer , intent(in) , optional :: outof
pos = 0 ; wth = zero ; ofs = 0
if (present(outof)) ofs = outof
if (isnan(xnow)) call error(' errror in interpolation: xnow is nan')
n = size(xgrid)
if (n.eq.1) then
pos = 1
wth = one
else
if (xnow.le.xgrid(1)) then
pos = 2
wth = zero
else if (xnow.ge.xgrid(n)) then
pos = n
wth = one
else if (xnow.gt.xgrid(1) .and. xnow.lt.xgrid(n)) then
j = 2
do while (xnow.gt.xgrid(j))
j = j + 1
end do
pos = j
wth = (xnow-xgrid(j-1))/(xgrid(j)-xgrid(j-1))
end if
end if
if (pos.lt.1 ) call error(' errror in interpolation: pos < 1')
if (pos.gt.n ) call error(' errror in interpolation: pos > size')
if (isnan(wth) ) call error(' errror in interpolation: wvar is nan')
return
end subroutine interpolation
! ----------------------------------------------------------------------------
! this set of functions return the linearly interpolated value of a
! n-dimensional vector with 6 >= n >= 1
! The user does not need oto call the specific subroutine, as the program will
! automatically call the appropiate one depending on the inputs.
! To use these subroutine, the command is:
!
! result = interpolate(val1,val2,...,valn,vector1,vector2,....vectorn,matrix)
!
! where "val1", "val2", ... are the values of the variables to be interpolated over
! their coresponding grids "vector1", "vector2, ...., and "matrix" is an
! n-dimensional array with the results.
function interpolate1d(x1,y1,m) result(xi)
implicit none
integer :: pos
real(dp) :: y1(:),m(:),x1,xi,wth
if (size(y1).ne.size(m)) call error(' error in interpolate: 1st dimension incorrect')
call interpolation(pos,wth,x1,y1)
xi = m(pos)*wth + m(pos-1)*(one-wth)
return
end function interpolate1d
function interpolate2d(x1,x2,y1,y2,m) result(xi)
implicit none
integer :: pos2
real(dp) :: wth2
real(dp) :: x1,x2,xi
real(dp) :: y1(:),y2(:),m(:,:)
if (size(m,2).ne.size(y2)) call error(' error in interpolate: 2nd dimension incorrect')
call interpolation(pos2,wth2,x2,y2)
xi = interpolate1d(x1,y1,m(:,pos2) )*wth2 + &
interpolate1d(x1,y1,m(:,pos2-1))*(one-wth2)
return
end function interpolate2d
function interpolate3d(x1,x2,x3,y1,y2,y3,m) result(xi)
implicit none
integer :: pos3
real(dp) :: y1(:),y2(:),y3(:),x1,x2,x3,xi
real(dp) :: wth3,m(:,:,:)
if (size(m,3).ne.size(y3)) call error(' error in interpolate: 3rd dimension incorrect')
call interpolation(pos3,wth3,x3,y3)
xi = interpolate2d(x1,x2,y1,y2,m(:,:,pos3) )*wth3 + &
interpolate2d(x1,x2,y1,y2,m(:,:,pos3-1))*(one-wth3)
return
end function interpolate3d
function interpolate4d(x1,x2,x3,x4,y1,y2,y3,y4,m) result(xi)
implicit none
integer :: pos4
real(dp) :: y1(:),y2(:),y3(:),y4(:),x1,x2,x3,x4,xi
real(dp) :: wth4,m(:,:,:,:)
if (size(m,4).ne.size(y4)) call error(' error in interpolate: 4th dimension incorrect')
call interpolation(pos4,wth4,x4,y4)
xi = interpolate3d(x1,x2,x3,y1,y2,y3,m(:,:,:,pos4) )*wth4 + &
interpolate3d(x1,x2,x3,y1,y2,y3,m(:,:,:,pos4-1))*(one-wth4)
return
end function interpolate4d
function interpolate5d(x1,x2,x3,x4,x5,y1,y2,y3,y4,y5,m) result(xi)
implicit none
integer :: pos5
real(dp) :: y1(:),y2(:),y3(:),y4(:),y5(:),x1,x2,x3,x4,x5,xi
real(dp) :: wth5,m(:,:,:,:,:)
if (size(m,5).ne.size(y5)) call error(' error in interpolate: 5th dimension incorrect')
call interpolation(pos5,wth5,x5,y5)
xi = interpolate4d(x1,x2,x3,x4,y1,y2,y3,y4,m(:,:,:,:,pos5))*wth5 + &
interpolate4d(x1,x2,x3,x4,y1,y2,y3,y4,m(:,:,:,:,pos5-1))*(one-wth5)
return
end function interpolate5d
function interpolate6d(x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6,m) result(xi)
implicit none
integer :: pos6
real(dp) :: y1(:),y2(:),y3(:),y4(:),y5(:),y6(:),x1,x2,x3,x4,x5,x6,xi
real(dp) :: wth6,m(:,:,:,:,:,:)
if (size(m,5).ne.size(y5)) call error(' error in interpolate: 6th dimension incorrect')
call interpolation(pos6,wth6,x6,y6)
xi = interpolate5d(x1,x2,x3,x4,x5,y1,y2,y3,y4,y5,m(:,:,:,:,:,pos6))*wth6 + &
interpolate5d(x1,x2,x3,x4,x5,y1,y2,y3,y4,y5,m(:,:,:,:,:,pos6-1))*(one-wth6)
return
end function interpolate6d
! ----------------------------------------------------------------------------
! this functions returns a timing number that is robust to parallel computing
! it returns the number of seconds since 00:00h of the 1st day of the month.
! the variable "mode" controls how time is measured:
! - if mode=1, time is measured in seconds (default).
! - if mode=2, time is measures in minutes.
! - if mode=3, time is measured in hours
function timing(mode) result(time)
implicit none
integer , optional :: mode
integer :: v1(8)
real(dp) :: time,v2(8) ; time = zero ; v2 = zero
call date_and_time(values=v1)
v2(2) = dble(v1(2)*30*24*60*60) ! months
v2(3) = dble(v1(3)* 24*60*60) ! days
v2(5) = dble(v1(5)* 60*60) ! hours
v2(6) = dble(v1(6)* 60) ! minutes
v2(7) = dble(v1(7) ) ! seconds
! measured in hours
if (present(mode)) then
if (mode.eq.3) then
time = sum(v2)/dble(60*60)
! measured in minutes
else if (mode.eq.2) then
time = sum(v2)/dble(60)
! measured in seconds
else
time = sum(v2)
end if
end if
return
end function timing
! ----------------------------------------------------------------------------
! this function checks whether a number "num" is a multiple of "xx".
function multiplo(num,xx) result(mul)
implicit none
integer :: num,xx
logical :: mul
if (xx*floor(dble(num)/dble(xx)).eq.num) mul = .true.
if (xx*floor(dble(num)/dble(xx)).ne.num) mul = .false.
return
end function multiplo
! ----------------------------------------------------------------------------
! this function checks whether a number "num" is an even number.
function iseven(num) result(ise)
implicit none
integer :: num
logical :: ise
ise = multiplo(num,2)
return
end function iseven
! ----------------------------------------------------------------------------
! this subroutine prints an error message.
subroutine error_0(mess)
implicit none
character(len=*) , intent(in) :: mess
write(*,*) trim(adjustl(mess))
return
end subroutine error_0
subroutine error_1(mess,i)
implicit none
integer , intent(out) :: i
character(len=*) , intent(in) :: mess
write(*,*) trim(adjustl(mess)) ; read * , i
return
end subroutine error_1
! ----------------------------------------------------------------------------
! this returns a string with the interger supplied by the user
function int2text(inter) result(txt)
implicit none
integer :: inter
character(len=100) :: txt0
character(len=:) , allocatable :: txt
write(txt0,'(i0)') inter
allocate(character(len=len(trim(adjustl(txt0)))) :: txt)
txt = trim(adjustl(txt0))
return
end function int2text
! ----------------------------------------------------------------------------
! this returns a string with the real number supplied by the user (w/ 2 decimals)
function real2text(realnum,decs) result(txt)
implicit none
real(dp) :: realnum
integer :: inter,decs0
integer , optional :: decs
character(len=100) :: txt0
character(len=:) , allocatable :: txt
decs0 = 2 ; if (present(decs)) decs0 = decs
inter = floor(realnum)
txt0 = int2text(inter)//"."//int2text(floor( (realnum-dble(inter))*dble(10.0**decs0) ))
allocate(character(len=len(trim(adjustl(txt0)))) :: txt)
txt = trim(adjustl(txt0))
return
end function real2text
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! statistics
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varmean(var,w,mask) result(meanvar)
implicit none
real(dp) :: var(:),meanvar
real(dp) , optional :: w(:)
logical , optional :: mask(:)
logical , allocatable :: mask1(:)
real(dp) , allocatable :: weig(:)
allocate(weig(size(var)))
allocate(mask1(size(var)))
weig(:) = one
mask1 = .true.
meanvar = zero
if (present(mask)) then
if (size(var).eq.size(mask)) then
mask1 = mask
else
call error('error in varmean: mask of incorrect size')
end if
end if
if (present(w)) then
if (size(var).ne.size(w)) call error('error in varmean!! var and w have different size')
!if (sum(w).lt.tolvl ) call error('error in varmean!! w are zero')
weig(:) = w(:)
end if
meanvar = sum(var(:)*weig(:),mask=mask1)/sum(weig,mask=mask1)
deallocate(weig)
deallocate(mask1)
return
end function varmean
! ----------------------------------------------------------------------------
! this function returns the standard deviation of a variable "var"
function varvar(var,w,mask) result(varian)
implicit none
real(dp) :: var(:),varian,mvar
real(dp) , optional :: w(:)
logical , optional :: mask(:)
logical , allocatable :: mask1(:)
real(dp) , allocatable :: weig(:)
allocate(weig(size(var)))
allocate(mask1(size(var)))
weig(:) = one
mask1 = .true.
varian = zero
mvar = zero
if (present(mask)) then
if (size(var).eq.size(mask)) then
mask1 = mask
else
call error('error in varvar: mask of incorrect size')
end if
end if
if (present(w)) then
if (size(var).ne.size(w)) call error('error in varvar!! var and w have different size')
!if (sum(w).lt.tolvl ) call error('error in varvar!! w are zero')
weig(:) = w(:)
end if
mvar = varmean(var,weig,mask=mask1.and..not.isnan(var))
varian = sum(weig*((var-mvar)**dble(2.00)),mask=mask1)/sum(weig,mask=mask1)
deallocate(weig)
deallocate(mask1)
return
end function varvar
! ----------------------------------------------------------------------------
! this function returns the standard deviation of a variable "var"
function varstd(var,w,mask) result(stdvar)
implicit none
real(dp) :: var(:),stdvar
real(dp) , optional :: w(:)
logical , optional :: mask(:)
logical , allocatable :: mask1(:)
real(dp) , allocatable :: weig(:)
allocate(weig(size(var)))
allocate(mask1(size(var)))
weig(:) = one
mask1 = .true.
stdvar = zero
if (present(mask)) then
if (size(var).eq.size(mask)) then
mask1 = mask
else
call error('error in varstd: mask of incorrect size')
end if
end if
if (present(w)) then
if (size(var).ne.size(w)) call error('error in varstd!! var and w have different size')
!if (sum(w).lt.tolvl ) call error('error in varstd!! w are zero')
weig(:) = w(:)
end if
stdvar = sqrt(varvar(var,weig,mask=mask1))
deallocate(weig)
deallocate(mask1)
return
end function varstd
! ----------------------------------------------------------------------------
! this function returns the correlation coefficient between two variables "xvar1" and "xvar2"
function correlation(xvar1,xvar2,w,mask) result(corr)
implicit none
real(dp) , optional :: w(:)
real(dp) :: xvar1(:),xvar2(:),corr
real(dp) :: aux1,aux2,aux3,aux4,aux5
logical , optional :: mask(:)
logical , allocatable :: mask1(:)
real(dp) , allocatable :: weig(:)
allocate(weig(size(xvar1)))
allocate(mask1(size(xvar1)))
corr = zero
weig(:) = one
mask1 = .true.
if (present(mask)) then
if (size(xvar1).eq.size(mask)) then
mask1 = mask
else
call error('error in varmean: mask of incorrect size')
end if
end if
if (size(xvar1).ne.size(xvar2)) call error('error in correaltion!! yvar and xvar of different sizes')
if (present(w)) then
if (size(xvar1).ne.size(w)) call error('error in correlation!! var and w have different size')
if (sum(w).lt.tolvl ) call error('error in correlation!! w are zero')
weig(:) = w(:)
end if
aux1 = varmean(xvar1,weig,mask=mask1)
aux2 = varstd(xvar1,weig,mask=mask1)
aux3 = varmean(xvar2,weig,mask=mask1)
aux4 = varstd(xvar2,weig,mask=mask1)
if (aux2.lt.tolvl) call error('error in correlation!! xvar1 is a constant')
if (aux4.lt.tolvl) call error('error in correlation!! xvar2 is a constant')
aux5 = sum(weig(:)*( (xvar1(:) - aux1)*(xvar2(:) - aux3) ),mask=mask1)/sum(weig,mask=mask1)
corr = aux5/(aux2*aux4)
deallocate(weig)
deallocate(mask1)
return
end function correlation
! ----------------------------------------------------------------------------
! this function returns the percentile "pct" for a distribution "xvec"
function percentile(xvec,pct,w,mask) result(cutoff)
implicit none
real(dp) :: xvec(:),pct,cutoff
real(dp) :: aux1,aux2,aux3,aux4
integer :: iter
real(dp) , optional :: w(:)
logical , optional :: mask(:)
logical , allocatable :: mask1(:)
real(dp) , allocatable :: weig(:)
allocate(weig(size(xvec)))
allocate(mask1(size(xvec)))
weig(:) = one
cutoff = zero
mask1 = .true.
if (present(mask)) then
if (size(xvec).eq.size(mask)) then
mask1 = mask
else
call error('error in percentile: mask of incorrect size')
end if
end if
if (present(w)) then
if (size(w).ne.size(w)) call error('error in percentile!! var and w have different size')
if (sum(w).lt.tolvl ) call error('error in percentile!! w are zero')
weig(:) = w(:)
end if
if (pct.gt.one ) call error('error in percentile!! invalid percetile: larger than 100')
if (pct.lt.zero) call error('error in percentile!! invalid percentile: negative value')
iter = 0
aux1 = maxval(xvec)
aux2 = minval(xvec)
do while ( abs(aux2-aux1).gt.tolvl .and. iter.lt.5000 ) ; iter = iter + 1
aux3 = half*(aux1+aux2)
aux4 = sum(weig,mask = xvec.le.aux3 .and. mask1)/sum(weig,mask=mask1)
if (aux4.le.pct) aux2 = aux3
if (aux4.ge.pct) aux1 = aux3
end do
cutoff = half*(aux1+aux2)
deallocate(weig)
deallocate(mask1)
return
end function percentile
! ----------------------------------------------------------------------------
! these functions return the coefficients from a ols regresion.
! it allows 1 and 2 explanatory variables, and returns the coefficients
! either as separate double precision variables or in a vector.
! The user can safely call the subroutine "ols(·)" without the need to specify
! the subroutine. The program will automatically call the corresponding subroutine
! depending on the number of variables and on the format of output variables
subroutine olsreg(coeffs,yvec,x1vec,x2vec,x3vec,x4vec,x5vec,x6vec,x7vec,x8vec,w,mask,iprint,stds)
implicit none
real(dp) , intent(out) :: coeffs(:)
real(dp) , intent(out) , optional :: stds(:)
real(dp) , intent(in) :: yvec(:)
real(dp) , intent(in) , optional :: x1vec(:),x2vec(:),x3vec(:),x4vec(:),x5vec(:),x6vec(:),x7vec(:),x8vec(:)
real(dp) , intent(in) , optional :: w(:)
logical , intent(in) , optional :: mask(:)
integer , intent(in) , optional :: iprint
logical , allocatable :: mask1(:)
real(dp) , allocatable :: yvar(:),xvars(:,:),zvar(:),wvar(:)
real(dp) , allocatable :: xTx(:,:),ixTx(:,:),xTy(:),wx(:,:)
real(dp) , allocatable :: evar(:),sdbeta(:,:),sdcoefs(:),tstats(:),inter(:,:)
real(dp) :: rsq,arsq
integer :: i,n0,no,nc,wc,nx ; nx = 1
n0 = size(yvec)
coeffs = -huge(one)
! mask – valid observations
allocate(mask1(n0)) ; mask1 = .true.
if (present(mask)) then
if (size(mask).eq.n0) mask1 = mask
if (size(mask).ne.n0) call error('error in olsreg!! mask of incorrect size')
end if
no = count(mask1) ! number of observations
if (no.eq.0) then
!call error('error in olsreg!! no observations')
return
end if
! weigths
allocate(wvar(n0)) ; wvar = one
if (present(w)) then
if (size(w).eq.n0) wvar = w
if (size(w).ne.n0) call error('error in olsreg!! weigths of incorrect size')
end if
! check number of explanatory variabkes
if (present(x1vec)) then ; nx = 1
if (n0.ne.size(x1vec)) call error('error in olsreg!! yvec and x1vec different observations')
end if
if (present(x2vec)) then ; nx = 2
if (n0.ne.size(x2vec)) call error('error in olsreg!! yvec and x2vec different observations')
end if
if (present(x3vec)) then ; nx = 3
if (n0.ne.size(x3vec)) call error('error in olsreg!! yvec and x3vec different observations')
end if
if (present(x4vec)) then ; nx = 4
if (n0.ne.size(x4vec)) call error('error in olsreg!! yvec and x4vec different observations')
end if
if (present(x5vec)) then ; nx = 5
if (n0.ne.size(x5vec)) call error('error in olsreg!! yvec and x5vec different observations')
end if
if (present(x6vec)) then ; nx = 6
if (n0.ne.size(x6vec)) call error('error in olsreg!! yvec and x6vec different observations')
end if
if (present(x7vec)) then ; nx = 7
if (n0.ne.size(x7vec)) call error('error in olsreg!! yvec and x7vec different observations')
end if
if (present(x8vec)) then ; nx = 8
if (n0.ne.size(x8vec)) call error('error in olsreg!! yvec and x8vec different observations')
end if
nc = size(coeffs) ! number of coefficients
wc = nc-nx ! with constant = 1, 0 if not
if (wc.ne.1 .and. wc.ne.0) then
print * , nc , nx , wc
call error('error in olsreg!! incorrect number of coefficients')
end if
if (present(stds)) then
if (size(stds).ne.size(coeffs)) call error('error in olsreg!! stds and coeffs of different size')
end if
! allocate y-variable and weigths
allocate(xvars(no,nc)) ; xvars = zero
allocate(yvar(no)) ; yvar = pack(yvec,mask1)
allocate(zvar(no)) ; zvar = pack(wvar,mask1)
! check weigths are positive
if (sum(zvar).lt.tolvl) call error('error in olsreg!! weigths are zero')
! fill constant (if exists) and first variable
if (wc.eq.1) xvars(:,1) = zvar/zvar
! fill remaining variables
if (present(x1vec)) xvars(:,1+wc) = pack(x1vec(:),mask1)
if (present(x2vec)) xvars(:,2+wc) = pack(x2vec(:),mask1)
if (present(x3vec)) xvars(:,3+wc) = pack(x3vec(:),mask1)
if (present(x4vec)) xvars(:,4+wc) = pack(x4vec(:),mask1)
if (present(x5vec)) xvars(:,5+wc) = pack(x5vec(:),mask1)
if (present(x6vec)) xvars(:,6+wc) = pack(x6vec(:),mask1)
if (present(x7vec)) xvars(:,7+wc) = pack(x7vec(:),mask1)
if (present(x8vec)) xvars(:,8+wc) = pack(x8vec(:),mask1)
! weigthed x-variables
allocate(wx(no,nc))
do i=1,no
wx(i,:) = xvars(i,:)*zvar(i)
end do
! allocate matrices for betas
allocate(xTx(nc,nc),ixTx(nc,nc),xTy(nc))
! compute betas
xTx = matmul(transmat(xvars),wx)
ixTx = inverse(xTx)
xTy = matmul(transmat(xvars),yvar(:)*zvar(:))
coeffs = matmul(ixTx,xTy)
allocate(evar(no),sdbeta(nc,nc),sdcoefs(nc),tstats(nc),inter(nc,2))
evar = yvar - matmul(xvars,coeffs)
sdbeta = ixTx*( sum(zvar*evar*evar) / dble(no-nc) )
sdcoefs = sqrt(diag(sdbeta))
tstats = abs(coeffs/sdcoefs)
if (present(stds)) then
stds = sdcoefs
end if
if (present(iprint)) then
if (iprint.ne.0) then
inter(:,1) = coeffs - dble(1.9601068)*sdcoefs
inter(:,2) = coeffs + dble(1.9601068)*sdcoefs
rsq = one - varvar(evar,w=zvar)/varvar(yvar,w=zvar)
arsq = one - ( (one-rsq)*dble(no-1)/dble(no-nc) )
write(*,99) ' '
write(*,99) ' '
write(*,'(a,i7 )') ' Number of variables = ',nc
write(*,'(a,i7 )') ' Number of observatios = ',n0
write(*,'(a,i7 )') ' Number of valid observatios = ',no
write(*,'(a,f7.4)') ' R-squared = ',rsq
write(*,'(a,f7.4)') ' Adjusted R-squared = ',arsq
write(*,99) ' '
write(*,99) ' -----------------------------------------------------------'
write(*,99) ' beta sd(b) minb maxb t-stat'
write(*,99) ' -----------------------------------------------------------'
if (wc.eq.1) then
write(*,99) ' Constant ' ,coeffs(wc),sdcoefs(wc),inter(wc,:),tstats(wc)
end if
do i=1,nx
write(*,98) ' Var ' ,i, ' ',coeffs(i+wc),sdcoefs(i+wc),inter(i+wc,:),tstats(i+wc)
end do
write(*,99) ' -----------------------------------------------------------'
write(*,99) ' '
end if
end if
deallocate(evar,sdbeta,sdcoefs,tstats,inter)
deallocate(xvars,xTx,ixTx,xTy,yvar,zvar,mask1,wvar)
return
99 format (a,f10.4,f10.4,f10.4,f10.4,f10.4)
98 format (a,i1,a,f10.4,f10.4,f10.4,f10.4,f10.4)
end subroutine olsreg
! ----------------------------------------------------------------------------
! this function returns the transition matrix for a discretized ar(1) process
! with gaussian shocks
subroutine tauchen(xvec,rho,mu,sigma,n,pmat)
implicit none
integer , intent(in) :: n
real(dp) , intent(in) :: rho,mu,sigma,xvec(n)
real(dp) , intent(out) :: pmat(n,n)
integer :: i
do i=1,n
pmat(i,:) = zero
call normaldist(xvec,mu+rho*xvec(i),sigma,n,pmat(i,:))
end do
return
end subroutine tauchen
! ----------------------------------------------------------------------------
! this function returns the transition matrix for a discretized ar(1) process
! with gaussian shocks
subroutine normaldist(xvec,mu,sigma,n,dist)
implicit none
integer , intent(in) :: n
real(dp) , intent(in) :: mu,sigma,xvec(n)
real(dp) , intent(out) :: dist(n)
real(dp) :: xvec0(n),aux1
integer :: j
xvec0 = (xvec-mu)/sigma
dist(1) = cdfn( dble(0.5)*(xvec0(2)+xvec0(1)) )
do j=2,n-1
dist(j) = cdfn( dble(0.5)*(xvec0(j+1)+xvec0(j)) ) - cdfn( dble(0.5)*(xvec0(j)+xvec0(j-1)) )
end do
dist(n) = 1.0 - cdfn( dble(0.5)*(xvec0(n)+xvec0(n-1)) )
aux1 = sum(dist)
dist = dist(:)/aux1
return
end subroutine normaldist
! ----------------------------------------------------------------------------
! this function returns a random number from a normal distributino with mean
! "mu" and stadard deviation "std"
subroutine randomnormal_scalar(shock,mu,std)
implicit none
real(dp) , intent(out) :: shock
real(dp) , intent(in) :: mu,std
real(dp) :: u,v,q
real(dp) , parameter :: s = 0.449871 , t = -0.386595 , a = 0.19600
real(dp) , parameter :: r1 = 0.275970 , r2 = 0.278460 , b = 0.25472
do
call random_number(u)
call random_number(v)
v = 1.7156 * (v - half)
q = (u-s)**2 + (abs(v)-t)*(a*(abs(v)-t) - b*(u-s))
if (q < r1) exit
if (q > r2) cycle
if (v**2 < -dble(4.0)*log(u)*u**dble(2.00)) exit
end do
shock = std*v/u + mu
return
end subroutine randomnormal_scalar
subroutine randomnormal_vec(shock,mu,std)
implicit none
integer :: i
real(dp) , intent(out) :: shock(:)
real(dp) , intent(in) :: mu,std
real(dp) :: q
do i=1,size(shock)
call randomnormal_scalar(shock(i),mu,std)
end do
q = sum(shock)/dble(size(shock))
shock = shock - q + mu
return
end subroutine randomnormal_vec
! ----------------------------------------------------------------------------
! given a value "x" (an scalar or a vector), the function returns f(x) = p(x<x),
! where f(·) is the cdf of a standard nomral distribution
elemental function cdfn(x) result(f)
implicit none
real(dp) , intent(in) :: x
real(dp) :: f,xabs,xsq
real(dp) , parameter :: a0 = 0.500000000000d0 , a1 = 0.398942280444d0
real(dp) , parameter :: a2 = 0.399903438504d0 , a3 = 5.758854804580d0
real(dp) , parameter :: a4 = 29.82135578080d0 , a5 = 2.624331216790d0
real(dp) , parameter :: a6 = 48.69599306920d0 , a7 = 5.928857244380d0
real(dp) , parameter :: b0 = 0.398942280385d0 , b1 = 3.8052d-8
real(dp) , parameter :: b2 = 1.000006153020d0 , b3 = 3.98064794d-4
real(dp) , parameter :: b4 = 1.986153813640d0 , b5 = 0.151679116635d0
real(dp) , parameter :: b6 = 5.293303249260d0 , b7 = 4.8385912808d0
real(dp) , parameter :: b8 = 15.15089724510d0 , b9 = 0.742380924027d0
real(dp) , parameter :: b10 = 30.78993303400d0 , b11 = 3.99019417011d0
xabs = abs(x)
xsq = a0*x**2
if (xabs <= 1.28d0)then
f = a0-xabs*(a1-a2*xsq/(xsq+a3-a4/(xsq+a5+a6/(xsq+a7))))
else if (xabs <= 12.7d0)then
f = b0*exp(-xsq)/(xabs-b1+b2/(xabs+b3+b4/(xabs-b5+b6/(xabs+b7-b8/ &
(xabs+b9+b10/(xabs+b11))))))
else
f = 0d0
end if
if (x > 0d0) f = 1d0-f
return
end function cdfn
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! linear algebra
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! ----------------------------------------------------------------------------
! these functions returns a vector with all the elements of a matrix.
! the function allows both double precission and integer matrices of
! 2-, 3- and 4-dimensions
function vectorize_dp_2d(mat) result(vec)
implicit none
real(dp) :: mat(:,:)
real(dp) :: vec(size(mat,1)*size(mat,2))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_dp_2d
function vectorize_dp_3d(mat) result(vec)
implicit none
real(dp) :: mat(:,:,:)
real(dp) :: vec(size(mat,1)*size(mat,2)*size(mat,3))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_dp_3d
function vectorize_dp_4d(mat) result(vec)
implicit none
real(dp) :: mat(:,:,:,:)
real(dp) :: vec(size(mat,1)*size(mat,2)*size(mat,3)*size(mat,4))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_dp_4d
function vectorize_dp_5d(mat) result(vec)
implicit none
real(dp) :: mat(:,:,:,:,:)
real(dp) :: vec(size(mat,1)*size(mat,2)*size(mat,3)*size(mat,4)*size(mat,5))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_dp_5d
function vectorize_int_2d(mat) result(vec)
implicit none
integer :: mat(:,:)
integer :: vec(size(mat,1)*size(mat,2))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_int_2d
function vectorize_int_3d(mat) result(vec)
implicit none
integer :: mat(:,:,:)
integer :: vec(size(mat,1)*size(mat,2)*size(mat,3))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_int_3d
function vectorize_int_4d(mat) result(vec)
implicit none
integer :: mat(:,:,:,:)
integer :: vec(size(mat,1)*size(mat,2)*size(mat,3)*size(mat,4))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_int_4d
function vectorize_int_5d(mat) result(vec)
implicit none
integer :: mat(:,:,:,:,:)
integer :: vec(size(mat,1)*size(mat,2)*size(mat,3)*size(mat,4)*size(mat,5))
vec = reshape(mat,(/size(vec)/))
return
end function vectorize_int_5d
! ----------------------------------------------------------------------------
! this function returns a vector "vec1" with the cummmulative sum of the elements
! of a vector "vec0"
function cumsum(vec0) result(vec1)
implicit none
real(dp) :: vec0(:),vec1(size(vec0))
integer :: i
vec1 = vec0(i) ; do i=2,size(vec0) ; vec1(i) = sum(vec0(1:i)) ; end do
return
end function cumsum
! ----------------------------------------------------------------------------
! this function returns the main diagonal of a matric "mat"
function diag(mat) result(vec)
implicit none
real(dp) :: mat(:,:),vec(size(mat,1))
integer :: i
if (size(mat,1).ne.size(mat,2)) call error(' error in diag: matrix not sqaure')
forall (i=1:size(mat,1)) vec(i) = mat(i,i)
return
end function diag
! ----------------------------------------------------------------------------
! returns the transpose of a matrix "mat"
function transmat(mat) result(matt)
implicit none
real(dp) :: mat(:,:),matt(size(mat,2),size(mat,1))
integer :: i
forall (i=1:size(mat,1)) matt(:,i) = mat(i,:)
return
end function transmat
! ----------------------------------------------------------------------------
! compute the inverse of a sqaure matrix "m"
function inverse(m) result(im)
implicit none
integer :: n,i,j,k
real(dp) :: m(:,:),coeff
real(dp) :: im(size(m,1),size(m,1)),b(size(m,1)),d(size(m,1)),x(size(m,1))
real(dp) :: l(size(m,1),size(m,1)),u(size(m,1),size(m,1)),mb(size(m,1),size(m,1))
if (size(m,1).ne.size(m,2)) call error(' error in inverse: matrix is not square')
n = size(m,1) ; l = zero ; u = zero ; b = zero ; mb = m
do k=1,n-1 ; do i=k+1,n
coeff = m(i,k)/m(k,k)
l(i,k) = coeff
do j=k+1,n
m(i,j) = m(i,j)-coeff*m(k,j)
end do
end do ; end do