This repository has been archived by the owner on Dec 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Varecia Ver 06 Ecological Niche Modeling.r
3597 lines (2489 loc) · 136 KB
/
Varecia Ver 06 Ecological Niche Modeling.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 range of Varecia, the Black-and-White Lemur (with Toni Lyn Morelli)
### Adam B. Smith | Missouri Botanical Garden | adamDOTsmithATmobotDOTorg | 2018-02
### This code is version 6 of attempts to model the exposure of two lemurs, Varecia variegata and Varecia rubra, to anticipated climate change and deforestation in Madagascar. The analysis depends on two models, one of deforestation and an ecological niche model using forest cover and climate as predictors.
# source('C:/Ecology/Drive/Research/Varecia (Toni Lyn Morelli)/Versions 06/Code/Varecia Ver 06 Ecological Niche Modeling.r')
# source('H:/Global Change Program/Research/Varecia (Toni Lyn Morelli)/Versions 06/Code/Varecia Ver 06 Ecological Niche Modeling.r')
# source('E:/ecology/Drive/Research/Varecia (Toni Lyn Morelli)/Versions 06/Code/Varecia Ver 06 Ecological Niche Modeling.r')
setwd('C:/ecology/Drive/Research/Varecia (Toni Lyn Morelli)/Versions 06')
# setwd('H:/Global Change Program/Research/Varecia (Toni Lyn Morelli)/Versions 06')
# setwd('E:/ecology/Drive/Research/Varecia (Toni Lyn Morelli)/Versions 06')
################
### CONTENTS ###
################
### SETUP ###
### libraries, functions, and definitions ###
### create masks of Madagascar (entire island) ###
### collate current environmental data for ecological niche models ###
### collate species data ###
### create display of occurrence records ###
### create display of Madagascar with PAs ###
### match occurrence records with environmental data ###
### select background sites ###
### calculate spatial autocorrelation between survey sites ###
### calculate survey site weights to correct for sampling bias ###
### collate occurrence records and background sites ###
### train ecological niche models ###
### select and collate future climate data for projecting ecological niche model ###
### visualize response curves of ecological niche models ###
### evaluate ecological niche models ###
### predict to current and future conditions ###
### create ensemble rasters for future climate ecological niche model projections ###
### calculate mean environmental suitability across entire region and elevation bands ###
### report values of mean environmental suitability across entire region and elevation bands ###
### compare elevational distribution of forest and occurrences ###
### evaluate changes in suitability in protected areas ###
### create fine-scale hillshade raster ###
### create displays of ecological niche model predictions ###
### create 3D displays of ecological niche model predictions ###
### create 3D displays of climate change ###
### create display range maps by surveyor ###
### niche overlap analysis ###
#############################################
### libraries, functions, and definitions ###
#############################################
memory.limit(memory.limit() * 2^30)
rm(list=ls())
gc()
library(omnibus)
library(enmSdm)
library(statisfactory)
library(legendary)
library(fasterRaster)
library(sp)
library(graticule)
library(raster)
library(parallel)
library(dismo)
library(rgeos)
library(geosphere)
library(brglm2)
# library(phcfM)
library(fpCompare)
library(scales)
library(rgl)
# library(rayshader)
library(tictoc)
say(date())
###############
### options ###
###############
options(stringsAsFactors=FALSE)
rasterOptions(format='GTiff', overwrite=TRUE)
#################
### variables ###
#################
taxa <- c('genus', 'variegata', 'rubra')
madEaProj <- '+init=epsg:32738'
bioclims <- c(4, 10, 15, 16) # BIOCLIM variables to use
predictors <- c(paste0('bio', prefix(bioclims, 2)), 'forestFragClass_utm38s') # predictors in ENMs
longLat <- c('longWgs84', 'latWgs84') # BIOCLIM variables to use
grassDir <- c('C:/OSGeo4W64/', 'grass-7.4.1', 'osgeo4W')
periods <- c('2041 to 2060', '2061 to 2080') # future time periods corresponding to WORLDCLIM data
rcps <- c('2pt6', '4pt5', '6pt0', '8pt5') # RCPs for future climate periods
# rcps <- c('2pt6', '6pt0') # RCPs for future climate periods
# rcps <- c('4pt5', '8pt5') # RCPs for future climate periods
### extents of insets for plots of maps
madFocus1 <- extent(929471, 1043462, 8234420, 8358325)
madFocus2 <- extent(850269, 944754, 7949353, 8048591)
madFocus3 <- extent(687756, 751211.0, 7433385, 7553616)
madFocus1 <- as(madFocus1, 'SpatialPolygons')
madFocus2 <- as(madFocus2, 'SpatialPolygons')
madFocus3 <- as(madFocus3, 'SpatialPolygons')
projection(madFocus1) <- projection(madEaProj)
projection(madFocus2) <- projection(madEaProj)
projection(madFocus3) <- projection(madEaProj)
#################
### functions ###
#################
# convert NAs to zeros
naToZeroFx <- function(x) ifelse(is.na(x), 0, x)
# equation for annualized forest loss rate from Puyravaud, J-P. 2003 Standardizing the calculation of the annual rate of deforestation. Forest Ecology and Management 177:593-596.
# t1, t1 Time 1 and 2
# A1, A2 Area of forest in times 1 and 2
compoundInterestLaw <- function(t1, t2, A1, A2) (1 / (t2 - t1)) * log(A2 / A1)
# predict ecological niche model, convert to integer to reduce file size
predictVareciaEnm <- function(model, predStack, cores=6) {
# model model object
# preds predictor stack
# cores nummber of cores
beginCluster(cores)
prediction <- clusterR(preds, predict, args=list(model=model, type='response'))
prediction <- 100 * prediction
prediction <- clusterR(prediction, round)
endCluster()
prediction
}
# calculate ensemble mean (across GCMs, say) for projection rasters from ecological niche model, convert to integer to reduce file size
ensembleVareciaEnmRasters <- function(predictions, cores=6) {
# predictions raster stack of prediction rasters
# cores number of cores
rangeFx <- function(x) max(x) - min(x)
beginCluster(cores)
meanPrediction <- clusterR(predictions, calc, args=list(fun=mean))
endCluster()
meanPrediction
}
# return nice names for predictors
predictorNice <- function(p, incUnits=FALSE) {
out <- if (p == 'bio04') {
'Temperature Seasonality'
} else if (p == 'bio10') {
'Warmest Quarter Temperature'
} else if (p == 'bio15') {
'Precipitation Seasonality'
} else if (p == 'bio16') {
'Wettest Quarter Precipitation'
} else if (p == 'forestFragmentationClass') {
'Forest Fragmentation Class'
}
if (incUnits) {
if (p == 'bio10') {
out <- paste0(out, ' (deg C)')
} else if (p == 'bio16') {
out <- paste0(out, ' (mm)')
}
}
out
}
# balance sum of weights of presences and background sites
balanceWeights <- function(x) {
# df data frame with at least these fields: 'presBg', 'weight'
weight <- x$weight
presWeight <- sum(weight[x$presBg == 1])
bgWeight <- sum(weight[x$presBg == 0])
if (presWeight > bgWeight) {
weight[x$presBg == 0] <- weight[x$presBg == 0] * (presWeight / bgWeight)
} else {
weight[x$presBg == 1]<- weight[x$presBg == 1] * (bgWeight / presWeight)
}
weight
}
### convert singlepart spatial polygons to multipart
multiPart <- function(shape) {
#vector of number of elementary polygons in each multipart polygon (for calculation of plot order, and initialization of islands)
nbpoly <- sapply(shape@polygons, function(x){ length(x@Polygons) })
#initialize the list of single Polygons to be built
islands <- vector('list', sum(nbpoly))
#initialize the vector plot order of single polygons to be built
plotorder <- vector('integer',sum(nbpoly))
#index of current single Polygons
k <- 0
#loop on all Polygons of the object
for (i in 1:length(shape)) {
#current multiple polygon
pols <- shape@polygons[[i]]@Polygons
ID <- shape@polygons[[i]]@ID
#number of polygons to plot before the current multiple one
prev <- sum(nbpoly[shape@plotOrder < shape@plotOrder[i]])
#loop on each elementary polygon of the current multiple polygon
for (j in 1:length(pols)) {
k <- k+1
IDs <- ifelse(length(pols)>1,paste(ID,'-',j,sep=''),ID)
islands[[k]] <- Polygons(list(pols[[j]]), IDs)
plotorder[k] <- rank(shape@polygons[[i]]@plotOrder,ties.method="first")[j]+prev
}
}
multitoone <- SpatialPolygons(islands,pO=plotorder)
if (!is.na(proj4string(shape))) proj4string(multitoone) <- proj4string(shape)
multitoone
}
### stack *current* predictors that use WGS84 30 arcsec resolution for Madagascar
#################################################################################
stackMadCurrent_wgs84 <- function() {
yrs <- c(2000, 2005, 2010, 2014)
out <- raster::stack(c(
'./Data/Topography - WORLDCLIM Ver 1pt4 Rel 3/elevation_wgs84.tif',
paste0('./Data/Forest - Vieilledent et al 2018/forest', yrs, '_wgs84.tif'),
paste0('./Data/Climate - WORLDCLIM Ver 2 Rel 1 Jun 2016 (1970-2000)/bio', prefix(bioclims, 2), '.tif')
))
out
}
### stack *future* climate predictors that use WGS84 30 arcsec resolution for Madagascar
########################################################################################
stackMadFuture_wgs84 <- function(gcm, period, rcp) {
# gcm
# period
# rcp
out <- raster::stack(
paste0('./Data/Climate - WORLDCLIM Ver 2 Rel 1 Jun 2016 (', period, ')/', gcm, ' RCP', rcp, '/bio', prefix(bioclims, 2), '.tif')
)
out
}
### stack *current* predictors that use WGS84 30 arcsec resolution for Madagascar
#################################################################################
stackMadCurrent_utm38s <- function() {
yrs <- c(2000, 2005, 2010, 2014)
out <- raster::stack(c(
paste0('./Data/Forest - Vieilledent et al 2018/forest', yrs, '.tif'),
paste0('./Data/Forest - Vieilledent et al 2018/forestFragClass', yrs, '_utm38s.tif'),
paste0('./Data/Forest - Vieilledent et al 2018/forestFragConnect', yrs, '_utm38s.tif'),
paste0('./Data/Forest - Vieilledent et al 2018/forestFragDensity', yrs, '_utm38s.tif')
))
names(out)[names(out) == 'forest2000'] <- 'forest2000_utm38s'
names(out)[names(out) == 'forest2005'] <- 'forest2005_utm38s'
names(out)[names(out) == 'forest2010'] <- 'forest2010_utm38s'
names(out)[names(out) == 'forest2014'] <- 'forest2014_utm38s'
out
}
# say('##################################################')
# say('### create masks of Madagascar (entire island) ###')
# say('##################################################')
# elev <- raster::getData(name='alt', country='MDG', path='C:/ecology/!Scratch')
# mask_wgs84 <- elev * 0 + 1
# names(mask_wgs84) <- 'mask_wgs84'
# writeRaster(mask_wgs84, './Study Region & Masks/WGS84 30-arcsec Resolution/mask_wgs84', datatype='INT1U')
# say('######################################################################')
# say('### collate current environmental data for ecological niche models ###')
# say('######################################################################')
# mask_wgs84 <- raster('./Study Region & Masks/WGS84 30-arcsec Resolution/mask_wgs84.tif')
# humidForestBufferMask_utm38s <- raster('./Study Region & Masks/UTM 38S 30-m Resolution/humidForestBufferMask_utm38s.tif')
# say('elevation...')
# dirCreate('./Data/Topography - WORLDCLIM Ver 1pt4 Rel 3')
# elev <- raster::getData(name='alt', country='MDG', path='C:/ecology/!Scratch')
# names(elev) <- 'elevation_wgs84'
# writeRaster(elev, './Data/Topography - WORLDCLIM Ver 1pt4 Rel 3/elevation_wgs84', datatype='INT4S')
# say('current forest cover...')
# forests <- c('forest2000', 'forest2005', 'forest2010', 'forest2014')
# for (thisForest in forests) {
# assign(thisForest, raster(paste0('./Data/Forest - Vieilledent et al 2018/', thisForest, '.tif')))
# }
# for (thisForest in forests) {
# say(thisForest)
# x <- get(thisForest)
# beginCluster(4)
# x0 <- clusterR(x, calc, args=list(fun=naToZeroFx))
# endCluster()
# x0 <- humidForestBufferMask_utm38s * x0
# gc()
# xFract <- fasterFocal(x0, w=3, fun=mean, na.rm=TRUE, pad=TRUE, cores=3)
# gc()
# beginCluster(4)
# xProj <- projectRaster(xFract, mask_wgs84, method='bilinear')
# endCluster()
# xProj <- mask_wgs84 * xProj
# names(xProj) <- paste0(thisForest, '_wgs84')
# writeRaster(xProj, paste0('./Data/Forest - Vieilledent et al 2018/', thisForest, '_wgs84'))
# }
# say('current climate...')
# dirCreate('./Data/Climate - WORLDCLIM Ver 2 Rel 1 Jun 2016 (1970-2000)')
# for (thisBio in c(bioclims, 1, 12)) {
# rast <- raster(paste0('D:/ecology/Climate/WORLDCLIM Ver 2 Rel June 1 2016/30 arcsec 1970 to 2000/wc2.0_bio_30s_', prefix(thisBio, 2), '.tif'))
# rast <- crop(rast, mask_wgs84)
# names(rast) <- paste0('bio', prefix(thisBio, 2))
# writeRaster(rast, paste0('./Data/Climate - WORLDCLIM Ver 2 Rel 1 Jun 2016 (1970-2000)/bio', prefix(thisBio, 2)))
# }
# say('############################')
# say('### collate species data ###')
# say('############################')
# varecia <- read.csv('./Data/Varecia/02 Master__Varecia_Point_Data_2017 - Removed and Corrected Badly Georeferenced Sites and Zahamena site by EEL on 3-10-2000.csv')
# say('Adding data from Ratsimbazafy...')
# # points already in WGS84
# ratWgs84 <- read.csv('./Data/Varecia/Ratsimbazafy Sites in WGS84.csv')
# varecia <- rbind(varecia, ratWgs84)
# # points in UTM 38S
# ratUtm38s <- read.csv('./Data/Varecia/Ratsimbazafy Sites in UTM 38S.csv')
# ratUtm38sPoints <- SpatialPoints(cbind(ratUtm38s$LONG_UTM38S, ratUtm38s$LAT_UTM38S), proj4=CRS(madEaProj))
# ratUtm38sPoints <- sp::spTransform(ratUtm38sPoints, getCRS('wgs84', TRUE))
# coords <- coordinates(ratUtm38sPoints)
# coords <- coords[ , 2:1]
# coords <- as.data.frame(coords)
# names(coords) <- c('LAT_WGS84', 'LONG_WGS84')
# ratUtm38s <- cbind(ratUtm38s[ , c('Species', 'Status')], coords, ratUtm38s[ , c('Provider', 'Site', 'Date')])
# varecia <- rbind(varecia, ratUtm38s)
# say('Renaming columns...')
# names(varecia)[names(varecia) %in% 'Species'] <- 'species'
# names(varecia)[names(varecia) %in% 'Status'] <- 'presAbs'
# names(varecia)[names(varecia) %in% 'LAT_WGS84'] <- 'latWgs84'
# names(varecia)[names(varecia) %in% 'LONG_WGS84'] <- 'longWgs84'
# names(varecia)[names(varecia) %in% 'Provider'] <- 'provider'
# names(varecia)[names(varecia) %in% 'Site'] <- 'site'
# names(varecia)[names(varecia) %in% 'Date'] <- 'origDate'
# say('Parsing years...')
# varecia$year <- omnibus::yearFromDate(varecia$origDate)
# for (i in 1:nrow(varecia)) {
# if (!is.na(varecia$year[i])) {
# if (varecia$year[i] >= 9900 & varecia$year[i] <= 9916) {
# varecia$year[i] <- varecia$year[i] - 9900 + 2000
# } else if (varecia$year[i] >= 9997) {
# varecia$year[i] <- varecia$year[i] - 9900 + 1900
# }
# }
# }
# varecia$year[varecia$origYear == 'after 1989'] <- 1990
# varecia <- varecia[varecia$longWgs84 > 44, ]
# write.csv(varecia, './Data/Varecia/03 Added Ratsimbazafy and Parsed Year.csv', row.names=FALSE)
# say('############################################')
# say('### create display of occurrence records ###')
# say('############################################')
# outDir <- './Figures & Tables/Maps of Occurrences/'
# dirCreate(outDir)
# # hillshading
# elev <- raster('./Data/Topography - WORLDCLIM Ver 1pt4 Rel 3/elevation_wgs84.tif')
# slope <- terrain(elev, 'slope')
# aspect <- terrain(elev, 'aspect')
# hs <- hillShade(slope, aspect, angle=315)
# hs <- projectRaster(hs, crs=CRS(madEaProj))
# # occurrences
# varecia <- read.csv('./Data/Varecia/03 Added Ratsimbazafy and Parsed Year.csv')
# varecia <- varecia[varecia$presAbs == 1, ]
# varecia <- SpatialPointsDataFrame(varecia[ , longLat], data=varecia, proj4=getCRS('wgs84', TRUE))
# varecia <- sp::spTransform(varecia, CRS(madEaProj))
# # ancillary geo data
# load('./Study Region & Masks/UTM 38S 30-m Resolution/Eastern Humid Forest Polygon Buffer.RData')
# load('./Study Region & Masks/UTM 38S 30-m Resolution/Eastern Humid Forest Polygon.RData')
# load('./Study Region & Masks/UTM 38S 30-m Resolution/Madagascar from GADM 3.6.RData')
# load('./Data/Protected Areas/WDPA_Sept2018_MDG-shapefile-polygons-onlyTerrestrial.RData')
# # pas <- crop(pas, humidForestBuffer_utm38s)
# pch <- ifelse(varecia$species == 'Varecia variegata', 21, 24)
# bg <- ifelse(varecia$species == 'Varecia variegata', 'white', 'red')
# grays <- paste0('gray', 0:100)
# png(paste0(outDir, '/Occurrence Map for Varecia - Both Species.png'), width=600, height=1200, res=300)
# par(mar=0.5 * c(1, 1, 1, 1), oma=c(1, 1, 1, 1), lwd=0.6)
# plot(humidForest_utm38s, ann=FALSE)
# for (i in seq_along(grays)) grays[i] <- alpha(grays[i], 0.4)
# plot(madagascar_utm38s)
# plot(hs, add=TRUE, col=grays, legend=FALSE)
# plot(madagascar_utm38s, add=TRUE)
# plot(humidForest_utm38s, add=TRUE, border=alpha('chartreuse', 0.4), col=alpha('chartreuse', 0.1), lwd=1.2)
# plot(humidForestBuffer_utm38s, add=TRUE, border='darkred', col=NA, lwd=1.2)
# plot(pas, add=TRUE, col=alpha('blue', 0.20), border='blue')
# points(varecia, pch=pch, bg=bg, cex=0.5)
# legend('topleft', inset=c(0, 0.15), bty='n', legend=c('V. variegata', 'V. rubra', 'Humid forest', 'Study region', 'Protected'), pch=c(21, 24, NA, NA, NA), col=c('black', 'black', NA, NA, NA), pt.bg=c('white', 'red', NA, NA, NA), border=c(NA, NA, 'chartreuse', 'darkred', 'blue'), fill=c(NA, NA, 'darkseagreen1', NA, alpha('blue', 0.2)), cex=0.5)
# title(sub=date(), cex.sub=0.3, line=-0, xpd=NA)
# dev.off()
# say('#############################################')
# say('### create display of Madagascar with PAs ###')
# say('#############################################')
# # no occurrence records in this map!
# outDir <- './Figures & Tables/'
# dirCreate(outDir)
# # hillshading
# elev <- raster('./Data/Topography - WORLDCLIM Ver 1pt4 Rel 3/elevation_wgs84.tif')
# slope <- terrain(elev, 'slope')
# aspect <- terrain(elev, 'aspect')
# hs <- hillShade(slope, aspect, angle=315)
# hs <- projectRaster(hs, crs=CRS(madEaProj))
# # ancillary geo data
# load('./Study Region & Masks/UTM 38S 30-m Resolution/Madagascar from GADM 3.6.RData')
# load('./Data/Protected Areas/WDPA_Sept2018_MDG-shapefile-polygons-onlyTerrestrial.RData')
# grays <- paste0('gray', 0:100)
# png(paste0(outDir, '/Madagascar with PAs.png'), width=800, height=1200, res=300)
# par(mar=0.1 * c(1, 1, 1, 1), oma=0.1 * c(1, 1, 1, 1))
# for (i in seq_along(grays)) grays[i] <- alpha(grays[i], 0.4)
# plot(madagascar_utm38s, border=NA, ann=FALSE)
# plot(hs, col=grays, legend=FALSE)
# plot(pas, add=TRUE, col=alpha('blue', 0.45), border=NA)
# title(sub=date(), cex.sub=0.3, line=0, xpd=NA)
# dev.off()
# say('########################################################')
# say('### match occurrence records with environmental data ###')
# say('########################################################')
# varecia <- read.csv('./Data/Varecia/03 Added Ratsimbazafy and Parsed Year.csv')
# # predictors in WGS84 30 arcsec resolution
# preds_wgs84 <- stackMadCurrent_wgs84()
# varecia_wgs84 <- SpatialPoints(varecia[ , longLat], getCRS('wgs84', TRUE))
# env <- raster::extract(preds_wgs84, varecia_wgs84)
# env <- as.data.frame(env)
# varecia <- cbind(varecia, env)
# # predictors in UTM38S 30-m resolution
# preds_utm38s <- stackMadCurrent_utm38s()
# varecia_utm38s <- sp::spTransform(varecia_wgs84, CRS(madEaProj))
# env <- raster::extract(preds_utm38s, varecia_utm38s)
# env <- as.data.frame(env)
# varecia <- cbind(varecia, env)
# coords <- coordinates(varecia_utm38s)
# coords <- as.data.frame(coords)
# names(coords) <- c('longUtm38s', 'latUtm38s')
# varecia <- insertCol(coords, into=varecia, at='longWgs84', before=FALSE)
# varecia$forest2000_utm38s[is.na(varecia$forest2000_utm38s)] <- 0
# varecia$forest2005_utm38s[is.na(varecia$forest2005_utm38s)] <- 0
# varecia$forest2010_utm38s[is.na(varecia$forest2010_utm38s)] <- 0
# varecia$forest2014_utm38s[is.na(varecia$forest2014_utm38s)] <- 0
# varecia$forestFragClass2000_utm38s <- as.factor(varecia$forestFragClass2000_utm38s)
# varecia$forestFragClass2005_utm38s <- as.factor(varecia$forestFragClass2005_utm38s)
# varecia$forestFragClass2010_utm38s <- as.factor(varecia$forestFragClass2010_utm38s)
# varecia$forestFragClass2014_utm38s <- as.factor(varecia$forestFragClass2014_utm38s)
# ### fil NAs: for sites in water use values from nearest terrestrial cell
# ########################################################################
# this <- which(varecia$species == 'Varecia rubra' & round(varecia$latWgs84, 5) == -15.67847 & varecia$longWgs84 == 49.9579 & varecia$provider == 'Borgerson' & varecia$origDate == '2011-2012')
# new <- orig <- varecia[this, ]
# new$longWgs84 <- 49.958594861
# new <- raster::extract(preds_wgs84, new[ , longLat])
# new <- as.data.frame(new)
# for (name in names(new)) if (is.na(orig[ , name])) orig[ , name] <- new[ , name]
# varecia[this, ] <- orig
# this <- which(varecia$species == 'Varecia rubra' & round(varecia$latWgs84, 5) == -15.67392 & round(varecia$longWgs84, 5) == 49.95717 & varecia$provider == 'Borgerson' & varecia$origDate == '2011-2012')
# new <- orig <- varecia[this, ]
# new$longWgs84 <- 49.958594861
# new <- raster::extract(preds_wgs84, new[ , longLat])
# new <- as.data.frame(new)
# for (name in names(new)) if (is.na(orig[ , name])) orig[ , name] <- new[ , name]
# varecia[this, ] <- orig
# this <- which(varecia$species == 'Varecia variegata' & round(varecia$latWgs84, 5) == -15.49833 & round(varecia$longWgs84, 5) == 49.76567 & varecia$provider == 'EEL' & varecia$origDate == '10/12/2004')
# new <- orig <- varecia[this, ]
# new$longWgs84 <- 49.766970898
# new <- raster::extract(preds_wgs84, new[ , longLat])
# new <- as.data.frame(new)
# for (name in names(new)) if (is.na(orig[ , name])) orig[ , name] <- new[ , name]
# varecia[this, ] <- orig
# this <- which(varecia$species == 'Varecia variegata' & round(varecia$latWgs84, 5) == -15.49308 & round(varecia$longWgs84, 5) == 49.76058 & varecia$provider == 'EEL' & varecia$origDate == '10/16/2004')
# new <- orig <- varecia[this, ]
# new$latWgs84 <- -15.491430824
# new <- raster::extract(preds_wgs84, new[ , longLat])
# new <- as.data.frame(new)
# for (name in names(new)) if (is.na(orig[ , name])) orig[ , name] <- new[ , name]
# varecia[this, ] <- orig
# write.csv(varecia, './Data/Varecia/04 Varecia Occurrences Matched with Environmental Data.csv', row.names=FALSE)
# say('###############################')
# say('### select background sites ###')
# say('###############################')
# elev <- raster('./Data/Topography - WORLDCLIM Ver 1pt4 Rel 3/elevation_wgs84.tif')
# sites <- randomPoints(elev, 11000)
# sites <- as.data.frame(sites)
# names(sites) <- longLat
# sites_wgs84 <- SpatialPoints(sites, getCRS('wgs84', TRUE))
# # predictors in WGS84 30 arcsec resolution
# preds_wgs84 <- stackMadCurrent_wgs84()
# env <- raster::extract(preds_wgs84, sites_wgs84)
# env <- as.data.frame(env)
# env$forest2000_wgs84[is.na(env$forest2000_wgs84)] <- 0
# env$forest2005_wgs84[is.na(env$forest2005_wgs84)] <- 0
# env$forest2010_wgs84[is.na(env$forest2010_wgs84)] <- 0
# env$forest2014_wgs84[is.na(env$forest2014_wgs84)] <- 0
# bg <- cbind(sites, env)
# # predictors in UTM38S 30-m resolution
# preds_utm38s <- stackMadCurrent_utm38s()
# sites_utm38s <- sp::spTransform(sites_wgs84, CRS(madEaProj))
# env <- raster::extract(preds_utm38s, sites_utm38s)
# env <- as.data.frame(env)
# bg <- cbind(bg, env)
# coords <- coordinates(sites_utm38s)
# coords <- as.data.frame(coords)
# names(coords) <- c('longUtm38s', 'latUtm38s')
# bg <- insertCol(coords, into=bg, at='longWgs84', before=FALSE)
# bg$forest2000_utm38s[is.na(bg$forest2000_utm38s)] <- 0
# bg$forest2005_utm38s[is.na(bg$forest2005_utm38s)] <- 0
# bg$forest2010_utm38s[is.na(bg$forest2010_utm38s)] <- 0
# bg$forest2014_utm38s[is.na(bg$forest2014_utm38s)] <- 0
# bg$forestFragClass2000_utm38s[is.na(bg$forestFragClass2000_utm38s)] <- 0
# bg$forestFragClass2005_utm38s[is.na(bg$forestFragClass2005_utm38s)] <- 0
# bg$forestFragClass2010_utm38s[is.na(bg$forestFragClass2010_utm38s)] <- 0
# bg$forestFragClass2014_utm38s[is.na(bg$forestFragClass2014_utm38s)] <- 0
# bg$forestFragClass2000_utm38s <- as.factor(bg$forestFragClass2000_utm38s)
# bg$forestFragClass2005_utm38s <- as.factor(bg$forestFragClass2005_utm38s)
# bg$forestFragClass2010_utm38s <- as.factor(bg$forestFragClass2010_utm38s)
# bg$forestFragClass2014_utm38s <- as.factor(bg$forestFragClass2014_utm38s)
# bg$forestFragConnect2000_utm38s[is.na(bg$forestFragConnect2000_utm38s)] <- 0
# bg$forestFragConnect2005_utm38s[is.na(bg$forestFragConnect2005_utm38s)] <- 0
# bg$forestFragConnect2010_utm38s[is.na(bg$forestFragConnect2010_utm38s)] <- 0
# bg$forestFragConnect2014_utm38s[is.na(bg$forestFragConnect2014_utm38s)] <- 0
# bg$forestFragDensity2000_utm38s[is.na(bg$forestFragDensity2000_utm38s)] <- 0
# bg$forestFragDensity2005_utm38s[is.na(bg$forestFragDensity2005_utm38s)] <- 0
# bg$forestFragDensity2010_utm38s[is.na(bg$forestFragDensity2010_utm38s)] <- 0
# bg$forestFragDensity2014_utm38s[is.na(bg$forestFragDensity2014_utm38s)] <- 0
# # remove rows with any NAs
# nas <- naRows(bg)
# if (length(bg) > 0) bg <- bg[-nas, ]
# bg <- bg[1:10000, ]
# rownames(bg) <- 1:10000
# dirCreate('./Ecological Niche Models')
# save(bg, file='./Ecological Niche Models/Random Background Sites from across Madagascar with Current Environmental Data.RData')
# say('##############################################################')
# say('### calculate spatial autocorrelation between survey sites ###')
# say('##############################################################')
# say('I want to use inverse-p weighting applied to survey sites to correct for spatial sampling bias. I will assume that two survey sites at the exact same location each have a weight of 1/2, three each have a weight of 1/3, and so on. At the other end of the spectrum survey sites that are far enough away should each have a weight of 1. I will define "far enough away" as the distance at which the proportion of pairwise observed distances falls below the upper 95th quantile of the distribution of pairwise distances from randomly located sites (one-tail). I will draw a number of randomly located sites in each iteration so it is equal to the total number of survey sites.', breaks=80)
# varecia <- read.csv('./Data/Varecia/04 Varecia Occurrences Matched with Environmental Data.csv')
# load('./Ecological Niche Models/Random Background Sites from across Madagascar with Current Environmental Data.RData')
# # remove duplicates (often survey sites for one species are also counted as surveys for the other)
# dups <- integer()
# for (i in 1:nrow(varecia)) {
# this <- varecia[i, ]
# matches <- which(this$longWgs84 %==% varecia$longWgs84 &
# this$latWgs84 %==% varecia$latWgs84 &
# this$provider == varecia$provider &
# this$origDate == varecia$origDate
# )
# matches <- matches[-which(matches <= i)]
# dups <- c(dups, matches)
# }
# vareciaNoDups <- varecia[-dups, ]
# # observed inter-point distances
# vareciaNoDups <- SpatialPoints(vareciaNoDups[ , longLat], getCRS('wgs84', TRUE))
# vareciaDists <- distm(vareciaNoDups)
# vareciaDists <- c(vareciaDists)
# vareciaDists <- vareciaDists / 1000
# distStep <- 20
# maxUpperDist <- distStep * ceiling(max(vareciaDists, na.rm=TRUE) / distStep)
# breaks <- matrix(
# c(
# seq(0, maxUpperDist, by=0.5 * distStep),
# seq(0, maxUpperDist, by=0.5 * distStep) + distStep
# ),
# ncol=2,
# byrow=FALSE
# )
# distDistrib <- histOverlap(vareciaDists, breaks=breaks, right=FALSE, graph=FALSE)
# # generate random inter-point distances using same number of points as observed
# randDists <- pointDist(bg[ , longLat])
# randDists <- randDists / 1000
# randIndex <- 1:nrow(bg)
# # iterate
# for (i in 1:100) {
# say(i)
# theseRand <- randDists[sample(randIndex, length(vareciaNoDups), replace=TRUE), ]
# theseRand <- c(theseRand)
# randDistDistrib <- histOverlap(theseRand, breaks=breaks, right=FALSE, graph=FALSE)
# distDistrib <- cbind(distDistrib, randDistDistrib[ , 'proportion'])
# colnames(distDistrib)[ncol(distDistrib)] <- paste0('rand', prefix(i, 3))
# }
# # plot
# dirCreate('./Figures & Tables/Spatial Autocorrelation between Survey Sites')
# png('./Figures & Tables/Spatial Autocorrelation between Survey Sites/Comparison of Distances between Survey Sites and Random Sites.png', width=1200, height=600, res=150)
# ylim <- c(0, max(c(distDistrib[ , 'proportion'], distDistrib[ , grepl(colnames(distDistrib), pattern='rand')])))
# ats <- rowMeans(distDistrib[ , 1:2])
# plot(ats, ats, ylim=ylim, col='white', main='Distances between Survey Sites and Random Sites', xlab='Distance (km)', ylab='Proportion of Sites')
# sigSoFar <- TRUE # flips on first time observed proportion of distances falls in 95% CI of randomized distribution of ranges
# countArrows <- 0
# for (i in 1:nrow(distDistrib)) {
# at <- ats[i]
# randProp <- c(distDistrib[i , grepl(colnames(distDistrib), pattern='rand')])
# randPropQuants <- quantile(randProp, c(0.05, 0.5, 0.95))
# points(at, randPropQuants[3], pch=5, col='blue')
# obsProp <- distDistrib[i , 'proportion']
# insig <- (obsProp <= randPropQuants[3])
# pch <- if (insig) { 1 } else { 16 }
# points(at, obsProp, pch=pch, cex=1)
# if (insig & sigSoFar) {
# countArrows <- countArrows + 1
# if (countArrows == 1) {
# charDist <- at
# arrows(x0=at, x1=at, y0=-0.19 * ylim[2], y1=-0.0025, col='red', angle=15, length=0.1, xpd=NA, lwd=1.5)
# }
# }
# }
# legend('topright', inset=0.01, bty='n', legend=c('Observed (not significant)', 'Observed (significant)', 'Random (Upper 95% CI)'), pch=c(1, 16, 5), col=c('black', 'black', 'blue'))
# dev.off()
# out <- data.frame(characteristicDistanceOfSurveys_km = charDist)
# write.csv(out, './Figures & Tables/Spatial Autocorrelation between Survey Sites/Characteristic Distance at which Presence of Survey Sites are No Longer Correlated.csv', row.names=FALSE)
# say('##################################################################')
# say('### calculate survey site weights to correct for sampling bias ###')
# say('##################################################################')
# varecia <- read.csv('./Data/Varecia/04 Varecia Occurrences Matched with Environmental Data.csv')
# charDist <- read.csv('./Figures & Tables/Spatial Autocorrelation between Survey Sites/Characteristic Distance at which Presence of Survey Sites are No Longer Correlated.csv')
# charDist <- charDist$characteristicDistanceOfSurveys_km
# # calculate pairwise distances
# vareciaDists <- pointDist(varecia[ , longLat])
# diag(vareciaDists) <- NA
# # calculate weights
# weight <- rep(NA, nrow(varecia))
# for (i in seq_along(weight)) {
# # get only sites within characteristic distance that are for this species
# neighIndex <- which(vareciaDists[i , ] < charDist & varecia$species[i] == varecia$species)
# neighDists <- vareciaDists[i, neighIndex]
# if (length(neighDists) == 0) {
# weight[i] <- 1
# } else {
# numNeighs <- length(neighDists)
# effectiveNeighs <- sum(1 - (charDist - neighDists) / charDist)
# weight[i] <- (1 + effectiveNeighs) / (1 + numNeighs)
# }
# }
# varecia$weight <- weight
# write.csv(varecia, './Data/Varecia/05 Varecia Occurrences with Weights Based on Neighbor Proximity.csv', row.names=FALSE)
# say('#######################################################')
# say('### collate occurrence records and background sites ###')
# say('#######################################################')
# load('./Ecological Niche Models/Random Background Sites from across Madagascar with Current Environmental Data.RData')
# varecia <- read.csv('./Data/Varecia/05 Varecia Occurrences with Weights Based on Neighbor Proximity.csv')
# bg$weight <- 1
# preds_wgs84 <- stackMadCurrent_wgs84()
# preds_utm38s <- stackMadCurrent_utm38s()
# for (taxon in taxa) {
# say(taxon)
# ### assign geographic folds to presences
# pres <- if (taxon == 'genus') {
# varecia[varecia$presAbs == 1, ]
# } else {
# varecia[varecia$species == paste('Varecia', taxon) & varecia$presAbs == 1, ]
# }
# if (taxon == 'genus') {
# presFold <- rep(NA, nrow(pres))
# presFold[pres$latWgs84 > -16.06] <- 1
# presFold[pres$latWgs84 <= -16.06 & pres$latWgs84 > -19.61] <- 2
# presFold[pres$latWgs84 <= -19.61] <- 3
# } else if (taxon == 'variegata') {
# presFold <- rep(NA, nrow(pres))
# presFold[pres$latWgs84 > -17.20] <- 1
# presFold[pres$latWgs84 <= -17.20 & pres$latWgs84 > -19.67] <- 2
# presFold[pres$latWgs84 <= -19.67] <- 3
# } else if (taxon == 'rubra') {
# presFold <- geoFold(pres[ , longLat], k=3, minIn=15, swaps=0)
# }
# ### assign background sites to fold of nearest presence site
# dists <- pointDist(pres[ , longLat], bg[ , longLat])
# closestSiteToBg <- apply(dists, 2, which.min)
# bgFold <- presFold[closestSiteToBg]
# foldName <- paste0('fold', capIt(taxon))
# pres$DUMMY <- presFold
# names(pres)[ncol(pres)] <- foldName
# bg$DUMMY <- bgFold
# names(bg)[ncol(bg)] <- foldName
# bg$year <- NA
# # combine presences and background sites
# presBg <- c(rep(1, nrow(pres)), rep(0, nrow(bg)))
# taxonData <- rbind(
# pres[ , c('longWgs84', 'latWgs84', 'year', names(preds_wgs84), names(preds_utm38s), 'weight', foldName)],
# bg[ , c('longWgs84', 'latWgs84', 'year', names(preds_wgs84), names(preds_utm38s), 'weight', foldName)]
# )
# taxonData <- cbind(presBg, taxonData)
# ### define "forestCover" and "forestFragClass" variables as forest cover or fragmentation class of year closest to the year of survey
# # use 2005 for background sites and survey sites with no date
# taxonData$forestCover_wgs84 <- NA
# taxonData$forestCover_utm38s <- NA
# taxonData$forestFragClass_utm38s <- NA
# forestYears <- c(2000, 2005, 2010, 2014)
# # assign forest of survey sites WITH census year
# yearNotNa <- which(!is.na(taxonData$year))
# if (length(yearNotNa) > 0) {
# for (thisRecord in yearNotNa) {
# yearDiff <- which.min(abs(forestYears - taxonData$year[thisRecord]))
# nearestYear <- forestYears[yearDiff]
# taxonData$forestCover_wgs84[thisRecord] <- taxonData[thisRecord, paste0('forest', nearestYear, '_wgs84')]
# taxonData$forestCover_utm38s[thisRecord] <- taxonData[thisRecord, paste0('forest', nearestYear, '_utm38s')]
# taxonData$forestFragClass_utm38s[thisRecord] <- taxonData[thisRecord, paste0('forestFragClass', nearestYear, '_utm38s')]
# }
# }
# # assign forest of survey sites WITHOUT census year
# medianYear <- median(taxonData$year, na.rm=TRUE)
# yearDiff <- which.min(abs(forestYears - medianYear))
# nearestYear <- forestYears[yearDiff]
# yearNa <- which(is.na(taxonData$year))
# taxonData$forestCover_wgs84[yearNa] <- taxonData[yearNa , paste0('forest', nearestYear, '_wgs84')]
# taxonData$forestCover_utm38s[yearNa] <- taxonData[yearNa , paste0('forest', nearestYear, '_utm38s')]
# taxonData$forestFragClass_utm38s[yearNa] <- taxonData[yearNa , paste0('forestFragClass', nearestYear, '_utm38s')]
# save(taxonData, file=paste0('./Ecological Niche Models/Collated Presence and Background Point Data for Varecia ', toupper(taxon), '.RData'))
# } # next taxon
# say('#####################################')
# say('### train ecological niche models ###')
# say('#####################################')
# for (taxon in taxa) {
# say(taxon, level=1)
# load(paste0('./Ecological Niche Models/Collated Presence and Background Point Data for Varecia ', toupper(taxon), '.RData'))
# taxonData$forestFragClass_utm38s <- as.factor(taxonData$forestFragClass_utm38s)
# taxonData[ , paste0('bio', prefix(bioclims, 2))] <- apply(taxonData[ , paste0('bio', prefix(bioclims, 2))], 2, stretchMinMax)
# foldName <- paste0('fold', capIt(taxon))
# ### by geo-fold
# ###############
# dirCreate('./Ecological Niche Models')
# for (k in 1:3) {
# say('k = ', k, ' =========================================================')
# trainData <- taxonData[taxonData[ , foldName] != k, ]
# trainWeight <- balanceWeights(trainData)
# model <- trainGlm(resp='presBg', preds=predictors, data=trainData, w=trainWeight, verboten=c('I(forestFragClass_utm38s^2)'), method='brglmFit', verbose=TRUE)
# save(model, file=paste0('./Ecological Niche Models/GLM Niche Model for Varecia ', taxon, ' for fold ', k, '.RData'))
# say('', post=2)
# ### NS
# model <- trainNs(data=trainData, resp='presBg', preds=predictors, w=trainWeight, verbose=TRUE)
# save(model, file=paste0('./Ecological Niche Models/NS Niche Model for Varecia ', taxon, ' for fold ', k, '.RData'))
# say('', post=4)
# }
# ### all-sites models
# ####################
# trainData <- taxonData
# trainWeight <- balanceWeights(trainData)