-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoolFunctions.R
executable file
·3456 lines (2864 loc) · 138 KB
/
toolFunctions.R
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
#### Aim of prog: Gathering tool functions, note that the required packages are not loaded here
## Table of Contents
# - getParams: Get fixed values parameters
# - getLastRun: Get name of the last run
# - lazyTrace: Bayesplot is having troubles on my mac (Arial font not always found), so I create my own traces plot
# - reshapeDraws: Function to reshape draws_array
# - lazyPosterior: Function to plot the prior and posterior of a parameter
# - lazyComparePosterior: Function to plot the posteriors of a parameter from a list of models
# - expand: Function to expand the basic names when there is more than one NFI
# - energyPairs: Function to do a pair plot of parameters versus energy
# - isProcessed: Detect if a species has been processed or not
# - centralised_fct: Wrapping function to call all the other plot functions and to gather informations on the runs
# - plot_correl_error: Function to plot the correlations energy <--> parameters for each species, and to plot rescaled error values
# - checkFunnels: Function to check if plotting one parameter against others shows some funnel structures
# - dbh_timeSeries: Function to plot latent dbh states time series (posteriorSim is generated by the centralised function)
# - rescaleParams: Function to rescale parameters (intercept and slopes)
# - computeGrowth: Function to compute growth, the data table must be sorted by year within tree id and plot id
# - growth_fct: Function computing the expected growth in the case growth ~ lognormal.
# - growth_fct_meanlog: Function computing the expected growth on the log scale (i.e., parameter meanlog of lognormal distribution)
# - optimumPredictorValue: Function to compute the optimum value of response variables with a quadratic term
# - plotGrowth: Function to plot growth vs a response variable with the uncertainty related to parameters estimation (minus process error)
# - getEnvSeries: Function to get the environment for a given species and run (i.e., a given index set)
# - infoSpecies: Function to give species-specific range and dataset range of predictors and dbh
# - climQuantiles: Function to compute, extract, and save climatic quantiles on rasters
# - printParams: Function to print the parameters in a latex table
# - gaussStyle: Function to get the parameters in a "gaussian style", i.e., rewrite growth as exp[-1/(2σ^2) (x - μ)^2]
# - extractClimate: Function to extract climate for a given species
# - extentPosterior: Function to Plot posterior extent, one variable per panel with all the species/methods
# - avgAnnualClimate: Function to average annual climate for a given period and area
#
## Comments
# This R file contains tool functions only that help me to analyse the results and do some check-up. Note that some functions are quite
# similar to bayesplot, but I use base plot rather than ggplot. Moreover, Bayesplot is having troubles on my mac (Arial font not always
# found), so I created my own traces and posterior plots.
#### Tool functions
## Get fixed values parameters (will not work for draws with third dimension > 1)
getParams = function(model_cmdstan, params_names, type = "mean", ...)
{
if (!(type %in% c("all", "chain-iter", "mean", "median", "quantile")))
stop("Unknown type. Please choose all, iter-chain, mean, median, or quantile")
args = list(...)
if (type %in% c("chain-iter", "mean", "median"))
{
vals = numeric(length(params_names))
names(vals) = params_names
if (type == "chain-iter")
{
if (!all(c("iter", "chain") %in% names(args)))
stop("You must provide iter and chain when using the option iter-chain")
iter = args[["iter"]]
chain = args[["chain"]]
if (iter > model_cmdstan$metadata()$iter_sampling)
stop("iter cannot be larger than iter_sampling")
if (chain > model_cmdstan$num_chains())
stop("chain cannot be larger than num_chains")
for (i in seq_along(params_names))
{
draws = model_cmdstan$draws(params_names[i])
if (dim(draws)[3] != 1)
stop("This function is not yet designed to handle a multi-params")
vals[i] = draws[iter, chain, 1]
}
return(vals)
} else {
for (i in seq_along(params_names))
{
vals[i] = ifelse(type == "mean",
mean(model_cmdstan$draws(params_names[i])),
median(model_cmdstan$draws(params_names[i])))
}
return(vals)
}
} else if (type == "quantile") {
if (!("probs" %in% names(args)))
{
probs = c(0, 0.05, 0.5, 0.95, 1)
vals = data.table(parameter = params_names, min = 0, q05 = 0, med = 0, avg = 0, q95 = 0, max = 0)
}
if ("probs" %in% names(args))
{
warning("I have not yet coded the general output, so far I use probs = c(0, 0.05, 0.5, 0.95, 1)")
probs = c(0, 0.05, 0.5, 0.95, 1)
vals = data.table(parameter = params_names, min = 0, q05 = 0, med = 0, avg = 0, q95 = 0, max = 0)
}
for (i in seq_along(params_names))
{
vals[i, c("min", "q05", "med", "q95", "max") := as.list(quantile(model_cmdstan$draws(params_names[i]), c(0, 0.05, 0.5, 0.95, 1)))]
vals[i, avg := mean(model_cmdstan$draws(params_names[i]))]
}
return(vals)
}
vals = model_cmdstan$draws(params_names)
return(vals)
}
## Get name of the last run
getLastRun = function(path, begin = "^growth-", extension = ".rds$", format = "ymd", run = NULL, getAll = FALSE, hour = TRUE)
{
if (format != "ymd")
stop("Format is not recognised. For now only year-month-day alias ymd works")
if (!is.null(run))
{
print(paste("Searching among runs =", run))
begin = paste0(begin, "run=", run, "-")
}
ls_files = list.files(path = path, pattern = paste0(begin, ".*", extension))
if (length(ls_files) == 0)
{
warning(paste0("No file detected in the folder '", path, "'. You were looking for '", begin, "*", extension, "'"))
return(list(file = NA, time_ended = NA))
}
ls_files_split = stri_split(
str = stri_sub(str = ls_files,
from = stri_locate(ls_files, regex = begin)[, "end"] + 1,
to = stri_locate_last(ls_files, regex = "_[[:digit:]].*.rds")[, "start"] - 1),
regex = "-", simplify = TRUE)
if (format == "ymd") # year month day
dt = data.table(file = ls_files, year = ls_files_split[, 1], month = ls_files_split[, 2], day = ls_files_split[, 3])
if (hour)
{
dt[, c("hour", "minute") := as.list(stri_split(str = stri_sub(str = file,
from = stri_locate_first(file, regex = "_")[, "end"] + 1,
to = stri_locate_first(file, regex = "_")[, "end"] + 5),
regex = "h", simplify = TRUE)), by = file]
}
dt[stri_detect(str = day, regex = extension), day := stri_sub(str = day, to = stri_locate_first(str = day, regex = "_")[, "start"] - 1)]
setorder(dt, year, month, day, hour, minute)
if (getAll)
return(list(file = dt[.N, file], time_ended = paste(dt[.N, year], dt[.N, month], dt[.N, day], sep = "-"), allFiles = dt))
if (hour)
return(list(file = dt[.N, file], time_ended = paste(dt[.N, year], dt[.N, month], dt[.N, day], sep = "-"),
hour = paste(dt[.N, hour], dt[.N, minute], sep = "h")))
return(list(file = dt[.N, file], time_ended = paste(dt[.N, year], dt[.N, month], dt[.N, day], sep = "-")))
}
## Bayesplot is having troubles on my mac (Arial font not always found), so I create my own traces plot
lazyTrace = function(draws, filename = NULL, run = NULL, ...)
{
if (!is.array(draws) && !all(class(draws) %in% c("draws_array", "draws", "array")))
stop("The class of draws should be either array, or compatible with cmdstanr (draws_array, draws, array)")
n_chains = dim(draws)[2]
n_iter = dim(draws)[1]
colours = MetBrewer::met.brewer("Hokusai3", n_chains)
colours_str = grDevices::colorRampPalette(colours)(n_chains)
min_val = min(draws)
max_val = max(draws)
providedArgs = list(...)
nbArgs = length(providedArgs)
ls_names = names(providedArgs)
val_ind = stri_detect(str = ls_names, regex = "val[[:digit:]]")
xlab_ind = (ls_names == "xlab")
ylab_ind = (ls_names == "ylab")
main_ind = (ls_names == "main")
label_ind = stri_detect(str = ls_names, regex = "label")
iter_ind = stri_detect(str = ls_names, regex = "iter[[:digit:]]")
scaling_ind = (ls_names == "scaling")
if (any(scaling_ind)) scaling = providedArgs[["scaling"]] else scaling = 1
if (any(label_ind))
par(mar = c(5, 4, 4, 4))
# Plot
if (!is.null(filename))
{
pdf(paste0(filename, ifelse(!is.null(run), paste0("_", run), ""), ".pdf"))
print(paste0("Figure saved under the name: ", filename, ifelse(!is.null(run), paste0("_", run), ""), ".pdf"))
}
plot(0, pch = "", xlim = c(0, n_iter), ylim = scaling*c(min_val, max_val), axes = TRUE, bg = "transparent",
xlab = ifelse(any(xlab_ind), providedArgs[["xlab"]], ""),
ylab = ifelse(any(ylab_ind), providedArgs[["ylab"]], ""),
main = ifelse(any(main_ind), providedArgs[["main"]], ""))
for (chain in 1:n_chains)
{
if (all(class(draws) %in% c("draws_array", "draws", "array")))
lines(1:n_iter, scaling*draws[, chain, ], type = "l", col = colours_str[chain])
if (is.array(draws) && !all(class(draws) %in% c("draws_array", "draws", "array")))
lines(1:n_iter, scaling*draws[, chain], type = "l", col = colours_str[chain])
}
if (any(val_ind))
{
for (val in ls_names[val_ind])
abline(h = scaling*providedArgs[[val]], col = "#CD212A", lwd = 4)
if (any(label_ind))
{
num_vals = stri_sub(str = ls_names[val_ind], from = stri_locate(str = ls_names[val_ind], regex = "val")[, "end"] + 1)
for (label in ls_names[label_ind])
{
num_label = stri_sub(str = label, from = stri_locate(str = label, regex = "label")[, "end"] + 1)
corresponding_val = (ls_names[val_ind])[num_vals == num_label]
axis(4, at = scaling*providedArgs[[corresponding_val]], providedArgs[[label]], las = 1)
}
}
}
if (any(iter_ind))
{
for (iter in ls_names[iter_ind])
abline(v = providedArgs[[iter]], col = "#66666644", lwd = 0.2)
}
if (!is.null(filename))
dev.off()
}
## Function to reshape draws_array
reshapeDraws = function(draws_array, id_latent, regex = "latent_dbh")
{
id_latent = unique(id_latent)
if (length(id_latent) != 1)
stop("A single id should be provided")
n_chains = ncol(draws_array)
length_chain = nrow(draws_array)
output = numeric(length = n_chains*length_chain)
for (i in 1:n_chains)
{
start = (i - 1)*length_chain + 1
end = i*length_chain
output[start:end] = draws_array[, i, paste0(regex, "[", id_latent, "]")]
}
return(output)
}
## Function to plot the prior and posterior of a parameter
lazyPosterior = function(draws, fun = NULL, expand_bounds = FALSE, filename = NULL, run = NULL, multi = FALSE, ls_nfi = NULL, ...)
{
# Dealing with draws as a list
if (is.list(draws))
{
# --- Check-up
nDraws = length(draws)
len = data.table(nIter = integer(nDraws), nChains = integer(nDraws), nVariables = integer(nDraws), variableNames = character(nDraws))
for (i in seq_along(draws))
{
if (!all(class(draws[[i]]) == c("draws_array", "draws", "array")))
stop(paste0("draws[", i, "] is not an array extracted from a CmdStanMCMC object"))
len[i, c("nIter", "nChains", "nVariables", "variableNames") := append(as.list(dim(draws[[i]])), summary(draws[[i]])[["variable"]])]
}
if (unique(len)[, .N] != 1)
stop("Dimensions or variables' name mismatch within the provided draws")
rm(len)
# --- Format
draws_unlist = posterior::bind_draws(draws[[1]], along = "iteration")
for (j in 2:length(draws))
draws_unlist = posterior::bind_draws(draws_unlist, draws[[i]], along = "iteration")
draws = draws_unlist
rm(draws_unlist)
}
# Check-up
if (!all(class(draws) == c("draws_array", "draws", "array")))
stop("Draws should be an array (a list) extracted from a CmdStanMCMC object (CmdStanMCMC objects)")
if (!is.null(fun))
{
if (!isTRUE(all.equal(fun, dnorm)) &&
!isTRUE(all.equal(fun, dlnorm)) &&
!isTRUE(all.equal(fun, dgamma)) &&
!isTRUE(all.equal(fun, dbeta))) # isFALSE will not work here, hence !isTRUE
{
stop("This function only accepts dnorm, dlnorm, dgamma, or dbeta as priors")
}
}
# Get list of arguments
providedArgs = list(...)
ls_names = names(providedArgs)
nbArgs = length(providedArgs)
# Get the argument for density if provided
n = 512
n_ind = (ls_names == "n")
if (any(n_ind))
{
n = providedArgs[["n"]]
print(paste0("Using n = ", n, " for the density plot"))
}
# Get the parameter's name if provided
params = ""
params_ind = (ls_names == "params")
if (any(params_ind))
params = providedArgs[["params"]]
# Get the index of the x-axis label
xlab_ind = (ls_names == "xlab")
# Get the indices of the x-axis limits
min_x_ind = (ls_names == "min_x")
max_x_ind = (ls_names == "max_x")
# Get the scaling on the x-axis if provided
scaling_ind = (ls_names == "scaling")
if (any(scaling_ind)) scaling = providedArgs[["scaling"]] else scaling = 1
# Get parameters for prior
if (isTRUE(all.equal(fun, dnorm)))
{
if ((!all(c("mean", "sd") %in% names(providedArgs))) && (!all(c("arg1", "arg2") %in% names(providedArgs))))
stop("You must provide mean and sd for dnorm")
if (all(c("mean", "sd") %in% names(providedArgs)))
{
arg1 = providedArgs[["mean"]]
arg2 = scaling*providedArgs[["sd"]]
} else {
arg1 = providedArgs[["arg1"]]
arg2 = scaling*providedArgs[["arg2"]]
}
}
if (isTRUE(all.equal(fun, dlnorm)))
{
if ((!all(c("mean", "sd") %in% names(providedArgs))) && (!all(c("arg1", "arg2") %in% names(providedArgs))) &&
(!all(c("meanlog", "sdlog") %in% names(providedArgs))))
stop("You must provide mean and sd or meanlog and sdlog for dlnorm")
if (all(c("mean", "sd") %in% names(providedArgs)))
{
dlnorm_mean = providedArgs[["mean"]]
dlnorm_sd = providedArgs[["sd"]]
arg1 = log(dlnorm_mean^2/sqrt(dlnorm_sd^2 + dlnorm_mean^2)) + log(scaling)
arg2 = sqrt(log(dlnorm_sd^2/dlnorm_mean^2 + 1))
} else if (all(c("meanlog", "sdlog") %in% names(providedArgs))) {
arg1 = providedArgs[["meanlog"]] + log(scaling)
arg2 = providedArgs[["sdlog"]]
} else {
print("args 1 and 2 provided; it is assumed they are meanlog and sdlog")
arg1 = providedArgs[["arg1"]] + log(scaling)
arg2 = providedArgs[["arg2"]]
}
}
if (isTRUE(all.equal(fun, dgamma)))
{
if ((!all(c("mean", "var") %in% names(providedArgs))) && (!all(c("shape", "rate") %in% names(providedArgs)))
&& (!all(c("arg1", "arg2") %in% names(providedArgs))))
stop("You must provide either mean and var or shape and rate for dgamma")
if (all(c("mean", "var") %in% names(providedArgs)))
{
temp1 = providedArgs[["mean"]]
temp2 = providedArgs[["var"]] # Squared because in this case it is a variance, not a std. dev.
arg1 = temp1^2/temp2 # shape
arg2 = temp1/(temp2*scaling) # rate
}
if (all(c("shape", "rate") %in% names(providedArgs)))
{
arg1 = providedArgs[["shape"]]
arg2 = providedArgs[["rate"]]/scaling
}
if (all(c("arg1", "arg2") %in% names(providedArgs)))
{
print("args 1 and 2 provided; it is assumed they are shape and rate")
arg1 = providedArgs[["arg1"]]
arg2 = providedArgs[["arg2"]]/scaling
}
}
if (isTRUE(all.equal(fun, dbeta)))
{
if ((!all(c("mean", "var") %in% names(providedArgs))) && (!all(c("shape1", "shape2") %in% names(providedArgs)))
&& (!all(c("arg1", "arg2") %in% names(providedArgs))))
stop("You must provide either mean and var or shape1 and shape2 for dbeta")
if (scaling != 1)
warning("I have not coded the scaling for the beta distribution. Your plot might be out of the window")
if (all(c("mean", "var") %in% names(providedArgs)))
{
temp1 = providedArgs[["mean"]]
temp2 = providedArgs[["var"]]
arg1 = ((1 - temp1)/temp2 - 1/temp1)*temp1^2 # shape 1
arg2 = arg1*(1/temp1 - 1) # shape 2
}
if (all(c("shape1", "shape2") %in% names(providedArgs)))
{
arg1 = providedArgs[["shape1"]]
arg2 = providedArgs[["shape2"]]
}
if (all(c("arg1", "arg2") %in% names(providedArgs)))
{
print("args 1 and 2 provided; it is assumed they are shape1 and shape2")
arg1 = providedArgs[["shape1"]]
arg2 = providedArgs[["shape2"]]
}
max_y_prior = optimise(f = fun, interval = c(0, 1), maximum = TRUE, shape1 = arg1, shape2 = arg2)[["objective"]]
}
# Get posterior
if (multi)
{
info = summary(draws)
setDT(info)
length_params = info[, .N]
density_from_draws = vector(mode = "list", length = length_params)
x = vector(mode = "list", length = length_params)
y = vector(mode = "list", length = length_params)
names(density_from_draws) = info[, variable]
names(x) = info[, variable]
names(y) = info[, variable]
for (varName in info[, variable])
{
density_from_draws[[varName]] = density(scaling*draws[, , varName], n = n)
x[[varName]] = density_from_draws[[varName]]$x
y[[varName]] = density_from_draws[[varName]]$y
}
min_x = min(sapply(x, min))
max_x = max(sapply(x, max))
max_y = max(sapply(y, max))
} else {
density_from_draws = density(draws, n = n)
x = density_from_draws$x
y = density_from_draws$y
min_x = min(x)
max_x = max(x)
max_y = max(y)
}
min_x = ifelse(min_x < 0, 1.1*min_x, 0.9*min_x) # To extend 10% from min_x
max_x = ifelse(max_x < 0, 0.9*max_x, 1.1*max_x) # To extend 10% from max_x
if (isTRUE(all.equal(fun, dnorm)))
{
max_y_prior = optimise(f = fun, interval = c(min_x, max_x), maximum = TRUE, mean = arg1, sd = arg2)[["objective"]]
if (expand_bounds)
{
check_min_bound = integrate(fun, lower = ifelse(min_x < 0, 10*min_x, -10*min_x), upper = min_x, mean = arg1, sd = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
while (check_min_bound$value > 0.1)
{
min_x = ifelse(min_x < 0, 1.1*min_x, 0.9*min_x) # To extend 10% from min_x
check_min_bound = integrate(fun, lower = ifelse(min_x < 0, 10*min_x, -10*min_x), upper = min_x, mean = arg1, sd = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
}
check_max_bound = integrate(fun, lower = max_x, upper = ifelse(max_x < 0, -10*max_x, 10*max_x), mean = arg1, sd = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
while (check_max_bound$value > 0.1)
{
max_x = ifelse(max_x < 0, 0.9*max_x, 1.1*max_x) # To extend 10% from max_x
check_max_bound = integrate(fun, lower = max_x, upper = ifelse(max_x < 0, -10*max_x, 10*max_x), mean = arg1, sd = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
}
}
}
if (isTRUE(all.equal(fun, dlnorm)))
{
max_y_prior = optimise(f = fun, interval = c(min_x, max_x), maximum = TRUE, meanlog = arg1, sdlog = arg2)[["objective"]]
if (expand_bounds)
{
check_min_bound = integrate(fun, lower = ifelse(min_x < 0, 10*min_x, -10*min_x), upper = min_x, meanlog = arg1,
sdlog = arg2, subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
while (check_min_bound$value > 0.1)
{
min_x = ifelse(min_x < 0, 1.1*min_x, 0.9*min_x) # To extend 10% from min_x
check_min_bound = integrate(fun, lower = ifelse(min_x < 0, 10*min_x, -10*min_x), upper = min_x, meanlog = arg1,
sdlog = arg2, subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
}
check_max_bound = integrate(fun, lower = max_x, upper = ifelse(max_x < 0, -10*max_x, 10*max_x), meanlog = arg1,
sdlog = arg2, subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
while (check_max_bound$value > 0.1)
{
max_x = ifelse(max_x < 0, 0.9*max_x, 1.1*max_x) # To extend 10% from max_x
check_max_bound = integrate(fun, lower = max_x, upper = ifelse(max_x < 0, -10*max_x, 10*max_x), meanlog = arg1,
sdlog = arg2, subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
}
}
}
if (isTRUE(all.equal(fun, dgamma)))
{
max_y_prior = optimise(f = fun, interval = c(min_x, max_x), maximum = TRUE, shape = arg1, rate = arg2)[["objective"]]
if (expand_bounds)
{
check_min_bound = integrate(fun, lower = ifelse(min_x < 0, 10*min_x, -10*min_x), upper = min_x, shape = arg1, rate = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
while (check_min_bound$value > 0.1)
{
min_x = ifelse(min_x < 0, 1.1*min_x, 0.9*min_x) # To extend 10% from min_x
check_min_bound = integrate(fun, lower = ifelse(min_x < 0, 10*min_x, -10*min_x), upper = min_x, shape = arg1, rate = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
}
check_max_bound = integrate(fun, lower = max_x, upper = ifelse(max_x < 0, -10*max_x, 10*max_x), shape = arg1, rate = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
while (check_max_bound$value > 0.1)
{
max_x = ifelse(max_x < 0, 0.9*max_x, 1.1*max_x) # To extend 10% from max_x
check_max_bound = integrate(fun, lower = max_x, upper = ifelse(max_x < 0, -10*max_x, 10*max_x), shape = arg1, rate = arg2,
subdivisions = 2000, rel.tol = .Machine$double.eps^0.1)
}
}
}
if (!is.null(fun))
max_y = max(max_y, max_y_prior)
max_y = ifelse(max_y < 0, 0.9*max_y, 1.1*max_y) # To extend 10% from max_y
# Plot
if (!is.null(filename))
{
filename = paste0(filename, ifelse(!is.null(run), paste0("_", run), ""), ".pdf")
pdf(filename)
print(paste0("Figure saved under the name: ", filename))
}
if (any(min_x_ind))
min_x = providedArgs[["min_x"]]
if (any(max_x_ind))
max_x = providedArgs[["max_x"]]
# Plot posterior
if (multi)
{
colours = MetBrewer::met.brewer("Hokusai3", length_params)
colours_str = grDevices::colorRampPalette(colours)(length_params)
colours_str_pol = paste0(colours_str, "66")
plot(0, type = "n", xlim = c(min_x, max_x), ylim = c(0, max_y), ylab = "frequence", main = paste("Prior and posterior", params),
xlab = ifelse(any(xlab_ind), providedArgs[["xlab"]], ""))
for (i in 1:length_params)
{
lines(x = density_from_draws[[i]]$x, y = density_from_draws[[i]]$y, col = colours_str[i], lwd = 2)
polygon(density_from_draws[[i]], col = colours_str_pol[i])
}
} else {
plot(density_from_draws, xlim = c(min_x, max_x), col = "#295384", lwd = 2, main = paste("Prior and posterior", params))
polygon(density_from_draws, col = "#29538466")
}
# Plot prior
if (!is.null(fun))
{
curve(fun(x, arg1, arg2), add = TRUE, lwd = 2, col = "#E9851D")
DescTools::Shade(fun(x, arg1, arg2), breaks = c(min_x, max_x), col = "#E9851D66", density = NA)
}
# Add legend
if (multi && !is.null(ls_nfi))
if (length(ls_nfi) != length_params)
warning("Dimension mismatch between ls_nfi and length_params! The legend might not be correctly printed")
if (!multi && !is.null(ls_nfi))
if (length(ls_nfi) != 1)
warning("Too many NFI provided in ls_nfi! The legend might not be correctly printed")
if (multi)
{
legend_text = ifelse(is.null(fun), paste("Posterior", if (!is.null(ls_nfi)) ls_nfi else 1:length_params),
c("Prior", paste("Posterior", if (!is.null(ls_nfi)) ls_nfi else 1:length_params)))
legend_colours = ifelse(is.null(fun), colours_str, c("#E9851D", colours_str))
legend(x = "topright", legend = legend_text, fill = legend_colours, box.lwd = 0)
} else {
legend_text = ifelse(is.null(fun), paste("Posterior", ifelse(!is.null(ls_nfi), ls_nfi, "")),
c("Prior", paste("Posterior", ifelse(!is.null(ls_nfi), ls_nfi, ""))))
legend_colours = ifelse(is.null(fun), "#295384", c("#E9851D", "#295384"))
legend(x = "topright", legend = legend_text, fill = legend_colours, box.lwd = 0)
}
if (!is.null(filename))
dev.off()
if (is.null(fun))
return(list(arg1 = NA, arg2 = NA, min_x = min_x, max_x = max_x, max_y = max_y, max_y_prior = NA, filename = filename))
return(list(arg1 = arg1, arg2 = arg2, min_x = min_x, max_x = max_x, max_y = max_y, max_y_prior = max_y_prior, filename = filename))
}
## Function to plot the posteriors of a parameter from a list of models
lazyComparePosterior = function(draws_ls, filename = NULL, run = NULL, multi_nfi = FALSE, ls_nfi = NULL, ...)
{
# Check-up
if (!is.list(draws_ls))
stop("Draws should be a list of arrays extracted from a CmdStanMCMC object")
nDraws = length(draws_ls)
len = data.table(nIter = integer(nDraws), nChains = integer(nDraws), nVariables = integer(nDraws))
for (i in seq_along(draws_ls))
{
if (!all(class(draws_ls[[i]]) == c("draws_array", "draws", "array")))
stop(paste0("draws_ls[", i, "] is not an array extracted from a CmdStanMCMC object"))
len[i, c("nIter", "nChains", "nVariables") := as.list(dim(draws_ls[[i]]))]
}
if (unique(len)[, .N] != 1)
stop("Dimensions mismatch within the provided draws")
# Get list of arguments
providedArgs = list(...)
ls_names = names(providedArgs)
nbArgs = length(providedArgs)
# Get the argument for density if provided
n = 512
n_ind = (ls_names == "n")
if (any(n_ind))
{
n = providedArgs[["n"]]
print(paste0("Using n = ", n, " for the density plot"))
}
# Get the parameter's name if provided
params = ""
params_ind = (ls_names == "params")
if (any(params_ind))
params = providedArgs[["params"]]
# Get the index of the x-axis label
xlab_ind = (ls_names == "xlab")
# Get the indices of the x-axis limits
min_x_ind = (ls_names == "min_x")
max_x_ind = (ls_names == "max_x")
# Get the index of the legend text
legend_ind = (ls_names == "legend")
# Create and fill list of posteriors
density_ls = vector(mode = "list", length = nDraws)
min_x = +Inf
max_x = -Inf
max_y = -Inf
for (i in seq_along(draws_ls))
{
# --- get posterior
if (multi_nfi)
{
info = summary(draws_ls[[i]])
setDT(info)
length_params = info[, .N]
density_ls[[i]] = vector(mode = "list", length = length_params)
x = vector(mode = "list", length = length_params)
y = vector(mode = "list", length = length_params)
names(density_ls[[i]]) = info[, variable]
names(x) = info[, variable]
names(y) = info[, variable]
for (varName in info[, variable])
{
density_ls[[i]][[varName]] = density(draws_ls[[i]][, , varName], n = n)
x[[varName]] = density_ls[[i]][[varName]]$x
y[[varName]] = density_ls[[i]][[varName]]$y
}
temporary_min_x = min(sapply(x, min))
temporary_max_x = max(sapply(x, max))
temporary_max_y = max(sapply(y, max))
} else {
density_ls[[i]] = density(draws_ls[[i]], n = n)
x = density_ls[[i]]$x
y = density_ls[[i]]$y
temporary_min_x = min(x)
temporary_max_x = max(x)
temporary_max_y = max(y)
}
if (temporary_min_x < min_x)
min_x = temporary_min_x
if (temporary_max_x > max_x)
max_x = temporary_max_x
if (temporary_max_y > max_y)
max_y = temporary_max_y
}
min_x = ifelse(min_x < 0, 1.01*min_x, 0.99*min_x) # To extend by 1% from min_x
max_x = ifelse(max_x < 0, 0.99*max_x, 1.01*max_x) # To extend by 1% from max_x
if (any(min_x_ind))
min_x = providedArgs[["min_x"]]
if (any(max_x_ind))
max_x = providedArgs[["max_x"]]
max_y = ifelse(max_y < 0, 0.99*max_y, 1.01*max_y) # To extend by 1% from max_y
names(density_ls) = paste("draw", 1:nDraws, sep = "_")
# Open file if plot printed in a pdf
if (!is.null(filename))
{
filename = paste0(filename, ifelse(!is.null(run), paste0("_", run), ""), ".pdf")
pdf(filename)
print(paste0("Figure saved under the name: ", filename))
}
# Plot posterior
# --- Prepare the posteriors colour
nbPosteriors = ifelse(multi_nfi, length_params*nDraws, nDraws)
colours = MetBrewer::met.brewer("Austria", nbPosteriors)
colours_str = grDevices::colorRampPalette(colours)(nbPosteriors)
colours_str_pol = paste0(colours_str, "66")
counterColour = 1
plot(0, type = "n", xlim = c(min_x, max_x), ylim = c(0, max_y), ylab = "frequence", main = paste("Posteriors", params),
xlab = ifelse(any(xlab_ind), providedArgs[["xlab"]], ""))
for (i in seq_along(draws_ls))
{
if (multi_nfi)
{
for (j in 1:length_params)
{
lines(x = density_ls[[i]][[j]]$x, y = density_ls[[i]][[j]]$y, col = colours_str[counterColour], lwd = 4, lty = i)
polygon(density_ls[[i]][[j]], col = colours_str_pol[counterColour])
counterColour = counterColour + 1
}
} else {
lines(density_ls[[i]], col = colours_str[counterColour], lwd = 4, lty = i)
polygon(density_ls[[i]], col = colours_str_pol[counterColour])
counterColour = counterColour + 1
}
}
# Add legend
if (multi_nfi && !is.null(ls_nfi))
if (length(ls_nfi) != length_params)
warning("Dimension mismatch between ls_nfi and length_params! The legend might not be correctly printed")
if (!multi_nfi && !is.null(ls_nfi))
if (length(ls_nfi) != 1)
warning("To many NFI provided in ls_nfi! The legend might not be correctly printed")
if (multi_nfi)
{
posterior_num = paste("Posterior", 1:nDraws)
posterior_country = if (!is.null(ls_nfi)) ls_nfi else 1:length_params
legend_text = CJ(posterior_num, posterior_country, sorted = FALSE)[, paste(posterior_num, posterior_country, sep = " ")]
legend_colours = colours_str
legend(x = "topright", legend = legend_text, col = legend_colours, lty = rep(1:nDraws, each = length_params), lwd = 2, box.lwd = 0)
} else {
if (!any(legend_ind))
{
posterior_num = paste("Posterior", 1:nDraws)
posterior_country = if (!is.null(ls_nfi)) ls_nfi else ""
legend_text = CJ(posterior_num, posterior_country, sorted = FALSE)[, paste(posterior_num, posterior_country, sep = " ")]
} else {
legend_text = providedArgs[["legend"]]
}
legend_colours = colours_str_pol
legend(x = "topright", legend = legend_text, fill = legend_colours, box.lwd = 0)
}
if (!is.null(filename))
dev.off()
return(list(min_x = min_x, max_x = max_x, max_y = max_y, filename = filename))
}
## Function to expand the basic names when there is more than one NFI
expand = function(base_names, nb_nfi, patterns = c("Obs", "proba"))
{
if (nb_nfi < 1)
stop("Nothing to expand")
new_names = vector(mode = "list", length = length(patterns))
old_names = base_names
for (i in seq_along(patterns))
{
reg = patterns[i]
toModify = base_names[stri_detect(base_names, regex = reg)]
base_names = base_names[!stri_detect(base_names, regex = reg)]
new_names[[i]] = character(length = nb_nfi*length(toModify))
for (j in seq_along(toModify))
new_names[[i]][((j - 1)*nb_nfi + 1):(j*nb_nfi)] = paste0(toModify[j], "[", 1:nb_nfi, "]")
}
combined_names = c(base_names, unlist(new_names))
return(list(old_names = old_names, new_names = combined_names))
}
## Function to do a pair plot of parameters versus energy
energyPairs = function(path, run, results, nb_nfi, energy, rm_names = c("latent", "Effect"), n_rows = 3, n_cols = 6, filename = "pairs.pdf")
{
if (!is.null(filename))
filename = paste0(path, ifelse(!is.null(run), paste0(run, "_"), run), "pairs.pdf")
params_names = results$metadata()$stan_variables
for (i in seq_along(rm_names))
params_names = params_names[!stri_detect(params_names, regex = rm_names[i])]
if (nb_nfi > 1)
params_names = expand(params_names, nb_nfi)[["new_names"]]
if (length(params_names) > n_rows*n_cols)
warning("Not enough rows or cols for the number of provided parameters")
if (!is.null(filename))
pdf(filename, height = 10, width = 10)
par(mfrow = c(n_rows, n_cols))
length_params = length(params_names)
correl_energy = data.table(parameters = params_names, correlation_energy = numeric(length_params))
for (i in 1:length_params)
{
smoothScatter(x = energy, y = as.vector(results$draws(params_names[i])), ylab = params_names[i])
correl_energy[i, correlation_energy := cor(energy, as.vector(results$draws(params_names[i])))]
}
if (!is.null(filename))
{
dev.off()
print(paste("Figure saved under the name:", filename))
}
return(correl_energy)
}
## Detect if a species has been processed or not
isProcessed = function(path, multi, lim_time, begin = "^growth-", extension = ".rds$", format = "ymd", lower = 1, upper = 4)
{
if (class(lim_time) != "Date")
lim_time = as.Date(lim_time)
run_vec = lower:upper
n_runs = length(run_vec)
processed = rep(FALSE, n_runs)
if (!dir.exists(path))
return(FALSE)
if (multi)
{
for (i in 1:n_runs)
{
run = run_vec[i]
date_run = getLastRun(path, begin = begin, extension = extension, format = format, run = i)[["time_ended"]]
date_run = as.Date(date_run)
if (!is.na(date_run) && (date_run > lim_time))
processed[i] = TRUE
}
} else {
date_run = getLastRun(path, begin = begin, extension = extension, format = format, run = 1)[["time_ended"]]
date_run = as.Date(date_run)
if (!is.na(date_run) && (date_run > lim_time))
processed = TRUE
}
return(all(processed))
}
## Wrapping function to call all the other plot functions and to gather informations on the runs
centralised_fct = function(species, multi, n_runs, ls_nfi, params_dt, run = NULL, isDBH_normalised = TRUE, simulatePosterior = TRUE)
{
path = paste0("./", species, "/")
n_nfi = length(ls_nfi)
error_dt = data.table(nfi = rep(c(ls_nfi, "all")), sigmaProc = numeric(n_nfi + 1),
etaObs = numeric(n_nfi + 1), proba = numeric(n_nfi + 1), correl_eta_proba = numeric(n_nfi + 1))
setkey(error_dt, nfi)
if (multi && !is.null(run))
{
print(paste0("Run = ", run, "; multi and n_runs parameters ignored"))
temporary = centralised_fct(species, FALSE, n_runs, ls_nfi, params_dt, run, isDBH_normalised, simulatePosterior) # Recursive call
error_dt = temporary[["error_dt"]]
correl_energy = temporary[["correl_energy"]]
} else if (multi && is.null(run)) {
error_ls = vector(mode = "list", length = n_runs)
correl_ls = vector(mode = "list", length = n_runs)
for (i in 1:n_runs)
{
temporary = centralised_fct(species, FALSE, n_runs, ls_nfi, params_dt, i, isDBH_normalised, simulatePosterior) # Recursive call
error_ls[[i]] = temporary[["error_dt"]]
correl_ls[[i]] = temporary[["correl_energy"]]
}
error_dt = rbindlist(error_ls) # , idcol = "run_id"
correl_energy = rbindlist(correl_ls) # , idcol = "run_id"
} else {
# Get inf last run
info_lastRun = getLastRun(path = path, run = run)
lastRun = info_lastRun[["file"]]
time_ended = info_lastRun[["time_ended"]]
# Load dbh standardising data if necessary
sd_dbh = 1
if (isDBH_normalised)
{
norm_dbh_dt = readRDS(paste0(path, ifelse(is.null(run), "", paste0(run, "_")), "dbh_normalisation.rds"))
sd_dbh = norm_dbh_dt[, sd]
}
# Load results and associated data set
results = readRDS(paste0(path, lastRun))
results$print(c("lp__", params_dt[, parameters], "etaObs", "proba", "sigmaProc"), max_rows = 20)
Sys.sleep(5)
## Pairs plot of parameters versus energy
# Extract energy
energy = as.vector(results$sampler_diagnostics(inc_warmup = FALSE)[, , "energy__"])
# Plot
correl_energy = energyPairs(path, run = run, results, nb_nfi = n_nfi, energy)
## Plot prior and posterior for error terms
# For process error (sigmaProc), it is a variance (of a gamma distrib)
sigmaProc_array = results$draws("sigmaProc")
lazyPosterior(draws = sigmaProc_array, fun = dlnorm, filename = paste0(path, "sigmaProc_posterior"), params = "process error",
meanlog = log(1.28) - log(sd_dbh), sdlog = 0.16, run = run, expand_bounds = TRUE)
lazyTrace(draws = sigmaProc_array, filename = paste0(path, "sigmaProc_traces"), run = run)
error_dt["all", sigmaProc := sd_dbh*sqrt(mean(sigmaProc_array))]
# For measurement error:
# --- Common variable
multi_NFI = if (n_nfi > 1) TRUE else FALSE
# --- Extreme error (etaObs), it is a sd (of a normal distrib)...
etaObs_array = results$draws("etaObs")
lazyPosterior(draws = etaObs_array, fun = dgamma, filename = paste0(path, "etaObs_posterior"), run = run, xlab = "Error in mm",
shape = 30^2/45.0, rate = sd_dbh*30/45.0, params = "extreme obs error", multi = multi_NFI, scaling = sd_dbh,
ls_nfi = ls_nfi, expand_bounds = TRUE)
# --- ... and its associated probability of occurrence
proba_array = results$draws("proba")
lazyPosterior(draws = proba_array, fun = dbeta, filename = paste0(path, "proba_posterior"), run = run, xlab = "Probability",
shape1 = 48.67, shape2 = 1714.84, params = "probability extreme obs error", multi = multi_NFI,
ls_nfi = ls_nfi)
for (i in 1:n_nfi)
{
lazyTrace(draws = results$draws(paste0("etaObs[", i, "]"), inc_warmup = FALSE),
filename = paste0(path, "etaObs[", i, "]_traces"), run = run)
lazyTrace(draws = results$draws(paste0("proba[", i, "]"), inc_warmup = FALSE),
filename = paste0(path, "proba[", i, "]_traces"), run = run)
}
error_dt["all", etaObs := sd_dbh*mean(etaObs_array)]
error_dt["all", proba := mean(proba_array)]
error_dt["all", correl_eta_proba := cor(etaObs_array, proba_array)]
count = 0
for (nfi in ls_nfi)
{
count = count + 1
etaObs_array = results$draws(paste0("etaObs[", count, "]"))
proba_array = results$draws(paste0("proba[", count, "]"))
error_dt[nfi, sigmaProc := NA]
error_dt[nfi, etaObs := mean(etaObs_array)]
error_dt[nfi, proba := mean(proba_array)]
error_dt[nfi, correl_eta_proba := cor(etaObs_array, proba_array)]
}
## Plot prior and posterior for main parameters (i.e., slopes and random effects, not the errors nor proba)
for (param in params_dt[, parameters])
{
lazyPosterior(draws = results$draws(param, inc_warmup = FALSE), fun = params_dt[param, priors][[1]], run = run,
expand_bounds = params_dt[param, expand_bounds], filename = paste0(path, param, "_posterior"),
params = params_dt[param, title], arg1 = params_dt[param, arg1], arg2 = params_dt[param, arg2])