-
Notifications
You must be signed in to change notification settings - Fork 1
/
51_model_evaluation_depth_layers_PFB-OOB_PFB-CV_LSK_LSK-SRS.R
3587 lines (3296 loc) · 173 KB
/
51_model_evaluation_depth_layers_PFB-OOB_PFB-CV_LSK_LSK-SRS.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
# Name: 51_model_evaluation_depth_layers_PFB_OOB_PFB_CV_LSK_LSK_SRS.R
#
# Content: - read in target variable regression matrix and fitted model
# - use "ranger" pkg to predict mean and all quantiles
# - evaluate map accuracy using 4 methods/measures SEPARATED
# INTO GSM DEPTH LAYERS:
# - PFB-OOB: out of bag (OOB) calibration data
# - PFB-CV: hold outs from location-grouped 10-fold CV of calibration data
# - LSK: independent validation/test data: LSK/CCNL
# - LSK-SRS: independent validation/test data (LSK/CCNL) taking into
# account probability sample, in our case stratified random
# sampling (SRS) because split into depth layers
# * PFB-OOB, PFB-CV & LSK are computed over all depths in script
# "50_model_evaluation_all_depths_PFB_OOB_PFB_CV_LSK.R"
# - model evaluation over space (2D), plotting residuals and PICP of
# PI90 per GSM depth increment over the entire NL
#
# Refs: - QRF package and vignettes:
# https://cran.r-project.org/web/packages/quantregForest/quantregForest.pdf
# https://mran.microsoft.com/snapshot/2015-07-15/web/packages/quantregForest/vignettes/quantregForest.pdf
# - General approach and equations for calculating accuracy metrics
# for each GSM depth layer for a stratified random sampling design:
# - "man/BIS-3D_validation_approach_GH_AH.pdf"
# - "man/STRS inference_part1.pdf"
# - "man/STRS inference_part2.pdf"
#
# Inputs: - target regression matrix: out/data/model/tbl_regmat_[TARGET].Rds
# - final fitted QRF model using all calibration data (optimal):
# "out/data/model/QRF_fit_[TARGET]_obs[]_p[]_[]CV_optimal.Rds"
# - series of (10) QRF model fits to use for CV results:
# "out/data/model/QRF_fit_[TARGET]_obs[]_p[]_[]CV_all_folds.Rds"
#
# Output: - Accuracy plots and metrics over GSM depth increments of PFB-OOB,
# PFB-CV, LSK and LSK-SRS
# - maps of residuals and PICP of PI90 at validation locations
# grouped by GSM depth increments
#
# Project: BIS+
# Author: Anatol Helfenstein
# Updated: June 2021
### Empty memory and workspace; load required packages -------------------------
gc()
rm(list=ls())
pkgs <- c("tidyverse", "sf", "ranger", "caret", "foreach", "viridis", "cowplot",
"ggspatial", "mapview", "data.table", "RColorBrewer", "scales",
"surveyplanning", "boot")
lapply(pkgs, library, character.only = TRUE)
# make sure 'mapview' pkg installed from github:
# remotes::install_github("r-spatial/mapview")
mapviewOptions(fgb = FALSE) # to visualize points on map
### Designate script parameters & load modelling data --------------------------
# 1) Specify DSM target soil property (response):
TARGET = "pH_KCl"
# expression of TARGET for model evaluation plots
TARGET_EXP = "pH [KCl]"
TARGET_PRED = expression(paste(hat(pH), " [KCl]"))
# 2) Regression matrix data containing calibration and validation data
tbl_regmat_target <- read_rds(paste0("out/data/model/tbl_regmat_",
TARGET,".Rds"))
# Separate tables for calibration and validation data
tbl_regmat_target_cal <- tbl_regmat_target %>%
filter(split %in% "train")
tbl_regmat_target_val <- tbl_regmat_target %>%
filter(split %in% "test")
# convert validation data to spatial sf (to incorporate sampling design later..)
sf_regmat_target_val <- tbl_regmat_target_val %>%
st_as_sf(., coords = c("X", "Y"), crs = "EPSG:28992")
# read in shapefile of LSK/CCNL (validation set) strata
sf_LSK_strata <- st_read("data/other/strata_ccnl.shp")
# read in NL border shapefile for mapping background
sf_NL_borders <- st_read("data/other/NL_borders.shp")
# 3) Specify which (previously fitted) optimal model to use:
QRF_FIT_optimal <- read_rds(paste0(
"out/data/model/QRF_fit_", TARGET,
"_obs", nrow(tbl_regmat_target_cal),
"_p", ncol(dplyr::select(tbl_regmat_target, -c(split:hor, all_of(TARGET)))),
"_LLO_10FCV_optimal.Rds"))
# 4) Specify which series of (10) models to use for cross-validation results
# (each model uses inidices from 1 fold of 10-fold CV):
QRF_FIT_all_folds <- read_rds(paste0(
"out/data/model/QRF_fit_", TARGET,
"_obs", nrow(tbl_regmat_target_cal),
"_p", ncol(dplyr::select(tbl_regmat_target, -c(split:hor, all_of(TARGET)))),
"_LLO_10FCV_all_folds.Rds"))
# 5) Specify which quantiles we want to predict:
# to calculate PICP we choose entire range at the 1% scale
QUANTILES <- seq(0.00, 1.00, 0.01)
# 6) Specify number of cores to use for parallel computation
THREADS = parallel::detectCores()
# 7) Set predicted vs. observed plotting X and Y axis min, max, range and breaks
# calibration/training data
XY_MIN_CAL = min(tbl_regmat_target_cal[TARGET])
XY_MAX_CAL = max(tbl_regmat_target_cal[TARGET])
XY_RANGE_CAL = diff(range(XY_MIN_CAL, XY_MAX_CAL))
XY_BREAKS_CAL = unique(round(seq(XY_MIN_CAL, XY_MAX_CAL, XY_RANGE_CAL/10)))
# validation/test data
XY_MIN_VAL = min(tbl_regmat_target_val[TARGET])
XY_MAX_VAL = max(tbl_regmat_target_val[TARGET])
XY_RANGE_VAL = diff(range(XY_MIN_VAL, XY_MAX_VAL))
XY_BREAKS_VAL = unique(round(seq(XY_MIN_VAL, XY_MAX_VAL, XY_RANGE_VAL/10)))
### Prepare model evaluation datasets ==========================================
# We want to evaluate models using:
# PFB-OOB: OOB predictions of optimal model (using all calibration data)
# PFB-CV: Cross-validated predictions fit using indices of 10-fold CV (each model/
# fold uses different subsets of calibration data)
# LSK: Independent model validation using LSK/CCNL (depending on TARGET soil
# property)
# Use modified ranger function from ISRIC to calculate mean in addition to the
# usual quantiles from QRF
source("R/other/predict_qrf_fun.R")
## PFB-OOB: OOB predictions of optimal model (calibration dataset) ------------------
# (QRF_FIT_optimal$finalModel$predictions are the inbag predictions....)
# OOB quantiles and mean
qrf_tree_cal_OOB <- predict.ranger.tree(QRF_FIT_optimal$finalModel,
data = NULL,
type = "treepred")
# predict all quantiles and then also the mean
tbl_qrf_cal_OOB <- data.frame(t(apply(qrf_tree_cal_OOB$predictions,
1, quantile, QUANTILES, na.rm = TRUE))) %>%
as_tibble() %>%
rename_all(~ paste0("quant_", QUANTILES * 100)) %>%
# predict mean value
add_column(pred_mean = apply(qrf_tree_cal_OOB$predictions,
1, mean, na.rm = TRUE),
.before = "quant_0")
# add observations, depths and compute logical if within PI90
tbl_predobs_cal_OOB <- tbl_qrf_cal_OOB %>%
add_column(d_upper = tbl_regmat_target_cal$d_upper,
d_lower = tbl_regmat_target_cal$d_lower,
d_mid = tbl_regmat_target_cal$d_mid,
obs = pull(tbl_regmat_target_cal, TARGET),
.before = "pred_mean") %>%
mutate(within_PI90 = if_else(obs >= quant_5 & obs <= quant_95,
TRUE, FALSE))
## PFB-CV: Location-grouped 10-fold CV of calibration dataset ----------------------
# only want to predict for samples in hold out of each model
ls_tbl_predictors_hold_out <- foreach(i = 1:length(QRF_FIT_all_folds)) %do% {
tbl_regmat_target_cal %>%
dplyr::select(-(split:hor), -pH_KCl) %>%
.[QRF_FIT_all_folds[[i]]$control$indexOut[[1]],]
}
# retrieve OOB predictions only for hold out samples for all quantiles
ls_qrf_cv_quantiles <- foreach(i = 1:length(QRF_FIT_all_folds)) %do% {
predict(QRF_FIT_all_folds[[i]]$finalModel,
data = ls_tbl_predictors_hold_out[[i]],
type = "quantiles",
quantiles = QUANTILES,
seed = 2021,
num.threads = THREADS,
verbose = TRUE)
}
# retrieve indices from final model of each fold (not all samples used in each fold)
ls_indices_hold_out <- map(QRF_FIT_all_folds, ~ .$control$indexOut) %>%
map(., ~unlist(.x, use.names = FALSE)) %>%
set_names(., paste0("Resample", 1:10))
# retrieve quantile predictions, indices indicating which samples in calibration
# data set used for final model of each fold/model and extend tibbles to include
# entire calibration dataset (filling in NA for folds/models where samples were
# not in final model)
ls_qrf_cal_cv <- map(ls_qrf_cv_quantiles, ~.$predictions) %>%
map(., ~ as_tibble(.x)) %>%
map(., ~ rename_all(.x, ~ paste0("quant_", QUANTILES * 100))) %>%
map2(.x = ., .y = ls_indices_hold_out, ~add_column(.x, index = .y)) %>%
map(., ~ complete(.x, index = full_seq(1:nrow(tbl_regmat_target_cal), 1))) %>%
set_names(., paste0("Resample", 1:10))
# combine predictions of quantiles across all folds/models into 1 tibble
v_colnames <- Reduce(intersect, lapply(ls_qrf_cal_cv, names))
tbl_predobs_cal_cv <- lapply(
ls_qrf_cal_cv,
function(x) setkeyv(data.table(x), v_colnames, physical = FALSE))
tbl_predobs_cal_cv <- Reduce(
function(...) merge(..., all = TRUE, sort = FALSE), tbl_predobs_cal_cv) %>%
as_tibble()
# remove NA's and arrange in same order as original calibration dataframe
tbl_predobs_cal_cv <- tbl_predobs_cal_cv %>%
drop_na() %>%
arrange(index) %>%
dplyr::select(-index) # no longer need index col
# add observations, depths, mean predictions & compute logical if within PI90
tbl_predobs_cal_cv <- tbl_predobs_cal_cv %>%
add_column(d_upper = tbl_regmat_target_cal$d_upper,
d_lower = tbl_regmat_target_cal$d_lower,
d_mid = tbl_regmat_target_cal$d_mid,
obs = pull(tbl_regmat_target_cal, TARGET),
pred_mean = QRF_FIT_optimal$pred %>%
as_tibble() %>%
arrange(rowIndex) %>%
pull(pred),
.before = "quant_0") %>%
mutate(within_PI90 = if_else(obs >= quant_5 & obs <= quant_95,
TRUE, FALSE))
## LSK: Predictions of independent validation dataset ---------------------------
# predict independent test dataset (LSK or CCNL)
qrf_tree_val <- predict.ranger.tree(QRF_FIT_optimal$finalModel,
data = tbl_regmat_target_val %>%
dplyr::select(-(split:hor), -pH_KCl),
type = "treepred")
# predict all quantiles and then also the mean
tbl_qrf_val <- data.frame(t(apply(qrf_tree_val$predictions,
1, quantile, QUANTILES, na.rm = TRUE))) %>%
as_tibble() %>%
rename_all(~ paste0("quant_", QUANTILES * 100)) %>%
# predict mean value
add_column(pred_mean = apply(qrf_tree_val$predictions,
1, mean, na.rm = TRUE),
.before = "quant_0")
# add observations, depths & compute logical if within PI90
tbl_predobs_val <- tbl_qrf_val %>%
add_column(d_upper = tbl_regmat_target_val$d_upper,
d_lower = tbl_regmat_target_val$d_lower,
d_mid = tbl_regmat_target_val$d_mid,
obs = pull(tbl_regmat_target_val, TARGET),
.before = "pred_mean") %>%
mutate(within_PI90 = if_else(obs >= quant_5 & obs <= quant_95,
TRUE, FALSE))
# include spatial component for assessing validation using sampling design (sf)
sf_predobs_val <- sf_regmat_target_val %>%
dplyr::select(sample_id:hor) %>%
bind_cols(., tbl_predobs_val)
# plot validation locations over probability sampling strata
m_sampling_design <- ggplot() +
geom_sf(data = sf_LSK_strata) +
geom_sf(data = sf_predobs_val)
# join points and polygons sf features (overlay)
sf_predobs_val <- st_join(sf_predobs_val, sf_LSK_strata) %>%
rename(str_id = OBJECTID,
str_code = stratum_cu,
str_leng = Shape_Leng,
str_area_m2 = Shape_Area,
str_area_ha = opp_ha)
# one location is in built-up area and has no designated stratum
mapview(sf_predobs_val %>%
filter(str_code %in% NA))
# remove it
sf_predobs_val <- sf_predobs_val %>%
filter(!str_code %in% NA)
# area of all strata (should be approx land area of NL excluding cities & water)
area_tot_m2 = as.numeric(sum(st_area(sf_LSK_strata))) # in m^2
### Group by GSM depth layers --------------------------------------------------
# split data into designated GSM depth increments
# PFB-OOB: calibration OOB data
tbl_predobs_cal_OOB_0_5 <- tbl_predobs_cal_OOB %>%
filter(between(d_mid, 0, 4.9))
tbl_predobs_cal_OOB_5_15 <- tbl_predobs_cal_OOB %>%
filter(between(d_mid, 5, 14.9))
tbl_predobs_cal_OOB_15_30 <- tbl_predobs_cal_OOB %>%
filter(between(d_mid, 15, 29.9))
tbl_predobs_cal_OOB_30_60 <- tbl_predobs_cal_OOB %>%
filter(between(d_mid, 30, 59.9))
tbl_predobs_cal_OOB_60_100 <- tbl_predobs_cal_OOB %>%
filter(between(d_mid, 60, 99.9))
tbl_predobs_cal_OOB_100_200 <- tbl_predobs_cal_OOB %>%
filter(between(d_mid, 100, 200))
# PFB-CV: Location-grouped 10-fold CV calibration data
tbl_predobs_cal_cv_0_5 <- tbl_predobs_cal_cv %>%
filter(between(d_mid, 0, 4.9))
tbl_predobs_cal_cv_5_15 <- tbl_predobs_cal_cv %>%
filter(between(d_mid, 5, 14.9))
tbl_predobs_cal_cv_15_30 <- tbl_predobs_cal_cv %>%
filter(between(d_mid, 15, 29.9))
tbl_predobs_cal_cv_30_60 <- tbl_predobs_cal_cv %>%
filter(between(d_mid, 30, 59.9))
tbl_predobs_cal_cv_60_100 <- tbl_predobs_cal_cv %>%
filter(between(d_mid, 60, 99.9))
tbl_predobs_cal_cv_100_200 <- tbl_predobs_cal_cv %>%
filter(between(d_mid, 100, 200))
# validation data
sf_predobs_val_0_5 <- sf_predobs_val %>%
filter(between(d_mid, 0, 4.9))
sf_predobs_val_5_15 <- sf_predobs_val %>%
filter(between(d_mid, 5, 14.9))
sf_predobs_val_15_30 <- sf_predobs_val %>%
filter(between(d_mid, 15, 29.9))
sf_predobs_val_30_60 <- sf_predobs_val %>%
filter(between(d_mid, 30, 59.9))
sf_predobs_val_60_100 <- sf_predobs_val %>%
filter(between(d_mid, 60, 99.9))
sf_predobs_val_100_200 <- sf_predobs_val %>%
filter(between(d_mid, 100, 200))
# number of samples below 2m
# PFB-OOB
n_below_2m_cal_OOB <- tbl_predobs_cal_OOB %>%
filter(d_mid > 200) %>%
nrow()
# PFB-CV
n_below_2m_cal_cv <- tbl_predobs_cal_cv %>%
filter(d_mid > 200) %>%
nrow()
# validation data
n_below_2m_val <- sf_predobs_val %>%
filter(d_mid > 200) %>%
nrow()
# CHECK: If no samples were forgotten, this should be TRUE:
# PFB-OOB
nrow(tbl_predobs_cal_OOB_0_5) + nrow(tbl_predobs_cal_OOB_5_15) +
nrow(tbl_predobs_cal_OOB_15_30) + nrow(tbl_predobs_cal_OOB_30_60) +
nrow(tbl_predobs_cal_OOB_60_100) + nrow(tbl_predobs_cal_OOB_100_200) +
n_below_2m_cal_OOB == nrow(tbl_predobs_cal_OOB)
# PFB-CV
nrow(tbl_predobs_cal_cv_0_5) + nrow(tbl_predobs_cal_cv_5_15) +
nrow(tbl_predobs_cal_cv_15_30) + nrow(tbl_predobs_cal_cv_30_60) +
nrow(tbl_predobs_cal_cv_60_100) + nrow(tbl_predobs_cal_cv_100_200) +
n_below_2m_cal_cv == nrow(tbl_predobs_cal_cv)
# validation data
nrow(sf_predobs_val_0_5) + nrow(sf_predobs_val_5_15) +
nrow(sf_predobs_val_15_30) + nrow(sf_predobs_val_30_60) +
nrow(sf_predobs_val_60_100) + nrow(sf_predobs_val_100_200) +
n_below_2m_val == nrow(sf_predobs_val)
### 0-5cm: Accuracy plots and metrics ------------------------------------------
# 0-5cm: PFB-OOB and PFB-CV accuracy plots and metrics -------------------------
# PFB-OOB accuracy metrics
tbl_accuracy_metrics_PFB_OOB_0_5 <- tibble(
n = length(tbl_predobs_cal_OOB_0_5$obs),
one_one = "1:1",
me = mean(tbl_predobs_cal_OOB_0_5$obs - tbl_predobs_cal_OOB_0_5$pred_mean),
me_median = mean(tbl_predobs_cal_OOB_0_5$obs - tbl_predobs_cal_OOB_0_5$quant_50),
rmse = sqrt(mean((tbl_predobs_cal_OOB_0_5$obs - tbl_predobs_cal_OOB_0_5$pred_mean)^2)),
rmse_median = sqrt(mean((tbl_predobs_cal_OOB_0_5$obs - tbl_predobs_cal_OOB_0_5$quant_50)^2)),
mec = 1-((sum((tbl_predobs_cal_OOB_0_5$obs - tbl_predobs_cal_OOB_0_5$pred_mean)^2))/
sum((tbl_predobs_cal_OOB_0_5$obs - mean(tbl_predobs_cal_OOB_0_5$obs))^2)),
mec_median = 1-((sum((tbl_predobs_cal_OOB_0_5$obs - tbl_predobs_cal_OOB_0_5$quant_50)^2))/
sum((tbl_predobs_cal_OOB_0_5$obs - mean(tbl_predobs_cal_OOB_0_5$obs))^2)),
n_within_PI90 = nrow(filter(tbl_predobs_cal_OOB_0_5, within_PI90 %in% TRUE))/n,
n_within_PI90_not = nrow(filter(tbl_predobs_cal_OOB_0_5, within_PI90 %in% FALSE))/n) %>%
# Modify columns for plot annotation (char = characters)
mutate(me_char = as.character(as.expression(paste0("ME == ", round(me, 2)))),
rmse_char = as.character(as.expression(paste0("RMSE == ", round(rmse, 2)))),
mec_char = as.character(as.expression(paste0("MEC == ", round(mec, 2)))),
n_char = as.character(as.expression(paste0("italic(n) == ", n))))
# PFB-CV accuracy metrics
tbl_accuracy_metrics_PFB_CV_0_5 <- tibble(
n = length(tbl_predobs_cal_cv_0_5$obs),
one_one = "1:1",
me = mean(tbl_predobs_cal_cv_0_5$obs - tbl_predobs_cal_cv_0_5$pred_mean),
me_median = mean(tbl_predobs_cal_cv_0_5$obs - tbl_predobs_cal_cv_0_5$quant_50),
rmse = sqrt(mean((tbl_predobs_cal_cv_0_5$obs - tbl_predobs_cal_cv_0_5$pred_mean)^2)),
rmse_median = sqrt(mean((tbl_predobs_cal_cv_0_5$obs - tbl_predobs_cal_cv_0_5$quant_50)^2)),
mec = 1-((sum((tbl_predobs_cal_cv_0_5$obs - tbl_predobs_cal_cv_0_5$pred_mean)^2))/
sum((tbl_predobs_cal_cv_0_5$obs - mean(tbl_predobs_cal_cv_0_5$obs))^2)),
mec_median = 1-((sum((tbl_predobs_cal_cv_0_5$obs - tbl_predobs_cal_cv_0_5$quant_50)^2))/
sum((tbl_predobs_cal_cv_0_5$obs - mean(tbl_predobs_cal_cv_0_5$obs))^2)),
n_within_PI90 = nrow(filter(tbl_predobs_cal_cv_0_5, within_PI90 %in% TRUE))/n,
n_within_PI90_not = nrow(filter(tbl_predobs_cal_cv_0_5, within_PI90 %in% FALSE))/n) %>%
# Modify columns for plot annotation (char = characters)
mutate(me_char = as.character(as.expression(paste0("ME == ", round(me, 2)))),
rmse_char = as.character(as.expression(paste0("RMSE == ", round(rmse, 2)))),
mec_char = as.character(as.expression(paste0("MEC == ", round(mec, 2)))),
n_char = as.character(as.expression(paste0("italic(n) == ", n))))
# PFB-OOB accuracy plot
p_pred_obs_PFB_OOB_0_5 <- tbl_predobs_cal_OOB_0_5 %>%
mutate(within_PI90 = case_when(
within_PI90 %in% TRUE ~ paste0('TRUE (',round(tbl_accuracy_metrics_PFB_OOB_0_5$n_within_PI90, 3), ')'),
within_PI90 %in% FALSE ~ paste0('FALSE (', round(tbl_accuracy_metrics_PFB_OOB_0_5$n_within_PI90_not, 3), ')'))) %>%
ggplot(aes(x = pred_mean, y = obs)) +
geom_errorbar(aes(xmin = quant_5, xmax = quant_95, y = obs),
color = "gray") +
geom_point(aes(color = within_PI90, shape = within_PI90)) +
scale_color_manual(values = c("#ef8a62", "#67a9cf")) +
scale_shape_manual(values = c(4, 21)) +
geom_abline(slope = 1, intercept = 0, color = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_0_5,
aes(x = Inf, y = Inf, label = one_one), size = 3,
hjust = 2.5, vjust = 2, colour = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_0_5,
aes(x = Inf, y = -Inf, label = n_char), size = 3,
hjust = 1.15, vjust = -8, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_0_5,
aes(x = Inf, y = -Inf, label = mec_char), size = 3,
hjust = 1.12, vjust = -5.75, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_0_5,
aes(x = Inf, y = -Inf, label = rmse_char), size = 3,
hjust = 1.08, vjust = -3.5, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_0_5,
aes(x = Inf, y = -Inf, label = me_char), size = 3,
hjust = 1.12, vjust = -1.5, parse = TRUE) +
ylab(as.expression(paste(TARGET_EXP))) +
xlab(TARGET_PRED) +
scale_x_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
scale_y_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
coord_fixed(ratio = 1) +
theme_bw() +
labs(col = "PICP of PI90",
shape = "PICP of PI90")
# PFB-CV accuracy plot
p_pred_obs_PFB_CV_0_5 <- tbl_predobs_cal_cv_0_5 %>%
mutate(within_PI90 = case_when(
within_PI90 %in% TRUE ~ paste0('TRUE (',round(tbl_accuracy_metrics_PFB_CV_0_5$n_within_PI90, 3), ')'),
within_PI90 %in% FALSE ~ paste0('FALSE (', round(tbl_accuracy_metrics_PFB_CV_0_5$n_within_PI90_not, 3), ')'))) %>%
ggplot(aes(x = pred_mean, y = obs)) +
geom_errorbar(aes(xmin = quant_5, xmax = quant_95, y = obs),
color = "gray") +
geom_point(aes(color = within_PI90, shape = within_PI90)) +
scale_color_manual(values = c("#ef8a62", "#67a9cf")) +
scale_shape_manual(values = c(4, 21)) +
geom_abline(slope = 1, intercept = 0, color = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_CV_0_5,
aes(x = Inf, y = Inf, label = one_one), size = 3,
hjust = 2.5, vjust = 2, colour = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_CV_0_5,
aes(x = Inf, y = -Inf, label = n_char), size = 3,
hjust = 1.15, vjust = -8, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_CV_0_5,
aes(x = Inf, y = -Inf, label = mec_char), size = 3,
hjust = 1.12, vjust = -5.75, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_CV_0_5,
aes(x = Inf, y = -Inf, label = rmse_char), size = 3,
hjust = 1.08, vjust = -3.5, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_CV_0_5,
aes(x = Inf, y = -Inf, label = me_char), size = 3,
hjust = 1.12, vjust = -1.5, parse = TRUE) +
ylab(as.expression(paste(TARGET_EXP))) +
xlab(TARGET_PRED) +
scale_x_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
scale_y_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
coord_fixed(ratio = 1) +
theme_bw() +
labs(col = "PICP of PI90",
shape = "PICP of PI90")
# 0-5cm: LSK and LSK-SRS accuracy plots and metrics ----------------------------
# NO accuracy plot or metrics for validation data for 0-5cm because only 1 obs
sf_predobs_val_0_5
### 5-15cm: Accuracy plots and metrics -----------------------------------------
# 5-15cm: PFB-OOB and PFB-CV accuracy plots and metrics ------------------------
# PFB-OOB accuracy metrics
tbl_accuracy_metrics_PFB_OOB_5_15 <- tibble(
n = length(tbl_predobs_cal_OOB_5_15$obs),
one_one = "1:1",
me = mean(tbl_predobs_cal_OOB_5_15$obs - tbl_predobs_cal_OOB_5_15$pred_mean),
me_median = mean(tbl_predobs_cal_OOB_5_15$obs - tbl_predobs_cal_OOB_5_15$quant_50),
rmse = sqrt(mean((tbl_predobs_cal_OOB_5_15$obs - tbl_predobs_cal_OOB_5_15$pred_mean)^2)),
rmse_median = sqrt(mean((tbl_predobs_cal_OOB_5_15$obs - tbl_predobs_cal_OOB_5_15$quant_50)^2)),
mec = 1-((sum((tbl_predobs_cal_OOB_5_15$obs - tbl_predobs_cal_OOB_5_15$pred_mean)^2))/
sum((tbl_predobs_cal_OOB_5_15$obs - mean(tbl_predobs_cal_OOB_5_15$obs))^2)),
mec_median = 1-((sum((tbl_predobs_cal_OOB_5_15$obs - tbl_predobs_cal_OOB_5_15$quant_50)^2))/
sum((tbl_predobs_cal_OOB_5_15$obs - mean(tbl_predobs_cal_OOB_5_15$obs))^2)),
n_within_PI90 = nrow(filter(tbl_predobs_cal_OOB_5_15, within_PI90 %in% TRUE))/n,
n_within_PI90_not = nrow(filter(tbl_predobs_cal_OOB_5_15, within_PI90 %in% FALSE))/n) %>%
# Modify columns for plot annotation (char = characters)
mutate(me_char = as.character(as.expression(paste0("ME == ", round(me, 2)))),
rmse_char = as.character(as.expression(paste0("RMSE == ", round(rmse, 2)))),
mec_char = as.character(as.expression(paste0("MEC == ", round(mec, 2)))),
n_char = as.character(as.expression(paste0("italic(n) == ", n))))
# PFB-CV accuracy metrics
tbl_accuracy_metrics_PFB_CV_5_15 <- tibble(
n = length(tbl_predobs_cal_cv_5_15$obs),
one_one = "1:1",
me = mean(tbl_predobs_cal_cv_5_15$obs - tbl_predobs_cal_cv_5_15$pred_mean),
me_median = mean(tbl_predobs_cal_cv_5_15$obs - tbl_predobs_cal_cv_5_15$quant_50),
rmse = sqrt(mean((tbl_predobs_cal_cv_5_15$obs - tbl_predobs_cal_cv_5_15$pred_mean)^2)),
rmse_median = sqrt(mean((tbl_predobs_cal_cv_5_15$obs - tbl_predobs_cal_cv_5_15$quant_50)^2)),
mec = 1-((sum((tbl_predobs_cal_cv_5_15$obs - tbl_predobs_cal_cv_5_15$pred_mean)^2))/
sum((tbl_predobs_cal_cv_5_15$obs - mean(tbl_predobs_cal_cv_5_15$obs))^2)),
mec_median = 1-((sum((tbl_predobs_cal_cv_5_15$obs - tbl_predobs_cal_cv_5_15$quant_50)^2))/
sum((tbl_predobs_cal_cv_5_15$obs - mean(tbl_predobs_cal_cv_5_15$obs))^2)),
n_within_PI90 = nrow(filter(tbl_predobs_cal_cv_5_15, within_PI90 %in% TRUE))/n,
n_within_PI90_not = nrow(filter(tbl_predobs_cal_cv_5_15, within_PI90 %in% FALSE))/n) %>%
# Modify columns for plot annotation (char = characters)
mutate(me_char = as.character(as.expression(paste0("ME == ", round(me, 2)))),
rmse_char = as.character(as.expression(paste0("RMSE == ", round(rmse, 2)))),
mec_char = as.character(as.expression(paste0("MEC == ", round(mec, 2)))),
n_char = as.character(as.expression(paste0("italic(n) == ", n))))
# PFB-OOB accuracy plot
p_pred_obs_PFB_OOB_5_15 <- tbl_predobs_cal_OOB_5_15 %>%
mutate(within_PI90 = case_when(
within_PI90 %in% TRUE ~ paste0('TRUE (',round(tbl_accuracy_metrics_PFB_OOB_5_15$n_within_PI90, 3), ')'),
within_PI90 %in% FALSE ~ paste0('FALSE (', round(tbl_accuracy_metrics_PFB_OOB_5_15$n_within_PI90_not, 3), ')'))) %>%
ggplot(aes(x = pred_mean, y = obs)) +
geom_errorbar(aes(xmin = quant_5, xmax = quant_95, y = obs),
color = "gray") +
geom_point(aes(color = within_PI90, shape = within_PI90)) +
scale_color_manual(values = c("#ef8a62", "#67a9cf")) +
scale_shape_manual(values = c(4, 21)) +
geom_abline(slope = 1, intercept = 0, color = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_5_15,
aes(x = Inf, y = Inf, label = one_one), size = 3,
hjust = 2.5, vjust = 2, colour = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_5_15,
aes(x = Inf, y = -Inf, label = n_char), size = 3,
hjust = 1.15, vjust = -8, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_5_15,
aes(x = Inf, y = -Inf, label = mec_char), size = 3,
hjust = 1.12, vjust = -5.75, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_5_15,
aes(x = Inf, y = -Inf, label = rmse_char), size = 3,
hjust = 1.08, vjust = -3.5, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_OOB_5_15,
aes(x = Inf, y = -Inf, label = me_char), size = 3,
hjust = 1.12, vjust = -1.5, parse = TRUE) +
ylab(as.expression(paste(TARGET_EXP))) +
xlab(TARGET_PRED) +
scale_x_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
scale_y_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
coord_fixed(ratio = 1) +
theme_bw() +
labs(col = "PICP of PI90",
shape = "PICP of PI90")
# PFB-CV accuracy plot
p_pred_obs_PFB_CV_5_15 <- tbl_predobs_cal_cv_5_15 %>%
mutate(within_PI90 = case_when(
within_PI90 %in% TRUE ~ paste0('TRUE (',round(tbl_accuracy_metrics_PFB_CV_5_15$n_within_PI90, 3), ')'),
within_PI90 %in% FALSE ~ paste0('FALSE (', round(tbl_accuracy_metrics_PFB_CV_5_15$n_within_PI90_not, 3), ')'))) %>%
ggplot(aes(x = pred_mean, y = obs)) +
geom_errorbar(aes(xmin = quant_5, xmax = quant_95, y = obs),
color = "gray") +
geom_point(aes(color = within_PI90, shape = within_PI90)) +
scale_color_manual(values = c("#ef8a62", "#67a9cf")) +
scale_shape_manual(values = c(4, 21)) +
geom_abline(slope = 1, intercept = 0, color = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_CV_5_15,
aes(x = Inf, y = Inf, label = one_one), size = 3,
hjust = 2.5, vjust = 2, colour = "gray") +
geom_text(data = tbl_accuracy_metrics_PFB_CV_5_15,
aes(x = Inf, y = -Inf, label = n_char), size = 3,
hjust = 1.15, vjust = -8, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_CV_5_15,
aes(x = Inf, y = -Inf, label = mec_char), size = 3,
hjust = 1.12, vjust = -5.75, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_CV_5_15,
aes(x = Inf, y = -Inf, label = rmse_char), size = 3,
hjust = 1.08, vjust = -3.5, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_PFB_CV_5_15,
aes(x = Inf, y = -Inf, label = me_char), size = 3,
hjust = 1.12, vjust = -1.5, parse = TRUE) +
ylab(as.expression(paste(TARGET_EXP))) +
xlab(TARGET_PRED) +
scale_x_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
scale_y_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
coord_fixed(ratio = 1) +
theme_bw() +
labs(col = "PICP of PI90",
shape = "PICP of PI90")
# 5-15cm: LSK and LSK-SRS accuracy plots and metrics ---------------------------
# first make accuracy plot and metrics for LSK, ignoring SRS (just for comparison)
# LSK accuracy metrics
tbl_accuracy_metrics_LSK_5_15 <- tibble(
n = length(sf_predobs_val_5_15$obs),
one_one = "1:1",
me = mean(sf_predobs_val_5_15$obs - sf_predobs_val_5_15$pred_mean),
me_median = mean(sf_predobs_val_5_15$obs - sf_predobs_val_5_15$quant_50),
rmse = sqrt(mean((sf_predobs_val_5_15$obs - sf_predobs_val_5_15$pred_mean)^2)),
rmse_median = sqrt(mean((sf_predobs_val_5_15$obs - sf_predobs_val_5_15$quant_50)^2)),
mec = 1-((sum((sf_predobs_val_5_15$obs - sf_predobs_val_5_15$pred_mean)^2))/
sum((sf_predobs_val_5_15$obs - mean(sf_predobs_val_5_15$obs))^2)),
mec_median = 1-((sum((sf_predobs_val_5_15$obs - sf_predobs_val_5_15$quant_50)^2))/
sum((sf_predobs_val_5_15$obs - mean(sf_predobs_val_5_15$obs))^2)),
n_within_PI90 = nrow(filter(sf_predobs_val_5_15, within_PI90 %in% TRUE))/n,
n_within_PI90_not = nrow(filter(sf_predobs_val_5_15, within_PI90 %in% FALSE))/n) %>%
# Modify columns for plot annotation (char = characters)
mutate(me_char = as.character(as.expression(paste0("ME == ", round(me, 2)))),
rmse_char = as.character(as.expression(paste0("RMSE == ", round(rmse, 2)))),
mec_char = as.character(as.expression(paste0("MEC == ", round(mec, 2)))),
n_char = as.character(as.expression(paste0("italic(n) == ", n))))
# LSK accuracy plot
p_pred_obs_LSK_5_15 <- sf_predobs_val_5_15 %>%
mutate(within_PI90 = case_when(
within_PI90 %in% TRUE ~ paste0('TRUE (',round(tbl_accuracy_metrics_LSK_5_15$n_within_PI90, 3), ')'),
within_PI90 %in% FALSE ~ paste0('FALSE (', round(tbl_accuracy_metrics_LSK_5_15$n_within_PI90_not, 3), ')'))) %>%
ggplot(aes(x = pred_mean, y = obs)) +
geom_errorbar(aes(xmin = quant_5, xmax = quant_95, y = obs),
color = "gray") +
geom_point(aes(color = within_PI90, shape = within_PI90)) +
scale_color_manual(values = c("#ef8a62", "#67a9cf")) +
scale_shape_manual(values = c(4, 21)) +
geom_abline(slope = 1, intercept = 0, color = "gray") +
geom_text(data = tbl_accuracy_metrics_LSK_5_15,
aes(x = Inf, y = Inf, label = one_one), size = 3,
hjust = 2.5, vjust = 2, colour = "gray") +
geom_text(data = tbl_accuracy_metrics_LSK_5_15,
aes(x = Inf, y = -Inf, label = n_char), size = 3,
hjust = 1.15, vjust = -8, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_LSK_5_15,
aes(x = Inf, y = -Inf, label = mec_char), size = 3,
hjust = 1.12, vjust = -5.75, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_LSK_5_15,
aes(x = Inf, y = -Inf, label = rmse_char), size = 3,
hjust = 1.08, vjust = -3.5, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_LSK_5_15,
aes(x = Inf, y = -Inf, label = me_char), size = 3,
hjust = 1.12, vjust = -1.5, parse = TRUE) +
ylab(as.expression(paste(TARGET_EXP))) +
xlab(TARGET_PRED) +
scale_x_continuous(breaks = XY_BREAKS_VAL,
limits = c(XY_MIN_VAL - 0.01 * XY_RANGE_VAL,
XY_MAX_VAL + 0.01 * XY_RANGE_VAL)) +
scale_y_continuous(breaks = XY_BREAKS_VAL,
limits = c(XY_MIN_VAL - 0.01 * XY_RANGE_VAL,
XY_MAX_VAL + 0.01 * XY_RANGE_VAL)) +
coord_fixed(ratio = 1) +
theme_bw() +
labs(col = "PICP of PI90",
shape = "PICP of PI90")
# LSK-SRS (ANALYSIS PREPARATION STARTS HERE)
# vector of locations where there are multiple observations with the same
# distance to the midpoint of the respective GSM depth layer
v_d_dist_mid_eq_5_15 <- sf_predobs_val_5_15 %>%
mutate(d_dist_mid = abs(10 - d_mid)) %>% # MIDPOINT OF GSM DEPTH LAYER = 10
group_by(site_id, d_dist_mid) %>%
tally() %>%
filter(n >= 2) %>%
.$site_id
# For SRS sampling design, can only have 1 observation per location and specified
# GSM depth layer. Therefore remove observations farther away from midpoint of
# GSM depth layer, or average (mean) if distances are the same
if (any(duplicated(sf_predobs_val_5_15$site_id))) {
sf_predobs_val_5_15 <- sf_predobs_val_5_15 %>%
mutate(d_dist_mid = abs(10 - d_mid)) %>% # MIDPOINT OF GSM DEPTH LAYER = 10
group_by(site_id) %>%
# average observations and predictions at same location where both observations
# have equal distance to GSM depth layer (see defined vector above)
mutate(across(obs:quant_100,
~ ifelse(site_id %in% v_d_dist_mid_eq_5_15, mean(.x), .x))) %>%
# select observation that is closest to midpoint of GSM depth layer
slice(which.min(d_dist_mid)) %>%
# remove temporary grouping variable
dplyr::select(-d_dist_mid) %>%
# calculate new PI90 because may change slightly after averaging...
mutate(within_PI90 = if_else(obs >= quant_5 & obs <= quant_95,
TRUE, FALSE))
} else {
sf_predobs_val_5_15 <- sf_predobs_val_5_15
}
# vector of strata codes that only have one observation
v_str_code_1obs_5_15 <- sf_predobs_val_5_15 %>%
group_by(str_code) %>%
tally() %>%
filter(n == 1) %>%
.$str_code
# for upcoming calculations, we need to calculate residuals, stratum (str) weights
# and number of samples per str; we leave tibble grouped by str
sf_predobs_val_5_15 <- sf_predobs_val_5_15 %>%
mutate(res = obs - pred_mean, # residuals
res_median = obs - quant_50, # residuals when using median prediction
str_weight = str_area_m2/area_tot_m2) %>% # str weights based on area
group_by(str_code) %>%
mutate(str_n = n()) # number of samples per str
# for str with only 1 observation, we estimate the within-str variance by taking
# the average of all within-str variances of all str with 2 or more observations;
# this mean variance has to be calculated for each metric separately
# Mean of all within str variances of Mean Error (ME = bias)
var_me_mean <- sf_predobs_val_5_15 %>%
mutate(str_var_me = 1/(str_n-1)*sum((res - mean(res))^2)) %>%
slice(1L) %>%
pull(str_var_me) %>%
mean(na.rm = TRUE) # NAs are from str with only 1 observation
# when using median instead of mean predictions
var_me_median_mean <- sf_predobs_val_5_15 %>%
mutate(str_var_me = 1/(str_n-1)*sum((res_median - mean(res_median))^2)) %>%
slice(1L) %>%
pull(str_var_me) %>%
mean(na.rm = TRUE) # NAs are from str with only 1 observation
# Mean of all within str variances of Mean Squared Error (MSE)
var_mse_mean <- sf_predobs_val_5_15 %>%
mutate(str_var_mse = 1/(str_n-1)*sum((res^2 - mean(res^2))^2)) %>%
slice(1L) %>%
pull(str_var_mse) %>%
mean(na.rm = TRUE) # NAs are from str with only 1 observation
# when using median instead of mean predictions
var_mse_median_mean <- sf_predobs_val_5_15 %>%
mutate(str_var_mse = 1/(str_n-1)*sum((res_median^2 - mean(res_median^2))^2)) %>%
slice(1L) %>%
pull(str_var_mse) %>%
mean(na.rm = TRUE) # NAs are from str with only 1 observation
# Mean of all within str variances of observations (for Var Y and MEC)
var_Y_mean <- sf_predobs_val_5_15 %>%
mutate(str_var_Y = str_weight^2*(1/(str_n*(str_n-1)))*sum((obs - mean(obs))^2)) %>%
slice(1L) %>%
pull(str_var_Y) %>%
mean(na.rm = TRUE) # NAs are from str with only 1 observation
# calculate model metrics of probability sampling design
sf_predobs_val_5_15 <- sf_predobs_val_5_15 %>%
# weighted ME per str
mutate(str_me = str_weight*mean(res),
# within str variances of ME
str_me_var = ifelse(str_n == 1, str_weight^2*(1/str_n)*var_me_mean,
str_weight^2*(1/(str_n*(str_n-1)))*sum((res - mean(res))^2)),
# weighted MSE per str
str_mse = str_weight*mean(res^2),
# within str variances of MSE
str_mse_var = ifelse(str_n == 1, str_weight^2*(1/str_n)*var_mse_mean,
str_weight^2*(1/(str_n*(str_n-1)))*sum((res^2 - mean(res^2))^2)),
# same as above but now using median instead of mean predictions
str_me_median = str_weight*mean(res_median),
str_me_median_var = ifelse(str_n == 1, str_weight^2*(1/str_n)*var_me_median_mean,
str_weight^2*(1/(str_n*(str_n-1)))*sum((res_median - mean(res_median))^2)),
str_mse_median = str_weight*mean(res_median^2),
str_mse_median_var = ifelse(str_n == 1, str_weight^2*(1/str_n)*var_mse_median_mean,
str_weight^2*(1/(str_n*(str_n-1)))*sum((res_median^2 - mean(res_median^2))^2)),
# for MEC, first need unbiased estimator of spatial variance (var(Y);
# see eqn. 7.16 in De Gruijter et al. 2006), where var(Y) is composed
# of the following terms (without yet taking sum of all str; this is done in
# "tbl_sum_stats_val" object below...):
# 1) Y^2st
str_Y2st = str_weight*(sum((obs)^2)/str_n),
# 2) Yst^2
str_Yst2 = str_weight*mean(obs),
# 3) v(Yst)
str_var_Yst = ifelse(str_n == 1, var_Y_mean,
str_weight^2*(1/(str_n*(str_n-1)))*sum((obs - mean(obs))^2))
)
# table of accuracy metrics for each str
tbl_accuracy_metrics_LSK_SRS_str_5_15 <- sf_predobs_val_5_15 %>%
dplyr::select(str_id:str_var_Yst) %>%
slice(1L) %>% # works since tibble is still grouped
as_tibble()
# degrees of freedom = sample size minus # of str
df = nrow(sf_predobs_val_5_15) - length(unique(sf_predobs_val_5_15$str_code))
# validation accuracy metrics for 5-15 cm GSM depth layer over all strata
tbl_accuracy_metrics_LSK_SRS_5_15 <- tibble(
n = length(sf_predobs_val_5_15$obs), # number of samples in this depth layer
# ME metrics (ME, ME variance, 95% confidence intervals (CI95) of ME)
me = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_me),
me_var = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_me_var),
me_ci_low = me - qt(0.975, df)*sqrt(me_var),
me_ci_up = me + qt(0.975, df)*sqrt(me_var),
# ME metrics when using median instead of mean predictions
me_median = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_me_median),
me_median_var = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_me_median_var),
me_median_ci_low = me_median - qt(0.975, df)*sqrt(me_median_var),
me_median_ci_up = me_median + qt(0.975, df)*sqrt(me_median_var),
# MSE metrics
mse = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_mse),
mse_var = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_mse_var),
mse_ci_low = mse - qt(0.975, df)*sqrt(mse_var),
mse_ci_up = mse + qt(0.975, df)*sqrt(mse_var),
# MSE metrics when using median instead of mean predictions
mse_median = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_mse_median),
mse_median_var = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_mse_median_var),
mse_median_ci_low = mse_median - qt(0.975, df)*sqrt(mse_median_var),
mse_median_ci_up = mse_median + qt(0.975, df)*sqrt(mse_median_var),
# RMSE metrics
rmse = sqrt(mse),
rmse_ci_low = sqrt(mse_ci_low),
rmse_ci_up = sqrt(mse_ci_up),
# RMSE metrics when using median instead of mean predictions
rmse_median = sqrt(mse_median),
rmse_median_ci_low = sqrt(mse_median_ci_low),
rmse_median_ci_up = sqrt(mse_median_ci_up),
# for MEC, first need unbiased estimator of spatial variance (var(Y);
# see eqn. 7.16 in De Gruijter et al. 2006)
var_Y = sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_Y2st) -
((sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_Yst2))^2) +
sum(tbl_accuracy_metrics_LSK_SRS_str_5_15$str_var_Yst),
# using function of package "surveyplanning": result is different!?
var_Y_pkg = s2(sf_predobs_val_5_15$obs, sf_predobs_val_5_15$str_weight),
# MEC
mec = 1 - mse/var_Y,
# MEC when using median instead of mean predictions
mec_median = 1 - mse_median/var_Y,
# obs within PI90
n_within_PI90 = nrow(filter(sf_predobs_val_5_15, within_PI90 %in% TRUE))/n,
n_within_PI90_not = nrow(filter(sf_predobs_val_5_15, within_PI90 %in% FALSE))/n)
# function to calculate MEC of a stratified random sampling dataset
fnc_MEC_SRS <- function(data, indices) {
d <- data[indices,] # allows boot to select sample
# calculations need to be done for each strata separately
d <- group_by(d, str_code)
# one of the terms in MEC equation is MSE
mse <- d %>%
mutate(str_mse = str_weight*mean(res^2)) %>%
slice(1L) %>%
pull(str_mse) %>%
sum()
# 1st term in Var Y equation (Y^2_st)
Y2st <- d %>%
mutate(str_Y2st = str_weight*(sum((obs)^2)/str_n)) %>%
slice(1L) %>%
pull(str_Y2st) %>%
sum()
# 2nd term in Var Y equation ((Y_st)^2)
Yst2 <- d %>%
mutate(str_Yst2 = str_weight*mean(obs)) %>%
slice(1L) %>%
pull(str_Yst2) %>%
sum()
# 3rd term in Var Y equation (V(Y_st))
var_Yst <- d %>%
mutate(var_Yst = ifelse(str_n == 1, var_Y_mean,
str_weight^2*(1/(str_n*(str_n-1)))*sum((obs - mean(obs))^2))) %>%
slice(1L) %>%
pull(var_Yst) %>%
sum()
# from these 3 terms we calculate Var(Y)
var_Y <- Y2st - (Yst2^2) + var_Yst
# calculate MEC using MSE and Var(Y)
return(mec = 1 - mse/var_Y)
}
# control randomness of bootstrapping for repoducibility
set.seed(2021)
# get bootstrap of MEC values
MEC_SRS_bootstrap_5_15 <- boot(data = sf_predobs_val_5_15,
statistic = fnc_MEC_SRS,
R = 1000,
strata = sf_predobs_val_5_15$str_code,
parallel = "multicore",
ncpus = parallel::detectCores())
# get CI95
MEC_SRS_90CI_5_15 <- boot.ci(boot.out = MEC_SRS_bootstrap_5_15,
conf = 0.95,
type = "perc")
# add CI95 of MEC to accuracy metrics tibble
tbl_accuracy_metrics_LSK_SRS_5_15 <- tbl_accuracy_metrics_LSK_SRS_5_15 %>%
add_column(mec_ci_low = MEC_SRS_90CI_5_15$percent[,4],
mec_ci_up = MEC_SRS_90CI_5_15$percent[,5])
# Modify columns for plot annotation
tbl_accuracy_metrics_LSK_SRS_5_15_annotate <- tbl_accuracy_metrics_LSK_SRS_5_15 %>%
add_column(one_one = "1:1") %>%
mutate(n = as.character(as.expression(paste0("italic(n) == ", n))),
me_ci = as.character(as.expression(paste0(
"ME = ", round(me, 2), " [", round(me_ci_low, 2),", ",
round(me_ci_up, 2), "]"))),
rmse_ci = as.character(as.expression(paste0(
"RMSE = ", round(rmse, 2), " [", round(rmse_ci_low, 2),", ",
round(rmse_ci_up, 2), "]"))),
mec_ci = as.character(as.expression(paste0(
"MEC = ", round(mec, 2), " [", round(mec_ci_low, 2),", ",
round(mec_ci_up, 2), "]"))))
# validation accuracy plot for 5-15 cm GSM depth layer
p_pred_obs_val_5_15 <- sf_predobs_val_5_15 %>%
mutate(within_PI90 = case_when(
within_PI90 %in% TRUE ~ paste0('TRUE (',round(tbl_accuracy_metrics_LSK_SRS_5_15_annotate$n_within_PI90, 3), ')'),
within_PI90 %in% FALSE ~ paste0('FALSE (', round(tbl_accuracy_metrics_LSK_SRS_5_15_annotate$n_within_PI90_not, 3), ')'))) %>%
ggplot(aes(x = pred_mean, y = obs)) +
geom_errorbar(aes(xmin = quant_5, xmax = quant_95, y = obs),
color = "gray") +
geom_point(aes(color = within_PI90, shape = within_PI90)) +
scale_color_manual(values = c("#ef8a62", "#67a9cf")) +
scale_shape_manual(values = c(4, 21)) +
geom_abline(slope = 1, intercept = 0, color = "gray") +
geom_text(data = tbl_accuracy_metrics_LSK_SRS_5_15_annotate,
aes(x = Inf, y = Inf, label = one_one), size = 3,
hjust = 2.5, vjust = 2, colour = "gray") +
geom_text(data = tbl_accuracy_metrics_LSK_SRS_5_15_annotate,
aes(x = Inf, y = -Inf, label = n), size = 3,
hjust = 1.15, vjust = -8, parse = TRUE) +
geom_text(data = tbl_accuracy_metrics_LSK_SRS_5_15_annotate,
aes(x = Inf, y = -Inf, label = mec_ci), size = 3,
hjust = 1.1, vjust = -5.75, parse = FALSE) +
geom_text(data = tbl_accuracy_metrics_LSK_SRS_5_15_annotate,
aes(x = Inf, y = -Inf, label = rmse_ci), size = 3,
hjust = 1.05, vjust = -3.5, parse = FALSE) +
geom_text(data = tbl_accuracy_metrics_LSK_SRS_5_15_annotate,
aes(x = Inf, y = -Inf, label = me_ci), size = 3,
hjust = 1.05, vjust = -1.4, parse = FALSE) +
ylab(as.expression(paste("pH [KCl]"))) +
xlab(expression(paste(hat(pH), " [KCl]"))) +
scale_x_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
scale_y_continuous(breaks = XY_BREAKS_CAL,
limits = c(XY_MIN_CAL - 0.01 * XY_RANGE_CAL,
XY_MAX_CAL + 0.01 * XY_RANGE_CAL)) +
coord_fixed(ratio = 1) +
theme_bw() +
labs(col = "PICP of PI90",
shape = "PICP of PI90")
# report which strata were excluded in spatial validation for this depth layer
(v_strata_excluded_5_15 = setdiff(unique(sf_predobs_val$str_code),
unique(sf_predobs_val_5_15$str_code)))
# area excluded in spatial validation for this depth layer in m^2
area_excluded_5_15_PFB_CV = sf_predobs_val %>%
filter(str_code %in% v_strata_excluded_5_15) %>%
group_by(str_code) %>%
slice(1L) %>%
pull(str_area_m2) %>%
sum()
# area included as a percentage of total area [%]
(area_included_5_15_per = (area_tot_m2 - area_excluded_5_15_PFB_CV)/area_tot_m2 *100)
### 15-30cm: Accuracy plots and metrics ----------------------------------------
# 15-30cm: PFB-OOB and PFB-CV accuracy plots and metrics -----------------------
# PFB-OOB accuracy metrics
tbl_accuracy_metrics_PFB_OOB_15_30 <- tibble(
n = length(tbl_predobs_cal_OOB_15_30$obs),
one_one = "1:1",
me = mean(tbl_predobs_cal_OOB_15_30$obs - tbl_predobs_cal_OOB_15_30$pred_mean),
me_median = mean(tbl_predobs_cal_OOB_15_30$obs - tbl_predobs_cal_OOB_15_30$quant_50),
rmse = sqrt(mean((tbl_predobs_cal_OOB_15_30$obs - tbl_predobs_cal_OOB_15_30$pred_mean)^2)),
rmse_median = sqrt(mean((tbl_predobs_cal_OOB_15_30$obs - tbl_predobs_cal_OOB_15_30$quant_50)^2)),
mec = 1-((sum((tbl_predobs_cal_OOB_15_30$obs - tbl_predobs_cal_OOB_15_30$pred_mean)^2))/
sum((tbl_predobs_cal_OOB_15_30$obs - mean(tbl_predobs_cal_OOB_15_30$obs))^2)),
mec_median = 1-((sum((tbl_predobs_cal_OOB_15_30$obs - tbl_predobs_cal_OOB_15_30$quant_50)^2))/
sum((tbl_predobs_cal_OOB_15_30$obs - mean(tbl_predobs_cal_OOB_15_30$obs))^2)),
n_within_PI90 = nrow(filter(tbl_predobs_cal_OOB_15_30, within_PI90 %in% TRUE))/n,
n_within_PI90_not = nrow(filter(tbl_predobs_cal_OOB_15_30, within_PI90 %in% FALSE))/n) %>%
# Modify columns for plot annotation (char = characters)