-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmo_mcmc.f90
2219 lines (1904 loc) · 104 KB
/
mo_mcmc.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
!> \file mo_mcmc.f90
!> \brief This module is Monte Carlo Markov Chain sampling of a posterior parameter distribution.
!> \details This module is Monte Carlo Markov Chain sampling of a posterior parameter distribution.
!> \authors Maren Goehler, Juliane Mai
!> \date Aug 2012
MODULE mo_mcmc
! License
! -------
! This file is part of the JAMS Fortran package, distributed under the MIT License.
!
! Copyright (c) 2012-2014 Juliane Mai
!
! Permission is hereby granted, free of charge, to any person obtaining a copy
! of this software and associated documentation files (the "Software"), to deal
! in the Software without restriction, including without limitation the rights
! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
! copies of the Software, and to permit persons to whom the Software is
! furnished to do so, subject to the following conditions:
!
! The above copyright notice and this permission notice shall be included in all
! copies or substantial portions of the Software.
!
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
! SOFTWARE.
USE mo_kind, only: i4, i8, dp
USE mo_xor4096, only: xor4096, xor4096g, get_timeseed, n_save_state
USE mo_append, only: append
USE mo_moment, only: stddev
!$ USE omp_lib, only: OMP_GET_NUM_THREADS
use mo_ncdump, only: dump_netcdf
IMPLICIT NONE
PUBLIC :: mcmc ! Sample posterior parameter distribution (measurement errors are either known or modeled)
PUBLIC :: mcmc_stddev ! Sample posterior parameter distribution (measurement errors are neither known nor modeled)
!-----------------------------------------------------------------------------------------------
!
! NAME
! mcmc
!
! PURPOSE
!> \brief This module is Monte Carlo Markov Chain sampling of a posterior parameter distribution
!> (measurement errors are either known or modeled).
!
!> \details Sample posterior parameter distribution with Metropolis Algorithm.\n
!> This sampling is performed in two steps, i.e. the burn-in phase for adjusting
!> model dependent parameters for the second step which is the proper
!> sampling using the Metropolis Hastings Algorithm.\n\n
!>
!> This sampler does not change the best parameter set, i.e.
!> it cannot be used as an optimiser.\n
!> However, the serial and the parallel version give therefore the bitwise same results.
!
!> <b>1. BURN IN PHASE: FIND THE OPTIMAL STEP SIZE </b>\n\n
!
!> <b><i>Purpose:</i></b>\n
!> Find optimal stepsize for each parameter such that the
!> acceptance ratio converges to a value around 0.3.\n
!>
!> <b><i>Important variables:</i></b>\n
!>
!> <b> Variable | Description </b>
!> ---------------------- | -----------------------------------------------------------------------
!> burnin_iter | length of markov chain performed to calculate acceptance ratio\n
!> acceptance ratio | ratio between accepted jumps and all trials (LEN)\n
!> acceptance multiplier | stepsize of a parameter is multiplied with this value when jump is
!> accepted (initial : 1.01)
!> rejection multiplier | stepsize of a parameter is multiplied with this value when jump is rejected
!> (initial : 0.99 and will never be changed)
!> stepsize | a new parameter value is chosen based on a uniform distribution
!> pnew_i = pold_i + Unif(-stepsize_i, stepsize_i) (initial : stepsize_i = 1.0 for all i)
!
!> \n
!> <b><i>Algorithm:</i></b>\n
!> <ol>
!> <li>start a new markov chain of length burnin_iter with initial parameter set is the OPTIMAL one</i>\n
!> - select a set of parameters to change:\n
!> * accurate --> choose one parameter,\n
!> * comput. efficient --> choose all parameters,\n
!> * moderate accurate & efficient --> choose half of the parameters\n
!> - change parameter(s) based on their stepsize\n
!> - decide whether changed parameter set is accepted or rejected:\n
!> * \f$ \mathrm{odds Ratio} = \frac{\mathrm{likelihood}(p_{new})}{\mathrm{likelihood}(p_{old})} \f$\n
!> * random number r = Uniform[0,1]\n
!> * odds Ratio > 0 --> positive accept\n
!> odds Ratio > r --> negative accept\n
!> odds Ratio < r --> reject\n
!> - adapt stepsize of parameters changed:\n
!> * accepted step: stepsize_i = stepsize_i * accptance multiplier\n
!> * rejected step: stepsize_i = stepsize_i * rejection multiplier\n
!> - if step is accepted: for all changed parameter(s) change stepsize\n
!
!> <li>calculate acceptance ratio of the Markov Chain</i>\n
!
!> <li>adjust acceptance multiplier acc_mult and
!> store good ratios in history list\n
!> - acceptance ratio < 0.23 --> acc_mult = acc_mult * 0.99\n
!> delete history list\n
!> - acceptance ratio > 0.44 --> acc_mult = acc_mult * 1.01\n
!> delete history list\n
!> - 0.23 < acceptance ratio < 0.44\n
!> add acceptance ratio to history list\n
!
!> <li>check if already 10 values are stored in history list and
!> if they have converged to a value above 0.3\n
!> ( mean above 0.3 and variance less \f$\sqrt{1/12*0.05^2}\f$ = Variance
!> of uniform [acc_ratio +/- 2.5%] )\n
!> - if check is positive abort and save stepsizes\n
!> else goto (1)\n\n
!> </ol>
!
!>
!> <b>2. MONTE CARLO MARKOV CHAIN: SAMPLE POSTERIOR DISTRIBUTION OF PARAMETER</b>\n\n
!> <b><i>Purpose:</i></b>\n
!> use the previous adapted stepsizes and perform ONE monte carlo markov chain\n
!> the accepted parameter sets show the posterior distribution of parameters\n
!>
!> <b><i>Important variables:</i></b>\n
!> <b> Variable | Description </b>
!> ---------------------- | -----------------------------------------------------------------------
!> iter_mcmc | length of the markov chain (>> iter_burnin)\n
!> stepsize | a new parameter value is chosen based on a uniform distribution
!> pnew_i = pold_i + Unif(-stepsize_i, stepsize_i) use stepsizes of the burn-in (1)\n
!
!> \n
!> <b><i>Algorithm:</i></b>\n
!> <ol>
!> <li> select a set of parameters to change\n
!> * accurate --> choose one parameter,\n
!> * comput. efficient --> choose all parameters,\n
!> * moderate accurate & efficient --> choose half of the parameters\n
!> <li> change parameter(s) based on their stepsize\n
!> <li> decide whether changed parameter set is accepted or rejected:\n
!> * \f$ \mathrm{odds Ratio} = \frac{\mathrm{likelihood}(p_{new})}{\mathrm{likelihood}(p_{old})} \f$\n
!> * random number r = Uniform[0,1]\n
!> * odds Ratio > 0 --> positive accept\n
!> odds Ratio > r --> negative accept\n
!> odds Ratio < r --> reject\n
!> <li> if step is accepted: save parameter set\n
!> <li> goto (1)\n
!> </ol>
! CALLING SEQUENCE
! call mcmc( likelihood, para, rangePar, mcmc_paras, burnin_paras, &
! seed_in=seeds, printflag_in=printflag, maskpara_in=maskpara, &
! tmp_file=tmp_file, loglike_in=loglike, &
! ParaSelectMode_in=ParaSelectMode, &
! iter_burnin_in=iter_burnin, iter_mcmc_in=iter_mcmc, &
! chains_in=chains, stepsize_in=stepsize)
! INTENT(IN)
!> \param[in] "real(dp) :: likelihood(x)" Interface Function which calculates likelihood
!> of given parameter set x
!> \param[in] "real(dp) :: para(:)" Inital parameter set (should be GOOD approximation
!> of best parameter set)
!> \param[in] "real(dp) :: rangePar(size(para),2)" Min/max range of parameters
! INTENT(INOUT)
! None
! INTENT(OUT)
!> \param[out] "real(dp), allocatable :: mcmc_paras(:,:)" Parameter sets sampled in proper MCMC part of algorithm
!> \param[out] "real(dp), allocatable :: burnin_paras(:,:)" Parameter sets sampled during burn-in part of algorithm
! INTENT(IN), OPTIONAL
!> \param[in] "integer(i8), optional :: seed_in" User seed to initialise the random number generator \n
!> (default: none --> initialized with timeseed)
!> \param[in] "logical, optional :: printflag_in" Print of output on command line \n
!> (default: .False.)
!> \param[in] "logical, optional :: maskpara_in(size(para))"
!> Parameter will be sampled (.True.) or not (.False.) \n
!> (default: .True.)
!> \param[in] "character(len=*), optional :: tmp_file" filename for temporal data saving: \n
!> every iter_mcmc_in iterations parameter sets are
!> appended to this file \n
!> the number of the chain will be prepended to filename \n
!> output format: netcdf \n
!> (default: no file writing)
!> \param[in] "logical, optional :: loglike_in" true if loglikelihood function is given instead of
!> likelihood function \n
!> (default: .false.)
!> \param[in] "integer(i4), optional :: ParaSelectMode_in"
!> How many parameters will be changed at once?
!> - half of the parameter --> 1_i4
!> - only one parameter --> 2_i4
!> - all parameter --> 3_i4
!> (default: 2_i4)
!> \param[in] "integer(i4), optional :: iter_burnin_in" Length of Markov chains of initial burn-in part \n
!> (default: Max(250, 200*count(maskpara)) )
!> \param[in] "integer(i4), optional :: iter_mcmc_in" Length of Markov chains of proper MCMC part \n
!> (default: 1000 * count(maskpara) )
!> \param[in] "integer(i4), optional :: chains_in" number of parallel mcmc chains \n
!> (default: 5_i4)
!> \param[in] "real(dp), DIMENSION(size(para,1)), optional :: stepsize_in"
!> stepsize for each parameter \n
!> if given burn-in is discarded \n
!> (default: none --> adjusted in burn-in)
! INTENT(INOUT), OPTIONAL
! None
! INTENT(OUT), OPTIONAL
! None
! RESTRICTIONS
!> \note Likelihood has to be defined as a function interface\n
!> The maximal number of parameters is 1000.
! -> see also example in test directory
! EXAMPLE
! -> see also example in test directory
! LITERATURE
! Gelman et. al (1995)
! Baysian Data Analyis, Chapman & Hall.
! Gelman et. al (1997)
! Efficient Metropolis Jumping Rules, Baysian Statistics 5, pp. 599-607
! Tautenhahn et. al (2012)
! Beyond distance-invariant survival in inverse recruitment modeling:
! A case study in Siberian Pinus sylvestris forests, Ecological Modelling, 233,
! 90-103. doi:10.1016/j.ecolmodel.2012.03.009.
! HISTORY
! Written Mai, Nov. 2014 : add new routine for mcmc
! mcmc, i.e. mcmc with "real" likelihood (sigma is given by e.g. error model)
!
INTERFACE mcmc
MODULE PROCEDURE mcmc_dp
END INTERFACE mcmc
!-----------------------------------------------------------------------------------------------
!
! NAME
! mcmc_stddev
!
! PURPOSE
!> \brief This module is Monte Carlo Markov Chain sampling of a posterior parameter distribution
!> (measurement errors are neither known nor modeled).
!
!> \details Sample posterior parameter distribution with Metropolis Algorithm.\n
!> This sampling is performed in two steps, i.e. the burn-in phase for adjusting
!> model dependent parameters for the second step which is the proper
!> sampling using the Metropolis Hastings Algorithm.\n\n
!
!> <b>1. BURN IN PHASE: FIND THE OPTIMAL STEP SIZE </b>\n\n
!
!> <b><i>Purpose:</i></b>\n
!> Find optimal stepsize for each parameter such that the
!> acceptance ratio converges to a value around 0.3.\n
!>
!> <b><i>Important variables:</i></b>\n
!>
!> <b> Variable | Description </b>
!> ---------------------- | -----------------------------------------------------------------------
!> burnin_iter | length of markov chain performed to calculate acceptance ratio\n
!> acceptance ratio | ratio between accepted jumps and all trials (LEN)\n
!> acceptance multiplier | stepsize of a parameter is multiplied with this value when jump is
!> accepted (initial : 1.01)
!> rejection multiplier | stepsize of a parameter is multiplied with this value when jump is rejected
!> (initial : 0.99 and will never be changed)
!> stepsize | a new parameter value is chosen based on a uniform distribution
!> pnew_i = pold_i + Unif(-stepsize_i, stepsize_i) (initial : stepsize_i = 1.0 for all i)
!
!> \n
!> <b><i>Algorithm:</i></b>\n
!> <ol>
!> <li>start a new markov chain of length burnin_iter with initial parameter set is the OPTIMAL one</i>\n
!> - select a set of parameters to change:\n
!> * accurate --> choose one parameter,\n
!> * comput. efficient --> choose all parameters,\n
!> * moderate accurate & efficient --> choose half of the parameters\n
!> - change parameter(s) based on their stepsize\n
!> - decide whether changed parameter set is accepted or rejected:\n
!> * \f$ \mathrm{odds Ratio} = \frac{\mathrm{likelihood}(p_{new})}{\mathrm{likelihood}(p_{old})} \f$\n
!> * random number r = Uniform[0,1]\n
!> * odds Ratio > 0 --> positive accept\n
!> odds Ratio > r --> negative accept\n
!> odds Ratio < r --> reject\n
!> - adapt stepsize of parameters changed:\n
!> * accepted step: stepsize_i = stepsize_i * accptance multiplier\n
!> * rejected step: stepsize_i = stepsize_i * rejection multiplier\n
!> - if step is accepted: for all changed parameter(s) change stepsize\n
!
!> <li>calculate acceptance ratio of the Markov Chain</i>\n
!
!> <li>adjust acceptance multiplier acc_mult and
!> store good ratios in history list\n
!> - acceptance ratio < 0.23 --> acc_mult = acc_mult * 0.99\n
!> delete history list\n
!> - acceptance ratio > 0.44 --> acc_mult = acc_mult * 1.01\n
!> delete history list\n
!> - 0.23 < acceptance ratio < 0.44\n
!> add acceptance ratio to history list\n
!
!> <li>check if already 10 values are stored in history list and
!> if they have converged to a value above 0.3\n
!> ( mean above 0.3 and variance less \f$\sqrt{1/12*0.05^2}\f$ = Variance
!> of uniform [acc_ratio +/- 2.5%] )\n
!> - if check is positive abort and save stepsizes\n
!> else goto (1)\n\n
!> </ol>
!
!>
!> <b>2. MONTE CARLO MARKOV CHAIN: SAMPLE POSTERIOR DISTRIBUTION OF PARAMETER</b>\n\n
!> <b><i>Purpose:</i></b>\n
!> use the previous adapted stepsizes and perform ONE monte carlo markov chain\n
!> the accepted parameter sets show the posterior distribution of parameters\n
!>
!> <b><i>Important variables:</i></b>\n
!> <b> Variable | Description </b>
!> ---------------------- | -----------------------------------------------------------------------
!> iter_mcmc | length of the markov chain (>> iter_burnin)\n
!> stepsize | a new parameter value is chosen based on a uniform distribution
!> pnew_i = pold_i + Unif(-stepsize_i, stepsize_i) use stepsizes of the burn-in (1)\n
!
!> \n
!> <b><i>Algorithm:</i></b>\n
!> <ol>
!> <li> select a set of parameters to change\n
!> * accurate --> choose one parameter,\n
!> * comput. efficient --> choose all parameters,\n
!> * moderate accurate & efficient --> choose half of the parameters\n
!> <li> change parameter(s) based on their stepsize\n
!> <li> decide whether changed parameter set is accepted or rejected:\n
!> * \f$ \mathrm{odds Ratio} = \frac{\mathrm{likelihood}(p_{new})}{\mathrm{likelihood}(p_{old})} \f$\n
!> * random number r = Uniform[0,1]\n
!> * odds Ratio > 0 --> positive accept\n
!> odds Ratio > r --> negative accept\n
!> odds Ratio < r --> reject\n
!> <li> if step is accepted: save parameter set\n
!> <li> goto (1)\n
!> </ol>
! CALLING SEQUENCE
! call mcmc( likelihood, para, rangePar, mcmc_paras, burnin_paras, &
! seed_in=seeds, printflag_in=printflag, maskpara_in=maskpara, &
! tmp_file=tmp_file, loglike_in=loglike, &
! ParaSelectMode_in=ParaSelectMode, &
! iter_burnin_in=iter_burnin, iter_mcmc_in=iter_mcmc, &
! chains_in=chains, stepsize_in=stepsize)
! INTENT(IN)
!> \param[in] "real(dp) :: likelihood(x,sigma,stddev_new,likeli_new)"
!> Interface Function which calculates likelihood
!> of given parameter set x and given standard deviation sigma
!> and returns optionally the standard deviation stddev_new
!> of the errors using x and
!> likelihood likeli_new using stddev_new
!> \param[in] "real(dp) :: para(:)" Inital parameter set (should be GOOD approximation
!> of best parameter set)
!> \param[in] "real(dp) :: rangePar(size(para),2)" Min/max range of parameters
! INTENT(INOUT)
! None
! INTENT(OUT)
!> \param[out] "real(dp), allocatable :: mcmc_paras(:,:)" Parameter sets sampled in proper MCMC part of algorithm
!> \param[out] "real(dp), allocatable :: burnin_paras(:,:)" Parameter sets sampled during burn-in part of algorithm
! INTENT(IN), OPTIONAL
!> \param[in] "integer(i8), optional :: seed_in" User seed to initialise the random number generator \n
!> (default: none --> initialized with timeseed)
!> \param[in] "logical, optional :: printflag_in" Print of output on command line \n
!> (default: .False.)
!> \param[in] "logical, optional :: maskpara_in(size(para))"
!> Parameter will be sampled (.True.) or not (.False.) \n
!> (default: .True.)
!> \param[in] "character(len=*), optional :: tmp_file" filename for temporal data saving: \n
!> every iter_mcmc_in iterations parameter sets are
!> appended to this file \n
!> the number of the chain will be prepended to filename \n
!> output format: netcdf \n
!> (default: no file writing)
!> \param[in] "logical, optional :: loglike_in" true if loglikelihood function is given instead of
!> likelihood function \n
!> (default: .false.)
!> \param[in] "integer(i4), optional :: ParaSelectMode_in"
!> How many parameters will be changed at once?
!> - half of the parameter --> 1_i4
!> - only one parameter --> 2_i4
!> - all parameter --> 3_i4
!> (default: 2_i4)
!> \param[in] "integer(i4), optional :: iter_burnin_in" Length of Markov chains of initial burn-in part \n
!> (default: Max(250, 200*count(maskpara)) )
!> \param[in] "integer(i4), optional :: iter_mcmc_in" Length of Markov chains of proper MCMC part \n
!> (default: 1000 * count(maskpara) )
!> \param[in] "integer(i4), optional :: chains_in" number of parallel mcmc chains \n
!> (default: 5_i4)
!> \param[in] "real(dp), DIMENSION(size(para,1)), optional :: stepsize_in"
!> stepsize for each parameter \n
!> if given burn-in is discarded \n
!> (default: none --> adjusted in burn-in)
! INTENT(INOUT), OPTIONAL
! None
! INTENT(OUT), OPTIONAL
! None
! RESTRICTIONS
! \note Likelihood has to be defined as a function interface
! -> see also example in test directory
! EXAMPLE
! -> see also example in test directory
! LITERATURE
! Gelman et. al (1995)
! Baysian Data Analyis, Chapman & Hall.
! Gelman et. al (1997)
! Efficient Metropolis Jumping Rules, Baysian Statistics 5, pp. 599-607
! Tautenhahn et. al (2012)
! Beyond distance-invariant survival in inverse recruitment modeling:
! A case study in Siberian Pinus sylvestris forests, Ecological Modelling, 233,
! 90-103. doi:10.1016/j.ecolmodel.2012.03.009.
! HISTORY
! Written Goehler, Sep. 2012 : Created using copy of Simulated Annealing
! - constant temperature T
! - burn-in for stepsize adaption
! - acceptance/ rejection multiplier
! Modified Mai, Sep. 2012 : Cleaning code and introduce likelihood
! - likelihood instead of objective function
! - odds ratio
! - convergence criteria for burn-in
! - different modes of parameter selection
! OpenMP for chains of MCMC
! optional file for temporal output
! Mai, Nov. 2012 : Temporary file writing as NetCDF
! Mai, Aug. 2013 : New likelihood interface to reduce number of function evaluations
! Only one seed has to be given
! Mai, Nov. 2014 : add new routine for mcmc
! mcmc_stddev, i.e. mcmc with likelihood with "faked sigma"
! mcmc, i.e. mcmc with "real" likelihood (sigma is given by e.g. error model)
! Cuntz, Mai Feb. 2015 : restart
! Mai, Apr. 2015 : handling of array-like variables in restart-namelists
!
INTERFACE mcmc_stddev
MODULE PROCEDURE mcmc_stddev_dp
END INTERFACE mcmc_stddev
!-----------------------------------------------------------------------------------------------
PRIVATE
!-----------------------------------------------------------------------------------------------
CONTAINS
!-----------------------------------------------------------------------------------------------
SUBROUTINE mcmc_dp(likelihood, para, rangePar, & ! obligatory IN
mcmc_paras, burnin_paras, & ! obligatory OUT
seed_in, printflag_in, maskpara_in, & ! optional IN
restart, restart_file, & ! optional IN: if mcmc is restarted and file which contains restart variables
tmp_file, & ! optional IN: filename for temporal output of
! ! MCMC parasets
loglike_in, & ! optional IN: true if loglikelihood is given
ParaSelectMode_in, & ! optional IN: (=1) half, (=2) one, (=3) all
iter_burnin_in, & ! optional IN: markov length of (1) burn-in
iter_mcmc_in, & ! optional IN: markov length of (2) mcmc
chains_in, & ! optional IN: number of parallel chains of MCMC
stepsize_in) ! optional IN: stepsize for each param. (no burn-in)
IMPLICIT NONE
INTERFACE
FUNCTION likelihood(paraset)
! calculates the likelihood function at a certain parameter set paraset
use mo_kind
REAL(DP), DIMENSION(:), INTENT(IN) :: paraset
REAL(DP) :: likelihood
END FUNCTION likelihood
END INTERFACE
REAL(DP), DIMENSION(:,:), INTENT(IN) :: rangePar ! range for each parameter
REAL(DP), DIMENSION(:), INTENT(IN) :: para ! initial parameter i
INTEGER(I8), OPTIONAL, INTENT(IN) :: seed_in ! Seeds of random numbers: dim1=chains, dim2=3
! ! (DEFAULT: Get_timeseed)
LOGICAL, OPTIONAL, INTENT(IN) :: printflag_in ! If command line output is written (.true.)
! ! (DEFAULT: .false.)
LOGICAL, OPTIONAL, DIMENSION(size(para,1)), &
INTENT(IN) :: maskpara_in ! true if parameter will be optimized
! ! false if parameter is discarded in optimization
! ! (DEFAULT = .true.)
logical, OPTIONAL, INTENT(in) :: restart ! if .true., start from restart file
! ! (DEFAULT: .false.)
character(len=*), OPTIONAL, INTENT(in) :: restart_file ! restart file name
! ! (DEFAULT: mo_mcmc.restart)
LOGICAL, OPTIONAL, INTENT(IN) :: loglike_in ! true if loglikelihood is given instead of likelihood
! ! (DEFAULT: .false.)
INTEGER(I4), OPTIONAL, INTENT(IN) :: ParaSelectMode_in ! how many parameters changed per iteration:
! ! 1: half of the parameters
! ! 2: only one (DEFAULT)
! ! 3: all
INTEGER(I4), OPTIONAL, INTENT(IN) :: iter_burnin_in ! # iterations before checking ac_ratio
! ! DEFAULT= MIN(250, 20_i4*n)
INTEGER(I4), OPTIONAL, INTENT(IN) :: iter_mcmc_in ! # iterations per chain for posterior sampling
! ! DEFAULT= 1000_i4*n
INTEGER(I4), OPTIONAL, INTENT(IN) :: chains_in ! number of parallel mcmc chains
! ! DEFAULT= 5_i4
REAL(DP), OPTIONAL, DIMENSION(size(para,1)), &
INTENT(IN) :: stepsize_in ! stepsize for each parameter
! ! if given burn-in is discarded
CHARACTER(len=*), OPTIONAL, INTENT(IN) :: tmp_file ! filename for temporal data saving: every iter_mcmc_in
! ! iterations parameter sets are appended to this file
! ! the number of the chain will be prepended to filename
! ! DEFAULT= no file writing
REAL(DP), DIMENSION(:,:), ALLOCATABLE, INTENT(OUT) :: mcmc_paras
! ! array to save para values of MCMC runs,
! ! dim1=sets of all chains, dim2=paras
REAL(DP), DIMENSION(:,:), ALLOCATABLE, INTENT(OUT) :: burnin_paras
! ! array to save para values of Burn in run
! local variables
INTEGER(I4) :: n ! Number of parameters
LOGICAL :: printflag ! If command line output is written
LOGICAL, DIMENSION(size(para,1)) :: maskpara ! true if parameter will be optimized
LOGICAL, DIMENSION(1000) :: dummy_maskpara ! dummy mask_para (only for namelist)
INTEGER(I4), DIMENSION(:), ALLOCATABLE :: truepara ! indexes of parameters to be optimized
LOGICAL :: loglike ! if loglikelihood is given
LOGICAL :: skip_burnin ! if stepsize is given --> burnin is skipped
logical :: itmp_file ! if temporal results wanted
#ifdef __pgiFortran__
character(len=299) :: istmp_file ! local copy of file for temporal results output
#else
character(len=1024) :: istmp_file ! local copy of file for temporal results output
#endif
logical :: irestart ! if restart wanted
character(len=1024) :: isrestart_file ! local copy of restart file name
! for random numbers
INTEGER(I8), dimension(:,:), allocatable :: seeds ! Seeds of random numbers: dim1=chains, dim2=3
REAL(DP) :: RN1, RN2, RN3 ! Random numbers
integer(I8), dimension(:,:), allocatable :: save_state_1 ! optional argument for restarting RN stream 1:
integer(I8), dimension(:,:), allocatable :: save_state_2 ! optional argument for restarting RN stream 2:
integer(I8), dimension(:,:), allocatable :: save_state_3 ! optional argument for restarting RN stream 3:
! ! dim1=chains, dim2=n_save_state
! Dummies
REAL(DP), DIMENSION(:,:,:), ALLOCATABLE :: tmp
integer(I4) :: idummy
logical :: oddsSwitch1, oddsSwitch2
character(100) :: str
character(200) :: outputfile
integer(i4) :: slash_pos
integer(i4) :: len_filename
character(200) :: filename
character(200) :: path
! FOR BURN-IN AND MCMC
REAL(DP), DIMENSION(:,:,:), ALLOCATABLE :: mcmc_paras_3d ! array to save para values of MCMC runs,
! ! dim1=sets, dim2=paras, dim3=chain
integer(I4) :: i
integer(I4), dimension(:), allocatable :: Ipos, Ineg
logical :: iStop
INTEGER(I4) :: ParaSelectMode ! how many parameters are changed per jump
INTEGER(I4) :: iter_burnin ! number fo iterations before checking ac_ratio
INTEGER(I4) :: iter_mcmc ! number fo iterations for posterior sampling
INTEGER(I4) :: chains ! number of parallel mcmc chains
INTEGER(I4) :: chain ! counter for chains, 1...chains
REAL(DP) :: accMult ! acceptance multiplier for stepsize
REAL(DP) :: rejMult ! rejection multiplier for stepsize
LOGICAL,DIMENSION(size(para,1)) :: ChangePara ! logical array to switch if parameter is changed
INTEGER(I4) :: trial ! number of trials for burn-in
REAL(DP),DIMENSION(size(para,1)) :: stepsize ! stepsize adjusted by burn-in and used by mcmc
REAL(DP),DIMENSION(1000) :: dummy_stepsize ! dummy stepsize (only for namelist)
REAL(DP),DIMENSION(size(para,1)) :: paraold ! old parameter set
REAL(DP),DIMENSION(size(para,1)) :: paranew ! new parameter set
REAL(DP),DIMENSION(size(para,1)) :: parabest ! best parameter set overall
REAL(DP),DIMENSION(1000) :: dummy_parabest ! dummy parabest (only for namelist)
REAL(DP),DIMENSION(size(para,1)) :: initial_paraset_mcmc ! best parameterset found in burn-in
REAL(DP),DIMENSION(1000) :: dummy_initial_paraset_mcmc ! dummy initial_paraset_mcmc (only for namelist)
REAL(DP) :: likeliold ! likelihood of old parameter set
REAL(DP) :: likelinew ! likelihood of new parameter set
REAL(DP) :: likelibest ! likelihood of best parameter set overall
INTEGER(I4) :: markov ! counter for markov chain
REAL(DP), DIMENSION(:,:), ALLOCATABLE :: burnin_paras_part ! accepted parameter sets of one MC in burn-in
REAL(DP) :: oddsRatio ! ratio of likelihoods = likelinew/likeliold
REAL(DP), dimension(:), allocatable :: accRatio ! acceptance ratio = (pos/neg) accepted/iter_burnin
REAL(DP) :: accratio_stddev ! stddev of accRatios in history
REAL(DP), DIMENSION(:), ALLOCATABLE :: history_accratio ! history of 'good' acceptance ratios
INTEGER(I4) :: accratio_n ! number of 'good' acceptance ratios
! for checking convergence of MCMC
real(dp), allocatable, dimension(:) :: sqrtR
real(dp), allocatable, dimension(:) :: vDotJ
real(dp), allocatable, dimension(:) :: s2
real(dp) :: vDotDot
real(dp) :: B
real(dp) :: W
integer(i4) :: n_start, n_end, iPar
LOGICAL :: converged ! if MCMC already converged
! for OMP
integer(i4) :: n_threads
namelist /restartnml1/ &
n, printflag, dummy_maskpara, loglike, skip_burnin, &
iStop, ParaSelectMode, iter_burnin, &
iter_mcmc, chains, accMult, rejMult, trial, dummy_stepsize, &
dummy_parabest, likelibest, dummy_initial_paraset_mcmc, &
accratio_stddev, &
accratio_n, vDotDot, B, W, converged, &
n_threads, &
itmp_file, istmp_file
namelist /restartnml2/ &
truepara, seeds, save_state_1, save_state_2, save_state_3, &
iPos, iNeg, mcmc_paras_3d, &
accRatio, &
sqrtR, vDotJ, s2
! CHECKING OPTIONALS
if (present(restart)) then
irestart = restart
else
irestart = .false.
endif
if (present(restart_file)) then
isrestart_file = restart_file
else
isrestart_file = 'mo_mcmc.restart'
endif
if (.not. irestart) then
if (present(tmp_file)) then
itmp_file = .true.
istmp_file = tmp_file
else
itmp_file = .false.
istmp_file = ''
end if
if (present(loglike_in)) then
loglike = loglike_in
else
loglike = .false.
end if
if (present(maskpara_in)) then
if (count(maskpara_in) .eq. 0_i4) then
stop 'Input argument maskpara: At least one element has to be true'
else
maskpara = maskpara_in
end if
else
maskpara = .true.
endif
allocate ( truepara(count(maskpara)) )
idummy = 0_i4
do i=1,size(para,1)
if ( maskpara(i) ) then
idummy = idummy+1_i4
truepara(idummy) = i
end if
end do
n = size(truepara,1)
if (present(ParaSelectMode_in)) then
ParaSelectMode = ParaSelectMode_in
else
! change only one parameter per jump
ParaSelectMode = 2_i4
end if
! after how many iterations do we compute ac_ratio???
if (present(iter_burnin_in)) then
if (iter_burnin_in .le. 0_i4) then
stop 'Input argument iter_burn_in must be greater than 0!'
else
iter_burnin = iter_burnin_in
end if
else
iter_burnin = Max(250_i4, 1000_i4*n)
endif
! how many iterations ('jumps') are performed in MCMC
! iter_mcmc_in is handled later properly (after acceptance ratio of burn_in is known)
if (present(iter_mcmc_in)) then
if (iter_mcmc_in .le. 0_i4) then
stop 'Input argument iter_mcmc must be greater than 0!'
else
iter_mcmc = iter_mcmc_in
end if
else
iter_mcmc = 1000_i4 * n
endif
if (present(chains_in)) then
if (chains_in .lt. 2_i4) then
stop 'Input argument chains must be at least 2!'
end if
chains = chains_in
else
chains = 5_i4
endif
if (present(stepsize_in)) then
stepsize = stepsize_in
skip_burnin = .true.
else
skip_burnin = .false.
end if
if (present(printflag_in)) then
printflag = printflag_in
else
printflag = .false.
endif
n_threads = 1
!$ write(*,*) '--------------------------------------------------'
!$ write(*,*) ' This program is parallel.'
!$OMP parallel
!$ n_threads = OMP_GET_NUM_THREADS()
!$OMP end parallel
!$ write(*,*) ' ',chains,' MCMC chains will run in ',n_threads,' threads'
!$ write(*,*) '--------------------------------------------------'
if (printflag) then
write(*,*) 'Following parameters will be sampled with MCMC: ',truepara
end if
allocate(seeds(chains,3))
allocate(save_state_1(chains,n_save_state))
allocate(save_state_2(chains,n_save_state))
allocate(save_state_3(chains,n_save_state))
allocate(Ipos(chains), Ineg(chains), accRatio(chains))
allocate(vDotJ(chains), s2(chains))
allocate(sqrtR(size(para)))
Ipos = -9999
Ineg = -9999
accRatio = -9999.0_dp
vDotJ = -9999.0_dp
s2 = -9999.0_dp
sqrtR = -9999.0_dp
if (present(seed_in)) then
seeds(1,:) = (/ seed_in, seed_in + 1000_i8, seed_in + 2000_i8 /)
else
! Seeds depend on actual time
call get_timeseed(seeds(1,:))
endif
do chain=2,chains
seeds(chain,:) = seeds(chain-1_i4,:) + 3000_i8
end do
do chain=1,chains
call xor4096(seeds(chain,1), RN1, save_state=save_state_1(chain,:))
call xor4096(seeds(chain,2), RN2, save_state=save_state_2(chain,:))
call xor4096g(seeds(chain,3), RN3, save_state=save_state_3(chain,:))
end do
seeds = 0_i8
parabest = para
! initialize likelihood
likelibest = likelihood(parabest)
!----------------------------------------------------------------------
! (1) BURN IN
!----------------------------------------------------------------------
if (.not. skip_burnin) then
if (printflag) then
write(*,*) ''
write(*,*) '--------------------------------------------------'
write(*,*) 'Starting Burn-In (iter_burnin = ',iter_burnin,')'
write(*,*) '--------------------------------------------------'
write(*,*) ''
end if
! INITIALIZATION
! probably too large, but large enough to store values of one markovchain
allocate(burnin_paras_part(iter_burnin,size(para)))
if (allocated(burnin_paras)) deallocate(burnin_paras)
if (allocated(history_accRatio)) deallocate(history_accRatio)
! parabestChanged = .false.
stepsize = 1.0_dp
trial = 1_i4
iStop = .false.
accMult = 1.01_dp
rejMult = 0.99_dp
if (printflag) then
write(*,*) ' '
write(*,*) 'Start Burn-In with: '
write(*,*) ' parabest = ', parabest
write(*,*) ' likelihood = ', likelibest
write(*,*) ' '
end if
! ----------------------------------------------------------------------------------
! repeats until convergence of acceptance ratio or better parameter set was found
! ----------------------------------------------------------------------------------
convergedBURNIN: do while ( .not. iStop )
Ipos = 0_i4 ! positive accepted
Ineg = 0_i4 ! negative accepted
paraold = parabest
likeliold = likelibest
! -------------------------------------------------------------------------------
! do a short-cut MCMC
! -------------------------------------------------------------------------------
markovchain: do markov=1, iter_burnin
! (A) Generate new parameter set
ChangePara = .false.
paranew = paraold
! using RN from chain #1
call GenerateNewParameterset_dp(ParaSelectMode, paraold, truepara, rangePar, stepsize, &
save_state_2(1,:),&
save_state_3(1,:),&
paranew,ChangePara)
! (B) new likelihood
likelinew = likelihood(paranew)
oddsSwitch1 = .false.
if (loglike) then
oddsRatio = likelinew-likeliold
if (oddsRatio .gt. 0.0_dp) oddsSwitch1 = .true.
else
oddsRatio = likelinew/likeliold
if (oddsRatio .gt. 1.0_dp) oddsSwitch1 = .true.
end if
! (C) Accept or Reject?
If (oddsSwitch1) then
! positive accept
Ipos(1) = Ipos(1) + 1_i4
paraold = paranew
likeliold = likelinew
where (changePara)
stepsize = stepsize * accMult
end where
if (likelinew .gt. likelibest) then
parabest = paranew
likeliold = likelinew
likelibest = likelinew
!
write(*,*) ''
write(*,*) 'best para changed: ',paranew
write(*,*) 'likelihood new: ',likelinew
write(*,*) ''
end if
burnin_paras_part(Ipos(1)+Ineg(1),:) = paranew(:)
else
call xor4096(seeds(1,1), RN1, save_state=save_state_1(1,:))
oddsSwitch2 = .false.
if (loglike) then
if (oddsRatio .lt. -700.0_dp) oddsRatio = -700.0_dp ! to avoid underflow
if (rn1 .lt. exp(oddsRatio)) oddsSwitch2 = .true.
else
if (rn1 .lt. oddsRatio) oddsSwitch2 = .true.
end if
If ( oddsSwitch2 ) then
! negative accept
Ineg(1) = Ineg(1) + 1_i4
paraold = paranew
likeliold = likelinew
where (changePara)
stepsize = stepsize * accMult
end where
burnin_paras_part(Ipos(1)+Ineg(1),:) = paranew(:)
else
! reject
where (changePara)
stepsize = stepsize * rejMult
end where
end if
end if
end do markovchain
accRatio(1) = real(Ipos(1) + Ineg(1),dp) / real(iter_burnin,dp)
if (printflag) then
write(str,'(A,I03,A)') '(A7,I4,A15,F5.3,A17,',size(para,1),'(E9.2,1X),A1)'
write(*,str) 'trial #',trial,' acc_ratio = ',accRatio(1),' (stepsize = ',stepsize,')'
end if
if (Ipos(1)+Ineg(1) .gt. 0_i4) then
call append(burnin_paras, burnin_paras_part(1:Ipos(1)+Ineg(1),:))
end if
! adjust acceptance multiplier
if (accRatio(1) .lt. 0.234_dp) accMult = accMult * 0.99_dp
if (accRatio(1) .gt. 0.441_dp) accMult = accMult * 1.01_dp
! store good accRatios in history and delete complete history if bad one appears
if (accRatio(1) .lt. 0.234_dp .or. accRatio(1) .gt. 0.441_dp) then
if( allocated(history_accRatio) ) deallocate(history_accRatio)
else
call append(history_accRatio, accRatio(1))
end if
! if in history more than 10 values, check for mean and variance
if ( allocated(history_accRatio) ) then
accRatio_n = size(history_accRatio,1)
if ( accRatio_n .ge. 10_i4 ) then
idummy = accRatio_n-9_i4
accRatio_stddev = stddev( history_accRatio(idummy:accRatio_n), ddof=1_i4 )
! Check of Convergence
if ( (accRatio_stddev .lt. Sqrt( 1._dp/12._dp * 0.05_dp**2 )) ) then
iStop = .true.
if (printflag) then
write(*,*) ''
write(*,*) 'STOP BURN-IN with accaptence ratio of ', history_accRatio(accRatio_n)
write(*,*) 'final stepsize: ',stepsize
write(*,*) 'best parameter set found: ',parabest
write(*,*) 'with likelihood: ',likelibest
end if
end if
end if
end if
trial = trial + 1_i4
end do convergedBURNIN
! end do betterParaFound
end if ! no burn-in skip
!
! ------------------------------------
! start initializing things for MCMC, i.e. initialization and allocation
! necessary for MCMC restart file
! ------------------------------------
! allocate arrays which will be used later
allocate(mcmc_paras_3d(iter_mcmc,size(para),chains))
mcmc_paras_3d = -9999.0_dp
vDotDot = -9999.0_dp
B = -9999.0_dp
W = -9999.0_dp
! just to be sure that all chains start with same initial parameter set
! in both parallel and sequential mode
! (although in between a new parabest will be found in chains)
initial_paraset_mcmc = parabest