-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmod_numerical.f90
1490 lines (1260 loc) · 43.5 KB
/
mod_numerical.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 mod_numerical
!=========================================================================!
! Written by Alessandro Di Nola
! Main sources:
! https://github.com/drarnau/Replication_Krusell-et-al-2017/blob/master/Utils.f90
! https://sites.google.com/site/greygordon/code
! Numerical recipes in F90: http://numerical.recipes/
! http://karibzhanov.com/
! Giulio Fella: https://github.com/gfell
! Fabian Kindermann: https://www.ce-fortran.com/
! Date Programmer Description of change
! ==== ========== =====================
! 20210817 A. Di Nola Original code
! 20210818 A. Di Nola Changed lrzcurve
! 20210830 A. Di Nola Added function gini
! 20210901 A. Di Nola Added function ind2sub
!=========================================================================!
! USE other modules
implicit none
private !Variables and internal proc are not visible outside of this module
! User-defined error function
public :: myerror
! Replicate basic Matlab functions
public :: linspace
public :: ones, eye, cumsum, cumprod
public :: outerprod
public :: ind2sub
! Sorting subroutines
public :: QsortC
! General-purpose routines
public :: is_monotone, my_closest, grid, mycorr
! Markov chain:
public :: my_ss
! Interpolation:
public :: linint, locate
! Discretization:
public :: discretize_pareto, bddparetocdf, tauchen
! Percentiles, Gini and Lorenz curve:
public :: quantili, calculate_quintiles, lrzcurve_basic, lrzcurve, unique, gini
! Optimization:
public :: golden_method !similar to fminbnd in Matlab
! Root-finding:
public :: rtbis, zbrent !similar to fzero in Matlab
contains
subroutine myerror(string)
implicit none
character(len=*), intent(in) :: string
write(*,*) "ERROR: ", string
write(*,*) "Program will terminate.."
pause
stop
end subroutine myerror
!===============================================================================!
function linspace(my_start, my_stop, n)
! Purpose: replicate Matlab function <linspace>
! Originally written by Arnau Valladares-Esteban
implicit none
! Inputs:
integer :: n
real(8) :: my_start, my_stop
! Function result:
real(8) :: linspace(n)
! Locals:
integer :: i
real(8) :: step, grid(n)
if (n == 1) then
grid(n) = (my_start+my_stop)/2.d0
elseif (n.ge.2) then
grid(1) = my_start
if (n.gt.2) then
step = (my_stop-my_start)/(real(n-1))
do i = 2, n-1
grid(i) = grid(i-1) + step
end do
end if
grid(n) = my_stop
endif
linspace = grid
end function linspace
!===============================================================================!
function ones(n) result(vec)
! Purpose: create a column vector of ones
! Input/output
integer, intent(in) :: n
real(8) :: vec(n)
!Local variables
integer :: i
! Body of ones
do i = 1,n
vec(i) = 1.0d0
end do
end function ones
!===============================================================================!
function eye(n) result(mat)
! Purpose: replicate function <eye> in Matlab
! Input/output
integer, intent(in) :: n
real(8) :: mat(n,n)
!Local variables
integer :: i
! Body of eye
mat = 0.0d0
do i = 1,n
mat(i,i) = 1.0d0
end do
end function eye
!===============================================================================!
function outerprod(a,b)
! Computes the outer product of two vectors
real(8), intent(in) :: a(:), b(:)
real(8) :: outerprod(size(a),size(b))
outerprod = spread(a,dim=2,ncopies=size(b)) * spread(b,dim=1,ncopies=size(a))
end function outerprod
!===============================================================================!
FUNCTION cumsum(arr) RESULT(ans)
! Purpose: it replicates matlab <cumsum> function
real(8), INTENT(IN) :: arr(:)
! Note that a Fortran function can return a value with an ALLOCATABLE
! attribute. The function result must be declared as ALLOCATABLE
! in the calling unit but will not be allocated on entry to the function.
real(8), allocatable :: ans(:)
INTEGER :: n,j
n=size(arr)
allocate(ans(n))
ans(1)=arr(1)
do j=2,n
ans(j)=ans(j-1)+arr(j)
end do
END FUNCTION cumsum
!===============================================================================!
function is_monotone(arr) result(ans)
! Purpose: Check is a real array is monotonically increasing
implicit none
!Declare inputs:
real(8), intent(in) :: arr(:)
!Declare function result:
logical :: ans
!Declare locals:
integer :: i,n
n = size(arr)
if (n==1) then
ans = .true.
return
endif
do i=1,n-1
if ( arr(i)<=arr(i+1) ) then
ans = .true.
else
ans = .false.
return
endif
enddo
end function is_monotone
!===============================================================================!
function my_closest(myvector,gp,myvalue)
! Purpose: FINDS CLOSEST POSITION OF A REAL IN A VECTOR OF REALS
! Originally written by Arnau Valladares-Esteban
implicit none
integer, intent(in) :: gp
real(8), intent(in) :: myvalue
real(8), dimension(gp), intent(in) :: myvector
real(8), dimension(gp) :: aux
! Function result:
integer :: my_closest
aux = abs(myvector-myvalue)
my_closest = minloc(aux, dim=1)
end function my_closest
!===============================================================================!
subroutine unique(x, x_u,ind_u)
! Purpose: Find unique values in array x
! Return a smaller array with only unique values and corresponding (last) indeces
! Identical to matlab function 'unique' with 'last' option
! WARNING: The input array x must be sorted in ascending order
implicit none
real(8), intent(in) :: x(:)
real(8), intent(out), allocatable :: x_u(:)
integer, intent(out), allocatable :: ind_u(:)
! Local variables
integer :: i, n, i_u
! Execution
n = size(x)
allocate(x_u(n),ind_u(n))
x_u(1) = x(1)
i_u = 1
do i=2,n
if (x(i)>x(i-1)) then
ind_u(i_u) = i-1
x_u(i_u+1) = x(i)
i_u = i_u+1
endif
enddo
ind_u(i_u) = n
! Outputs
x_u = x_u(1:i_u)
ind_u = ind_u(1:i_u)
end subroutine unique
!===============================================================================!
function my_ss(tmatrix,gp)
! Purpose: STEADY STATE MARKOV CHAIN
! Originally written by Arnau Valladares-Esteban
implicit none
integer :: gp
integer :: row, col, iter
real(8) :: aux_sum
real(8), dimension(gp) :: my_ss
real(8), dimension(gp) :: dist, ndist
real(8), dimension(gp,gp) :: tmatrix
! Initialise distribution
dist = 1.d0/real(gp)
do iter = 1, 10000
ndist = 0.d0
do col = 1, gp
do row = 1, gp
ndist(col) = ndist(col) + (dist(row)*tmatrix(row,col))
end do
end do
aux_sum = sum(abs(ndist-dist))
dist = ndist
if (aux_sum.lt.1.0d-10) then
exit
end if
end do
my_ss = dist
end function my_ss
!===============================================================================!
SUBROUTINE grid(x,xmin,xmax,s)
! Purpose: Generate grid x on [xmin,xmax] using spacing parameter s set as follows:
! s=1 linear spacing
! s>1 left skewed grid spacing with power s
! 0<s<1 right skewed grid spacing with power s
! s<0 geometric spacing with distances changing by a factor -s^(1/(n-1)), (>1 grow, <1 shrink)
! s=-1 logarithmic spacing with distances changing by a factor (xmax-xmin+1)^(1/(n-1))
! s=0 logarithmic spacing with distances changing by a factor (xmax/xmin)^(1/(n-1)), only if xmax,xmin>0
IMPLICIT NONE
REAL(8), DIMENSION(:), INTENT(OUT) :: x
REAL(8), INTENT(IN) :: xmin,xmax,s
REAL(8) :: c ! growth rate of grid subintervals for logarithmic spacing
INTEGER :: n,i
n=size(x)
FORALL(i=1:n) x(i)=(i-1)/real(n-1,8)
IF (s>0.0d0) THEN
x=x**s*(xmax-xmin)+xmin
!IF (s==1.0d0) THEN
! PRINT '(a,i8,a,f7.3,a,f7.3,a)', 'Using ',n,' equally spaced grid points over domain [',xmin,',',xmax,']'
!ELSE
! PRINT '(a,i8,a,f7.3,a,f7.3,a,f7.3,a)', 'Using ',n,' skewed spaced grid points with power ',s,' over domain [',xmin,',',xmax,']'
!END IF
ELSE
IF (s==-1.0d0) THEN
c=xmax-xmin+1
! ELSEIF (s==0.0d0) THEN
! IF (xmin>0.0d0) THEN
! c=xmax/xmin
! ELSE
! STOP 'grid: can not use logarithmic spacing for nonpositive values'
! END IF
ELSE
c=-s
END IF
PRINT '(a,i8,a,f6.3,a,f6.3,a,f6.3,a)', 'Using ',n,' logarithmically spaced grid points with growth rate ',c,' over domain [',xmin,',',xmax,']'
x=((xmax-xmin)/(c-1))*(c**x)-((xmax-c*xmin)/(c-1))
END IF
END SUBROUTINE grid
!===============================================================================!
FUNCTION linint(x,y,xi)
! Purpose: linear interpolation of function y on grid x at interpolation point xi
! To make it pure, cannot use PRINT or STOP statements
IMPLICIT NONE
REAL(8), DIMENSION(:), INTENT(IN) :: x,y
REAL(8), INTENT(IN) :: xi
REAL(8) :: linint
REAL(8) :: a,b,d
INTEGER :: n,i
n=size(x)
IF (size(y)/=n) THEN
PRINT *, 'linint: x and y must be of the same size'
PAUSE
STOP 'program terminated by linint'
END IF
i=max(min(locate(x,xi),n-1),1)
d=x(i+1)-x(i)
!IF (d == 0.0) STOP 'bad x input in splint'
a=(x(i+1)-xi)/d
b=(xi-x(i))/d
linint=a*y(i)+b*y(i+1)
END FUNCTION linint
!===============================================================================!
PURE FUNCTION locate(xx,x)
IMPLICIT NONE
REAL(8), DIMENSION(:), INTENT(IN) :: xx
REAL(8), INTENT(IN) :: x
INTEGER :: locate
INTEGER :: n,il,im,iu
n=size(xx)
il=0
iu=n+1
do
if (iu-il <= 1) exit
im=(iu+il)/2
if (x >= xx(im)) then
il=im
else
iu=im
end if
end do
if (x == xx(1)) then
locate=1
else if (x == xx(n)) then
locate=n-1
else
locate=il
end if
END FUNCTION locate
!===============================================================================!
!===============================================================================!
!subroutine bracket(x, xval, l, r)
! ! original code by John Burkardt
! real(8), intent(in), dimension(:) :: x
! real(8), intent(in) :: xval
! integer, intent(out) :: l, r
! integer :: i, n
!
! n=size(x)
! do i = 2, n - 1
! if ( xval < x(i) ) then
! l = i - 1
! r = i
! return
! end if
! end do
! l = n - 1
! r = n
!end subroutine bracket
!===============================================================================!
function gini(x_in, y_in)
! DESCRIPTION: computes Lorenz curve and Gini coefficient
! Notes: written by F.Kindermann
! See: https://www.ce-fortran.com/forums/topic/gini-coefficient-and-lorenz-curve/#post-1951
use toolbox, only: sort, plot, execplot
real(8), intent(in) :: x_in(:), y_in(:)
real(8) :: gini
integer :: n, ic
real(8), allocatable :: xs(:), ys(:), xcum(:), ycum(:)
integer, allocatable :: iorder(:)
! get array size
n = size(x_in, 1)
! ALLOCATE LARGE ARRAYS TO AVOID SIZE PROBLEMS
! first deallocate
if(allocated(xs))deallocate(xs)
if(allocated(ys))deallocate(ys)
if(allocated(xcum))deallocate(xcum)
if(allocated(ycum))deallocate(ycum)
if(allocated(iorder))deallocate(iorder)
! then allocate
allocate(xs(n))
allocate(ys(n))
allocate(xcum(0:n))
allocate(ycum(0:n))
allocate(iorder(n))
! NOW CALCULATE GINI INDEX
! sort array
xs = x_in
call sort(xs, iorder)
! sort y's and normalize to 1
do ic = 1, n
ys(ic) = y_in(iorder(ic))
enddo
ys = ys/sum(ys)
! calculate cumulative distributions
xcum(0) = 0d0
ycum(0) = 0d0
do ic = 1, n
xcum(ic) = xcum(ic-1) + ys(ic)*xs(ic)
ycum(ic) = ycum(ic-1) + ys(ic)
enddo
! now normalize cumulated attributes
xcum = xcum/xcum(n)
! plot the Lorenz curve
call plot(ycum, ycum, linewidth=1d0, color="black", dashtype="--")
call plot(ycum, xcum)
call execplot()
! determine gini index
gini = 0d0
do ic = 1, n
gini = gini + ys(ic)*(xcum(ic-1) + xcum(ic))
enddo
gini = 1d0 - gini
end function gini
!===============================================================================!
function quantili(x,w,q) result(y)
! Purpose: computes quantiles q of x with weights w
! w is discrete prob function (or PMF)
! need not be sorted or normalized
! Sources: Cagetti and De Nardi M-function quantili.m
! Note: takes care of repeated values
! Dependencies: calls subroutine unique
use toolbox, only: sort
implicit none
!Declare inputs:
real(8), intent(in) :: x(:)
real(8), intent(in) :: w(:)
real(8), intent(in) :: q(:)
!Declare output:
real(8) :: y(size(q))
!Declare locals
integer :: i, n, istat
integer, allocatable :: ix(:), ind_u(:)
real(8), allocatable :: xs(:), ws(:), cums(:)
real(8), allocatable :: cums_u(:), xs_u(:)
n = size(x)
allocate( ix(n), xs(n),ws(n),cums(n),stat=istat )
if (istat/=0) then
call myerror("quantili: Allocation failed!")
endif
!!Check inputs
if (size(w)/=n) then
call myerror("quantili: x (variable) and w (pmf) must be of the same size")
endif
!xs is x sorted, ix is the sorting index
xs = x
call sort(xs,ix)
ws=w(ix)
ws=ws/sum(ws)
cums=cumsum(ws)
![xs_u,ind_u] = unique(xs,'last')
call unique(xs, xs_u,ind_u)
cums_u = cums(ind_u)
y = 0.0d0
do i=1,size(q)
if (cums_u(1)<=q(i)) then
y(i) = linint(cums_u,xs_u,q(i))
else
y(i) = xs_u(1)
endif
enddo
end function quantili
!===============================================================================!
subroutine calculate_quintiles(a_input,a_dist,thresholds, quantiles)
!Source: Kindermann's book pp. 467-469
!Compare to function "quantili" in this module (see below)
use toolbox, only: sort
implicit none
!Declare inputs:
real(8), intent(in) :: a_input(:)
real(8), intent(inout) :: a_dist(:)
real(8) :: thresholds(:)
!Declare outputs:
real(8), intent(out) :: quantiles(size(thresholds, 1))
!Declare locals:
integer :: ia, ic, it, NC, istat
real(8) :: slope
integer, allocatable :: iorder(:)
real(8), allocatable :: a_sort(:), a_cdist(:)
! define quantile thresholds (now passed as inputs to subr)
!thresholds = (/0.05d0, 0.25d0, 0.50d0, 0.75d0, 0.95d0/)
quantiles = 0d0
! K only uses asset levels with pop share of at least 10^(12)
! This is similar to getting rid of zeros as I do in lrzcurve
! --- SKIP FOR NOW ---!
NC = size(a_dist,1)
!!Check inputs
if (size(a_input)/=NC) then
call myerror("calculate_quintiles: a (variable) and a_dist (pmf) must be of the same size")
endif
allocate( iorder(NC), a_sort(NC), a_cdist(NC), stat=istat )
if (istat/=0) then
call myerror("calculate_quintiles: Allocation failed!")
endif
! sort array and distribution
a_sort = a_input
call sort(a_sort(1:NC), iorder(1:NC))
! calculate cumulative distribution (attention ordering)
a_cdist(1) = a_dist(iorder(1))
do ic = 2, NC
a_cdist(ic) = a_cdist(ic-1) + a_dist(iorder(ic))
enddo
! get quantiles
do it = 1, size(thresholds, 1)
if(thresholds(it) <= a_cdist(1))then
quantiles(it) = a_sort(1)
else
do ic = 2, NC
if(thresholds(it) < a_cdist(ic)) then
slope = (a_sort(ic)-a_sort(ic-1))/(a_cdist(ic)-a_cdist(ic-1))
quantiles(it) = a_sort(ic-1) + slope*(thresholds(it)-a_cdist(ic-1))
exit
elseif(ic == NC)then
quantiles(it) = a_sort(NC)
endif
enddo
endif
enddo
end subroutine calculate_quintiles
!===============================================================================!
subroutine lrzcurve_basic(f_in,y,gini)
! Purpose: It computes the Gini WITHOUT eliminating the zeros
! Source: This is a simplified version of Matlab <lrzcurve>
use toolbox, only: sort
implicit none
!Declare inputs and outputs:
real(8), intent(in) :: f_in(:) !Distribution
real(8), intent(in) :: y(:) !Variable of interest
real(8), intent(out) :: gini !Gini coefficient
!Declare local variables:
real(8) :: minpop
integer :: i,n, istat
real(8), allocatable :: f(:),y_sort(:), Scum(:),S(:),f_temp(:)
integer, allocatable :: key(:)
n = size(y)
!Check inputs
if (size(f_in)/=n) then
call myerror("lrzcurve_basic: f (distrib.) and y (var. of interest) must be of the same size")
endif
allocate(f(n),y_sort(n),Scum(n),S(n),key(n),stat=istat)
if (istat/=0) then
call myerror("lrzcurve_basic: Allocation failed!")
endif
!I do not want to modify f_in
f = f_in
!Sort x in scending order
!Sort p
y_sort = y
call sort(y_sort,key)
!f = f(key) !stack overflow occurs here
f_temp = f
do i=1,size(f)
f(i) = f_temp(key(i))
enddo
deallocate(f_temp)
S = y_sort*f
Scum = cumsum(S)
gini = f(1)*Scum(1)
do i=2,n
gini = gini + (Scum(i) + Scum(i-1))*f(i)
enddo
gini = 1.0d0 - (gini/Scum(n))
minpop = minval(f)
! Normalize the gini (smth not always done...)
gini = gini/(1.0d0 - minpop)
end subroutine lrzcurve_basic
!===============================================================================!
subroutine lrzcurve(p,x,gini_out,fx_out,sx_out,mean_x_out,stdv_x_out)
! ------------------------- LEGEND --------------------------------!
! Purpose: compute Lorenz curve, gini coeff, mean and std
! INPUTS:
! p is the probability distrib (it must sum to 1)
! x is a vector with the values of the variable of interest
! OUTPUTS:
! fx(:) is share of population
! sx(:) is the corresponding share of wealth/income/etc.
! E.g. plot Lorenz curve with fx on the x-axis and sx on the y-axis
! See wiki: https://en.wikipedia.org/wiki/Lorenz_curve
! DEPENDENCIES:
! lrzcurve calls a subroutine to sort arrays. It can either be
! <sort> from Kindermann's toolbox (and in this case you need to use
! the toolbox) or <QsortC> which is stored in this module
! -----------------------------------------------------------------!
!use toolbox, only: sort
implicit none
!Declare inputs:
real(8), intent(in) :: p(:)
real(8), intent(in) :: x(:)
!Declare outputs:
real(8), intent(out) :: gini_out
real(8), allocatable, intent(out), optional :: fx_out(:)
real(8), allocatable, intent(out), optional :: sx_out(:)
real(8), intent(out), optional :: mean_x_out
real(8), intent(out), optional :: stdv_x_out
!Declare locals:
integer :: n, i, n_valid, istat
real(8) :: minpop, mean_x, stdv_x, gini
real(8), allocatable :: p1(:), x1(:), fx(:), sx(:)
integer, allocatable :: key(:)
n = size(x)
if (size(p)/=n) then
call myerror("lrzcurve: x and p must have the same size")
endif
if (abs(sum(p)-1.0d0)>1d-8) then
call myerror("lrzcurve: p must sum to one")
endif
!Preliminary step
!Matlab code:
!%% Eliminate elements with zero probability
!p1=p; p(p1==0) = []; x(p1==0) = [];
p1 = pack(p,p/=0.0d0)
x1 = pack(x,p/=0.0d0)
n_valid = count(p/=0.0d0)
allocate(key(n_valid),stat=istat)
key = [ (i,i=1,n_valid) ]
if (istat/=0) then
call myerror("lrzcurve: Allocation failed!")
endif
!Compute mean and standard deviation
mean_x = dot_product(p1,x1)
stdv_x = dot_product(p1,(x1-mean_x)**2)
!Sort x1 in ascending order
!call sort(x1,key)
call QsortC(x1,key)
!Sort distribution accordingly
fx = p1(key)
!sx(i) is the term x(i)*fx(i)
sx = (x1*fx)
sx = sx/mean_x
!Add initial zero
fx = [0d0, fx]
sx = [0d0, sx]
!Compute cumulative sums:
! sx is the cumulative share of x
sx = cumsum(sx)
!Compute Gini coefficient:
gini = sx(1)*fx(1)
do i = 2,size(fx)
gini = gini +(sx(i)+sx(i-1))*fx(i)
enddo
gini = 1.0d0-(gini/sx(size(sx)))
! Keep the smallest population, needed to normalize the Gini coefficient
minpop = minval(p1)
! Normalize the gini (smth not always done...)
gini = gini/(1.0d0 - minpop)
! Assign outputs
gini_out = gini
! Assign optional outputs
! Lorenz curve(i) is (fx(i), shareX(i))
if (present(fx_out)) then
fx_out = cumsum(fx)
endif
if (present(sx_out)) then
sx_out = sx
endif
if (present(mean_x_out)) then
mean_x_out = mean_x
endif
if (present(stdv_x_out)) then
stdv_x_out = stdv_x
endif
end subroutine lrzcurve
!===============================================================================!
subroutine golden_method(f, a, b, x1, f1, mytol, mymaxit)
! Purpose: Applies Golden-section search to search for the *maximum* of a function
! in the interval (a, b).
! Source: https://en.wikipedia.org/wiki/Golden-section_search
! Adapted to Fortran90 from: https://github.com/QuantEcon
!---------------------------------------------------!
!INPUTS
interface
function f(x)
implicit none
real(8), intent(in) :: x
real(8) :: f
end function f
end interface
real(8), intent(in) :: a, b
!Some optional inputs
integer, optional :: mymaxit
real(8), optional :: mytol
!OUTPUTS
real(8), intent(out) :: x1, f1
!---------------------------------------------------!
!Locals
integer :: maxit, it
real(8) :: tol, alpha1, alpha2, d, f2, x2, s
!! Assign default value to maxit if not defined by user
if (present(mymaxit)) then
maxit = mymaxit
else
maxit = 1000
end if
! Assign default value to tol if not defined by user
if (present(mytol)) then
tol = mytol
else
tol = 1.0d-6
end if
alpha1 = (3.d0 - sqrt(5.d0)) / 2.d0
alpha2 = 1.d0 - alpha1
d = b - a
x1 = a + alpha1*d
x2 = a + alpha2*d
s = 1.d0
f1 = f(x1)
f2 = f(x2)
d = alpha1*alpha2*d
it = 0
do while ((d.gt.tol).and.(it.lt.maxit))
it = it + 1
d = d*alpha2
if (f2.gt.f1) then
x1 = x2
f1 = f2
x2 = x1 + s*d
else
x2 = x1 - s*d
end if
s = sign(s, x2-x1)
f2 = f(x2)
end do
if (it.ge.maxit) then
print *, "Golden method: Maximum iterations exceeded"
end if
if (f2.gt.f1) then
x1 = x2
f1 = f2
end if
end subroutine golden_method
!===============================================================================!
subroutine max_nonconvex(f, a, b, xmax, fmax, mytol, mymaxit, mynx)
! Purpose: Maximize the univariate function f(x) in [a,b]
! using either grid search or golden method or both
! Deals with non-concave objective functions
!---------------------------------------------------!
! INPUTS:
interface
function f(x)
implicit none
real(8), intent(in) :: x
real(8) :: f
end function f
end interface
real(8), intent(in) :: a, b
! Optional inputs:
integer, optional :: mymaxit
real(8), optional :: mytol
integer, optional :: mynx
! OUTPUTS:
real(8), intent(out) :: xmax, fmax
!---------------------------------------------------!
!Locals
integer :: maxit, x_c, max_ind, left_loc, right_loc
real(8) :: tol, x_val, max_val, temp, x1, f1
integer :: nx
real(8), allocatable :: x_grid(:)
! Assign default value to maxit if not defined by user
if (present(mymaxit)) then
maxit = mymaxit
else
maxit = 1000
end if
! Assign default value to tol if not defined by user
if (present(mytol)) then
tol = mytol
else
tol = 1.0d-6
end if
! Assign default value to nx if not defined by user
if (present(mynx)) then
nx = max(mynx,2)
else
nx = 100
end if
! Preliminary step: define the grid
allocate(x_grid(nx))
x_grid = linspace(a,b,nx)
! First step: grid search
max_val = -huge(0d0)
max_ind = 1
do x_c = 1,nx
x_val = x_grid(x_c)
temp = f(x_val)
if (temp>max_val) then
max_val = temp
max_ind = x_c
endif
enddo
! Second step: find the interval that brackets the true maximum
left_loc = max(max_ind-1,1)
right_loc = min(max_ind+1,nx)
! Last step: call golden_method section search
call golden_method(f, x_grid(left_loc), x_grid(right_loc), x1, f1, tol, maxit)
! Assign outputs
xmax = x1 ! arg max
fmax = f1 ! f(arg max)
end subroutine max_nonconvex
!===============================================================================!
FUNCTION rtbis(func,x1,x2,xacc,MAXIT)
!-------------------------------------------------------------!
! DESCRIPTION:
! Bisection to find root x of a nonlinear function func(x)=0
! INPUTS:
! func: function to pass to the rootfinder
! [x1 x2]: bracketing interval
! xacc: accuracy criterion
! MAXIT: maximum number of iterations
! OUTPUT
! rtbis: root of the function in [x1 x2]
! SOURCE:
! http://numerical.recipes/
!-------------------------------------------------------------!
IMPLICIT NONE
REAL(8), INTENT(IN) :: x1,x2,xacc
INTEGER, INTENT(IN) :: MAXIT
REAL(8) :: rtbis
INTERFACE
FUNCTION func(x)
IMPLICIT NONE
REAL(8), INTENT(IN) :: x
REAL(8) :: func
END FUNCTION func
END INTERFACE
!INTEGER, PARAMETER :: MAXIT=40
INTEGER :: j
REAL(8) :: dx,f,fmid,xmid
fmid = func(x2)
f = func(x1)
if (f*fmid >= 0.0d0) then
call myerror("rtbis: root must be bracketed")
endif
if (f < 0.0d0) then
rtbis=x1
dx=x2-x1
else
rtbis=x2
dx=x1-x2
end if
do j=1,MAXIT
dx=dx*0.5d0
xmid=rtbis+dx
fmid=func(xmid)
if (fmid <= 0.0d0) rtbis=xmid
if (abs(dx) < xacc .or. fmid == 0.0d0) RETURN
end do
write(*,*) "WARNING: rtbis: too many bisections"
END FUNCTION rtbis
!===============================================================================!
FUNCTION zbrent(func,x1,x2,tol,ITMAX)
!-------------------------------------------------------------!
! DESCRIPTION:
! Brent's method to find root x of a nonlinear function func(x)=0
! It is the same as fzero in Matlab. Brent's method is generally
! better than bisection.
! INPUTS:
! func: function to pass to the rootfinder
! [x1 x2]: bracketing interval
! tol: accuracy criterion
! MAXIT: maximum number of iterations ???
! OUTPUT
! rtbis: root of the function in [x1 x2]