-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-isocape-jack-knife.Rmd
1645 lines (1213 loc) · 61.4 KB
/
04-isocape-jack-knife.Rmd
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
---
title: "Precipitation sinusoidal isocape model: jackknifing"
author: "Bruce Dudley (NIWA), Andy McKenzie (NIWA)"
date: "`r format(Sys.Date(), '%d %B, %Y')`"
output:
html_document:
theme: united
code_folding: show
toc: yes
toc_float:
collapsed: true
fig_caption: yes
number_sections: yes
df_print: kable
word_document:
toc: yes
pdf_document:
toc: yes
fig_caption: yes
number_sections: yes
editor_options:
chunk_output_type: console
markdown:
wrap: 72
---
```{r setup, include=FALSE}
# Global options
#
# echo = TRUE. Show the code
# comment = "". Don't put anything in front of results from code
# warning = FALSE. Don't display warning messages
# cache = TRUE. Only process new code when you knit
# dev = 'png'. Save graphics in figure folder as png
# fig.height = 5. Height of figures (in inches)
# unlink("Output/JackKnifeResults", recursive = TRUE)
# dir.create("Output/JackKnifeResults")
knitr::opts_chunk$set(
echo = TRUE,
comment = "",
warning = FALSE,
message = FALSE,
cache = TRUE,
dev = "png", dpi = 300,
fig.height = 5
)
# tidyverse packages
library(tidyr)
library(dplyr)
library(ggplot2)
library(lubridate)
library(readr)
library(stringr) # for str_replace() function
# https://docs.stadiamaps.com/guides/migrating-from-stamen-map-tiles/#ggmap
# devtools::install_github("stadiamaps/ggmap”)
library(ggmap) # get_stamenmap() & ggmap
# register_stadiamaps("ff428357-71cc-4a08-8912-9111113265ec", write = TRUE)
# For map plotting
library(sf)
library(stars)
# devtools::install_github("ropensci/rnaturalearthhires")
library(rnaturalearthhires)
library(rnaturalearth)
library(rnaturalearthdata)
library(ggrepel) # geom_text_repel()
library(cowplot) # multiple plots for a figure
# model kriging
library(gstat)
rm(list = ls())
source("auxiliary.code.R")
ft <- function(input.data, caption = "", num.rows = Inf) {
ft <- input.data |>
slice_head(n = num.rows) |>
flextable() |>
autofit() |>
theme_zebra() |>
set_caption(caption)
ft
}
```
# Load in data
## Site and mean VCSN data and predicated sinusoidal parameters
```{r}
load("Output/Data/combine.vcsn.reg.RData")
glimpse(combine.vcsn.reg)
crs_projected_target <- "EPSG:2193"
combine.vcsn.reg.proj <- st_as_sf(combine.vcsn.reg,
coords = c("VCSN.lon", "VCSN.lat"),
remove = FALSE,
crs = 4326) |>
st_transform(crs = crs_projected_target)
```
## VCSN agent locations and CRS
```{r}
load("Output/Data/vcsn.agent.locations.RData")
glimpse(vcsn.agent.locations)
agent.CRS <- sf::st_crs(vcsn.agent.locations)
```
And a different version
```{r}
load("Output/Data/vcsn.agent.locations1.RData")
glimpse(vcsn.agent.locations1)
# used for left_join with resids in a few place latter on
vcsn.agent.locations1.subset <- vcsn.agent.locations1 |>
select(VCSN.Agent, vcsn.lon, vcsn.lat) |>
mutate(VCSN.Agent = as.character(VCSN.Agent))
```
## NZ grid in long format
```{r}
load("Output/Data/nzgrid.long.format.RData")
glimpse(nzgrid.long.format)
```
## d18O for Baisden and monthly mean value of VCSN data
```{r}
load("Output/Data/meanBaisden.RData")
glimpse(meanBaisden)
```
## Month checkdata
```{r}
load("Output/Data/monthly.checkdata.RData")
glimpse(monthly.checkdata)
```
## Julian days
```{r}
# Copied over from "03-isocape-monthly-residuals.Rmd" code
# collection on 15th of each month
julian.day.month.midpoints <- c(15, 46, 74, 105, 135, 166, 196, 227, 258, 288, 319, 349)
julian.days <- julian.day.month.midpoints / 365
julian.days
```
## Mean value climate data and predicted sinusoidal parameters
```{r}
# Mean value of climate data at an agent location, with appended columns for predicted value
# - output from 02-isoscape-kriging-sinusoidal-parameters.Rmd
# - load R object has name "national.climate.summary"
load(file = "Output/Data/national.climate.summary.02.output.RData")
dim(national.climate.summary)
names(national.climate.summary)
```
## Mean value vcsn data
```{r}
load(file = "Output/Data/vcsn.mean.RData")
dim(vcsn.mean)
names(vcsn.mean)
```
#Jackknife time
## Amplitude
In our research we are concerned about amplitudes of the seasonal precipitation isotope cycle because we wish to compare young water fractions in rivers across New Zealand. Many of our river measurement sites have no precipitation isotope records, so we wish to know which model predicts the seasonal amplitudes of new (unmeasured) sites best.
To examine amplitude prediction we will run a three jackknife analyses, one for each of our interpolation methods.
To do this we remove one of the 51 training sites at a time, and (having applied our modelling method using the other 50 sites) predict the amplitude at the omitted site. We then calculate the difference between measured and modelled amplitude at our omitted site. At the end of this loop we can calculate 'Rjack', a summary measure of residuals for each model.
### Jackknife test for uncorrected Allen model (stepwise reduced)
```{r}
amp.jack <- c()
for (i in 1:length(combine.vcsn.reg$Amplitude)) {
mod1 <- lm(Amplitude ~ VCSN.lon + height + AnnualTempRange, data = combine.vcsn.reg[-i, ])
new_value <- predict(mod1, newdata = combine.vcsn.reg[i, ])
amp.jack <- c(amp.jack, new_value)
}
rjack.allen <- lm(amp.jack ~ combine.vcsn.reg$Amplitude)
summary(rjack.allen)
```
### Jackknife test for uncorrected full VCSN model (stepwise reduced )
```{r}
amp.jack.lm <- c()
for (i in 1:length(combine.vcsn.reg$Amplitude)) {
mod1 <- lm(Amplitude ~ height + VCSN.lat + VCSN.lon + PET +
Rad + VP + Wind, data = combine.vcsn.reg[-i, ])
new_value <- predict(mod1, newdata = combine.vcsn.reg[i, ])
amp.jack.lm <- c(amp.jack.lm, new_value)
}
rjack.lm <- lm(amp.jack.lm ~ combine.vcsn.reg$Amplitude)
summary(rjack.lm)
```
### Jackknife test for universial kriging of amplitude using Rad and AnnualTempRange
```{r}
amp.jack.radkrig <- c()
for (i in 1:length(combine.vcsn.reg.proj$Amplitude)) {
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
v.trend2 <- gstat::variogram(Amplitude ~ Rad + AnnualTempRange, combine.vcsn.reg.proj[-i, ])
v.trend.model2 <- gstat::fit.variogram(v.trend2, vgm(model = "Exp"))
amp.loop.trend <- gstat::krige(
Amplitude ~ Rad + AnnualTempRange,
combine.vcsn.reg.proj[-i, ],
nzgrid.long.format,
v.trend.model2
)
amp.loop.trend.sf <- amp.loop.trend |>
sf::st_transform(crs = agent.CRS)
vcsn.agent.locations99 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations, amp.loop.trend.sf)
vcsn.agent.locations99$Amplitude <- amp.loop.trend.sf$var1.pred[kriging.row.index]
vcsn.agent.locations99 <- st_drop_geometry(vcsn.agent.locations99)
vcsn.agent.locations99$Agent <- as.character(vcsn.agent.locations99$Agent)
newframe <- dplyr::filter(vcsn.agent.locations99, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
amp.jack.radkrig <- c(amp.jack.radkrig, new_value)
print(paste0("finished ", i))
}
krigjack.lm <- lm(amp.jack.radkrig ~ combine.vcsn.reg$Amplitude)
summary(krigjack.lm)
```
### Jackknife test for universial kriging of amplitude using SoilM
```{r}
amp.jack.soilMkrig <- c()
for (i in 1:length(combine.vcsn.reg.proj$Amplitude)) {
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
v.trend3 <- gstat::variogram(Amplitude ~ SoilM, combine.vcsn.reg.proj[-i, ])
v.trend.model3 <- gstat::fit.variogram(v.trend3, vgm(model = "Exp"))
amp.loop.trend2 <- gstat::krige(
Amplitude ~ SoilM,
combine.vcsn.reg.proj[-i, ],
nzgrid.long.format,
v.trend.model3
)
amp.loop.trend.sf2 <- amp.loop.trend2 |>
sf::st_transform(crs = agent.CRS)
vcsn.agent.locations100 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations100, amp.loop.trend.sf2)
vcsn.agent.locations100$Amplitude <-
amp.loop.trend.sf2$var1.pred[kriging.row.index]
vcsn.agent.locations100 <- st_drop_geometry(vcsn.agent.locations100)
vcsn.agent.locations100$Agent <- as.character(vcsn.agent.locations100$Agent)
newframe <- dplyr::filter(vcsn.agent.locations100, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
amp.jack.soilMkrig <- c(amp.jack.soilMkrig, new_value)
print(paste0("finished ", i))
}
krigjack2.lm <- lm(amp.jack.soilMkrig ~ combine.vcsn.reg$Amplitude)
summary(krigjack2.lm)
```
### Jackknife test for a two step amplitude map: Allen model, plus ordinary kriging of residuals as a correction layer.
```{r}
# dummy vector
amp.jack.corrected <- c()
for (i in 1:length(combine.vcsn.reg.proj$Amplitude)) {
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
combine.vcsn.reg.proj.temp <- combine.vcsn.reg.proj[-i, ]
mod1 <- lm(Amplitude ~ VCSN.lon + height + AnnualTempRange,
data = combine.vcsn.reg.proj.temp)
combine.vcsn.reg.proj.temp$new_values <- predict(mod1, newdata = combine.vcsn.reg.proj.temp)
combine.vcsn.reg.proj.temp$lin.mod.resids <- combine.vcsn.reg.proj.temp$new_values - combine.vcsn.reg.proj.temp$Amplitude
v.constant <- gstat::variogram(lin.mod.resids ~ 1, combine.vcsn.reg.proj.temp)
v.constant.model <- gstat::fit.variogram(v.constant, vgm(model = "Exp"))
krig.constant <- gstat::krige(
lin.mod.resids ~ 1,
combine.vcsn.reg.proj.temp,
nzgrid.long.format,
v.constant.model
)
krig.constant.sf <- krig.constant |> sf::st_transform(crs = agent.CRS)
vcsn.agent.locations101 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations101, krig.constant.sf)
vcsn.agent.locations101$correction <- krig.constant.sf$var1.pred[kriging.row.index]
vcsn.agent.locations101 <- st_drop_geometry(vcsn.agent.locations101)
vcsn.agent.locations101$Agent <- as.character(vcsn.agent.locations101$Agent)
newframe <- dplyr::filter(vcsn.agent.locations101, Agent == vcsn.point)
correction_value <- as.numeric(newframe[4])
new_value <- predict(mod1, newdata = combine.vcsn.reg.proj[i, ])
corrected_new_value <- new_value - correction_value
amp.jack.corrected <- c(amp.jack.corrected, corrected_new_value)
print(paste0("finished ", i))
}
rjack.allen.corr <- lm(amp.jack.corrected ~ combine.vcsn.reg$Amplitude)
summary(rjack.allen.corr)
```
Plot the residuals from the last example of the cut-down model
```{r}
krig.constant.stars <- stars::st_as_stars(krig.constant)
plot.krig.constant <-
ggplot() +
geom_stars(data = krig.constant.stars, aes(fill = var1.pred, x = x, y = y)) +
geom_sf(data = combine.vcsn.reg.proj.temp) +
coord_sf(expand = FALSE) +
scale_fill_continuous(type = "viridis") +
labs(fill = "var1") +
xlab("Longitude") +
ylab("Latitude") +
ggtitle("linear model residuals: ordinary kriging interpolation")
plot.krig.constant
```
###Jackknife test for the two-step (ordinary-kriging-corrected) Full model.
```{r}
#dummy vector
amp.jack.full.corrected <- c()
for(i in 1:length(combine.vcsn.reg.proj$Amplitude)){
vcsn.site<-st_drop_geometry((combine.vcsn.reg.proj[i,19]))
vcsn.point<-as.character(vcsn.site[1,1])
combine.vcsn.reg.proj.temp<-combine.vcsn.reg.proj[-i,]
mod1 <- lm(Amplitude ~ height + VCSN.lat + VCSN.lon + PET +
Rad + VP + Wind, data = combine.vcsn.reg.proj.temp)
combine.vcsn.reg.proj.temp$new_values<-predict(mod1, newdata=combine.vcsn.reg.proj.temp)
combine.vcsn.reg.proj.temp$lin.mod.resids<-combine.vcsn.reg.proj.temp$new_values - combine.vcsn.reg.proj.temp$Amplitude
v.constant <- gstat::variogram(lin.mod.resids ~ 1, combine.vcsn.reg.proj.temp)
v.constant.model <- gstat::fit.variogram(v.constant, vgm(model = "Exp"))
krig.constant <- gstat::krige(lin.mod.resids ~ 1,
combine.vcsn.reg.proj.temp,
nzgrid.long.format,
v.constant.model)
krig.constant.sf <- krig.constant |> sf::st_transform(crs = agent.CRS)
vcsn.agent.locations101<-vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations101, krig.constant.sf)
vcsn.agent.locations101$correction <-
krig.constant.sf$var1.pred[kriging.row.index]
vcsn.agent.locations101<-st_drop_geometry(vcsn.agent.locations101)
vcsn.agent.locations101$Agent<-as.character(vcsn.agent.locations101$Agent)
newframe<-dplyr::filter(vcsn.agent.locations101, Agent == vcsn.point)
correction_value<-as.numeric(newframe[4])
new_value<-predict(mod1, newdata=combine.vcsn.reg.proj[i,])
corrected_new_value<-new_value - correction_value
amp.jack.full.corrected <- c(amp.jack.full.corrected, corrected_new_value)
print(paste0("finished ", i))
}
rjack.full.corr<-lm(amp.jack.full.corrected~combine.vcsn.reg$Amplitude)
summary(rjack.full.corr)
```
### Jackknife for regression kriging plus kriging of correction layer.
```{r}
#dummy vector
soilMkrig.corrected <- c()
#Loop to make universal kriging dataframe, pull out ith value, make residuals dataframe using other 50 sites, ordinary krig it, pull out correction for ith site and subtract it from the uncorrected value...then add it to the amplitude vector.
for (i in 1:length(combine.vcsn.reg.proj$Amplitude)) {
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
combine.vcsn.reg.proj.temp <- combine.vcsn.reg.proj[-i, c(1:20)]
# run the soilM universal kriging using n-1 sites
v.trend3 <- gstat::variogram(Amplitude ~ SoilM, combine.vcsn.reg.proj.temp)
v.trend.model3 <- gstat::fit.variogram(v.trend3, vgm(model = "Exp"))
amp.loop.trend2 <- gstat::krige(
Amplitude ~ SoilM,
combine.vcsn.reg.proj.temp,
nzgrid.long.format,
v.trend.model3
)
amp.loop.trend.sf2 <- amp.loop.trend2 |>
sf::st_transform(crs = agent.CRS)
# Attach the results to the VCSN grid
vcsn.agent.locations100 <- vcsn.agent.locations
vcsn.agent.locations100 <- vcsn.agent.locations100 |>
sf::st_as_sf(coords = c("vcsn.lon", "vcsn.lat"), crs = agent.CRS)
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations100, amp.loop.trend.sf2)
vcsn.agent.locations100$mod.amplitude <-
amp.loop.trend.sf2$var1.pred[kriging.row.index]
# Pull out the uncorrected value for the n-1 point
vcsn.agent.locations100 <- st_drop_geometry(vcsn.agent.locations100)
newframe <- dplyr::filter(vcsn.agent.locations100, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
# Then select the results from the grid to match the other 50 measurement sites
combine.vcsn.reg.proj.temp <- as.data.frame(st_drop_geometry(combine.vcsn.reg.proj.temp))
colnames(combine.vcsn.reg.proj.temp)[19] <- "Agent"
combine.vcsn.reg.proj.temp <- dplyr::inner_join(combine.vcsn.reg.proj.temp, vcsn.agent.locations100, by = "Agent")
# make residuals column
combine.vcsn.reg.proj.temp$krigM.resids <- combine.vcsn.reg.proj.temp$mod.amplitude - combine.vcsn.reg.proj.temp$Amplitude
## convert back to simple features object with projected crs
combine.vcsn.reg.proj.temp <- combine.vcsn.reg.proj.temp |>
sf::st_as_sf(coords = c("vcsn.lon", "vcsn.lat"), crs = crs_projected_target)
v.constant <- gstat::variogram(krigM.resids ~ 1, combine.vcsn.reg.proj.temp)
v.constant.model <- gstat::fit.variogram(v.constant, vgm(model = "Exp"))
krig.constant <- gstat::krige(
krigM.resids ~ 1,
combine.vcsn.reg.proj.temp,
nzgrid.long.format,
v.constant.model
)
krig.constant.sf <- krig.constant |>
sf::st_transform(crs = agent.CRS)
vcsn.agent.locations101 <- vcsn.agent.locations
vcsn.agent.locations101 <- vcsn.agent.locations101 |>
sf::st_as_sf(coords = c("vcsn.lon", "vcsn.lat"), crs = agent.CRS)
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations101, krig.constant.sf)
vcsn.agent.locations101$correction <-
krig.constant.sf$var1.pred[kriging.row.index]
# pull out correction values for ith site
vcsn.agent.locations101 <- st_drop_geometry(vcsn.agent.locations101)
vcsn.agent.locations101$Agent <- as.character(vcsn.agent.locations101$Agent)
newframe1 <- dplyr::filter(vcsn.agent.locations101, Agent == vcsn.point)
correction_value <- as.numeric(newframe1[4])
# get corrected value and add to vector
corrected_new_value <- new_value - correction_value
soilMkrig.corrected <- c(soilMkrig.corrected, new_value)
print(paste0("finished ", i))
}
soilMkrig.corr <- lm(soilMkrig.corrected ~ combine.vcsn.reg$Amplitude)
summary(rjack.full.corr)
```
##Offset
We can use LOOCV to test linear model performance, and we are not interested in offset as an 'output', so here we will only use the jackknife loops to test a few different options for universal kriging. First the model selected from the regression trees
###Full regression tree model - universal kriging
```{r}
jack.offset <- c()
for (i in 1:length(combine.vcsn.reg.proj$offset)) {
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
v.trend3 <- gstat::variogram(offset ~ VP + AnnualTempRange + ETmp + SoilM, combine.vcsn.reg.proj[-i, ])
v.trend.model3 <- gstat::fit.variogram(v.trend3, vgm(model = "Exp"))
amp.loop.trend2 <- gstat::krige(
offset ~ VP + AnnualTempRange + ETmp + SoilM,
combine.vcsn.reg.proj[-i, ],
nzgrid.long.format,
v.trend.model3
)
amp.loop.trend.sf2 <- amp.loop.trend2 |>
sf::st_transform(crs = agent.CRS)
vcsn.agent.locations100 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations100, amp.loop.trend.sf2)
vcsn.agent.locations100$offset <-
amp.loop.trend.sf2$var1.pred[kriging.row.index]
vcsn.agent.locations100 <- st_drop_geometry(vcsn.agent.locations100)
vcsn.agent.locations100$Agent <- as.character(vcsn.agent.locations100$Agent)
newframe <- dplyr::filter(vcsn.agent.locations100, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
jack.offset <- c(jack.offset, new_value)
print(paste0("finished ", i))
}
krigjackoffset.lm <- lm(jack.offset ~ combine.vcsn.reg$offset)
summary(krigjackoffset.lm)
```
### Reduced regression tree model - universal kriging
```{r}
jack.offset.small <- c()
for (i in 1:length(combine.vcsn.reg.proj$offset)) {
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
v.trend3 <- gstat::variogram(offset ~ SoilM, combine.vcsn.reg.proj[-i, ])
v.trend.model3 <- gstat::fit.variogram(v.trend3, vgm(model = "Exp"))
amp.loop.trend2 <- gstat::krige(
offset ~ SoilM,
combine.vcsn.reg.proj[-i, ],
nzgrid.long.format,
v.trend.model3
)
amp.loop.trend.sf2 <- amp.loop.trend2 |> sf::st_transform(crs = agent.CRS)
vcsn.agent.locations100 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations100, amp.loop.trend.sf2)
vcsn.agent.locations100$offset <- amp.loop.trend.sf2$var1.pred[kriging.row.index]
vcsn.agent.locations100 <- st_drop_geometry(vcsn.agent.locations100)
vcsn.agent.locations100$Agent <- as.character(vcsn.agent.locations100$Agent)
newframe <- dplyr::filter(vcsn.agent.locations100, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
jack.offset.small <- c(jack.offset.small, new_value)
print(paste0("finished ", i))
}
krigjackoffsmall.lm <- lm(jack.offset.small ~ combine.vcsn.reg$offset)
summary(krigjackoffsmall.lm)
```
# Jackknife tests for monthly isotope predictions
We have six models to compare. Each of these models generates monthly isotope predictions at VCSN sites. We test them against mean monthly isotope values from the Frew/Baisden dataset.
The mean isotope values for each site are in the data frame 'meanBaisden'
```{r}
head(meanBaisden)
```
The six models are:
- The Allen linear model without and then with ordinary kriging correction on monthly outputs
- The 'full' VCSN parameter linear model without and then with ordinary kriging correction on monthly outputs
- The regression kriging (universal kriging) model without and with ordinary kriging correction on monthly outputs.
In this last case it seems that the second kriging step is redundant, and makes
the results worse, so probably won't be included in the final summary.
##Uncorrected Allen model
Using the predictors selected by Allen et al. (2018) applied to the Frew dataset, The amplitude, phase and offset models selected using StepAIC and LOOCV follow the form:
Amplitude: Amplitude ~ VCSN.lon + height + AnnualTempRange
Phase: phase ~ VCSN.lat + VCSN.lon
Offset: VCSN.lat + VCSN.lon + height + Rain_bc + AnnualTempRange
```{r}
amp.jack <- c()
phase.jack <- c()
offset.jack <- c()
for (i in 1:length(combine.vcsn.reg$Amplitude)) {
mod1.amp <- lm(Amplitude ~ VCSN.lon + height + AnnualTempRange, data = combine.vcsn.reg[-i, ])
new_amp_value <- predict(mod1.amp, newdata = combine.vcsn.reg[i, ])
amp.jack <- c(amp.jack, new_amp_value)
mod1.phase <- lm(phase ~ VCSN.lat + VCSN.lon, data = combine.vcsn.reg[-i, ])
new_phase_value <- predict(mod1.phase, newdata = combine.vcsn.reg[i, ])
phase.jack <- c(phase.jack, new_phase_value)
mod1.offset <- lm(offset ~ VCSN.lat + VCSN.lon, data = combine.vcsn.reg[-i, ])
new_offset_value <- predict(mod1.offset, newdata = combine.vcsn.reg[i, ])
offset.jack <- c(offset.jack, new_offset_value)
}
VCSN.Agent <- combine.vcsn.reg$VCSN.Agent
dummy_df <- data.frame(amp.jack, phase.jack, offset.jack, VCSN.Agent)
calc_precip_isotope <- function(julian.fraction) {
dummy_df$amp.jack * (sin((2 * pi * julian.fraction) - dummy_df$phase.jack)) + dummy_df$offset.jack
}
for (i in julian.days) {
new <- calc_precip_isotope(i) # Create new column of d18O predictions
dummy_df[, ncol(dummy_df) + 1] <- new # Append new column
colnames(dummy_df)[ncol(dummy_df)] <- paste0("new", i) # Rename column name
}
names(dummy_df) <- c("amplitude", "phase", "offset", "VCSN.Agent", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")
dummy_df.long <- dummy_df |> gather(month, d18O, as.character(1:12), factor_key = TRUE)
dummy_df.long$VCSN.Agent <- as.character(dummy_df.long$VCSN.Agent)
dummy_df.long$month <- as.character(dummy_df.long$month)
monthly.checkdata$VCSN.Agent <- as.character(monthly.checkdata$VCSN.Agent)
monthly.checkdata$month <- as.character(monthly.checkdata$month)
dummy_df.long <- dummy_df.long[, 4:6]
names(dummy_df.long) <- c("VCSN.Agent", "month", "d18O.Allen.jack")
head(dummy_df.long)
tail(dummy_df.long)
jacked.data <- dplyr::inner_join(monthly.checkdata, dummy_df.long,
by = c("VCSN.Agent" = "VCSN.Agent", "month" = "month")
)
plot(jacked.data$meas.18O.mean ~ jacked.data$d18O.Allen.jack)
allen.jack.check <- lm(formula = jacked.data$meas.18O.mean ~ jacked.data$d18O.Allen.jack)
summary(allen.jack.check)
write.csv(jacked.data, "Output/JackKnifeResults/Allen model jackknife results.csv")
```
##Uncorrected 'full' model
Model structure selected using StepAIC and LOOCV from the full range of VCSN parameters, plus lat, long, annual temperature range and elevation. Again, predictor selections were tested using the Frew dataset. The amplitude, phase and offset models follow the form:
Amplitude:Amplitude ~ height + VCSN.lat + VCSN.lon + PET +
Rad + VP + Wind(A.mod1.step)
Phase:phase ~ height + island + VCSN.lat + VCSN.lon + VCSN.lat:VCSN.lon +
MSLP + Rad + SoilM +
VP + Wind + AnnualTempRange
Offset:offset ~ height +
island +
VCSN.lon +
ETmp + MSLP +
Rain_bc +
RH +
VP + AnnualTempRange
```{r}
amp.jack <- c()
phase.jack <- c()
offset.jack <- c()
for (i in 1:length(combine.vcsn.reg$Amplitude)) {
mod1.amp <- lm(Amplitude ~ height + VCSN.lat + VCSN.lon + PET +
Rad + VP + Wind, data = combine.vcsn.reg[-i, ])
new_amp_value <- predict(mod1.amp, newdata = combine.vcsn.reg[i, ])
amp.jack <- c(amp.jack, new_amp_value)
mod1.phase <- lm(phase ~ height + island + VCSN.lat + VCSN.lon + VCSN.lat:VCSN.lon +
MSLP + Rad + SoilM +
VP + Wind + AnnualTempRange, data = combine.vcsn.reg[-i, ])
new_phase_value <- predict(mod1.phase, newdata = combine.vcsn.reg[i, ])
phase.jack <- c(phase.jack, new_phase_value)
mod1.offset <- lm(offset ~ height +
island +
VCSN.lon +
ETmp + MSLP +
Rain_bc +
RH +
VP + AnnualTempRange, data = combine.vcsn.reg[-i, ])
new_offset_value <- predict(mod1.offset, newdata = combine.vcsn.reg[i, ])
offset.jack <- c(offset.jack, new_offset_value)
}
VCSN.Agent <- combine.vcsn.reg$VCSN.Agent
dummy_df <- data.frame(amp.jack, phase.jack, offset.jack, VCSN.Agent)
calc_precip_isotope <- function(julian.fraction) {
dummy_df$amp.jack * (sin((2 * pi * julian.fraction) - dummy_df$phase.jack)) + dummy_df$offset.jack
}
for (i in julian.days) {
new <- calc_precip_isotope(i) # Create new column of d18O predictions
dummy_df[, ncol(dummy_df) + 1] <- new # Append new column
colnames(dummy_df)[ncol(dummy_df)] <- paste0("new", i) # Rename column name
}
names(dummy_df) <- c("amplitude", "phase", "offset", "VCSN.Agent", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")
dummy_df.long <- dummy_df |> gather(month, d18O, as.character(1:12), factor_key = TRUE)
dummy_df.long$VCSN.Agent <- as.character(dummy_df.long$VCSN.Agent)
dummy_df.long$month <- as.character(dummy_df.long$month)
monthly.checkdata$VCSN.Agent <- as.character(monthly.checkdata$VCSN.Agent)
monthly.checkdata$month <- as.character(monthly.checkdata$month)
dummy_df.long <- dummy_df.long[, 4:6]
names(dummy_df.long) <- c("VCSN.Agent", "month", "d18O.Full.jack")
head(dummy_df.long)
tail(dummy_df.long)
jacked.data <- dplyr::inner_join(monthly.checkdata, dummy_df.long, by = c("VCSN.Agent" = "VCSN.Agent", "month" = "month"))
plot(jacked.data$meas.18O.mean ~ jacked.data$d18O.Full.jack)
full.jack.check <- lm(formula = jacked.data$meas.18O.mean ~ jacked.data$d18O.Full.jack)
summary(full.jack.check)
write.csv(jacked.data, "Output/JackKnifeResults/Full linear model jackknife results.csv")
```
## Uncorrected 'universal kriging' model
Parameters in the regression parts of these kriging predictions were selected using regression trees from the full range of VCSN parameters, plus lat, long, annual temperature range and elevation. Some models were tested using performance in predicting fitted parameters (in jackknife tests) as above. Again, all model selections were tested using the Frew dataset. The amplitude, phase and offset models follow the form:
Amplitude: <- gstat::variogram(Amplitude ~ SoilM, combine.vcsn.reg.proj)
Phase: <- gstat::variogram(phase ~ VP + height
Offset: <- gstat::variogram(offset ~ VP + AnnualTempRange + ETmp + SoilM
```{r}
amp.jack <- c()
phase.jack <- c()
offset.jack <- c()
# amplitude
for (i in 1:length(combine.vcsn.reg.proj$Amplitude)) {
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
v.trend3 <- gstat::variogram(Amplitude ~ SoilM, combine.vcsn.reg.proj[-i, ])
v.trend.model3 <- gstat::fit.variogram(v.trend3, vgm(model = "Exp"))
amp.loop.trend2 <- gstat::krige(
Amplitude ~ SoilM,
combine.vcsn.reg.proj[-i, ],
nzgrid.long.format,
v.trend.model3
)
amp.loop.trend.sf2 <- amp.loop.trend2 |>
sf::st_transform(crs = agent.CRS)
vcsn.agent.locations100 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations100, amp.loop.trend.sf2)
vcsn.agent.locations100$Amplitude <-
amp.loop.trend.sf2$var1.pred[kriging.row.index]
vcsn.agent.locations100 <- st_drop_geometry(vcsn.agent.locations100)
vcsn.agent.locations100$Agent <- as.character(vcsn.agent.locations100$Agent)
newframe <- dplyr::filter(vcsn.agent.locations100, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
amp.jack <- c(amp.jack, new_value)
# phase
v.trend3 <- gstat::variogram(phase ~ VP + height, combine.vcsn.reg.proj[-i, ])
v.trend.model3 <- gstat::fit.variogram(v.trend3, vgm(model = "Exp"))
amp.loop.trend2 <- gstat::krige(
phase ~ VP + height,
combine.vcsn.reg.proj[-i, ],
nzgrid.long.format,
v.trend.model3
)
amp.loop.trend.sf2 <- amp.loop.trend2 |>
sf::st_transform(crs = agent.CRS)
vcsn.agent.locations100 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations100, amp.loop.trend.sf2)
vcsn.agent.locations100$offset <-
amp.loop.trend.sf2$var1.pred[kriging.row.index]
vcsn.agent.locations100 <- st_drop_geometry(vcsn.agent.locations100)
vcsn.agent.locations100$Agent <- as.character(vcsn.agent.locations100$Agent)
newframe <- dplyr::filter(vcsn.agent.locations100, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
phase.jack <- c(phase.jack, new_value)
# offset
v.trend3 <- gstat::variogram(offset ~ VP + AnnualTempRange + ETmp + SoilM, combine.vcsn.reg.proj[-i, ])
v.trend.model3 <- gstat::fit.variogram(v.trend3, vgm(model = "Exp"))
amp.loop.trend2 <- gstat::krige(
offset ~ VP + AnnualTempRange + ETmp + SoilM,
combine.vcsn.reg.proj[-i, ],
nzgrid.long.format,
v.trend.model3
)
amp.loop.trend.sf2 <- amp.loop.trend2 |>
sf::st_transform(crs = agent.CRS)
vcsn.agent.locations100 <- vcsn.agent.locations
kriging.row.index <- sf::st_nearest_feature(vcsn.agent.locations100, amp.loop.trend.sf2)
vcsn.agent.locations100$offset <-
amp.loop.trend.sf2$var1.pred[kriging.row.index]
vcsn.agent.locations100 <- st_drop_geometry(vcsn.agent.locations100)
vcsn.agent.locations100$Agent <- as.character(vcsn.agent.locations100$Agent)
newframe <- dplyr::filter(vcsn.agent.locations100, Agent == vcsn.point)
new_value <- as.numeric(newframe[4])
offset.jack <- c(offset.jack, new_value)
print(paste0("finished ", i))
} # end of loop over sites
VCSN.Agent <- combine.vcsn.reg$VCSN.Agent
dummy_df <- data.frame(amp.jack, phase.jack, offset.jack, VCSN.Agent)
calc_precip_isotope <- function(julian.fraction) {
dummy_df$amp.jack * (sin((2 * pi * julian.fraction) - dummy_df$phase.jack)) + dummy_df$offset.jack
}
for (i in julian.days) {
new <- calc_precip_isotope(i) # Create new column of d18O predictions
dummy_df[, ncol(dummy_df) + 1] <- new # Append new column
colnames(dummy_df)[ncol(dummy_df)] <- paste0("new", i) # Rename column name
}
names(dummy_df) <- c("amplitude", "phase", "offset", "VCSN.Agent", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")
dummy_df.long <- dummy_df |> gather(month, d18O, as.character(1:12), factor_key = TRUE)
dummy_df.long$VCSN.Agent <- as.character(dummy_df.long$VCSN.Agent)
dummy_df.long$month <- as.character(dummy_df.long$month)
monthly.checkdata$VCSN.Agent <- as.character(monthly.checkdata$VCSN.Agent)
monthly.checkdata$month <- as.character(monthly.checkdata$month)
dummy_df.long <- dummy_df.long[, 4:6]
names(dummy_df.long) <- c("VCSN.Agent", "month", "d18O.Full.jack")
head(dummy_df.long)
tail(dummy_df.long)
jacked.data <- dplyr::inner_join(monthly.checkdata, dummy_df.long, by = c("VCSN.Agent" = "VCSN.Agent", "month" = "month"))
plot(jacked.data$meas.18O.mean ~ jacked.data$d18O.Full.jack)
krig.jack.check <- lm(formula = jacked.data$meas.18O.mean ~ jacked.data$d18O.Full.jack)
summary(krig.jack.check)
write.csv(jacked.data, "Output/JackKnifeResults/Full universal kriging model jackknife results.csv")
```
## Corrected Allen model
This requires the basic linear model, and a correction for each month of the year.
```{r}
acdf <- c(1:12)
dummy_mat <- matrix(acdf, ncol = 1)
Allen.corr.df <- as.data.frame(dummy_mat)
calc_precip_isotope <- function(julian.fraction) {
dummy_df$amp.jack * (sin((2 * pi * julian.fraction) - dummy_df$phase.jack)) + dummy_df$offset.jack
}
for (i in 1:length(combine.vcsn.reg$Amplitude)) {
# point we're pulling out at the end of each loop
vcsn.site <- st_drop_geometry((combine.vcsn.reg.proj[i, 19]))
vcsn.point <- as.character(vcsn.site[1, 1])
# All VCSN points without climate data
vcsn.agent.locations_dummy <- vcsn.agent.locations
# all vcsn locations and climate data
national.climate.summary_dummy <- national.climate.summary[, 1:15]
# dataframe of measurement sites and their climate data except the n-1 site
test.dataframe <- combine.vcsn.reg[-i, 1:20]
# vector of unique vcsn numbers in the n-1 dataframe
vcsn.vector <- unique(test.dataframe$VCSN.Agent)
# begin modelling
mod1.amp <- lm(Amplitude ~ VCSN.lon + height + AnnualTempRange, data = test.dataframe)
amp.jack <- predict(mod1.amp, newdata = national.climate.summary_dummy)
mod1.phase <- lm(phase ~ VCSN.lat + VCSN.lon, data = test.dataframe)
phase.jack <- predict(mod1.phase, newdata = national.climate.summary_dummy)
mod1.offset <- lm(offset ~ VCSN.lat + VCSN.lon, data = test.dataframe)
offset.jack <- predict(mod1.offset, newdata = national.climate.summary_dummy)
VCSN.Agent <- national.climate.summary_dummy$VCSN.Agent
dummy_df <- data.frame(amp.jack, phase.jack, offset.jack, VCSN.Agent)
for (j in julian.days) {
new <- calc_precip_isotope(j) # Create new column of d18O predictions
dummy_df[, ncol(dummy_df) + 1] <- new # Append new column
colnames(dummy_df)[ncol(dummy_df)] <- paste0("new", j) # Rename column name
}
names(dummy_df) <- c("amplitude", "phase", "offset", "VCSN.Agent", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")
dummy_df.long <- dummy_df |> gather(month, d18O, as.character(1:12), factor_key = TRUE)
dummy_df.long$VCSN.Agent <- as.character(dummy_df.long$VCSN.Agent)
dummy_df.long$month <- as.character(dummy_df.long$month)
monthly.checkdata1 <- dplyr::filter(monthly.checkdata, VCSN.Agent %in% vcsn.vector)
monthly.checkdata1$VCSN.Agent <- as.character(monthly.checkdata1$VCSN.Agent)
monthly.checkdata1$month <- as.character(monthly.checkdata1$month)
dummy_df.long <- dummy_df.long[, 4:6]
names(dummy_df.long) <- c("VCSN.Agent", "month", "d18O.Allen.jack")
head(dummy_df.long)
tail(dummy_df.long)
jacked.data <- dplyr::inner_join(monthly.checkdata1,
dummy_df.long,
by = c("VCSN.Agent" = "VCSN.Agent", "month" = "month"))
jacked.data$Allen.resid <- jacked.data$d18O.Allen.jack - jacked.data$meas.18O.mean
resids.frame <- jacked.data
resids.frame <- left_join(resids.frame,
vcsn.agent.locations1.subset,
by = c("VCSN.Agent" = "VCSN.Agent"))
vcsn.mean$Agent <- as.character(vcsn.mean$Agent)