-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMNE.R
283 lines (230 loc) · 9.65 KB
/
MNE.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
#
# This code was developed by
# - Juan M. Barrrios [email protected]
# - Angela P. Cuervo-Robayo [email protected]
#
library("rgdal", quietly = TRUE)
library("fuzzySim", quietly = TRUE)
library("ENMeval", quietly = TRUE)
library("ROCR", quietly = TRUE)
library("magrittr", quietly = TRUE)
library("readr", quietly = TRUE)
library("dplyr", quietly = TRUE)
library("tools", quietly = TRUE)
library("raster", quietly = TRUE)
set.seed(1)
####DataFormating ####
# Regionalization shapefile folder
shapePath <- '../data/shapes/'
shapeLayer <- "wwf_terr_ecos_a"
regionalizacion <- rgdal::readOGR(shapePath, shapeLayer)
# Raster covariables folder
covarDataFolder <- '../data/covar_rasters'
# Raster covariables folder where the model will be projected
# IMPORTANT: The raster files on `covarDataFolder` and `covarAOIDataFolder`
# must have the same name in order to the model can be evaluated.
covarAOIDataFolder <- '../data/covar_raster_PSC'
args = commandArgs(trailingOnly = TRUE)
if (length(args) == 0) {
stop("Please enter a single parameter (input file).\n", call. = FALSE)
} else if (length(args) == 1) {
print(paste("Processing model for file ", args[1]))
} else {
stop("Single parameter is needed (input file).\n", call. = FALSE)
}
inputDataFile <- args[1]
outputFolder <- inputDataFile %>%
basename %>%
file_path_sans_ext
if (!dir.exists(outputFolder)) {
dir.create(outputFolder, recursive = TRUE)
}
####Cleaning duplicate records on a cell####
crs.wgs84 <- sp::CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
occsData <- readr::read_csv(inputDataFile)
sp::coordinates(occsData) <- c("Dec_Long", "Dec_Lat")
sp::proj4string(occsData) <- crs.wgs84
occsData <- sp::remove.duplicates(occsData, zero=0.00833333333)
write.csv(cbind(occsData@data, coordinates(occsData)),
file = file.path(outputFolder, "data_wo_duplicates.csv"),
row.names = FALSE)
#### ENVIROMENTAL VARIABLES####
covarFileList <- list_files_with_exts(covarDataFolder, "tif")
enviromentalVariables <- raster::stack(covarFileList)
covarAOIFileList <- list_files_with_exts(covarAOIDataFolder, "tif")
enviromentalVariablesAOI <- raster::stack(covarAOIFileList)
#### VARIABLES + PRESENCIAS####
covarData <- raster::extract(enviromentalVariables, occsData)
covarData <- cbind(occsData, covarData)
completeDataCases <- covarData@data %>%
dplyr::select_(.dots=names(enviromentalVariables)) %>%
complete.cases
covarData <- covarData[completeDataCases, ]
####SELECCION DE VARIABLES####
speciesCol <- match("Presence", names(occsData))
varCols <- ncol(occsData) + 1
correlacion <- corSelect(
data = covarData@data,
sp.cols = speciesCol,
var.cols = varCols:ncol(covarData),
cor.thresh = 0.8,
use = "pairwise.complete.obs"
)
select_var <- correlacion$selected.vars
write(select_var, file = file.path(outputFolder, "selected_variables.txt"))
selectedVariables <- enviromentalVariables[[select_var]]
selectedVariablesAOI <- enviromentalVariablesAOI[[select_var]]
# Selects the M of the species, base on Olson´s ecoregions
# Download: https://www.worldwildlife.org/publications/terrestrial-ecoregions-of-the-world
# Intersects the occurrence data with polygons
ecoregionsOfInterest <- sp::over(occsData, regionalizacion) %>%
filter(!is.na(ECO_ID))
idsEcoRegions <- unique(ecoregionsOfInterest$ECO_ID)
polygonsOfInterest <- regionalizacion[regionalizacion$ECO_ID %in% idsEcoRegions, ]
writeOGR(polygonsOfInterest, layer = 'ecoregionsOI', outputFolder, driver="ESRI Shapefile")
# Mask rasters with ecoregions of interest
selectedVariablesCrop <- raster::crop(selectedVariables, polygonsOfInterest)
env <- raster::mask(selectedVariablesCrop,
polygonsOfInterest) #Species variables delimited by M
writeRaster(env,
file.path(outputFolder, "covars.tif"),
bylayer = T, suffix='names',
overwrite = TRUE)
#### Calibration ####
# Divides your data into trainining and test data sets. 70/30 %
sampleDataPoints <- sample.int(
nrow(covarData),
size = floor(0.7*nrow(covarData))
)
selectedValues <- rep(0, nrow(covarData)) %>% inset(sampleDataPoints, 1)
covarData$isTrain <- selectedValues
write.csv(cbind(covarData@data, coordinates(covarData)), file.path(outputFolder, "speciesCovarDB.csv"),
row.names = FALSE)
# MAXENT calibration
# We used ENMeval package to estimate optimal model complexity (Muscarrella et al. 2014)
# Modeling process, first separate the calibration and validation data
occsCalibracion <- covarData %>%
as.data.frame() %>%
dplyr::filter(isTrain == 1) %>%
dplyr::select(Dec_Long, Dec_Lat)
occsValidacion <- covarData %>%
as.data.frame() %>%
dplyr::filter(isTrain == 0) %>%
dplyr::select(Dec_Long, Dec_Lat)
# Background
bg.df <- dismo::randomPoints(env[[1]], n = 10000) %>% as.data.frame()
#Divide backgeound into train and test
sample.bg <- sample.int(
nrow(bg.df),
size = floor(0.7*nrow(bg.df))
)
selectedValues.bg <- rep(0, nrow(bg.df)) %>% inset(sample.bg, 1)
bg.df$isTrain <- selectedValues.bg
write.csv(bg.df, file = file.path(outputFolder, "background_points.csv"),
row.names = FALSE)
#training background
bg.df.cal <- bg.df %>%
dplyr::filter(isTrain == 1) %>%
dplyr::select(x, y)
# ENMeval
sp.models <- ENMevaluate(occsCalibracion, env, bg.df.cal, RMvalues = seq(0.5, 4, 0.5),
fc = c("L", "LQ", "H", "LQH", "LQHP", "LQHPT"),
method = "randomkfold", kfolds = 2, bin.output = TRUE,
parallel = TRUE, numCores = parallel::detectCores()-1,
updateProgress = TRUE)
resultados_enmeval <- sp.models@results
write.csv(resultados_enmeval,
file = file.path(outputFolder, "enmeval_results.csv"),
row.names = FALSE)
# delta_aic <- which(resultados_enmeval$delta.AICc == 0)
modelsAIC0 <- resultados_enmeval %>%
mutate(index = rownames(resultados_enmeval)) %>%
filter(delta.AICc == 0) %>%
select(index, settings) %>%
mutate(index = as.numeric(index), settings = as.character(settings))
# save species niche (raw output) model over raster
saveRasterWithSettings <- function(models, predictions, prefix) {
raster::writeRaster(predictions[[models["settings"]]],
file.path(outputFolder, paste0(prefix,
models["settings"],
".tif")),
overwrite = TRUE)
}
apply(modelsAIC0, 1, saveRasterWithSettings,
predictions = sp.models@predictions, prefix = "ENM_prediction_M_raw_")
#### Projection ####
# predict choicemodel over current climate variables
predictAndSave <- function(model, models, data, prefix, occs) {
choicedModel <- models[[as.integer(model["index"])]]
predictions <- dismo::predict(choicedModel, data)
raster::writeRaster(predictions,
file.path(outputFolder, paste0(prefix,
"log_",
model["settings"],
".tif")),
overwrite = TRUE)
#Threshold prediction using minimum traning (min) and 10 percentil (q10) values
occsValues <- raster::extract(predictions, occs)
minValOcc <- min(occsValues, na.rm = TRUE)
raster::writeRaster(reclassify(predictions,
c(-Inf, minValOcc, 0, minValOcc, Inf, 1)),
file.path(outputFolder, paste0(prefix,
"bin_min_",
model["settings"],
".tif")),
overwrite = TRUE)
q10ValOcc <- quantile(occsValues, 0.1, na.rm = TRUE)
raster::writeRaster(reclassify(predictions,
c(-Inf, q10ValOcc, 0, q10ValOcc, Inf, 1)),
file.path(outputFolder, paste0(prefix,
"bin_q10_",
model["settings"],
".tif")),
overwrite = TRUE)
}
apply(modelsAIC0, 1, predictAndSave,
models = sp.models@models, data = env, prefix = "ENM_prediction_M_",
occs = occsCalibracion)
apply(modelsAIC0, 1, predictAndSave,
models = sp.models@models, data = selectedVariablesAOI, prefix = "ENM_",
occs = occsCalibracion)
####ENMTest####
#Threslhold independent
#AUC
aucCalculator <- function(prediction, occs, bgPoints) {
data <- rbind(occs, setNames(bgPoints, names(occs)))
labels <- c(rep(1, nrow(occs)),
rep(0, nrow(bgPoints)))
scores <- raster::extract(prediction, data)
pred <- ROCR::prediction(scores, labels)
# perf <- performance(pred, "tpr", "fpr")
auc <- performance(pred, "auc")@y.values[[1]]
return(auc)
}
aucStatistcs <- function(model, models, env, occs, bgPoints) {
result <- apply(model, 1, function(x, models, env, occs, bgPoints){
choicedModel <- models[[as.integer(x["index"])]]
prediction <- dismo::predict(choicedModel, env)
auc <- aucCalculator(prediction, occs, bgPoints)
return(c(x["settings"], auc))
},
models = models,
env = env,
occs = occs,
bgPoints = bgPoints)
result <- data.frame(
matrix(unlist(result), nrow = nrow(model), byrow = TRUE),
stringsAsFactors = FALSE
)
names(result) <- c("settings", "AUC")
result <- result %>% mutate(AUC = as.numeric(AUC))
return(result)
}
# Testing background
bg.df.test <- bg.df %>%
dplyr::filter(isTrain == 0) %>%
dplyr::select(x, y)
resultsAUC <- aucStatistcs(modelsAIC0, sp.models@models, env, occsValidacion, bg.df.test)
write.csv(resultsAUC,
file = file.path(outputFolder, "data_auc.csv"),
row.names = FALSE)