-
Notifications
You must be signed in to change notification settings - Fork 0
/
enms_for_fraxinus_pennsylvanica.r
2466 lines (1784 loc) · 96.9 KB
/
enms_for_fraxinus_pennsylvanica.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
### modeling green ash
### Adam B. Smith | [email protected] | Missouri Botanical Garden | Spring 2019
###
### INTRODUCTION
### The goal of this project is to generate a "bank" of ~10 ENMs for Green Ash (*Fraxinus pennsylvanica*) for use in TIMBER. The models will be projected back in time to ~21 Kypb.
###
### We will define models based on combinations of:
###
### * Occurrence set (broad, narrow)
### * SDM algorithm (Maxent, GLM)
### * Global circulation model (ECBilt, CCSM)
###
### for a total of 2 * 2 * 2 = 8 models. This script draws on several data sources that are not downloaded or generated in the script:
### * Paleo and current climate data from Lorenz et al 2016 Scientific Data
### * Little's range map of Fraxinus pennsylvanica
###
### CONTENTS
### setup ###
### constants ###
### obtain and process basemap data ###
### obtain and clean occurrences ###
### define calibration regions ###
### select climate variables ###
### collate calibration/evaluation data ###
### calibrate models ###
### calibrate and evaluate final models ###
### plot model performance against present-day data ###
### assess differences between model output ###
### project models back in time ###
### determine thresholds that best recreate Little range ###
### make maps of unthresholded predictions ###
### make maps of thresholded predictions ###
### collage ENMs for demographic simulations ###
### calculate biotic velocity ###
### plot biotic velocity for periods < 21 Ka ###
### plot biotic velocity for periods of 21 Ka ###
### NOTES
### Variable naming conventions:
### * objects that are spatial (ie polygons/points) will be suffixed with "Sp" as in "speciesRecordsSp"
### * spatial objects that are in an equal-area projection will be further suffixed with "Alb" as in "speciesRecordsSpAlb"
#############
### setup ###
#############
memory.limit(memory.limit() * 2^30)
rm(list=ls()) # reproducibility!
options(keep.source=FALSE) # manage memory
gc()
print('')
print(date())
# ### setup to run on Adam's computer
# ### source('C:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/enms/code/enms_for_fraxinus_pennsylvanica.r')
# setwd('C:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/enms')
# lorenzPath <- 'D:/Ecology/Climate/Lorenz et al 2016 North America 21Kybp to 2100 CE/Version 2017-06-16/'
# studyRegionRastsFileName <- 'C:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/!study_region_raster_masks/study_region_daltonIceMask_lakesMasked_linearIceSheetInterpolation.tif'
# elevationRastFileName <- 'D:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/!study_region_raster_masks/study_region_elevationInMeters_fromEtop.tif'
# tempDir <- 'D:/ecology/!Scratch/_temp'
### setup to run on SHIGOTO computer
### source('E:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/enms/code/enms_for_fraxinus_pennsylvanica.r')
setwd('E:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/enms')
lorenzPath <- 'E:/Ecology/Climate/Lorenz et al 2016 North America 21Kybp to 2100 CE/Version 2017-06-16/'
studyRegionRastsFileName <- 'E:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/!study_region_raster_masks/study_region_daltonIceMask_lakesMasked_linearIceSheetInterpolation.tif'
demoGeneticRasterTemplate <- 'E:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/!study_region_raster_masks/study_region_resampled_to_genetic_demographic_simulation_resolution.tif'
elevationRastFileName <- 'E:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/!study_region_raster_masks/study_region_elevationInMeters_fromEtop.tif'
tempDir <- 'E:/ecology/!Scratch/_temp'
# ### setup to run on POWERBANK
# ### source('H:/Global Change Program/Research/ABC for Biogeographic History of Trees/code/enms_for_fraxinus_pennsylvanica.r')
# setwd('H:/Global Change Program/Research/ABC for Biogeographic History of Trees')
# lorenzPath <- './!lorenz_et_al/Version 2017-06-16/'
# studyRegionRastsFileName <- './!study_region_raster_masks/study_region_daltonIceMask_lakesMasked_linearIceSheetInterpolation.tif' # for POWERBANK computers
# elevationRastFileName <- 'H:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/!study_region_raster_masks/study_region_elevationInMeters_fromEtop.tif'
# tempDir <- 'E:/ecology/!Scratch/_temp'
options(stringsAsFactors=FALSE)
raster::rasterOptions(format='GTiff', overwrite=TRUE)
library(BIEN)
library(brglm2)
library(cluster)
library(dismo)
library(geosphere)
library(holoSimCell)
library(rgdal)
library(raster)
library(RColorBrewer)
library(rgeos)
library(rJava)
library(scales)
library(sp)
library(omnibus) # Adam's grab-bag library (https://github.com/adamlilith/omnibus)
library(enmSdm) # Adam's SDM library (https://github.com/adamlilith/enmSdm)
library(statisfactory) # Adam's statistics library (https://github.com/adamlilith/statisfactory)
library(legendary) # Adam's plotting library (https://github.com/adamlilith/legenday)
# source('./code/assign_refugia_from_abundance_raster.r')
dirCreate(tempDir)
dirCreate('./figures_and_tables')
dirCreate('./species_records')
dirCreate('./regions')
dirCreate('./environmental_rasters')
dirCreate('./environmental_rasters/lorenz_et_al_2016')
dirCreate('./models')
dirCreate('./predictions')
### return stack of climate rasters for North America from Lorenz et al. 2016 Scientific Reports data set
#########################################################################################################
# note that these are assumed to live in a folder outside the folder for green ash
getClimRasts <- function(gcm, year, variables, rescale = TRUE, fillCoasts = FALSE) {
# gcm 'ccsm' or 'ecbilt'
# year year BP (from 0 to 21000 for ccsm or 22000 for ecbilt)
# variables names of variables
# rescale TRUE ==> rescale rasters to [0, 1] using present-day values for min/max
# fillCoasts FALSE ==> use rasters as-is; TRUE ==> extrapolate to NA cells immediately adjacent to non-NA cells (typically coastal cells)
gcmFolder <- if (gcm == 'ccsm') {
'ccsm3_22-0k_all_tifs'
} else if (gcm == 'ecbilt') {
'ecbilt_21-0k_all_tifs'
}
# get current version of each variable
for (variable in variables) {
rast <- stack(paste0(lorenzPath, '/', gcmFolder, '/', year, 'BP/', variable, '.tif'))
names(rast) <- variable
rasts <- if (exists('rasts', inherits=FALSE)) {
stack(rasts, rast)
} else {
rast
}
}
# rescale
if (rescale) {
# not present... rescale by present-day values
if (year != 0 | file.exists ('./environmental_rasters/lorenz_et_al_2016/variable_statistics_0bp_across_north_america.csv')) {
variableStats <- read.csv('./environmental_rasters/lorenz_et_al_2016/variable_statistics_0bp_across_north_america.csv')
for (variable in variables) {
minVal <- variableStats$min[variableStats$gcm == gcm & variableStats$variable == variable]
maxVal <- variableStats$max[variableStats$gcm == gcm & variableStats$variable == variable]
rasts[[variable]] <- (rasts[[variable]] - minVal) / (maxVal - minVal)
}
# present-day... just rescale to [0, 1]
} else {
for (i in 1:nlayers(rasts)) rasts[[i]] <- stretch(rasts[[i]], 0, 1)
}
}
if (fillCoasts) {
name <- names(rasts)
# fill NA cells near coasts to account for fact that some records may not fall in a cell near a coast
for (i in 1:nlayers(rasts)) {
rasts[[i]] <- focal(rasts[[i]], w=matrix(1, nrow=3, ncol=3), fun=mean, na.rm=TRUE, NAonly=TRUE)
}
names(rasts) <- name
}
names(rasts) <- paste0(gcm, '_', variables)
rasts
}
#################
### constants ###
#################
set.seed(pi)
# species name
species <- 'Fraxinus pennsylvanica'
# buffer around occurrences ("accessible" area) used to define calibration area
exts <- c(80, 160, 320) # in km
# generation time
genTime_yr <- 30 # generation time in year
genTimes <- seq(0, 21000, by=genTime_yr)
# maximum pairwise correlation allowable between variables
maxCor <- 0.7
# longitude/latitude field names
ll <- c('longitude', 'latitude')
# minimum number of occurrences in a k-fold
minFoldSize <- 200
# buffer around each training/test fold to be excluded (in meters)
foldBuffer_m <- 8 * 40 * 1000
# GCMs
gcms <- c('ccsm', 'ecbilt')
# SDM algorithms
algos <- c('brt', 'glm', 'maxent', 'ns')
# desired number of final model clusters... used to simplify output
numModelClusts <- 8
# colors for clusters... only the first "numModelClusts" will be used
clustCols <- c('#a6cee3','#1f78b4','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928', '#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462','#b3de69','#fccde5','#d9d9d9','#bc80bd','#ccebc5','#ffed6f')
# decided in "### process current/paleoclimate layers ###"
if (file.exists('./figures_and_tables/predictors.rda')) load('./figures_and_tables/predictors.rda')
# study region polygon
if (file.exists('./regions/studyRegion.rda')) load('./regions/studyRegion.rda')
# mask raster for present-day land (1 = land, NA = not)
if (file.exists('./regions/maskRaster.tif')) {
maskRast <- raster('./regions/maskRaster.tif')
} else {
# mask raster for entire projection region
maskRast <- raster('D:/Ecology/Climate/Lorenz et al 2016 North America 21Kybp to 2100 CE/ccsm3_22-0k_all_tifs/0BP/an_avg_ETR.tif')
maskRast <- 0 * maskRast + 1
names(maskRast) <- 'mask'
writeRaster(maskRast, './regions/maskRaster', datatype='INT2U')
}
maskRastAlb <- projectRaster(maskRast, crs=getCRS('albersNA'))
# states that are undersampled for Fraxinus pennsylvanica species in BIEN 4.1
undersampled <- c('Louisiana', 'Kentucky')
# calibration regions
if (file.exists('./regions/calibration_regions.rda')) load('./regions/calibration_regions.rda')
if (file.exists('./regions/studyRegion_croppedToPresentLand.rda')) load('./regions/studyRegion_croppedToPresentLand.rda')
# North America spatial polygons
if (file.exists('./regions/greatLakesSpAlb.rda')) load('./regions/greatLakesSpAlb.rda')
if (file.exists('./regions/gadm36_northAmerica_sp_level_0.rda')) load('./regions/gadm36_northAmerica_sp_level_0.rda')
if (file.exists('./regions/gadm36_northAmerica_spAlb_level_0.rda')) load('./regions/gadm36_northAmerica_spAlb_level_0.rda')
if (file.exists('./regions/gadm36_northAmerica_sp_level_1.rda')) load('./regions/gadm36_northAmerica_sp_level_1.rda')
if (file.exists('./regions/gadm36_northAmerica_spAlb_level_1.rda')) load('./regions/gadm36_northAmerica_spAlb_level_1.rda')
if (file.exists('./regions/gadm36_northAmerica_spAlb_continental.rda')) load('./regions/gadm36_northAmerica_spAlb_continental.rda')
if (file.exists('./regions/gadm36_northAmerica_spAlb_continental_cropToStudyRegion.rda')) load('./regions/gadm36_northAmerica_spAlb_continental_cropToStudyRegion.rda')
# range maps
if (file.exists('./regions/bien_range_map/Fraxinus_pennsylvanica.shp')) {
bienRange <- shapefile('./regions/bien_range_map/Fraxinus_pennsylvanica.shp')
bienRangeAlb <- sp::spTransform(bienRange, getCRS('albersNA', TRUE))
}
if (file.exists('./regions/little_range_map/littleRangeSpAlb.rda')) load('./regions/little_range_map/littleRangeSpAlb.rda')
# say('#######################################', pre=1)
# say('### obtain and process basemap data ###')
# say('#######################################', post=2)
# say('Basemap data includes shapefiles of North American countries and the range maps of the species from BIEN and Little. We will create equal-area versions of each in an Albers projection (object names will be suffixed with "Alb")', breaks=80)
# # study region
# if (!file.exists('./regions/studyRegion.rda')) {
# studyRegionSpAlb <- shapefile('C:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/study_region_spatial_polygons/study_region_mask_without_glaciers')
# save(studyRegionSpAlb, file='./regions/studyRegion.rda')
# }
# ### North America Level 2
# mex <- getData('GADM', country='MEX', level=2, path='D:/ecology/!Scratch')
# usa <- getData('GADM', country='USA', level=2, path='D:/ecology/!Scratch')
# can <- getData('GADM', country='CAN', level=2, path='D:/ecology/!Scratch')
# nam2Sp <- rbind(can, usa, mex)
# # get lakes for removal from other geographies... add small buffer because lake borders don't exactly align
# greatLakesSp2 <- nam2Sp[nam2Sp$ENGTYPE_2 == 'Water body', ]
# greatLakesSpAlb2 <- sp::spTransform(greatLakesSp2, getCRS('albersNA', TRUE))
# greatLakesSpAlb2 <- gBuffer(greatLakesSpAlb2, width=10)
# greatLakesSp2 <- sp::spTransform(greatLakesSpAlb2, getCRS('wgs84', TRUE))
# greatLakesSp <- gUnaryUnion(greatLakesSp2)
# greatLakesSpAlb <- sp::spTransform(greatLakesSp2, getCRS('albersNA', TRUE))
# # names of level 1 areas with lakes
# lakeNames0 <- unique(nam2Sp@data$NAME_0[nam2Sp@data$ENGTYPE_2 == 'Water body'])
# lakeNames1 <- unique(nam2Sp@data$NAME_1[nam2Sp@data$ENGTYPE_2 == 'Water body'])
# # remove lakes
# nam2Sp <- nam2Sp[nam2Sp@data$ENGTYPE_2 != 'Water body', ]
# # not saving because only need for identifying lake areas
# save(greatLakesSpAlb, file='./regions/greatLakesSpAlb.rda')
# ### North America Level 1
# mex <- getData('GADM', country='MEX', level=1, path='D:/ecology/!Scratch')
# usa <- getData('GADM', country='USA', level=1, path='D:/ecology/!Scratch')
# can <- getData('GADM', country='CAN', level=1, path='D:/ecology/!Scratch')
# nam1Sp <- rbind(can, usa, mex)
# for (thisLevel in lakeNames1) {
# thisLargerSp <- nam1Sp[nam1Sp@data$NAME_1 == thisLevel, ]
# df <- thisLargerSp@data
# nam1Sp <- nam1Sp[-which(nam1Sp@data$NAME_1 == thisLevel), ]
# thisLargerSansLakesSp <- gDifference(thisLargerSp, greatLakesSp)
# thisLargerSansLakesSp <- as(thisLargerSansLakesSp, 'SpatialPolygonsDataFrame')
# projection(thisLargerSansLakesSp) <- projection(nam1Sp)
# thisLargerSansLakesSp@data <- df
# nam1Sp <- rbind(nam1Sp, thisLargerSansLakesSp)
# }
# nam1SpAlb <- sp::spTransform(nam1Sp, getCRS('albersNA', TRUE))
# save(nam1Sp, file='./regions/gadm36_northAmerica_sp_level_1.rda')
# save(nam1SpAlb, file='./regions/gadm36_northAmerica_spAlb_level_1.rda')
# ### North America level 0
# mex <- getData('GADM', country='MEX', level=0, path='D:/ecology/!Scratch')
# usa <- getData('GADM', country='USA', level=0, path='D:/ecology/!Scratch')
# can <- getData('GADM', country='CAN', level=0, path='D:/ecology/!Scratch')
# nam0Sp <- rbind(can, usa, mex)
# for (thisLevel in lakeNames0) {
# thisLargerSp <- nam0Sp[nam0Sp@data$NAME_0 == thisLevel, ]
# df <- thisLargerSp@data
# nam0Sp <- nam0Sp[-which(nam0Sp@data$NAME_0 == thisLevel), ]
# thisLargerSansLakesSp <- gDifference(thisLargerSp, greatLakesSp)
# thisLargerSansLakesSp <- as(thisLargerSansLakesSp, 'SpatialPolygonsDataFrame')
# projection(thisLargerSansLakesSp) <- projection(nam1Sp)
# thisLargerSansLakesSp@data <- df
# nam0Sp <- rbind(nam0Sp, thisLargerSansLakesSp)
# }
# nam0SpAlb <- sp::spTransform(nam0Sp, getCRS('albersNA', TRUE))
# save(nam0Sp, file='./regions/gadm36_northAmerica_sp_level_0.rda')
# save(nam0SpAlb, file='./regions/gadm36_northAmerica_spAlb_level_0.rda')
# # continent
# namSpAlb <- gUnaryUnion(nam0SpAlb)
# save(namSpAlb, file='./regions/gadm36_northAmerica_spAlb_continental.rda')
# # # continent cropped to study region
# studyRegionRasts <- brick('C:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/study_region/!study_region_raster_masks/study_region_daltonIceMask_lakesMasked_linearIceSheetInterpolation.tif')
# namSpAlbStudyRegion <- crop(namSpAlb, studyRegionRasts[[1]])
# save(namSpAlbStudyRegion, file='./regions/gadm36_northAmerica_spAlb_continental_cropToStudyRegion.rda')
# ### study region cropped to present-day land
# if (!exists('studyRegionCroppedToPresentSpAlb')) {
# studyRegionCroppedToPresentSpAlb <- crop(studyRegionSpAlb, nam0SpAlb)
# save(studyRegionCroppedToPresentSpAlb, file='./regions/studyRegion_croppedToPresentLand.rda')
# }
# ### range maps
# dirCreate('./regions/bien_range_map')
# BIEN_ranges_species(species, directory='./regions/bien_range_map')
# bienRange <- BIEN_ranges_load_species(species)
# bienRangeAlb <- sp::spTransform(bienRange, getCRS('albersNA', TRUE))
# littleRangeFileName <- 'C:/Ecology/Drive/Research/ABC vs Biogeography/NSF_ABI_2018_2021/data_and_analyses/green_ash/range_maps/little/fraxpenn.shp'
# littleRange <- shapefile(littleRangeFileName)
# projection(littleRange) <- getCRS('wgs84')
# littleRange <- littleRange[littleRange$CODE == 1, ] # remove holes
# littleRangeSpAlb <- sp::spTransform(littleRange, getCRS('albersNA', TRUE))
# dirCreate('./regions/little_range_map')
# save(littleRangeSpAlb, file='./regions/little_range_map/littleRangeSpAlb.rda')
# say('####################################', pre=1)
# say('### obtain and clean occurrences ###')
# say('####################################', post=2)
# ### obtain records
# ##################
# speciesFileName <- paste0(
# './species_records/00_',
# gsub(tolower(species), pattern=' ', replacement='_'),
# '_bien_all_occurrences.rda'
# )
# if (file.exists(speciesFileName)) {
# load(speciesFileName)
# } else {
# occsRaw <- BIEN_occurrence_species(
# species=species,
# cultivated = FALSE,
# only.new.world = TRUE,
# all.taxonomy = FALSE,
# native.status = FALSE,
# natives.only = TRUE,
# observation.type = TRUE,
# political.boundaries = TRUE,
# collection.info = TRUE
# )
# sink('./species_records/bien_download.txt')
# say('Data representing species records were downloaded from BIEN on', date(), '.')
# sink()
# save(occsRaw, file=speciesFileName)
# }
# ### remove occurrences with missing coordinates and dates:
# occs <- occsRaw[!(is.na(occsRaw$longitude) | is.na(occsRaw$latitude) | is.na(occsRaw$date_collected)), ]
# dim(occs)
# ### remove records <1950 (period covered by Lorenz et al. 2016 climate data is 1950-2005):
# occs$date_collected <- as.Date(occs$date_collected)
# occs <- occs[!is.na(occs$date_collected), ]
# occs <- occs[which(occs$date_collected >= as.Date(paste0(1950 + genTime_yr, '-01-01'))), ]
# ### remove records in states where green ash has been naturalized (according to BONAP)
# ######################################################################################
# occs <- occs[!(occs$state_province %in% c('Washington', 'Oregon', 'Idaho', 'Utah', 'Colorado', 'Arizona', 'New Mexico', 'Chihuahua', 'British Columbia')), ]
# occs <- occs[-which(occs$state_province == 'Texas' & occs$county == 'El Paso'), ]
# ### inspect occurrences
# #######################
# ### convert occurrences to spatial object
# occsSp <- SpatialPointsDataFrame(
# occs[ , ll],
# data=occs,
# proj4=getCRS('wgs84', TRUE)
# )
# occsSpAlb <- sp::spTransform(occsSp, getCRS('albersNA', TRUE))
# png('./figures_and_tables/occurrences_raw.png', width=1200, height=1000)
# par(mfrow=c(1, 2))
# # plot occurrences with BIEN range map
# plot(occsSpAlb, col=NA, main='BIEN range map')
# plot(bienRangeAlb, col=alpha('green', 0.4), border='green', add=TRUE)
# points(occsSpAlb, pch=16, cex=0.9, col='black')
# plot(nam1SpAlb, add=TRUE, border='gray')
# # plot occurrences with Little's range map
# plot(occsSpAlb, col=NA, main='Little range map')
# plot(littleRangeSpAlb, col=alpha('red', 0.4), border='red', add=TRUE)
# points(occsSpAlb, pch=16, cex=0.9, col='black')
# plot(nam1SpAlb, add=TRUE, border='gray')
# title(sub=date(), outer=TRUE, cex.sub=0.7, line=-2)
# dev.off()
# say('Things to note:')
# say('* There is at least one occurrence in South America or its vicinity.')
# say('* There are many occurrences outside Little\'s range polygon.')
# say('* ...Especially in the northern part of peninsular Florida', post=2)
# say('* ...and the western US', post=2)
# ### examine areas in vicinity of Kentucky and Louisiana that appear to lack data
# png('./figures_and_tables/occurrences_near_louisiana_kentucky.png', width=1200, height=1000)
# par(mfrow=c(1, 2))
# plot(nam1SpAlb[nam1SpAlb@data$NAME_1 == 'Kentucky', ])
# points(occsSpAlb, pch=16, cex=0.9, col='black')
# plot(nam1SpAlb[nam1SpAlb@data$NAME_1 == 'Louisiana', ])
# points(occsSpAlb, pch=16, cex=0.9, col='black')
# title(main=paste0('Missing records in ', paste(undersampled, collapse=' and ')), sub=date(), outer=TRUE, cex.sub=0.7, line=-2)
# dev.off()
# say('So, yes, there is a bias in the central and Appalachian region of Kentucky... Note that the species genuinely does not appear in the "high" Appalachians. This is disturbing since the usual methods of correcting for bias like inverse-p weighting or spatial thinning would remove signal from its absence in these areas *plus* in areas that are undersampled like Kentucky and Louisiana.', post=2, breaks=80)
# say('So, we are going to remove Louisiana and Kentucky from the training set. This means occurrences from these areas will be be use to train the models, nor will background sites drawn from these areas.', post=2, breaks=80)
# ### remove occurrences in undersampled areas and in South America
# #################################################################
# nrowStart <- nrow(occsSpAlb)
# occsSpAlb <- occsSpAlb[(occsSpAlb@data$country %in% c('Canada', 'United States', 'Mexico')) & !(occsSpAlb@data$state_province %in% undersampled), ]
# sink('./species_records/cleaning_notes_outliers_undersampled.txt', split=TRUE)
# say('By removing occurrences outside Mexico/US/Canada we reduced the number of occurrences from ', nrowStart, ' to ', nrow(occsSpAlb), '.')
# sink()
# ### correct for hypothesized spatial sampling bias
# ##################################################
# say('To remove sampling bias we will spatially thin occurrences so that there is but one occurrence per cell.')
# # get occurrences in WGS84 CRS
# priority <- rep(NA, nrow(occsSpAlb))
# priority[occsSpAlb$observation_type == 'plot'] <- 1
# priority[occsSpAlb$observation_type == 'specimen'] <- 2
# priority[occsSpAlb$observation_type == 'trait occurrence'] <- 3
# priority[occsSpAlb$observation_type == 'human observation'] <- 4
# priority[occsSpAlb$observation_type == 'unknown'] <- 5
# nrowStart <- nrow(occsSpAlb)
# occsSpAlb <- elimCellDups(occsSpAlb, r=maskRastAlb, priority=priority)
# sink('./species_records/cleaning_notes_thinning.txt', split=TRUE)
# say('Through spatial thinning we reduced the number of occurrences from ', nrowStart, ' to ', nrow(occsSpAlb), '.')
# sink()
# # inspect
# png('./figures_and_tables/occurrences_thinned_one_per_cell.png', width=1200, height=1000)
# plot(occsSpAlb, pch=16, cex=1.8, main='All cleaned and thinnned occurrences')
# plot(nam1SpAlb, add=TRUE, border='gray')
# title(sub=date(), outer=TRUE, cex.sub=0.7, line=-2)
# dev.off()
# # save
# save(occsSpAlb, file=paste0('./species_records/01_', (gsub(tolower(species), pattern=' ', replacement='_')), '_bien_cleaned_occurrences_thinned.rda'))
# say('##################################', pre=1)
# say('### define calibration regions ###')
# say('##################################', post=2)
# say('Currently, best practices assert that one should model the niche using only data from an area considered accessible to the species over long time. However, in practice this is very difficult to estimate, so we will use buffers of different size (defined above in the "### constants ###" section above).', post=2, breaks=80)
# ### load data
# load(paste0('./species_records/01_', gsub(tolower(species), pattern=' ', replacement='_'), '_bien_cleaned_occurrences_thinned.rda'))
# ### create buffers
# if (!exists('calibRegionsSpAlb')) {
# # buffer around occurrences
# calibRegionsSpAlb <- list()
# for (i in seq_along(exts)) {
# calibRegionsSpAlb[[i]] <- gBuffer(occsSpAlb, width=exts[i] * 1000)
# }
# # crop area outside North America, remove undersampled states, remove Great Lakes
# undersampledSpAlb <- nam1SpAlb[nam1SpAlb$NAME_1 %in% undersampled, ]
# for (i in seq_along(exts)) {
# # calibRegionsSpAlb[[i]] <- gIntersection(calibRegionsSpAlb[[i]], sr) # not doing this because some points outside study region
# calibRegionsSpAlb[[i]] <- rgeos::gIntersection(calibRegionsSpAlb[[i]], nam0SpAlb)
# calibRegionsSpAlb[[i]] <- rgeos::gDifference(calibRegionsSpAlb[[i]], undersampledSpAlb, checkValidity=TRUE)
# calibRegionsSpAlb[[i]] <- rgeos::gDifference(calibRegionsSpAlb[[i]], greatLakesSpAlb, checkValidity=TRUE)
# }
# studyRegionCroppedToPresentSpAlb <- crop(studyRegionSpAlb, nam0SpAlb)
# # inspect
# png('./figures_and_tables/regions.png', width=1200, height=1000)
# par(cex.main=1.4)
# plot(calibRegionsSpAlb[[length(calibRegionsSpAlb)]], border=NA, col=NA, main='Calibration Regions')
# plot(studyRegionCroppedToPresentSpAlb, add=TRUE, lwd=0.8, col='khaki1')
# for (i in rev(seq_along(exts))) {
# plot(calibRegionsSpAlb[[i]], col=paste0('aquamarine', 4 + 1 - i), lwd=0.8, add=TRUE)
# }
# plot(nam1SpAlb, add=TRUE)
# points(occsSpAlb, pch=16, cex=1.4)
# legend <- c('Records', paste('Calibration region:', rev(exts), 'km'), 'Study region (modern)')
# fill <- c(NA, paste0('aquamarine', 4 + 1 - rev(seq_along(exts))), 'khaki1')
# pch <- c(16, rep(NA, length(exts)), NA)
# pt.cex <- c(1.4, rep(NA, length(exts)), NA)
# border <- c(NA, rep(0.8, length(exts)), 0.8)
# col <- c('black', rep(NA, length(exts)), NA)
# legend('bottomright',
# legend=legend,
# fill=fill,
# pch=pch,
# pt.cex=pt.cex,
# border=border,
# col=col,
# bty='n', cex=1.6
# )
# dev.off()
# names(calibRegionsSpAlb) <- paste0('bufferAroundOccs_', exts, 'km')
# save(calibRegionsSpAlb, file='./regions/calibration_regions.rda')
# }
# say('################################', pre=1)
# say('### select climate variables ###')
# say('################################', post=2)
# say('We will be using the paleo climate layers prepared by Lorenz, D.J., Nieto-Lugilde, D., Blois, J.L., Fitzpatrick, M.C., and Williams, J.W. 2016. Downscaled and debiased climate simulations for North America from 21,000 years ago to 2100 AD. Scientific Data 3:160048. The DOI of the original data is 10.5061/dryad.1597g. This data set contains future, current, and historical GCM projections. We will be using the current and historical model output from the ECBilt and CCSM GCMs (other models have only current/future projections associated with them). The spatial resolution is 0.5deg for all of North America.', breaks=80, post=2)
# say('Available variables include min/max temperature, precipitation, growing degree days, AET, PET, ETR (= AET/PET), and WDI (PET - precipitation), summarized across an annual, quarterly, or monthly basis. Variables are projected back to 22 Kybp (CCSM) or 21 Kybp (ECBilt) in 500-yr timeslices. The current period covers averages across 1950-2005. Past climate encompasses averages across 200-yr intervals centered on every 500 yr (e.g., 500 ypb, 1000 ypb, 1500 ypb, etc.).', breaks=80, post=2)
# say('We will *not* use variable "an_cv_ETR" because it has NAs in Canada during the present in large portions of Canada (and possibly through time).', breaks=80, post=2)
# say('We will *not* use variable "an_cv_WDI" because it has some very extreme values in just a few cells in Mexico at 0 ybp (and possibly through time).', breaks=80, post=2)
# say('Tasks to complete include:')
# say('* Selecting variables.')
# say('* Cropping/masking rasters to study region *extent* (versus the areas within the study region).')
# say('* Interpolating rasters to 30-yr intervals (approximate generation time for green ash).')
# say('### select variables', level=2)
# ####################################
# calibRegionBroadestSp <- calibRegionsSpAlb[[paste0('bufferAroundOccs_', max(exts), 'km')]]
# ### get set of randomly located points for assessing collinearity between variables
# climCcsm_0ypb <- raster::stack(listFiles('D:/Ecology/Climate/Lorenz et al 2016 North America 21Kybp to 2100 CE/ccsm3_22-0k_all_tifs/0BP', pattern='an_'))
# climEcbilt_0ypb <- raster::stack(listFiles('D:/Ecology/Climate/Lorenz et al 2016 North America 21Kybp to 2100 CE/ecbilt_21-0k_all_tifs/0BP', pattern='an_'))
# # remove an_cv_ETR and an_cv_WDI
# keeps <- names(climCcsm_0ypb)[-which(names(climCcsm_0ypb) %in% c('an_cv_ETR', 'an_cv_WDI'))]
# climCcsm_0ypb <- subset(climCcsm_0ypb, keeps)
# climEcbilt_0ypb <- subset(climEcbilt_0ypb, keeps)
# maskBroad0ypb <- rasterize(calibRegionBroadestSp, climCcsm_0ypb[[1]])
# randBg <- randomPoints(maskBroad0ypb, 11000)
# randBg <- as.data.frame(randBg)
# names(randBg) <- ll
# envCcsm_0ybp <- extract(climCcsm_0ypb, randBg)
# envEcbilt_0ybp <- extract(climEcbilt_0ypb, randBg)
# completeCases <- complete.cases(envCcsm_0ybp) & complete.cases(envEcbilt_0ybp)
# randBg <- randBg[completeCases, ]
# randBg <- randBg[1:max(nrow(randBg), 10000), ]
# envCcsm_0ybp <- envCcsm_0ybp[completeCases, ]
# envEcbilt_0ybp <- envEcbilt_0ybp[completeCases, ]
# env <- rbind(envCcsm_0ybp, envEcbilt_0ybp)
# env <- as.data.frame(env)
# envScaled <- scale(env)
# variableSel <- usdm::vifcor(envScaled, maxCor, maxobservations=Inf)
# sink('./figures_and_tables/variable_selection.txt', split=TRUE)
# say('Based on a threshold maximum correlation of ', maxCor, ' and VIF, we will use the following variables:')
# print(variableSel)
# sink()
# predictors <- variableSel@results$Variables
# save(predictors, file='./figures_and_tables/predictors.rda')
# say('calculate statistics for rescaling rasters from present-day rasters', level=2)
# ###################################################################################
# # saves statistics on each variable (min/max/etc)
# variableStats <- data.frame()
# for (gcm in gcms) {
# rasts <- getClimRasts(gcm=gcm, year=0, variables=predictors, rescale = FALSE)
# mins <- minValue(rasts)
# maxs <- maxValue(rasts)
# # remember
# variableStats <- rbind(
# variableStats,
# data.frame(
# gcm = gcm,
# variable = predictors,
# min = mins,
# max = maxs
# )
# )
# } # next GCM
# write.csv(variableStats, './environmental_rasters/lorenz_et_al_2016/variable_statistics_0bp_across_north_america.csv', row.names=FALSE)
# say('###########################################', pre=1)
# say('### collate calibration/evaluation data ###')
# say('###########################################', post=2)
# say('In this step we will:')
# say('* Extract environmental data.')
# say('* Locate background sites.')
# say('* Define geographically distinct cross-validation folds for model evaluation.')
# calibRegionsSp <- calibRegionsSpAlb
# for (i in seq_along(calibRegionsSp)) {
# calibRegionsSp[[i]] <- sp::spTransform(calibRegionsSp[[i]], getCRS('wgs84', TRUE))
# }
# load(paste0('./species_records/01_', gsub(tolower(species), pattern=' ', replacement='_'), '_bien_cleaned_occurrences_thinned.rda'))
# occsSp <- sp::spTransform(occsSpAlb, getCRS('wgs84', TRUE))
# say('extract environmental data', level=2)
# ##########################################
# # by GCM
# for (gcm in gcms) {
# if (exists('rasts', inherits=FALSE)) rm(rasts)
# # get current version of each variable raster
# rasts <- getClimRasts(gcm=gcm, year=0, variables=predictors, rescale=TRUE, fillCoasts=TRUE)
# areas <- area(rasts[[1]])
# # extract
# env <- raster::extract(rasts, occsSp)
# env <- as.data.frame(env)
# thisArea <- raster::extract(areas, occsSp)
# thisArea <- as.data.frame(thisArea)
# names(thisArea) <- 'cellArea_km2'
# thisEnv <- cbind(thisArea, env)
# # remember
# occsSpAlb@data <- cbind(occsSpAlb@data, thisEnv)
# } # next GCM
# # remove occurrences with incomplete environmental data
# vars <- character()
# for (gcm in gcms) vars <- c(vars, paste0(gcm, '_', predictors))
# noNas <- complete.cases(occsSpAlb@data[ , vars])
# occsSpAlb <- occsSpAlb[noNas, ]
# say('generate test background sites', level=2)
# ##############################################
# calibRegionSpAlb <- calibRegionsSpAlb[[paste0('bufferAroundOccs_', max(exts), 'km')]]
# # get random background sites
# bgTestSpAlb <- spsample(calibRegionSpAlb, n=11000, type='random', iter=10)
# bgTestSp <- sp::spTransform(bgTestSpAlb, getCRS('wgs84', TRUE))
# bgTest <- as.data.frame(coordinates(bgTestSp))
# names(bgTest) <- ll
# if (exists('env')) rm(env)
# # by GCM
# for (gcm in gcms) {
# # get current version of each variable raster
# rasts <- getClimRasts(gcm=gcm, year=0, variables=predictors, rescale=TRUE, fillCoasts=TRUE)
# areas <- area(rasts[[1]])
# # extract
# thisEnv <- raster::extract(rasts, bgTest)
# thisEnv <- as.data.frame(thisEnv)
# thisArea <- raster::extract(areas, bgTest)
# thisArea <- as.data.frame(thisArea)
# names(thisArea) <- 'cellArea_km2'
# thisEnv <- cbind(thisArea, thisEnv)
# # remember
# env <- if (exists('env', inherits=FALSE)) {
# cbind(env, thisEnv)
# } else {
# thisEnv
# }
# } # next GCM
# # cull NA cases
# bgTest <- cbind(bgTest, env)
# bgTest <- bgTest[complete.cases(bgTest), ]
# bgTest <- bgTest[1:min(nrow(bgTest), 10000), ]
# say('generate training background sites', level=2)
# ##################################################
# for (countExt in seq_along(exts)) {
# ext <- exts[countExt]
# calibRegionSpAlb <- calibRegionsSpAlb[[countExt]]
# # get random background sites
# bgCalibSpAlb <- spsample(calibRegionSpAlb, n=11000, type='random', iter=10)
# bgCalibSp <- sp::spTransform(bgCalibSpAlb, getCRS('wgs84', TRUE))
# bgCalib <- as.data.frame(coordinates(bgCalibSp))
# names(bgCalib) <- ll
# if (exists('env')) rm(env)
# # by GCM
# for (gcm in gcms) {
# # get current version of each variable raster
# rasts <- getClimRasts(gcm=gcm, year=0, variables=predictors, rescale=TRUE, fillCoasts=TRUE)
# areas <- area(rasts[[1]])
# # extract
# thisEnv <- raster::extract(rasts, bgCalib)
# thisEnv <- as.data.frame(thisEnv)
# thisArea <- raster::extract(areas, bgCalib)
# thisArea <- as.data.frame(thisArea)
# names(thisArea) <- 'cellArea_km2'
# thisEnv <- cbind(thisArea, thisEnv)
# # remember
# env <- if (exists('env', inherits=FALSE)) {
# cbind(env, thisEnv)
# } else {
# thisEnv
# }
# } # next GCM
# # cull NA cases
# bgCalib <- cbind(bgCalib, env)
# bgCalib <- bgCalib[complete.cases(bgCalib), ]
# bgCalib <- bgCalib[1:min(nrow(bgCalib), 10000), ]
# # remember
# assign(paste0('bgCalib_extent', exts[countExt], 'km'), bgCalib)
# } # next calibration region
# say('assign spatially exclusive training/calibration/evaluation cross-validation folds', level=2)
# #################################################################################################
# bgTestSp <- SpatialPoints(bgTest[ , ll], getCRS('wgs84', TRUE))
# bgTestSpAlb <- sp::spTransform(bgTestSp, getCRS('albersNA', TRUE))
# blockRast <- rastWithSquareCells(studyRegionCroppedToPresentSpAlb, res=foldBuffer_m)
# # create folds based on occurrences such that there is at least a minimum number of occurrences per fold
# minNumInFold <- -Inf
# numFolds <- 50
# maxTries <- 20
# tries <- 1
# while (minNumInFold < minFoldSize) {
# values(blockRast) <- sample(1:numFolds, ncell(blockRast), replace=TRUE)
# folds <- extract(blockRast, occsSpAlb)
# minNumInFold <- min(table(folds))
# tries <- tries + 1
# if (tries == maxTries) {
# tries <- 1
# numFolds <- numFolds - 1
# }
# }
# say('Final number of folds: ', numFolds)
# occs <- occsSpAlb@data
# folds <- data.frame(fold=folds)
# occs <- cbind(occs, folds)
# # assign folds to test background sites
# bgTestSp <- SpatialPointsDataFrame(bgTest[ , ll], data=bgTest, proj4string=getCRS('wgs84', TRUE))
# bgTestSpAlb <- sp::spTransform(bgTestSp, getCRS('albersNA', TRUE))
# bgTestFolds <- extract(blockRast, bgTestSpAlb)
# bgTestSpAlb$fold <- bgTestFolds
# bgTest <- bgTestSpAlb@data
# # assign folds to calibration background sites
# for (ext in exts) {
# x <- get(paste0('bgCalib_extent', ext, 'km'))
# xSp <- SpatialPointsDataFrame(x[ , ll], data=x, proj4string=getCRS('wgs84', TRUE))
# xSpAlb <- sp::spTransform(xSp, getCRS('albersNA', TRUE))
# bgCalibFolds <- extract(blockRast, xSpAlb)
# x$fold <- bgCalibFolds
# x <- as.data.frame(x)
# assign(paste0('bgCalib_extent', ext, 'km'), x)
# }
# say('collate calibration and evaluation occurrences and background sites', level=2)
# ##################################################################################
# occsBg <- list()
# occsBg$note <- 'This list object contains spatially thinned occurrence data and associated background sites. $testBg is a set of background sites drawn from the largest training region extent. $calibEvalOccsBg[[i]] is a list of lists, one per training region extent. Each sublist has two data frames. $calibEvalOccsBg[[i]]occsBg is a data frame representing calibration occurrences and background sites. Weights are 1 for occurrences and a fractional value for background sites such that their combined weight is equal to the total weight of occurrences. Folds are geographically exclusive and comprise a set of intermingled spatial blocks. $calibEvalOccsBg[[i]]$folds is a data frame with one row per row in $calibEvalOccsBg[[i]]$occsBg and one column per fold. Values in each column are 1 (training data), 2 (calibration data), or NA (masked... these represent evaluation data censored from the training and calibration sets).'
# occsBg$meta <- data.frame(
# item = c(
# 'numOccs',
# 'numFolds',
# 'minFoldSize_numOccs'
# ),
# value = c(
# nrow(occs),
# numFolds,
# minFoldSize
# )
# )
# columnsJustBg <- c('fold', ll, 'cellArea_km2', paste0(rep(gcms, each=length(predictors)), '_', predictors))
# columnsOccsAndBg <- c('presBg', 'fold', 'weight', ll, 'cellArea_km2', paste0(rep(gcms, each=length(predictors)), '_', predictors))
# occsBg$allOccsThinned <- occs
# occsBg$testBg <- bgTest[ , columnsJustBg]
# occsBg$calibEvalOccsBg <- list()
# for (countExents in seq_along(exts)) {
# ext <- exts[countExents]
# # collate occurrences and background sites
# thisOccs <- occs
# thisOccs$presBg <- 1
# thisOccs$weight <- 1
# thisOccs <- thisOccs[ , columnsOccsAndBg]
# thisBg <- get(paste0('bgCalib_extent', ext, 'km'))
# thisBg$presBg <- 0
# thisBg$weight <- nrow(thisOccs) / nrow(thisBg)
# thisBg <- thisBg[ , columnsOccsAndBg]
# thisOccsBg <- rbind(thisOccs, thisBg)
# # make matrix indicating which occurrences/background sites are in which fold set
# if (exists('folds')) rm(folds)
# for (calibFold in 1:numFolds) {
# for (evalFold in (1:numFolds)[-calibFold]) {
# designation <- rep(1, nrow(thisOccsBg)) # start with all training
# designation[thisOccsBg$fold == calibFold] <- 2 # calibration folds
# designation[thisOccsBg$fold == evalFold] <- NA # mask evaluation folds
# designation <- matrix(designation, ncol=1)
# colnames(designation) <- paste0('calib', calibFold, '_vs_eval', evalFold)
# folds <- if (exists('folds')) {
# cbind(folds, designation)
# } else {
# designation
# }
# }
# }
# occsBg$calibEvalOccsBg[[countExents]] <- list()
# occsBg$calibEvalOccsBg[[countExents]]$occsBg <- thisOccsBg
# occsBg$calibEvalOccsBg[[countExents]]$folds <- folds
# }
# names(occsBg$calibEvalOccsBg) <- paste0('occsBg_extent', exts, 'km')
# ### make a map of calibration/evaluation sites
# calibFold <- 1
# evalFold <- 2
# cex <- 0.6
# pch <- 3
# png('./figures_and_tables/example_of_training_calibration_evaluation_folds.png', width=1800, height=600)