content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# run_wallace.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title Run \emph{Wallace} Application
#' @description This function runs the \emph{Wallace} application in the user's
#' default web browser.
#' @param launch.browser Whether or not to launch a new browser window.
#' @param port The port for the shiny server to listen on. Defaults to a
#' random available port.
#' @note Please see the official website (\url{https://wallaceecomod.github.io/})
#' for more details. If you have questions about the application,
#' please participate in the \href{https://groups.google.com/forum/#!forum/wallaceecomod}{Google Group},
#' or email the team directly: \email{wallaceEcoMod@@gmail.com}.
#'
#' @examples
#' if(interactive()) {
#' run_wallace()
#' }
#' @author Jamie Kass <jkass@@gradcenter.cuny.edu>
#' @author Gonzalo E. Pinilla-Buitrago <gepinillab@@gmail.com>
#' @export
run_wallace <- function(launch.browser = TRUE, port = getOption("shiny.port")) {
app_path <- system.file("shiny", package = "wallace")
knitcitations::cleanbib()
options("citation_format" = "pandoc")
preexisting_objects <- ls(envir = .GlobalEnv)
on.exit(rm(list = setdiff(ls(envir = .GlobalEnv), preexisting_objects), envir = .GlobalEnv))
return(shiny::runApp(app_path, launch.browser = launch.browser, port = port))
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/run_wallace.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# vis_bioclimPlot.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title vis_bioclimPlot Visualize bivariate plot of BIOCLIM model
#' @description
#' This functions creates a bivariate plot with two of the environmental
#' variables used for modeling as x and y axes and occurrences as observations.
#'
#' @details
#' This is a bivariate plot with x and y axes representing two of the
#' environmental layers used for modeling (user selected although 1 and 2 as
#' default). Occurrences used for modeling are shown with differential
#' visualization if they are outside of the selected percentile distribution
#' (for any variable). Plot also includes a rectangle representing the
#' bivariate bioclimatic envelope according to a provided percentile.
#'
#' @param x bioclim model including values for each environmental layer at
#' each occurrence point
#' @param a numeric Environmental layer to be used as x axis. Default is
#' layer 1.
#' @param b numeric. Environmental layer to be used as x axis. Default is
#' layer 2.
#' @param p numeric. (0-1) percentile distribution to be used for plotting
#' envelope and showing points outside of envelope. Default is 0.9
#' @examples
#' \dontrun{
#' envs <- envs_userEnvs(rasPath = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$", full.names = TRUE),
#' rasName = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$", full.names = FALSE))
#' occs <- read.csv(system.file("extdata/Bassaricyon_alleni.csv",
#' package = "wallace"))
#' bg <- read.csv(system.file("extdata/Bassaricyon_alleni_bgPoints.csv",
#' package = "wallace"))
#' partblock <- part_partitionOccs(occs, bg, method = 'block')
#' m <- model_bioclim(occs, bg, partblock, envs)
#' bioclimPlot <- vis_bioclimPlot(x = m@@models$bioclim,
#' a = 1, b = 2, p = 1)
#' }
#'
#' @return A bivariate plot of environmental values for occurrences. Includes a
#' blue rectangle representing the bioclimatic envelope given p. Occurrences
#' that are inside the envelope for all layers (included those not plotted)
#' are shown as green circles and those outside of the envelope for one ore
#' more variables are plotted as orange triangles.
#' @author Jamie Kass <jkass@@gradcenter.cuny.edu>
#' @author Gonzalo E. Pinilla-Buitrago <gepinillab@@gmail.com>
# @note
#' @seealso
#'\code{\link{model_bioclim}} \code{\link[ENMeval]{ENMevaluate}}
#' @export
vis_bioclimPlot <- function(x, a = 1, b = 2, p = 0.9) {
d <- x@presence
myquantile <- function(x, p) {
p <- min(1, max(0, p))
x <- sort(as.vector(stats::na.omit(x)))
if (p == 0) return(x[1])
if (p == 1) return(x[length(x)])
i = (length(x)-1) * p + 1
ti <- trunc(i)
below = x[ti]
above = x[ti+1]
below + (above-below)*(i-ti)
}
p <- min(1, max(0, p))
if (p > 0.5) p <- 1 - p
p <- p / 2
prd <- dismo::predict(x, d, useC = FALSE)
i <- prd > p & prd < (1-p)
plot(d[,a], d[,b], xlab=colnames(d)[a], ylab=colnames(d)[b], cex=0)
type=6
x1 <- stats::quantile(d[,a], probs=p, type=type)
x2 <- stats::quantile(d[,a], probs=1-p, type=type)
y1 <- stats::quantile(d[,b], probs=p, type=type)
y2 <- stats::quantile(d[,b], probs=1-p, type=type)
graphics::polygon(rbind(c(x1,y1), c(x1,y2), c(x2,y2), c(x2,y1), c(x1,y1)),
border = '#0072B2', lwd = 2)
graphics::points(d[i,a], d[i,b], xlab = colnames(x)[a], ylab = colnames(x)[b],
col = '#009E73', pch = 16)
graphics::points(d[!i,a], d[!i,b], col = "#D55E00", pch = 17)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/vis_bioclimPlot.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# wallace-package.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @name wallace-package
#' @aliases wallace
#' @aliases wallace-package
#' @docType package
#' @title \emph{Wallace}: A modular platform for reproducible ecological modeling
#' @description \emph{Wallace} is a \code{shiny} app that guides users through a complete
#' species niche/distributional modeling analysis, from the acquisition of
#' species occurrence and environmental data to visualizing model predictions
#' on an interactive map (\code{rleaflet}), thus bundling complex workflows
#' into a single, streamlined GUI interface. New functionality, in the form of
#' modules, can be added to \emph{Wallace} via contributions from the user
#' community. In addition, executable session code (R Markdown format) can
#' be downloaded to share with others or use as supplementary information
#' for scientific papers and reports. The application is run via the
#' function \code{\link{run_wallace}}.
#'
#' @details Please see the official website (\url{https://wallaceecomod.github.io/}) for
#' more details. If you have questions about the application, please participate
#' in the \href{https://groups.google.com/forum/#!forum/wallaceecomod}{Google Group},
#' or email the team directly: \email{wallaceEcoMod@@gmail.com}.
#'
#' @import leaflet shiny
#' @importFrom magrittr "%>%"
NULL
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/wallace-package.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_area.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title xfer_area Transfer model to a new area
#' @description Function transfers the model generated in previous components to
#' a new user drawn area.
#'
#' @details
#' This functions transfers the model created in previous
#' components to a new area. The area of transfer is user provided in the map
#' of the GUI. The model will be transferred to the new area as long as the
#' environmental variables are available for the area. This function returns
#' a list including the cropped environmental variables used for transferring
#' and the transferred model.
#' @param evalOut ENMevaluate output from previous module and using any of the
#' available algorithms.
#' @param curModel If algorithm is maxent, model selected by user as best or
#' optimal, in terms of feature class and regularization multiplier
#' (e.g 'L_1'). Else must be 1.
#' @param envs environmental layers to be used for transferring the model. They
#' must match the layers used for generating the model in the model component.
#' @param outputType output type to be used when algorithm is maxnet
#' or maxent.jar.
#' @param alg character. modeling algorithm used in the model component. Can
#' be one of : 'BIOCLIM', 'maxent.jar' or 'maxnet'.
#' @param xfExt extent of the area to transfer the model. This is defined by the
#' user in the map of the GUI and is provided as a SpatialPolygons object.
#' @param clamp logical. Whether transfer will be of clamped or unclamped
#' model.
#' @param logger Stores all notification messages to be displayed in the Log
#' Window of Wallace GUI. Insert the logger reactive list here for running
#' in shiny, otherwise leave the default NULL.
#' @param spN Character used to obtain species name for logger messages
#' @examples
#' \dontrun{
#' envs <- envs_userEnvs(rasPath = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$", full.names = TRUE),
#' rasName = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$", full.names = FALSE))
#' # extent of transfer
#' longitude <- c(-71.58400, -78.81300, -79.34034, -69.83331,
#' -66.47149, -66.71319, -71.11931)
#' latitude <- c(13.18379, 7.52315, 0.93105,
#' -1.70167, 0.98391, 6.09208, 12.74980)
#' selCoords <- matrix(c(longitude, latitude), byrow = FALSE, ncol = 2)
#' polyExt <-
#' sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(selCoords)),
#' ID = 1)))
#' # load model
#' m <- readRDS(system.file("extdata/model.RDS",
#' package = "wallace"))
#' modXfer <- xfer_area(evalOut = m, curModel = 1, envs,
#' outputType = 'cloglog', alg = 'maxent.jar',
#' clamp = TRUE, xfExt = polyExt)
#' }
#'
#' @return A list of two elements: xferExt and xferArea. The first is a
#' RasterBrick or a RasterStack of the environmental variables cropped to the
#' area of transfer. The second element is a raster of the transferred model with
#' the specified output type.
#' @author Jamie Kass <jkass@@gradcenter.cuny.edu>
#' @author Andrea Paz <paz.andreita@@gmail.com>
#' @author Gonzalo E. Pinilla-Buitrago <gepinillab@@gmail.com>
# @note
#' @seealso \code{\link[dismo]{predict}}, \code{\link{xfer_time}}
#' \code{\link{xfer_userEnvs}}
#' @export
xfer_area <- function(evalOut, curModel, envs, xfExt, alg, outputType = NULL,
clamp = NULL, logger = NULL, spN = NULL) {
newPoly <- xfExt
if (alg == 'BIOCLIM') {
logger %>% writeLog(hlSpp(spN),
'New area of transfer for BIOCLIM model.')
} else if (alg == 'maxent.jar'| clamp == TRUE) {
logger %>% writeLog(hlSpp(spN),
'New area of transfer for clamped model ',
curModel, '.')
} else if (clamp == FALSE) {
logger %>% writeLog(hlSpp(spN),
'New area of transfer for unclamped model ',
curModel, '.')
}
smartProgress(
logger,
message = "Masking environmental grids to extent of transfer...", {
xferMsk <- raster::crop(envs, newPoly)
xferMsk <- raster::mask(xferMsk, newPoly)
})
smartProgress(logger, message = 'Transferring model to new area...', {
if (alg == 'BIOCLIM') {
modXferArea <- dismo::predict(evalOut@models[[curModel]], xferMsk,
useC = FALSE)
} else if (alg == 'maxnet') {
if (outputType == "raw") outputType <- "exponential"
modXferArea <- predictMaxnet(evalOut@models[[curModel]], xferMsk,
type = outputType, clamp = clamp)
} else if (alg == 'maxent.jar') {
modXferArea <- dismo::predict(
evalOut@models[[curModel]], xferMsk,
args = c(paste0("outputformat=", outputType),
paste0("doclamp=", tolower(as.character(clamp)))),
na.rm = TRUE)
}
})
return(list(xferExt = xferMsk, xferArea = modXferArea))
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/xfer_area.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_draw.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title xfer_draw Draw extent of transfer
#' @description This function creates a polygon object from coordinates of user
#' drawn poylgon in the GUI.
#'
#' @details
#' This function is used in the transfer model component. In the GUI, the user
#' draws a polygon to be used as the extent of transfer and may include a
#' buffer to the given polygon. The function returns a
#' SpatialPolygonsDataFrame object of the desired extent (+ buffer).
#' @param polyXfXY coordinates of polygon endpoints obtained from user
#' drawn polygon
#' @param polyXfID numeric .ID to be used in the generation of the polygon
#' @param drawXfBuf the buffer to be used in generating the
#' SpatialPolygonsDataFrame, must be >=0 . A number must be specified.
#' @param logger Stores all notification messages to be displayed in the
#' Log Window of Wallace GUI. Insert the logger reactive list here for
#' running in shiny, otherwise leave the default NULL
#' @param spN character. Used to obtain species name for logger messages
#' @examples
#' longitude <- c(-27.78641, -74.09170, -84.01930, -129.74867,
#' -142.19085, -45.55045, -28.56050)
#' latitude <- c(-40.40539, -37.02010, 2.28455, 40.75350,
#' 56.35954, 54.55045, -7.11861)
#' userDrawPoly <- matrix(c(longitude, latitude), byrow = FALSE,
#' ncol = 2)
#' drawXfBuf <- 0.5
#' polyXfID <- 1
#' polygonTest <- xfer_draw(polyXfXY = userDrawPoly, polyXfID,
#' drawXfBuf)
#'
#' @return This functions returns a SpatialPolygons object based on the user
#' specified coordinates (drawn on map). This SpatialPolygonsDataFrame may be
#' larger than specified if drawBgBuf > 0.
#' @author Gonzalo Pinilla <gepinillab@@gmail.com>
#' @author Bethany A. Johnson <bjohnso005@@citymail.cuny.edu>
# @note
#' @seealso \code{\link{xfer_userEnvs}}
#' @export
xfer_draw <- function(polyXfXY, polyXfID, drawXfBuf, logger = NULL, spN = NULL) {
newPoly <- sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(polyXfXY)),
ID = polyXfID)))
newPoly.sf <- sf::st_as_sf(newPoly)
bgExt <- sf::st_buffer(newPoly.sf, dist = drawXfBuf)
bgExt <- sf::as_Spatial(bgExt)
if (drawXfBuf == 0) {
logger %>% writeLog(hlSpp(spN), 'Draw polygon without buffer.')
} else {
logger %>% writeLog(hlSpp(spN), 'Draw polygon with buffer of ',
drawXfBuf, ' degrees.')
}
return(bgExt)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/xfer_draw.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_mess.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title xfer_mess generate MESS map for transferred raster
#' @description This function generates a MESS map for the new variables for
#' transferring based on variables and points used for modeling in previous
#' components.
#'
#' @details
#' This functions allows for the creation of a MESS map for the new provided
#' variables for transferring. These variables are either user uploaded or
#' selected from WorldClim database. MESS map is based on occurrence and
#' background points used for generating the model and the environmental values
#' at those points.
#'
#' @param occs a data frame of occurrences used for modeling and values of
#' environmental variables for each point.
#' @param bg a data frame of points used as background for modeling and values
#' of environmental variables for each point.
#' @param bgMsk a rasterBrick or rasterStack of environmental variables used
#' for modeling. They must be cropped and masked to extent used in model
#' training.
#' @param xferExtRas a rasterStack or rasterBrick of environmental variables
#' to be used for transferring.
#' @param logger Stores all notification messages to be displayed in the Log
#' Window of Wallace GUI. Insert the logger reactive list here for running
#' in shiny, otherwise leave the default NULL.
#' @param spN character. Used to obtain species name for logger messages
#' @examples
#' \dontrun{
#' envs <- envs_userEnvs(rasPath = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$", full.names = TRUE),
#' rasName = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$", full.names = FALSE))
#' # load model
#' m <- readRDS(system.file("extdata/model.RDS",
#' package = "wallace"))
#' occsEnvs <- m@@occs
#' bgEnvs <- m@@bg
#' envsFut <- list.files(path = system.file('extdata/wc/future',
#' package = "wallace"),
#' full.names = TRUE)
#' envsFut <- raster::stack(envsFut)
#' ## run function
#' xferMess <- xfer_mess(occs = occsEnvs, bg = bgEnvs, bgMsk = envs,
#' xferExtRas = envsFut)
#' }
# @return
#' @author Jamie Kass <jkass@@gradcenter.cuny.edu>
#' @author Gonzalo E. Pinilla-Buitrago <gepinillab@@gmail.com>
# @note
#' @seealso \code{\link[dismo]{mess}}, \code{\link{xfer_time}}
#' \code{\link{xfer_userEnvs}}
#' @export
xfer_mess <- function(occs, bg, bgMsk, xferExtRas, logger = NULL, spN = NULL) {
occsVals <- occs[, names(bgMsk)]
if (is.null(bg)) {
allVals <- occsVals
} else {
bgVals <- bg[, names(bgMsk)]
allVals <- rbind(occsVals, bgVals)
}
# rename rasters to match originals
xferExtRas2 <- xferExtRas
names(xferExtRas2) <- names(bgMsk)
smartProgress(logger, message = "Generating MESS map...", {
mss <- suppressWarnings(dismo::mess(xferExtRas2, allVals))
# for mapping purposes, set all infinite values to NA
mss[is.infinite(mss)] <- NA
logger %>% writeLog(hlSpp(spN), "Generated MESS map.")
})
return(mss)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/xfer_mess.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_time.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title xfer_time Transfer model to a new time
#' @description Function transfers the model generated in previous components to
#' a new time and area using provided layers.
#' @details
#' This functions allows transferring the model created in previous
#' components to a new time and area. The area of transfer is user provided in
#' the map of the GUI and the transfer time user selected. The model will
#' be transferred to the new area and time as long as the environmental
#' variables are available for the area. This function returns a list
#' including the cropped environmental variables used for transferring and
#' the transferred model.
#'
#' @param evalOut ENMevaluate output from previous module and using any of
#' the available algorithms.
#' @param curModel if algorithm is maxent, model selected by user as best
#' or optimal, in terms of feature class and regularization multiplier (e.g
#' 'L_1'). Otherwise must be 1.
#' @param envs environmental layers of different time to be used for transferring
#' the model. They must match the layers used for generating the model in the
#' model component.
#' @param outputType output type to be used when algorithm is maxnet or
#' maxent.jar.
#' @param alg modeling algorithm used in the model component. Can be one of:
#' 'bioclim', 'maxent.jar' or 'maxnet'.
#' @param xfExt extent of the area to transfer the model. This is defined by the
#' user in the map of the GUI and is provided as a SpatialPolygons object.
#' @param clamp logical. Whether transfer will be of clamped or unclamped
#' model.
#' @param logger Stores all notification messages to be displayed in the Log
#' Window of Wallace GUI. Insert the logger reactive list here for running in
#' shiny, otherwise leave the default NULL.
#' @param spN character. Used to obtain species name for logger messages.
#' @examples
#' \dontrun{
#' envs <- envs_userEnvs(rasPath = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$",
#' full.names = TRUE),
#' rasName = list.files(system.file("extdata/wc",
#' package = "wallace"),
#' pattern = ".tif$",
#' full.names = FALSE))
#' ## extent to transfer
#' # set coordinates
#' longitude <- c(-71.58400, -78.81300, -79.34034, -69.83331, -66.47149, -66.71319,
#' -71.11931)
#' latitude <- c(13.18379, 7.52315, 0.93105, -1.70167, 0.98391, 6.09208, 12.74980)
#' # generate matrix
#' selCoords <- matrix(c(longitude, latitude), byrow = FALSE, ncol = 2)
#' polyExt <- sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(selCoords)),
#' ID = 1)))
#' # load model
#' m <- readRDS(system.file("extdata/model.RDS",
#' package = "wallace"))
#' occsEnvs <- m@@occs
#' bgEnvs <- m@@bg
#' envsFut <- list.files(path = system.file('extdata/wc/future',
#' package = "wallace"),
#' full.names = TRUE)
#' envsFut <- raster::stack(envsFut)
#' modXfer <- xfer_time(evalOut = m, curModel = 1,
#' envs = envsFut, alg = 'maxent.jar',
#' xfExt = polyExt, clamp = FALSE, outputType = 'cloglog')
#' }
#' @return A list of two elements: xferExt and xferTime. The first is a
#' RasterBrick or RasterStack of the environmental variables cropped to the
#' area of transfer. The second element is a raster of the transferred model
#' with the specified output type.
#' @author Jamie Kass <jkass@@gradcenter.cuny.edu>
#' @author Andrea Paz <paz.andreita@@gmail.com>
#' @author Gonzalo E. Pinilla-Buitrago <gepinillab@@gmail.com>
#' @author Bethany A. Johnson <bjohnso005@@citymail.cuny.edu>
#' @seealso \code{\link[dismo]{predict}}, \code{\link{xfer_time}}
#' \code{\link{xfer_userEnvs}}
#' @export
xfer_time <- function(evalOut, curModel, envs, xfExt, alg, outputType = NULL,
clamp = NULL, logger = NULL, spN = NULL) {
newPoly <- xfExt
if (alg == 'BIOCLIM') {
logger %>% writeLog(
hlSpp(spN),
'Transferring in time for BIOCLIM model.')
} else if (alg == 'maxent.jar'| clamp == TRUE) {
logger %>% writeLog(
hlSpp(spN),
'Transferring in time for clamped model ', curModel, '.')
} else if (clamp == FALSE) {
logger %>% writeLog(
hlSpp(spN),
'New time transfer for unclamped model' , curModel, '.')
}
smartProgress(
logger,
message = "Clipping environmental data to current extent...", {
xftMsk <- raster::crop(envs, newPoly)
xftMsk <- raster::mask(xftMsk, newPoly)
})
smartProgress(
logger,
message = ("Transferring to new time..."), {
if (alg == 'BIOCLIM') {
modXferTime <- dismo::predict(evalOut@models[[curModel]], xftMsk,
useC = FALSE)
} else if (alg == 'maxnet') {
if (outputType == "raw") outputType <- "exponential"
modXferTime <- predictMaxnet(evalOut@models[[curModel]], xftMsk,
type = outputType, clamp = clamp)
} else if (alg == 'maxent.jar') {
modXferTime <- dismo::predict(
evalOut@models[[curModel]], xftMsk,
args = c(paste0("outputformat=", outputType),
paste0("doclamp=", tolower(as.character(clamp)))),
na.rm = TRUE)
}
})
return(list(xferExt = xftMsk, xferTime = modXferTime))
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/xfer_time.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_userEnvs.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title xfer_userEnvs Transfer model to user specified area and time
#' @description The function transfers the model generated in previous components
#' to user uploaded environmental variables.
#'
#' @details
#' This functions allows transferring the model created in previous
#' components to a new time and area provided by the user. The transferring
#' time and area is user-provided. The model will be transferred to the new
#' time and area as long as the environmental variables provided are
#' available for the area and match the variables used for model building.
#' This function returns a list including the cropped environmental variables
#' used for transferring and the transferred model.
#' @param evalOut ENMevaluate output from previous module and using any of the
#' available algorithms.
#' @param curModel if algorithm is maxent, model selected by user as best or
#' optimal, in terms of feature class and regularization multiplier (e.g
#' 'L_1'). Otherwise it must be 1.
#' @param envs user provided environmental layers (in raster format) to be
#' used for transferring.
#' @param outputType output type to be used when algorithm is maxnet or
#' maxent.jar.
#' @param alg modeling algorithm used in the model component. Can be one of:
#' 'BIOCLIM', 'maxent.jar' or 'maxnet'.
#' @param xfExt extent of the area to transfer the model. This must be provided
#' by the user as a shapefile or as a SpatialPolygons object.
#' @param clamp logical. Whether transfer will be of clamped or unclamped
#' model.
#' @param logger Stores all notification messages to be displayed in the Log
#' Window of Wallace GUI. Insert the logger reactive list here for running in
#' shiny, otherwise leave the default NULL.
#' @param spN character. Used to obtain species name for logger messages.
#' @examples
#' \dontrun{
#' ## extent to transfer
#' # set coordinates
#' longitude <- c(-71.58400, -78.81300, -79.34034, -69.83331, -66.47149, -66.71319,
#' -71.11931)
#' latitude <- c(13.18379, 7.52315, 0.93105, -1.70167, 0.98391, 6.09208, 12.74980)
#' # generate matrix
#' selCoords <- matrix(c(longitude, latitude), byrow = FALSE, ncol = 2)
#' polyExt <- sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(selCoords)),
#' ID = 1)))
#' # load model
#' m <- readRDS(system.file("extdata/model.RDS",
#' package = "wallace"))
#' envsFut <- list.files(path = system.file('extdata/wc/future',
#' package = "wallace"),
#' full.names = TRUE)
#' envsFut <- raster::stack(envsFut)
#' ### run function
#' modXfer <- xfer_userEnvs(evalOut = m, curModel = 1, envs = envsFut,
#' outputType = "cloglog", alg = "maxent.jar",
#' clamp = FALSE, xfExt = polyExt)
#' }
#'
#' @author Jamie Kass <jkass@@gradcenter.cuny.edu>
#' @author Andrea Paz <paz.andreita@@gmail.com>
#' @author Gonzalo E. Pinilla-Buitrago <gepinillab@@gmail.com>
# @note
#' @seealso \code{\link[dismo]{predict}}, \code{\link{xfer_time}}
#' \code{\link{xfer_userExtent}}
#' @export
xfer_userEnvs <- function(evalOut, curModel, envs, xfExt, alg, outputType = NULL,
clamp = NULL, logger = NULL, spN = NULL) {
newPoly <- xfExt
if (alg == 'BIOCLIM') {
logger %>% writeLog(
hlSpp(spN),
'User specified transfer for BIOCLIM model.')
} else if (alg == 'maxent.jar' | clamp == TRUE) {
logger %>% writeLog(
hlSpp(spN),
'User specified transfer for clamped model ', curModel, '.')
} else if (clamp == FALSE) {
logger %>% writeLog(
hlSpp(spN),
'User specified transfer for unclamped model', curModel, '.')
}
smartProgress(
logger,
message = "Masking environmental grids to transfer extent...", {
xferMsk <- raster::crop(envs, newPoly)
xferMsk <- raster::mask(xferMsk, newPoly)
})
smartProgress(
logger,
message = 'Transferring model to user uploaded environmental variables & area', {
if (alg == 'BIOCLIM') {
modXferUser <- dismo::predict(evalOut@models[[curModel]], xferMsk,
useC = FALSE)
} else if (alg == 'maxnet') {
if (outputType == "raw") outputType <- "exponential"
modXferUser <- predictMaxnet(evalOut@models[[curModel]], xferMsk,
type = outputType, clamp = clamp)
} else if (alg == 'maxent.jar') {
modXferUser <- dismo::predict(
evalOut@models[[curModel]], xferMsk,
args = c(paste0("outputformat=", outputType),
paste0("doclamp=", tolower(as.character(clamp)))),
na.rm = TRUE)
}
})
return(list(xferExt = xferMsk, xferUser = modXferUser))
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/xfer_userEnvs.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_userExtent.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
#' @title xfer_userExtent: user provided extent of transfer
#' @description This function generates an area of transfer according to a user
#' provided polygon and buffer.
#'
#' @details
#' This function is used in the transfer component. Here, the user provides
#' either a shapefile or a csv with vertex coordinates with the desired shape
#' for the extent of transfer, the user may include a buffer to the given
#' polygon. The function returns a SpatialPolygons object of the desired
#' extent (+ buffer).
#'
#' @param bgShp_path path to the user provided shapefile or csv with
#' vertex coordinates.
#' @param bgShp_name name of the user provided shapefile or csv with
#' vertex coordinates.
#' @param userBgBuf numeric. Buffer to be used in creating the background
#' extent must be >= 0.
#' @param logger Stores all notification messages to be displayed in the Log
#' Window of Wallace GUI. Insert the logger reactive list here for running
#' in shiny, otherwise leave the default NULL.
#' @param spN data frame of cleaned occurrences obtained from component
#' occs: Obtain occurrence data. Used to obtain species name for logger
#' messages.
#' @examples
#' pathShp <- list.files(system.file("extdata/shp", package = "wallace"),
#' full.names = TRUE)
#' nameShp <- list.files(system.file("extdata/shp", package = "wallace"),
#' full.names = FALSE)
#' xferUser <- xfer_userExtent(bgShp_path = pathShp, bgShp_name = nameShp,
#' userBgBuf = 1)
#' @return This function returns a SpatialPolygons object with the user
#' provided shape (+ a buffer is userBgBuf >0).
#' @author Jamie Kass <jamie.m.kass@@gmail.com>
#' @author Gonzalo E. Pinilla-Buitrago <gepinillab@@gmail.com>
#' @author Andrea Paz <paz.andreita@@gmail.com>
#' @author Bethany A. Johnson <bjohnso005@@citymail.cuny.edu>
#' @seealso \code{\link{penvs_drawBgExtent}}, \code{\link{penvs_bgExtent}},
#' \code{\link{penvs_bgMask}} , \code{\link{penvs_bgSample}}
#' @export
xfer_userExtent <- function(bgShp_path, bgShp_name, userBgBuf,
logger = NULL, spN = NULL) {
pathdir <- dirname(bgShp_path)
pathfile <- basename(bgShp_path)
# get extensions of all input files
exts <- sapply(strsplit(bgShp_name, '\\.'), FUN = function(x) x[2])
if (length(exts) == 1 & exts[1] == 'csv') {
f <- utils::read.csv(bgShp_path, header = TRUE)
bgExt <- sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(f)), 1)))
} else if ('shp' %in% exts) {
if (length(exts) < 3) {
logger %>%
writeLog(type = 'error',
paste0('If entering a shapefile, please select all the ',
'following files: .shp, .shx, .dbf.'))
return()
}
# get index of .shp
i <- which(exts == 'shp')
if (!file.exists(file.path(pathdir, bgShp_name)[i])) {
file.rename(bgShp_path, file.path(pathdir, bgShp_name))
}
# read in shapefile and extract coords
bgExt <- sf::st_read(file.path(pathdir, bgShp_name)[i])
bgExt <- sf::as_Spatial(bgExt)
} else {
logger %>%
writeLog(type = 'error',
paste0('Please enter either a CSV file of vertex coordinates ',
'or shapefile (.shp, .shx, .dbf).'))
return()
}
if (userBgBuf > 0) {
bgExt <- sf::st_as_sf(bgExt)
bgExt <- sf::st_buffer(bgExt, dist = userBgBuf)
bgExt <- sf::as_Spatial(bgExt)
logger %>% writeLog(
hlSpp(spN),
'Transferring extent user-defined polygon buffered by ',
userBgBuf, ' degrees.')
} else if (userBgBuf < 0) {
logger %>%
writeLog(type = 'error',
'Change buffer distance to a positive value.')
return()
} else {
logger %>% writeLog(
hlSpp(spN),
"Transferring extent: user-defined polygon.")
}
return(bgExt)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/R/xfer_userExtent.R
|
{{id}}_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
# UI
actionButton(ns("run"), "Run module {{id}}")
)
}
{{id}}_module_server <- function(input, output, session, common) {
observeEvent(input$run, {
# WARNING ####
# FUNCTION CALL ####
# LOAD INTO SPP ####
# METADATA ####
})
output$result <- renderText({
# Result
})
return(list(
save = function() {
# Save any values that should be saved when the current session is saved
},
load = function(state) {
# Load
}
))
}
{{id}}_module_result <- function(id) {
ns <- NS(id)
# Result UI
verbatimTextOutput(ns("result"))
}
{{id}}_module_map <- function(map, common) {
# Map logic
}
{{id}}_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
{{id}}_knit = species$rmm$code$wallace$someFlag,
var1 = species$rmm$code$wallace$someSetting1,
var2 = species$rmm$code$wallace$someSetting2
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/module_skeleton/skeleton.R
|
```{asis, echo = {{moduleID_knit}}, eval = {{moduleID_knit}}, include = {{moduleID_knit}}}
# Remember to change moduleID to the name of your module
# (e.g. moduleID_knit => occs_queryDb_knit)
Description of what the code will do {{var1}}
```
```{r, echo = {{moduleID_knit}}, include = {{moduleID_knit}}}
# R code to run {{var2}}
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/module_skeleton/skeleton.Rmd
|
---
title: "envs"
output: html_document
---
### **Component: Obtain Environmental Data**
**ORIENTATION**
In addition to occurrence data, algorithms for niche/distributional modeling require environmental predictor variables (Franklin 2010 chap. 5, Peterson et al. 2011 chap. 6). **Component: Obtain Environmental Data** allows users to obtain these variables from online sources in the form of raster grids. In recent years, a number of global databases of climatic data have emerged (Hijmans et al. 2005, Kriticos et al. 2012, Sbrocco and Barber 2013, Karger et al. 2016). Currently, Wallace provides three options for environmental data. First, it offers access to present-day averaged climatic data from the WorldClim dataset, which has near-global coverage of terrestrial areas (Module: *WorldClim Bioclims*).
Second, users may access present and past (paleo) climatic data from ecoClimate (Module: *ecoClimate*). Third, users may alternatively upload environmental raster grids (Module: *User-Specified*).
We envision that future releases will offer other terrestrial climate datasets (with different interpolation methodologies, e.g. CHELSA; or with different variables, e.g. CliMond); marine climate datasets (e.g. MARSPEC); and vegetation/land cover/land-use data. In the meantime, such datasets can be used in Wallace via the *User-Specified* option, but users should be careful to use environmental data relevant for the time frame of the occurrences (e.g., not using recent land cover along with older occurrence data).
**REFERENCES**
Franklin, J. (2010). Mapping Species Distributions: Spatial Inference and Prediction. Data for species distribution models: the environmental data. In: *Mapping species distributions: spatial inference and prediction*. Cambridge: Cambridge University Press. <a href="https://doi.org/10.1017/CBO9780511810602" target="_blank">DOI: 10.1017/CBO9780511810602</a>
Hijmans, R.J., Cameron, S.E., Parra, J.L., Jones, P.G., & Jarvis, A. (2005). Very high resolution interpolated climate surfaces for global land areas. *International Journal of Climatology*, 25(15), 1965-1978. <a href="https://doi.org/10.1002/joc.1276" target="_blank">DOI: 10.1002/joc.1276</a>
Karger, D.N., Conrad, O., Böhner, J., Kawohl, T., Kreft, H., Soria-Auza, R.W., Zimmermann, N.E, Linder, H.P., & Kessler, M. (2016). Climatologies at high resolution for the earth's land surface areas (Version 1.1). World Data Center for Climate. <a href="http://dx.doi.org/doi:10.1594/WDCC/CHELSA_v1_1" target="_blank">DOI: 10.1594/WDCC/CHELSA_v1_1</a>
Kriticos, D.J., Webber, B.L., Leriche, A., Ota, N., Macadam, I., Bathols, J., & Scott, J.K. (2012). CliMond: global high-resolution historical and future scenario climate surfaces for bioclimatic modelling. *Methods in Ecology and Evolution*, 3(1), 53-64. <a href="https://doi.org/10.1111/j.2041-210X.2011.00134.x" target="_blank">DOI: 10.1111/j.2041-210X.2011.00134.x</a>
Peterson, A.T., Soberón, J., Pearson, R.G., Anderson, R.P., Martinez-Meyer, E., Nakamura, M., & Araújo, M.B. (2011). Environmental Data. In: *Ecological Niches and Geographic Distributions*. Princeton, New Jersey: *Monographs in Population Biology*, 49. Princeton University Press. <a href="https://doi.org/10.23943/princeton/9780691136868.003.0006" target="_blank">DOI: 10.23943/princeton/9780691136868.003.0006</a>
Sbrocco, E.J., Barber, P.H. (2013). MARSPEC: ocean climate layers for marine spatial ecology. *Ecology*, 94(4), 979-979. <a href="https://doi.org/10.1890/12-1358.1" target="_blank">DOI: 10.1890/12-1358.1</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_envs.Rmd
|
---
title: "espace"
output: html_document
---
### **Component: Characterize Environmental Space**
**ORIENTATION**
The concept of the ecological niche is central to ecology and intersecting fields, yet has seen varied definitions, emphases, and usages (Holt 2009; Soberón & Nakamura 2009). Several definitions have been proposed by different authors depending largely on whether they consider abiotic and/or biotic factors. As originally defined, the Grinnellian niche is determined by the habitat in which the species lives and its associated behavioral adaptations (e.g., the chaparral habitat is the niche of the California thrasher; Grinnell 1917). In contrast, the Eltonian niche (Chase & Leibold 2003) includes the functional role of a species, considering not only the requirements that allow the species to persist but also how it changes the availability of depletable resources (e.g. a beaver modifies both abiotic conditions by building dams and also resources for other species by chopping down trees). Here, we use the Hutchinsonian formalization of the niche which characterizes an n-dimensional hypervolume where a species can persist and reproduce in a mathematical space defined by non-depletable environmental gradients (Hutchinson 1957; see overlap with the Grinnellian conceptualization; Soberón & Nakamura 2009; Peterson et al. 2011).
The **Characterize Environmental Space** component performs analyses and visualizations of the Hutchinsonian niche for two selected species. Wallace currently allows the user to: 1) perform a Principal Components Analysis (PCA; Module: *Environmental Ordination*) to reduce the dimensionality of the original environmental space, 2) calculate the density of occurrences of the species along the two first components of the PCA (Module: *Occurrence Density Grid*), and 3) perform niche-overlap analyses (Module: *Niche Overlap*).
**REFERENCES**
Grinnell, J. (1917). "The niche-relationships of the California Thrasher". *The Auk*, 34(4), 427–433. <a href="https://www.jstor.org/stable/4072262" target="_blank">DOI:10.2307/4072271</a>
Chase, J.M., & Leibold, M.A. (2003). *Ecological Niches: Linking Classical and Contemporary Approaches*. <a href="https://press.uchicago.edu/ucp/books/book/chicago/E/bo3638660.html" target="_blank">University of Chicago Press.</a>
Holt, R.D. (2009). Bringing the Hutchinsonian niche into the 21st century: Ecological and evolutionary perspectives. *Proceedings of the National Academy of Sciences*, 106(2), 19659-19665. <a href="https://doi.org/10.1073/pnas.0905137106" target="_blank">DOI:10.1073/pnas.0905137106</a>
Hutchinson, G.E. (1957). "Concluding remarks". *Cold Spring Harbor Symposia on Quantitative Biology*, 22, 415–427. <a href="http://dx.doi.org/10.1101/SQB.1957.022.01.039" target="_blank">DOI:10.1101/SQB.1957.022.01.039</a>
Peterson, A.T., Soberón, J., Pearson, R.G., Anderson, R.P., Martinez-Meyer, E., Nakamura, M., & Araújo, M.B. (2011). Environmental Data. In: *Ecological Niches and Geographic Distributions*. Princeton, New Jersey: *Monographs in Population Biology*, 49. <a href="https://doi.org/10.23943/princeton/9780691136868.003.0005" target="_blank">Princeton University Press.</a>
Soberón, J., Nakamura, M. (2009). Niches and distributional areas: Concepts, methods, and assumptions. *Proceedings of the National Academy of Sciences*, 106(2), 19644-19650. <a href="https://doi.org/10.1073/pnas.0901637106" target="_blank">DOI:10.1073/pnas.0901637106</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_espace.Rmd
|
---
title: "model"
output: html_document
---
### **Component: Build and Evaluate Niche Model**
Many approaches and algorithms exist for building models of species niches/distributions, as well as for evaluating them (Guisan and Thuiller, 2005; Elith et al. 2006; Franklin 2010 chaps. 6, 7, 8). **Component: Build and Evaluate Niche Model** uses the output from earlier components to build models using either presence-only or presence-background data (and associated environmental information). Wallace currently allows users to build models using either: 1) the presence-only approach BIOCLIM (Module: *BIOCLIM*), or 2) the presence-background algorithm Maxent (Module: *Maxent*).
As noted, various evaluation metrics exist for assessing niche/distributional model performance, and many are based on the ability to predict localities that are withheld for evaluation (Peterson et al. 2011). As in Zurell et al. 2020 and Kass et al. 2021, Wallace now follows the terminology of Hastie et al. (2009), which distinguishes among:
1. training data used for model building (also called ‘fitting’);
2. validation data withheld from model building and used instead for estimating prediction errors for model selection and averaging/ensembling; and
3. test data fully withheld from model building and selection/averaging/ensembling and instead used only to assess the final model (for uses in forecasting and transfer).
Wallace currently implements extensive evaluations based on splits into training and validation data.
In addition to a single split, some more-complicated data-partitioning schemes involve iterative splits where a different subset of localities is withheld in turn (e.g., k-fold cross-validation). As part of **Component: Build and Evaluate Niche Model**, Wallace provides a table of a few commonly used evaluation metrics, including Area Under the Curve (AUC), omission rate, Continuous Boyce Index (CBI), and Akaike Information Criterion (AIC; which does not use withheld localities at all). There is no single “best” way to evaluate niche/distributional models (especially without absence data), so Wallace seeks to provide a number of them and let users decide which ones fit their research purposes.
**AUC** stands for the Area Under the Curve (AUC) of a Receiver Operating Characteristic (ROC) plot. AUC is a non-parametric measure of the ability of a classifier (here, the model) to rank positive records higher than negative ones across the full range of suitability values of the model; thus, it judges the model's discriminative ability. AUC ranges from 0 to 1, but major complications for interpreting AUC exist when true negative data (e.g., absences) do not exist (Lobo et al. 2008; Peterson et al. 2008; Peterson et al. 2011 chap. 9). As the niche/distributional models offered in Wallace are presence-only or presence-background, AUC values should only be considered as relative indicators of performance (e.g., between different settings of the same algorithm, for the same dataset of a given species). Wallace uses ENMeval 2.0 (Kass et al. 2021) to: 1) calculate AUC using the model made with all occurrence localities and “evaluate” it with the same records, i.e. the training localities (training AUC), 2) calculate AUC for each iteration of k-fold cross validation separately, using each model built with the training localities and evaluating based on the validation localities for that iteration (validation AUC, the average across the k iterations), and 3) take the difference between the training and validation AUC for each iteration of k-fold cross validation (AUC diff, again averaged over the k iterations). Validation AUC constitutes the way that AUC usually is applied in the field and is important to consider before performing model transfers to other areas/times (Roberts et al. 2017). Higher AUC difference should indicate greater model overfitting, as overfit models should perform better on training than testing data (Warren and Seifert 2011) and hence be avoided. If a set of occurrence records are completely withheld (never used for training), then true testing AUC can be calculated (not currently implemented in Wallace).
Five fields in the “Results” table pertain to AUC:
* auc.train: AUC calculated using all occurrence localities
* auc.val.avg and auc.val.sd: mean and standard deviation of the k validation AUCs (one for each partition)
* auc.diff.avg and auc.diff.sd: mean and standard deviation of all differences between the k training and validation AUCs
The omission rate (**OR**) is a method for evaluating the ability of a binary classifier (here, the model) to predict localities (usually withheld ones), typically after applying a threshold to a continuous or ordinal model prediction (see Module Map Prediction). Application of the threshold makes the prediction binary (e.g., 0s and 1s), and the omission rate then equals the proportion of withheld localities that fall in grid cells with a 0 (i.e. below the threshold; Peterson et al. 2011). An OR of 0 indicates that no localities fall outside the prediction, whereas an OR of 1 indicates that all of them do. There are many possible thresholding rules, but Wallace offers two for evaluation that are commonly used: minimum training presence (MTP) and 10 percentile training presence (10pct). MTP is the lowest suitability score for any occurrence localities used to train the model. 10pct is the lowest suitability score for such localities after excluding the lowest 10% of them. Thus, 10pct is stricter than MTP. As with AUC, Wallace calculates OR for each partition; it does so by applying a threshold to the continuous prediction and finding the proportion of validation localities that fall outside the resulting binary prediction. Four fields in the “Results” table pertain to omission rate:
* or.mtp.avg and or.mtp.sd: mean and standard deviation of all test MTP omission rates
* or.10p.avg and or.10p.sd: mean and standard deviation of all test 10pct omission rates
Continuous Boyce Index (**CBI**), evaluates models based on dividing the suitability range into ‘b’ classes, as opposed to only two. For each class, it calculates the ratio of the frequency of evaluation localities predicted by the model over their expected frequency (the latter based on the proportion of the study region corresponding to that class). An ideal model will have an increasing curve; low suitability classes should have fewer evaluation presences than a random model, and the ratio of predicted/expected should increase with higher suitability (Boyce et al. 2002; Hirzel et al. 2006).
CBI values range from -1 to 1, with positive values denoting a model having predictions consistent with the evaluation data and negative ones showing a poor model(Hirzel et al. 2006).
* cbi.val.avg and cbi.val.sd: mean and standard deviation of the test CBIs
**AIC**, or the Akaike Information Criterion, is a model evaluation metric used often with regression-based techniques. Models with the lowest AIC are identified as optimal among candidate models. It is calculated in this way (Burnham and Anderson 2002):
\(AIC = 2k - 2ln(L)\)
Here, k = number of model parameters, and ln(L) is the log likelihood of the model (note that here k has a different meaning than used elsewhere in Wallace for k-fold partitioning). Models with more parameters will have a greater positive number for the first term, and those with higher likelihoods will have a greater negative number for the second term. Therefore, simpler models with fewer parameters and models with high likelihoods will both receive lower AIC scores. As an example, if two models have approximately the same likelihood, the one with fewer parameters will have a lower AIC. In this way, in general AIC penalizes complex models, but it does reward complex ones with high likelihoods, with the intent of finding the best balance between complexity and fit (Burnham and Anderson 2002). For Maxent, Wallace calculates AICc (corrected for finite sample sizes) using the methodology outlined in Warren and Seifert (2011); it does not calculate AIC for BIOCLIM. AIC is calculated on the full model only, and thus does not consider partitions. Four fields in the “Results” table pertain to AIC:
* ncoef: number of parameters (coefficients) in the model (for Maxent, this includes features of variables as well (e.g. four hinges of bio1 means 4 parameters, a quadratic term for bio11 means 2 parameters, etc.)
* AICc
* delta.AICc: absolute difference between the lowest AICc and each AICc (e.g. delta.AICc = 0 is the model with the lowest AICc)
* w.AIC: the AIC weight, calculated as the average relative model likelihood (exp(-0.5 * delta.AICc)) across all models, can be used in model averaging (Burnham and Anderson 2002)
Evaluation statistics are shown in the ‘Results’ tab, for the full model, the average of the partitions, and the individual partitions. If run in sequence, the current model results will overwrite the previous ones. We envision that this component will grow substantially in future releases, with the addition of new modules implementing other modeling techniques.
**REFERENCES**
Boyce, M.S., Vernier, P.R., Nielsen, S.E., & Schmiegelow, F.K.A. (2002). Evaluating resource selection functions. *Ecological Modelling*, 157(2-3), 281–300. <a href="https://doi.org/10.1016/S0304-3800(02)00200-4" target="_blank">DOI: 10.1016/S0304-3800(02)00200-4</a>
Burnham, K.P., & Anderson, D.R. (2002). Model selection and multimodel inference : a practical information-theoretic approach. Springer, New York. <a href="https://doi.org/10.1007/b97636" target="_blank">DOI: 10.1007/b97636</a>
Elith, J., Graham, C.H., Anderson, R.P., Dudík, M., Ferrier, S., Guisan, A., Hijmans, R.J., Huettmann, F., Leathwick, J.R., Leahmann, A., Li, J., Lohmann, L.G., Loiselle, B.A., Manion, G., Moritz, C., Nakamura, M., Nakazawa, Y., Overton, J.M., Peterson, A.T., Phillips, S.J., Richardson, K.S., Scachetti-Pereira, R., Schapire, R.E., Soberón, J., Williams, S., Wisz, M.S., & Zimmermann, N.E. (2006). Novel methods improve prediction of species' distributions from occurrence data. *Ecography*, 29(2), 129-151. <a href="https://doi.org/10.1111/j.2006.0906-7590.04596.x" target="_blank">DOI: 10.1111/j.2006.0906-7590.04596.x</a>
Franklin, J. (2010). *Mapping Species Distributions: Spatial Inference and Prediction*. Statistical models - modern regression; Machine learning methods; Classification, similarity and other methods for presence-only data. Cambridge: Cambridge University Press. <a href="https://doi.org/10.1017/CBO9780511810602" target="_blank">DOI: 10.1017/CBO9780511810602</a>
Guisan, A., & Thuiller, W. (2005). Predicting species distribution: offering more than simple habitat models. *Ecology Letters*, 8, 993-1009. <a href="https://doi.org/10.1111/j.1461-0248.2005.00792.x" target="_blank">DOI: 10.1111/j.1461-0248.2005.00792.x</a>
Hastie, T., Tibshirani, R., & Friedman, J.H. (2009). *The elements of Statistical Learning: Data Mining, Inference, and prediction*. Springer. <a href="https://link.springer.com/book/10.1007/978-0-387-84858-7" target="_blank">The Elements of Statistical Learning</a>
Hirzel, A.H., Lay, G.L., Helfer, H., Randin, C., & Guisan, A. (2006) Evaluating the ability of habitat suitability models to predict species presences. *Ecological Modelling*, 199(2), 142–152. <a href="https://doi.org/10.1016/j.ecolmodel.2006.05.017" target="_blank">DOI: 10.1016/j.ecolmodel.2006.05.017</a>
Kass, J., Muscarella, R., Galante, P.J., Bohl, C.L., Pinilla-Buitrago, G.E., Boria, R.A., Soley-Guardia, M., & Anderson, R.P. (2021). ENMeval 2.0: Redesigned for customizable and reproducible modeling of species’ niches and distributions. *Methods in Ecology and Evolution*, 12(9), 1602-1608. <a href="https://doi.org/10.1111/2041-210X.13628" target="_blank">DOI: 10.1111/2041-210X.13628</a>
Lobo, J.M., Jiménez-Valverde, A., & Real, R. (2008). AUC: a misleading measure of the performance of predictive distribution models. *Global Ecology and Biogeography*, 17(2), 145-151. <a href="https://doi.org/10.1111/j.1466-8238.2007.00358.x" target="_blank">DOI: 10.1111/j.1466-8238.2007.00358.x</a>
Peterson, A.T., Papeş, M., & Soberón, J. (2008). Rethinking receiver operating characteristic analysis applications in ecological niche modeling. *Ecological Modelling*, 213(1), 63-72. <a href="https://doi.org/10.1016/j.ecolmodel.2007.11.008" target="_blank">DOI: 10.1016/j.ecolmodel.2007.11.008</a>
Peterson, A.T., Soberón, J., Pearson, R.G., Anderson, R.P., Martinez-Meyer, E., Nakamura, M., & Araújo, M.B. (2011). Evaluating Model Performance and Significance. In: *Ecological Niches and Geographic Distributions*. Princeton, New Jersey: *Monographs in Population Biology*, 49. Princeton University Press. <a href="https://doi.org/10.23943/princeton/9780691136868.003.0005" target="_blank">DOI: 10.23943/princeton/9780691136868.003.0005</a>
Roberts, D.R., Bahn, V., Ciuti, S., Boyce, M.S., Elith, J., Guillera-Arroita, G., Hauenstein, S., Lahoz-Monfort, J.J., Schröder, B., Thuiller, W., Warton, D.I., Wintle, B.A., Hartig, F., & Dormann, C.F. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. *Ecography*, 40(8), 913-929. <a href="https://doi.org/10.1111/ecog.02881" target="_blank">DOI: 10.1111/ecog.02881</a>
Warren, D.L., & Seifert, S.N. (2011). Ecological niche modeling in Maxent: the importance of model complexity and the performance of model selection criteria. *Ecological Applications*, 21(2), 335-342. <a href="https://doi.org/10.1890/10-1171.1" target="_blank">DOI: 10.1890/10-1171.1</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_model.Rmd
|
---
title: "occs"
output: html_document
---
### **Component: Obtain Occurrence Data**
**ORIENTATION**
Niche/distributional modeling analyses require georeferenced occurrence records for the species (e.g., with latitude/longitude). At present, **Component: Obtain Occurrence Records** focuses on data documenting the presence of the species (i.e., not any information on its absence or non-detection; Franklin 2010, Chapter 4; Peterson et al. 2011, Chapter 5; Anderson 2012). *Wallace* currently allows users to: 1) obtain present-day occurrence records (from dates in the past century or so) from selected online biodiversity databases and download the information (Module: *Query Database [Present]*), 2) obtain paleontological occurrence records from selected online biodiversity databases and download the information (Module: *Query Database [Paleo]*);
or 3) upload their own dataset (Module: *User-specified Occurrences*).
Unlike previous versions of *Wallace*, multiple species now can be uploaded in the same session.
*Note: As of 01 September 2023, Module: Query Database [Paleo] will be temporarily unavailable.*
**REFERENCES**
Anderson, R.P. (2012). Harnessing the world's biodiversity data: promise and peril in ecological niche modeling of species distributions. *Annals of the New York Academy of Sciences*, 1260(1), 66-80. <a href="https://doi.org/10.1111/j.1749-6632.2011.06440.x" target="_blank">DOI: 10.1111/j.1749-6632.2011.06440.x</a>
Franklin, J. (2010). Data for species distribution models: The biological data. In: *Mapping Species Distributions: Spatial Inference and Prediction* (Ecology, Biodiversity and Conservation, pp. 55-75). Cambridge: Cambridge University Press. <a href="https://doi.org/10.1017/CBO9780511810602.007" target="_blank">DOI: 10.1017/CBO9780511810602.007</a>
Peterson, A.T., Soberón, J., Pearson, R.G., Anderson, R.P., Martinez-Meyer, E., Nakamura, M., & Araújo, M.B. (2011). Species' Occurrence Data. In: *Ecological Niches and Geographic Distributions*. Princeton, New Jersey: Monographs in Population Biology, 49. Princeton University Press. <a href="https://doi.org/10.23943/princeton/9780691136868.003.0005" target="_blank">DOI: 10.23943/princeton/9780691136868.003.0005</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_occs.Rmd
|
---
title: "part"
output: html_document
---
### **Component: Partition Occurrence Data**
**ORIENTATION**
Evaluating the accuracy of a predictive model usually requires testing it on independent data; however, as truly independent data are difficult to obtain for most biodiversity datasets, researchers often partition a single dataset into subsets. Occurrence data are partitioned into two categories: 1) those used to make the model (i.e. "training" or "calibration"), and 2) others that are withheld for evaluating it (i.e. "testing" or "evaluation" data) (Guisan and Zimmermann 2000; Peterson et al. 2011). One widely-used technique, *k*-fold cross-validation, involves partitioning the full dataset into *k* groups, then iteratively building a model using all groups but one and testing this model on the left-out group. This iterative process results in *k* models. Evaluation statistics can be averaged over these *k* models to help in model selection, leading to the production of a full model that includes all the data if desired.
There are myriad particular ways to partition data for niche/distributional models, but they can be split into two main categories that are offered in 1) Module: *Non-spatial Partition* and 2) Module: *Spatial Partition*.
**REFERENCES**
Guisan A., & Zimmermann N.E. (2000). Predictive habitat distribution models in ecology. *Ecological Modelling*, 135(2-3), 147-186. <a href="https://doi.org/10.1016/S0304-3800(00)00354-9" target="_blank">DOI: 10.1016/S0304-3800(00)00354-9</a>
Peterson, A.T., Soberón J., Pearson, R.G., Anderson, R.P., Martinez-Meyer, E., Nakamura M., & Araújo, M.B. (2011). Evaluating Model Performance and Significance. In: *Ecological Niches and Geographic Distributions*, Princeton, New Jersey: *Monographs in Population Biology*, 49. Princeton University Press. <a href="https://doi.org/10.23943/princeton/9780691136868.003.0009" target="_blank">DOI: 10.23943/princeton/9780691136868.003.0009</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_part.Rmd
|
---
title: "penvs"
output: html_document
---
### **Component: Process Environmental Data**
**ORIENTATION**
Environmental data may be processed in many ways for niche/distributional modeling: reclassification (re-categorizing the original cell values), resampling (changing the cell size), masking (cropping the grid based on a specified shape), etc. At present, **Component: Process Environmental Data** addresses one critical step: selecting a study region for analysis by masking the predictor variable grids. This determines the spatial extent for model building, including the environmental characteristics of the data used for comparison with records of the species' presence (e.g., the 'background' data; Peterson et al. 2011 chap. 7). By doing so, it also sets the range (and combinations) of environmental conditions associated with model building, allowing later flagging of 'non-analogous' conditions (e.g., when applying a model to another region or time period; Williams and Jackson 2007).
Selection of a study region is critical for niche/distribution modeling approaches that compare the environments associated with species presence data with those of some comparison dataset (including the Maxent approach; see **Component: Build and Evaluate Niche Model**). This decision defines the extent of grid cells for the comparison dataset (absences provided by the user, or pseudoabsence or background points sampled by the algorithm; Anderson 2013). Various, sometimes conflicting, principles for selecting a study region have been set forth in the literature (Peterson et al. 2011 chap. 7). Many researchers emphasize the geographic or environmental domain over which to build the model, whereas others suggest identification of areas where the species is likely to be at environmental equilibrium with the predictor variables (Vanderwal et al. 2009; Anderson and Raza 2010; Barve et al. 2011; Saupe et al. 2012; Franklin 2010 chap. 4; Anderson 2013; Merow et al. 2013). For example, one critical guiding principle (when estimates of suitability are desired, especially for use in other places and times) is that the study region should not include geographic areas that the species does not inhabit due to dispersal barriers. Inclusion of such areas will send a false negative signal, biasing the model's estimated response to the environment (Anderson 2015). Despite these theoretical suggestions, operational selection of the study region usually still depends on expert opinion and available natural history information (Acevedo et al. 2012; Gerstner et al. 2018).
*Wallace* provides several alternative ways for delimiting a study region. The first three options are based on shapes around the occurrence data, found under Module: *Select Study Region*: 1) a rectangular “bounding box” around occurrence localities, 2) a convex shape drawn around occurrence localities with minimized area (minimum convex polygon), or 3) buffers around occurrence localities. Users also have the option of drawing a study region by using the polygon drawing tool (Module: *Draw Study Region*. Alternatively, users can upload a polygon (Module: *User-specified Study Region*).
Any of these options can then be buffered by a user-defined distance in degrees.
After choosing a way to delimit the study region (**Step 1**), Wallace samples background points (= pixels; **Step 2**) from the environmental data according the number provided by the user. If that number is smaller than the total in the environmental data (within the chosen background extent), some environmental conditions may be missed in the sample. Depending upon the variables used in the final model, such a situation may lead to the need for environmental extrapolation in order to make a prediction to the full background extent (see **Components: Build and Evaluate Niche Model**, **Visualize Model Results**, and **Model Transfer**; Guevara et al. 2018). Conversely, if the user-specified number is higher than the total in the environmental data, a warning message advising the use of a smaller number will appear, including the maximum number of points allowed (the number of background points cannot be higher than total available in the chosen background extent).
**REFERENCES**
Acevedo, P., Jiménez‐Valverde, A., Lobo, J.M., & Real, R. (2012). Delimiting the geographical background in species distribution modelling. *Journal of Biogeography*, 39(8), 1383-1390. <a href="https://doi.org/10.1111/j.1365-2699.2012.02713.x" target="_blank">DOI: 10.1111/j.1365-2699.2012.02713.x</a>
Anderson, R.P. (2015). El modelado de nichos y distribuciones: no es simplemente "clic, clic, clic." [With English and French translations: Modeling niches and distributions: it's not just "click, click, click" and La modélisation de niche et de distributions: ce n'est pas juste "clic, clic, clic"]. *Biogeografía*, 8, 4-27. <a href="https://2278aec0-37af-4634-a250-8bb191f1aab7.filesusr.com/ugd/e41566_e8acb6f9c20c44fa9cd729161582857d.pdf" target="_blank">pdf</a>
Anderson, R.P. (2013). A framework for using niche models to estimate impacts of climate change on species distributions. *Annals of the New York Academy of Sciences*, 1297(1), 8-28. <a href="https://doi.org/10.1111/nyas.12264" target="_blank">DOI: 10.1111/nyas.12264</a>
Anderson, R.P., & Raza A. (2010). The effect of the extent of the study region on GIS models of species geographic distributions and estimates of niche evolution: preliminary tests with montane rodents (genus *Nephelomys*) in Venezuela. *Journal of Biogeography*, 37(7), 1378-1393. <a href="https://doi.org/10.1111/j.1365-2699.2010.02290.x" target="_blank">DOI: 10.1111/j.1365-2699.2010.02290.x</a>
Barve, N., Barve, V., Jiménez-Valverde, A., Lira-Noriega, A., Maher, S.P., Peterson A.T., Soberón J., & Villalobos F. (2011). The crucial role of the accessible area in ecological niche modeling and species distribution modeling. *Ecological Modelling*, 222(11), 1810-1819. <a href="https://doi.org/10.1016/j.ecolmodel.2011.02.011" target="_blank">DOI: 10.1016/j.ecolmodel.2011.02.011</a>
Franklin, J. (2010). Mapping Species Distributions: Spatial Inference and Prediction. Data for species distribution models: the biological data. In: *Mapping species distributions: spatial inference and prediction*. Cambridge: Cambridge University Press. <a href="https://doi.org/10.1017/CBO9780511810602" target="_blank">DOI: 10.1017/CBO9780511810602</a>
Gerstner, B.E., Kass, J.M., Kays, R., Helgen, K.M., & Anderson, R.P. (2018). Revised distributional estimates for the recently discovered olinguito (*Bassaricyon neblina*), with comments on natural and taxonomic history. *Journal of Mammalogy*, 99(2), 321-332. <a href="https://doi.org/10.1093/jmammal/gyy012" target="_blank">DOI: 10.1093/jmammal/gyy012</a>
Guevara, L., Gerstner, B.E., Kass, J.M., & Anderson, R.P. (2018). Toward ecologically realistic predictions of species distributions: A cross-time example from tropical montane cloud forests. *Global Change Biology*, 24(4), 1511-1522. <a href="https://doi.org/10.1111/gcb.13992" target="_blank">DOI: 10.1111/gcb.13992</a>
Merow, C., Smith, M.J., & Silander, J.A. (2013). A practical guide to MaxEnt for modeling species' distributions: what it does, and why inputs and settings matter. *Ecography*, 36(10), 1058-1069. <a href="https://doi.org/10.1111/j.1600-0587.2013.07872.x" target="_blank">DOI: 10.1111/j.1600-0587.2013.07872.x</a>
Peterson, A.T., Soberón, J., Pearson, R.G., Anderson, R.P., Martinez-Meyer, E., Nakamura M., & Araújo M.B. (2011). Modeling Ecological Niches. In: *Ecological Niches and Geographic Distributions*. Princeton, New Jersey: *Monographs in Population Biology*, 49. Princeton University Press. <a href="https://doi.org/10.23943/princeton/9780691136868.003.0005" target="_blank">DOI: 10.23943/princeton/9780691136868.003.0005</a>
Saupe, E.E., Barve, V., Myers, C.E., Soberón, J., Barve, N., Hensz, C.M., Peterson, A.T., Owens, H.L., & Lira-Noriega, A. (2012). Variation in niche and distribution model performance: the need for a priori assessment of key causal factors. *Ecological Modelling*, 237-238, 11-22. <a href="https://doi.org/10.1016/j.ecolmodel.2012.04.001" target="_blank">DOI: 10.1016/j.ecolmodel.2012.04.001</a>
Williams, J.W., & Jackson, S.T. (2007). Novel climates, no-analog communities, and ecological surprises. *Frontiers in Ecology and the Environment*, 5(9), 475-482. <a href="https://doi.org/10.1890/070037" target="_blank">DOI: 10.1890/070037</a>
VanDerWal, J., Shoo, L.P., Graham, C., & Williams, S.E. (2009). Selecting pseudo-absence data for presence-only distribution modeling: How far should you stray from what you know?. *Ecological Modelling*, 220(4), 589-594. <a href="https://doi.org/10.1016/j.ecolmodel.2008.11.010" target="_blank">DOI: 10.1016/j.ecolmodel.2008.11.010</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_penvs.Rmd
|
---
title: "poccs"
output: html_document
---
### **Component: Process Occurrence Data**
**ORIENTATION**
Biodiversity data (especially from aggregated online databases) typically suffer from errors and sampling biases, calling for better data quality and checking protocols (Costello et al. 2013). **Component: Process Occurrence Data** provides some simple ways for users to clean and process such datasets in order to reduce the effects of data characteristics that may be detrimental to results. *Wallace* currently allows users either to: 1) remove records by ID (Module: *Remove Occurrences By ID*), 2) spatial selection (Module: *Select Occurrences On Map*), or 3) thin records within a user-specified distance (Module: *Spatial Thin*). The first module addresses user-detected data errors, such as in georeferencing or identification (and also allows users to select occurrences from a subset of a species' range for analysis), whereas the second aims to reduce the effects of spatial sampling biases. These modules can be run in sequence (e.g. select points on the map, and then spatially thin).
**REFERENCES**
Costello, M. J., Michener, W. K., Gahegan, M., Zhang, Z. Q., & Bourne, P. E. (2013). Biodiversity data should be published, cited, and peer reviewed. *Trends in Ecology & Evolution*, 28(8), 454-461. <a href="https://doi.org/10.1016/j.tree.2013.05.002" target="_blank">DOI: 10.1016/j.tree.2013.05.002</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_poccs.Rmd
|
---
title: "Reproduce"
output: html_document
---
### **Component: Reproduce**
**ORIENTATION**
Over the decade of the 2010s, scientific practice increasingly emphasized documentation and reproducibility. In biodiversity science, the area of modeling species niches/distributions has advanced rapidly in this regard via the emergence of various kinds of community-driven standards (see Fitzpatrick et al. 2021 for an overview). These include checklists for data and model reporting (Feng et al. 2019), standardized metadata frameworks (RMMS, Merow et al. 2019; occCite, Owens et al., 2021), and detailed protocols for reporting (ODMAP, Zurell et al. 2020). These tools facilitate the implementation of best-practice guidelines to assess the quality of a model, indicating whether it meets minimal standards for applied biodiversity uses (Araújo et al. 2019; Sofaer et al. 2019). Heavily leveraging `ENMeval 2.0` and `rangeModelMetadata`, *Wallace* now uses Range Modeling Metadata Standards (RMMS) data objects (which also form the basis of ODMAP reporting) and allows the user to download them as a CSV file (or a ZIP file for multiple species). *Wallace* promotes documentation and downstream assessment of modeling quality by allowing users to download extensive information that includes sources of input data, methodological decisions, and results. One option for the documentation (see Module: *Download Session Code*) is a file that can be re-run in R to reproduce the analyses (if re-run on exactly the same versions of R and dependent packages). Many intermediate and advanced users of R likely will find this file useful as a template for modification. Additionally, *Wallace* now provides citations of the particular R packages (and their versions) used in a given analysis (Module: *Reference Packages*).
**REFERENCES**
Araújo, M.B., Anderson, R.P., Barbosa, A.M., Beale, C.M., Dormann, C.F., Early, R., Garcia, R.A., Guisan, A., Maiorano, L., Naimi, B., O’Hara, R.B., Zimmermann, N.E., & Rahbek, C. (2019). Standards for distribution models in biodiversity assessments. *Science Advances*, 5, 1. <a href="https://doi.org/10.1126/sciadv.aat4858" target="_blank">DOI: 10.1126/sciadv.aat4858</a>
Feng, X., Park, D.S., Walker, C., Peterson, A.T., Merow, C., & Papeş, M. (2019). A checklist for maximizing reproducibility of ecological niche models. *Nature Ecology & Evolution*, 3, 1382–1395. <a href="https://doi.org/10.1038/s41559-019-0972-5" target="_blank">DOI: 10.1038/s41559-019-0972-5</a>
Fitzpatrick, F.C., Lachmuth, S., & Haydt, N.T. (2021). The ODMAP protocol: a new tool for standardized reporting that could revolutionize species distribution modeling. *Ecography*, 44(7), 1067-1070. <a href="https://doi.org/10.1111/ecog.05700" target="_blank">DOI: 10.1111/ecog.05700</a>
Kass, J. M, Muscarella, R., Galante, P. J, Bohl, C. L., Pinilla-Buitrago, G. E., Boria, R. A., Soley-Guardia, M., Anderson, R. P. (2021). ENMeval 2.0: Redesigned for customizable and reproducible modeling of species’ niches and distributions. *Methods in Ecology and Evolution*, 12(9), 1602– 1608. <a href="https://doi.org/10.1111/2041-210X.13628" target="_blank">DOI: 10.1111/2041-210X.13628</a>
Merow, C., Maitner, B.S., Owens, H.L., Kass, J.M., Enquist, B.J., Jetz, W., & Guralnick, R.P. (2019). Species’ range model metadata standards: RMMS. *Global Ecology and Biogeography*, 28(12), 1912–1924. <a href="https://doi.org/10.1111/geb.12993" target="_blank">DOI: 10.1111/geb.12993</a>
Owens, H.L., Merow, C., Maitner, B.S., Kass, J.M., Barve, V., Guralnick, R.P., (2021). occCite: Tools for querying and managing large biodiversity occurrence datasets. *Ecography*, 44(8), 1228-1235. <a href="https://doi.org/10.1111/ecog.05618" target="_blank">DOI: 10.1111/ecog.05618</a>
Sofaer, H.R., Jarnevich, C.S., Pearse, I.S., Smyth, R.L, Auer, S., Cook, G.L., Edwards, T.C., Guala, G.F., Howard, T.G., Morisette, J.T., & Hamiliton, H. (2019). Development and delivery of species distribution models to inform decision-making. *BioScience*, 69(7), 544–557.
<a href="https://doi.org/10.1093/biosci/biz045" target="_blank">DOI: 10.1093/biosci/biz045</a>
Zurell, D., et al. (2020). A standard protocol for reporting species distribution models. *Ecography*, 43(9), 1261–1277. <a href="https://doi.org/10.1111/ecog.04960" target="_blank">DOI: 10.1111/ecog.04960</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_rep.Rmd
|
---
title: "vis"
output: html_document
---
### **Component: Visualize Model Results**
**ORIENTATION**
Niche/distributional models can be used to make transfers across geographic space, and the modeled response can be examined in environmental space as well (Elith and Graham 2009; Guisan and Zimmermann 2000). Additionally, inspecting quantitative measures of performance constitutes a key exercise. **Component: Visualize Model Results** gives the user options for all of these. *Wallace* provides 1) bivariate environmental envelope plots for BIOCLIM models (Module: *BIOCLIM Envelope Plots*), 2) plots showing evaluation results over the range of Maxent models explored (Module: *Maxent Evaluation Plots*), 3) response curves that depict how model suitability relates to changes in the environmental predictor variables (Module: *Plot Response Curves*), and 4) maps of model predictions in the study region (Module: *Map Prediction*). All plots are displayed in the “Results” tab, and the geographic projection appears in the “Map” tab.
**REFERENCES**
Elith, J., & Graham, C.H. (2009). Do they? How do they? WHY do they differ? On finding reasons for differing performances of species distribution models. *Ecography*, 32, 66-77. <a href="https://doi.org/10.1111/j.1600-0587.2008.05505.x" target="_blank">DOI: 10.1111/j.1600-0587.2008.05505.x</a>
Guisan, A., & Zimmermann, N.E. (2000). Predictive habitat distribution models in ecology. *Ecological Modelling*, 135(2-3), 147-186. <a href="https://doi.org/10.1016/S0304-3800(00)00354-9" target="_blank">DOI: 10.1016/S0304-3800(00)00354-9</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_vis.Rmd
|
---
title: "xfer"
output: html_document
---
### **Component: Model Transfer**
**ORIENTATION**
Frequently, research questions require the application (or “transfer”) of a model to a geographic region or time period different from those used to build it (e.g., for studies of invasive species or the effects of climate change). **Component: Model Transfer** allows certain functionalities for such transfers, as well as the means for assessing issues regarding environmental conditions not found in the space and time where the model was built (non-analog environments; Williams and Jackson 2007, Fitzpatrick and Hargrove 2009). Wallace currently allows users to transfer a model to: 1) another region (Module: *Transfer to New Extent*), 2) another time period (Module: *Transfer to new time*), or 3) a user-provided environment (Module: *Transfer to User environment*).
Note: Transferring can also be known as a “projection”, but users should not confuse this with the GIS concept of geographic projections.
Furthermore, at present *Wallace* provides some information characterizing the degree to which the environment in the spatial/temporal transfer differs from that used to make the model (Module: *Calculate Environmental Similarity*). For these functionalities, only one transfer can be displayed at a time, and Module: *Calculate Environmental Similarity* can only be run after a transfer has been made.
**REFERENCES**
Fitzpatrick, M.C., & Hargrove, W.W. (2009). The projection of species distribution models and the problem of non-analog climate. *Biodiversity and Conservation*, 18, 2255. <a href="https://doi.org/10.1007/s10531-009-9584-8" target="_blank">DOI: 10.1007/s10531-009-9584-8</a>
Williams, J.W., & Jackson, S.T. (2007). Novel climates, no-analog communities, and ecological surprises. *Frontiers in Ecology and the Environment*, 5(9), 475-482. <a href="https://doi.org/10.1890/070037" target="_blank">DOI: 10.1890/070037</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/gtext_xfer.Rmd
|
---
title: 'REFERENCES'
bibliography: 'references.bib'
nocite: '@*'
---
```{r, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
knitr::opts_chunk$set(message = FALSE, warning = FALSE, eval = FALSE)
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/references.Rmd
|
---
title: "intro"
output: html_document
---
### **What is *Wallace*?**
<img src="logo.png" alt="logo" style="width: 150px; float:right; padding:10px;"/>
Welcome to *Wallace*, a flexible application for reproducible ecological modeling, built for community expansion. The current version of *Wallace* (v2.1.2) steps the user through a full niche/distribution modeling analysis, from data acquisition to visualizing results.
The application is written in `R` with the web app development package `shiny`. Please find the stable version of *Wallace* on <a href="https://CRAN.R-project.org/package=wallace" target="_blank">CRAN</a>, and the development version on <a href="https://github.com/wallaceEcoMod/wallace" target="_blank">Github</a>. We also maintain a *Wallace* <a href="https://wallaceecomod.github.io/" target="_blank">website</a> that has some basic info, links, and will be updated with tutorial materials in the near future.
*Wallace* is designed to facilitate spatial biodiversity research, and currently concentrates on modeling species niches and distributions using occurrence datasets and environmental predictor variables. These models provide an estimate of the species' response to environmental conditions, and can be used to generate maps that indicate suitable areas for the species (i.e. its potential geographic distribution; Guisan & Thuiller 2005; Elith & Leathwick 2009; Franklin 2010a; Peterson et al. 2011). This research area has grown tremendously over the past two decades, with applications to pressing environmental issues such as conservation biology (Franklin 2010b), invasive species (Ficetola et al. 2007), zoonotic diseases (González et al. 2010), and climate-change impacts (Kearney et al. 2010).
Also, for more detail, please see our initial publication in *Methods in Ecology and Evolution* and our follow-up in *Ecography*.
Kass J. M., Vilela B., Aiello-Lammens M. E., Muscarella R., Merow C., Anderson R. P. (2018). *Wallace*: A flexible platform for reproducible modeling of species niches and distributions built for community expansion. *Methods in Ecology and Evolultion*, 9(4): 1151-1156. <a href="https://doi.org/10.1111/2041-210X.12945" target="_blank">DOI: 10.1111/2041-210X.12945</a>
Kass, J.M., Pinilla-Buitrago, G.E, Paz, A., Johnson, B.A., Grisales-Betancur, V., Meenan, S.I., Attali, D., Broennimann, O., Galante, P.J., Maitner, B.S., Owens, H.L., Varela, S., Aiello-Lammens, M.E., Merow, C., Blair, M.E., Anderson R.P. (2022). *wallace* 2: a shiny app for modeling species niches and distributions redesigned to facilitate expansion via module contributions. *Ecography*, 2023(3): e06547. <a href="https://doi.org/10.1111/ecog.06547" target="_blank">DOI: 10.1111/ecog.06547</a>.
### **Who is *Wallace* for?**
We engineered *Wallace* to be used by a broad audience that includes graduate students, ecologists, conservation practitioners, natural resource managers, educators, and programmers. Anyone, regardless of programming ability, can use *Wallace* to perform an analysis, learn about the methods, and share the results. Additionally, those who want to disseminate a technique can author a module for *Wallace*.
### **Attributes of _Wallace_**
* **accessible**: lowers barriers to implement cutting-edge SDM techniques, offers support through various networks (Google Group, email, etc.)
* **open**: the code is free to use and modify (GPL 3.0), and it gives users access to some of the largest public online biodiversity databases
* **expandible**: users can author and contribute modules that enable new methodological options
* **flexible**: options for user uploads and downloads of results
* **interactive**: includes an embedded zoomable `leaflet` map, sortable `DF` data tables, and visualizations of results
* **instructive**: features guidance text that educates users about theoretical and analytical aspects of each step in the workflow
* **reproducible**: users can download an `rmarkdown` .Rmd file that when run reproduces the analysis, ability to save sessions and load later
### **_Wallace_ website**
For more information and relevant links see our <a href="https://wallaceecomod.github.io/" target="_blank">website</a>.
### **Watch webinars about _Wallace_**
*The following webinar was part of "ENM 2020", a free online course on ecological niche modeling, organized by Town Peterson. The full series can be found on YouTube: <a href="https://www.youtube.com/playlist?list=PLhEJuWmv8Jf67qSdifDvgOk5DOJsNNiam" target="_blank">ENM 2020</a>.*
Kass, J.M. and G.E. Pinilla-Buitrago. 18 May 2020. “Wallace Ecological Modeling Application: flexible and reproducible modeling of species’ niches and distributions built for community expansion.” ENM 2020: Online course in ecological niche modeling (Peterson, A. T. editor), <a href="https://youtu.be/kWNyNd2X1uo" target="_blank">Week 19, Talk 2</a>.
*The following webinar was the "37th Global Online Biodiversity Informatics Seminar" in the Biodiversity Informatics Training Curriculum organized by Town Peterson.*
Kass, J. M. 9 May 2018. "WALLACE: A flexible platform for reproducible modeling of species niches and distributions built for community expansion." Broadcast from the City College of New York, City University of New York. <a href="https://www.youtube.com/watch?v=00CSd9vx2CE&feature=youtu.be" target="_blank">Global Online Seminar #37 - Wallace</a>.
*Para seminarios en español, los siguientes seminarios fueron organizados por Angela Cuervo como parte de la serie Modelado de Distribuciones Potenciales y Analisis Espaciales.*
Paz, A. 3 October 2023. "Wallace EcoMod: Nuevas funcionalidades para aplicaciones en conservación". <a href="https://www.youtube.com/live/_X5fXqRJ_EY?si=xHbQSw9dnvQemqAJ" target="_blank">Seminarios 2023 - Wallace EcoMod</a>
Anderson, R. P. 21 May 2018. "El software Wallace para modelar nichos y distribuciones: Un coche con motor R, volante de ratón y cerebro de humano." Broadcast from the City College of New York, City University of New York. <a href="https://www.youtube.com/watch?v=0652g9PDKp4" target="_blank">Analisis espaciales: 2017 - El software Wallace</a>.
*For more videos, check out the <a href="https://www.youtube.com/channel/UCDSLCE5bmw12B7oqmlKk7rg" target="_blank">Wallace EcoMod YouTube channel</a>.*
### **Contribute to _Wallace_**
Contributors should submit pull requests to the *Wallace* <a href="https://github.com/wallaceEcoMod/wallace" target="_blank">Github account</a> for module authorship or significant code contributions to either the UI or server files. Also, please connect on Github to post code-related issues and the <a href="https://groups.google.com/forum/#!forum/wallaceecomod" target="_blank">Google Group</a> for methodological and other broader-scope questions, thoughts, or suggestions for improvement.
If you use *Wallace* in your teaching, we would like to hear about your experiences. Please take a moment to complete the short survey: <a href="https://docs.google.com/forms/d/e/1FAIpQLSdR4qVprBBpyEZwF4sAurjKuXrxggEA7jWnINenltnUY3nWnA/viewform?usp=sf_link" target="_blank">Wallace external workshop and curriculum survey</a>.
### **Contact us**
Please <a href="mailto:[email protected]" target="_blank">email us</a> with any other questions.
### **Cite _Wallace_**
If you use Wallace in your research, please cite:
Kass, J.M., Pinilla-Buitrago, G.E, Paz, A., Johnson, B.A., Grisales-Betancur, V., Meenan, S.I., Attali, D., Broennimann, O., Galante, P.J., Maitner, B.S., Owens, H.L., Varela, S., Aiello-Lammens, M.E., Merow, C., Blair, M.E., Anderson R.P. (2022). *wallace* 2: a shiny app for modeling species niches and distributions redesigned to facilitate expansion via module contributions. *Ecography*, 2023(3): e06547. <a href="https://doi.org/10.1111/ecog.06547" target="_blank">DOI: 10.1111/ecog.06547</a>
***
#### **Acknowledgments**
We dedicate this software to Alfred Russel Wallace, the co-discoverer of evolution by natural selection and the founder of the field of biogeography.
Currently, *Wallace* is being expanded via funding from the U.S. National Science Foundation DBI-1661510 and NASA 80NSSC18K0406.
*Wallace* was inspired by the 2015 Ebbe Nielsen Challenge of the Global Biodiversity Information Facility (GBIF), for which it was recognized as a finalist and received prize funding.
This material is based upon work supported by the U.S. National Science Foundation (NSF) and National Aeronautics and Space Administration (NASA) under Grant Numbers NSF DBI-1661510 (RPA), DBI-1650241 (RPA), DEB-1119915 (RPA), DEB-1046328 (MEA), and DBI-1401312 (RM); and NASA 80NSSC18K0406. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation or of NASA.
Additional sources of funding include: for JMK, a CUNY Science Scholarship and a CUNY Graduate Center Provost Digital Innovation Grant; for BV, a Coordination for the Improvement of Higher Education Personnel (CAPES) doctoral grant from Brazil; for Grisales-Betancur, a fellowship of the 'Asociación Nacional de Empresarios' from Colombia; for Meenan, the City College Fellows program.
Mahmoud Shahin designed the WallaceEcoMod logo with inspiration from “Wallace’s butterfly” (*Ornithoptera croesus*; Wallace’s golden birdwing), an idea first suggested by Samuel Chang.
#### **References**
1. Anderson, R. P. (2012). Harnessing the world's biodiversity data: promise and peril in ecological niche modeling of species distributions. *Annals of the New York Academy of Sciences*, 1260: 66-80.
2. Anderson, R. P. (2015). El modelado de nichos y distribuciones: no es simplemente "clic, clic, clic." [With English and French translations: Modeling niches and distributions: it's not just "click, click, click" and La modélisation de niche et de distributions: ce n'est pas juste "clic, clic, clic"]. *Biogeografía*, 8: 4-27.
3. Elith J. & Leathwick J.R. (2009). Species distribution models: ecological explanation and prediction across space and time. *Annual Review of Ecology, Evolution, and Systematics*, 40: 677-697.
4. Ficetola G.F., Thuiller W. & Miaud C. (2007) Prediction and validation of the potential global distribution of a problematic alien invasive species ― the American bullfrog. *Diversity and Distributions*, 13: 476-485.
5. Franklin J. (2010a). Mapping species distributions: spatial inference and prediction. Cambridge: Cambridge University Press.
6. Franklin J. (2010b) Moving beyond static species distribution models in support of conservation biogeography. *Diversity and Distributions*, 16: 321-330.
7. González, C., Wang, O., Strutz, S. E., González-Salazar, C., Sánchez-Cordero, V., & Sarkar, S. 2010. Climate change and risk of leishmaniasis in North America: predictions from ecological niche models of vector and reservoir species. *PLoS Neglected Tropical Diseases*, 4: e585.
8. Guisan A. & Thuiller W. (2005). Predicting species distribution: offering more than simple habitat models. *Ecology Letters*, 8: 993-1009.
9. Kearney M.R., Wintle B.A. & Porter W.P. (2010) Correlative and mechanistic models of species distribution provide congruent forecasts under climate change. *Conservation Letters*, 3: 203-213.
10. Peterson A.T., Soberón J., Pearson R.G., Anderson R.P., Martinez-Meyer E., Nakamura M., Araújo M.B. (2011). Ecological niches and geographic distributions. Princeton, New Jersey: Monographs in Population Biology, 49. Princeton University Press.
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/text_about.Rmd
|
---
title: "How To Use Wallace"
output: html_document
---
### **Overview of** ***Wallace***
This information is designed to orient the user to the *Wallace* interface. For detailed instructions and a sample walkthrough, please consult the <a href="https://wallaceecomod.github.io/wallace/articles/tutorial-v2.html" target="_blank">vignette</a>.
*Para obtener instrucciones detalladas y un tutorial de muestra en español, consulte <a href="https://wallaceecomod.github.io/wallace/articles/tutorial-v2-esp.html" target="_blank">la viñeta en español</a>.*
#### **Components and Modules**
*Wallace* is composed of **Components** – discrete steps in the workflow. Navigate through the components by clicking on the names in the top orange navigation panel. Components need to be run consecutively, but a few are optional (e.g., **Env Space**).
Within each component, there are various major options that can be run. These are the ***modules***. Selecting a module opens the control panel to make decisions and run the module’s functionalities. For some components, the modules are mutually exclusive (e.g., in **Env Data**, only one choice can be selected), but in others this is not the case (e.g., in **Process Occs**, all three modules can be run successively).
#### **Log Window and Visualization Panel**
Analyses performed will be detailed in the log window. This is also where error messages appear.
After running the functionalities of a *module*, outputs appear in the Visualization panel, which includes an interactive map, Occurrence table, and the Results tab, as relevant. The Visualization panel also includes guidance texts and the Save tab (see below).
#### **Guidance Texts**
While Wallace makes it easy to perform analyses through the workflow of its Graphical User Interface (GUI) without coding, the theory and methodologies behind the decisions should be considered carefully (Kass et al. 2018). The title of one essay aimed at students and researchers entering the field put it more bluntly: ‘Modeling niches and distributions: it's not just "click, click, click"’ (Anderson, 2015). Wallace aims to fulfill the call for software in the field that automates “repetitive aspects of the process, while allowing (and forcing) the user to provide input when critical biological and conceptual decisions need to be made” (Anderson, 2012: p. 77).
Wallace promotes thought and careful decision making by offering guidance text for each component and module to orient the user and assist in best practices. To understand the analyses run in Wallace and be able to explain and justify them, users likely will need to read relevant literature and discuss many issues extensively with their peers. An enormous literature now exists regarding models of species niches and distributions (Franklin 2010, Peterson et al. 2011, Guisan et al. 2017, Zurell et al. 2020). To facilitate entry into this literature, the Wallace guidance text points users toward some sources relevant to the given component or module. Additionally, extensive open-access online resources exist (e.g., free lectures from the ENM2020 course; Peterson et al. 2022).
As the user proceeds through the Wallace workflow, the relevant guidance texts can be found to the right of the Results tab in the Visualization panel.
If more support is needed, the Support tab in the orange navigation bar at the top provides links to the Wallace homepage, Google group, GitHub, and email.
#### **Saving and Reproducing Results**
Some users may wish to stop an analysis and restart it later. To do so, the option to save the workflow progress as an RDS file is found in the Save tab. This file can be loaded into Wallace later using the Intro component’s Load Prior Session tab, to restart the analysis where the user left off.
Additionally, *Wallace* allows the user to download their results. After each step of analysis (i.e., after running each module), the results for that particular model may be downloaded from the Save tab in the Visualization panel.
A great quality of *Wallace* is reproducibility. To download the session code or metadata (documenting all of the analyses run to that point in the Wallace session), use the **Reproduce** component. This includes the option of an R Markdown file that can be opened and rerun in R.
Closing the browser window will terminate the Wallace analysis, but R will remain running. To close Wallace and stop functions running in R, use the power button in the top right corner in the navigation bar.
#### **References**
Anderson, R. P. (2015). El modelado de nichos y distribuciones: no es simplemente "clic, clic, clic." [With English and French translations: Modeling niches and distributions: it's not just "click, click, click" and La modélisation de niche et de distributions: ce n'est pas juste "clic, clic, clic"]. *Biogeografía*, 8, 4-27. <a href="https://2278aec0-37af-4634-a250-8bb191f1aab7.filesusr.com/ugd/e41566_e8acb6f9c20c44fa9cd729161582857d.pdf" target="_blank">pdf</a>
Anderson, R.P. (2012). Harnessing the world's biodiversity data: promise and peril in ecological niche modeling of species distributions. *Annals of the New York Academy of Sciences*, 1260(1), 66-80. <a href="https://doi.org/10.1111/j.1749-6632.2011.06440.x" target="_blank">DOI:10.1111/j.1749-6632.2011.06440.x</a>
Franklin, J. (2010). *Mapping species distributions*. Cambridge University Press. <a href="https://doi.org/10.1017/CBO9780511810602" target="_blank">DOI:10.1017/CBO9780511810602</a>
Guisan, A., Thuiller, W., & Zimmermann, N. E. (2017). Habitat suitability and distribution models: With applications in R. Cambridge University Press. <a href="https://doi.org/10.1017/9781139028271" target="_blank">DOI:10.1017/9781139028271</a>
Kass, J.M., Vilela, B., Aiello-Lammens, M.E., Muscarella, R., Merow, C., & Anderson, R.P. (2018). Wallace: A flexible platform for reproducible modeling of species niches and distributions built for community expansion. *Methods in Ecology and Evolution*, 9(4), 1151-1156. <a href="https://doi.org/10.1111/2041-210X.12945" target="_blank">DOI:10.1111/2041-210X.12945</a>
Peterson, A. T. et al. (2022). ENM2020: A Free Online Course and Set of Resources on Modeling Species’ Niches and Distributions. *Biodiversity Informatics*, 17. <a href="https://doi.org/10.17161/bi.v17i.15016" target="_blank">DOI:10.17161/bi.v17i.15016</a>
Peterson, A. T., Soberón, J., Pearson, R. G., Anderson, R. P., Martínez-Meyer, E., Nakamura, M., & Araújo, M. B. (2011). *Ecological niches and geographic distributions* (MPB-49). Princeton University Press. <a href="https://press.princeton.edu/books/paperback/9780691136882/ecological-niches-and-geographic-distributions-mpb-49" target="_blank">Princeton University Press</a>
Zurell, D., Franklin, J., König, C., Bouchet, P.J., Dormann, C.F., Elith, J., Fandos, G., Feng, X., Guillera-Arroita, G., Guisan, A., Lahoz-Monfort, J.J., Leitão, P.J., Park, D.S., Peterson, A.T., Rapacciuolo, G., Schmatz, D.R., Schröder, B., Serra-Diaz, J.M., Thuiller, W., Yates, K.L., Zimmermann,N.E., & Merow, C. (2020). A standard protocol for reporting species distribution models. *Ecography*, 43(9), 1261-1277. <a href="https://doi.org/10.1111/ecog.04960" target="_blank">DOI:10.1111/ecog.04960</a>
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/text_how_to_use.Rmd
|
---
title: "intro_tab"
output: html_document
---
#### WORKFLOW
*Wallace* (v2.1.2) currently includes ten components, or steps of a possible workflow. Each component includes two or more modules, which are possible analyses for that step.
**Components:**
**1.** *Obtain Occurrence Data*
- Query Present Database
- User-specified Occurrences
**2.** *Obtain Environmental Data*
- WorldClim
- EcoClimate
- User-specified Environmental Data
**3.** *Process Occurrence Data*
- Select Occurrences on Map
- Remove Occurrences by ID
- Spatial Thin
**4.** *Process Environmental Data*
- Select Study Region by Extent
- Draw Study Region
- User-specified Study Region
**5.** *Characterize Environmental Space*
- Environmental Ordination
- Occurrence Density Grid
- Niche Overlap
**6.** *Partition Occurrence Data*
- Non-spatial Partition
- Spatial Partition
**7.** *Build and Evaluate Niche Model*
- Maxent
- BIOCLIM
**8.** *Visualize Model Results*
- Map Prediction
- Maxent Evaluation Plots
- Plot Response Curves
- BIOCLIM Envelope Plots
**9.** *Model Transfer*
- Transfer to New Extent
- Transfer to New Time
- Transfer to User Environments
- Calculate Environmental Similarity
**10.** *Reproduce*
- Download Session Code
- Download Metadata
- Download Package References
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/text_intro_tab.Rmd
|
---
title: "text_loadsesh"
output: html_document
---
Users now have the option to stop and save their work, so that they can resume at a later time.
Each component (Obtain Occurrence Data, Obtain Environmental Data, etc.) has a Save Session feature within the ‘Save’ tab, allowing users to save their progress up to that point as an RDS file (.rds).
This file can be uploaded here, in the Load Session tab, allowing the user to continue the workflow where they left off.
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/text_loadsesh.Rmd
|
---
title: "team"
output: html_document
---
#### *Wallace* was created and expanded by an international team of ecologists and biogeographers:
<br>
## Developers
<img src="img/jamie.jpg" alt="jamie" style="width: 100px;"/>
<a href=" https://jamiemkass.github.io/" target="_blank">Jamie M. Kass</a> (co-lead developer) received his PhD at CUNY Graduate Center and City College of New York, did a Postdoc at Okinawa Institute of Science and Technology, and currently is Associate Professor at Tohoku University.
<br>
<img src="img/gonzalo.png" alt="gonzalo" style="width: 100px;"/>
<a href="https://scholar.google.no/citations?user=xlxAr_EAAAAJ&hl=en" target="_blank">Gonzalo E. Pinilla-Buitrago</a> (co-lead developer) received his PhD from the CUNY Graduate Center and City College of New York. He is currently a Postdoctoral Researcher at University of Connecticut.
<br>
<img src="img/andrea.png" alt="andrea" style="width: 100px;"/>
<a href="https://andrepazv.github.io" target="_blank">Andrea Paz</a> (developer) received her PhD at CUNY Graduate Center and City College of New York, after which she was a Postdoctoral Researcher at the Crowther Lab in ETH Zürich. She is now an Assistant Professor at the Biological Sciences Department, University of Montréal.
<br>
<img src="img/bethany.jpg" alt="bethany" style="width: 100px;"/>
<a href="https://github.com/bjohnso005" target="_blank">Bethany A. Johnson</a> (developer) received her MS in Biology from the City College of New York and is currently a Visiting Scientist at the Center for Biodiversity & Conservation at the American Museum of Natural History.
<br>
<img src="img/daniel.jpeg" alt="dani" style="width: 100px;"/>
<a href="https://www.amnh.org/research/staff-directory/daniel-lopez-lozano" target="_blank">Daniel López Lozano</a> (developer) is a Biodiversity Informatics Specialist at the American Museum of Natural History's Center for Biodiversity & Conservation.
<br>
<img src="img/valentina.jpeg" alt="valentina" style="width: 100px;"/>
<a href="https://www.researchgate.net/profile/Valentina-Grisales-Betancur" target="_blank">Valentina Grisales-Betancur</a> (developer) completed her undergraduate degree at EAFIT University in Colombia and visited the Anderson lab at CCNY and Blair lab at AMNH.
<br>
<img src="img/dean.png" alt="dean" style="width: 100px;"/>
<a href="https://deanattali.com" target="_blank">Dean Attali</a> (developer, consultant) is an R-Shiny developer and consultant with a MSc in Bioinformatics from the University of British Columbia.
<br>
## Managers
<img src="img/rob.jpeg" alt="rob" style="width: 100px;"/>
<a href="https://www.andersonlab.ccny.cuny.edu/" target="_blank">Robert P. Anderson</a> (lead manager, developer) is a Professor of Biology at City College of New York, CUNY.
<br>
<img src="img/matt.png" alt="matt" style="width: 100px;"/>
<a href="https://www.pace.edu/profile/matthew-aiello-lammens?dyson" target="_blank">Matthew Aiello-Lammens</a> (co-manager, developer) is an Associate Professor of Biology at Pace University.
<br>
<img src="img/cory.png" alt="cory" style="width: 100px;"/>
<a href="https://scholar.google.com/citations?user=AjOjxAsAAAAJ&hl=en" target="_blank">Cory Merow</a> (co-manager, developer) is currently a faculty researcher at the University of Connecticut.
<br>
<img src="img/mary.png" alt="mary" style="width: 100px;"/>
<a href="https://www.amnh.org/research/staff-directory/mary-e-blair" target="_blank">Mary E. Blair</a> (co-manager) is the Director of Biodiversity Informatics Research at the Center for Biodiversity & Conservation at the American Museum of Natural History.
<br>
## Contributors
<img src="img/sarah.png" alt="sarah" style="width: 100px;"/>
Sarah Meenan (contributor) completed her undergraduate degree from the City College of New York and now works for the NYC Parks Department.
<br>
<img src="img/olivier.jpeg" alt="olivier" style="width: 100px;"/>
<a href="https://www.unil.ch/ecospat/en/home/menuinst/teamstudentsvisitors/team/in-lausanne/olivier-broennimann-first-as.html" target="_blank">Olivier Broennimann</a> (contributor, external partner) is a staff scientist in the Department of Ecology and Evolution at University of Lausanne.
<br>
<img src="img/peteG.jpg" alt="peteG" style="width: 100px;"/>
<a href="https://www.amnh.org/research/staff-directory/peter-galante" target="_blank">Peter J. Galante</a> (contributor) was formerly a Biodiversity Informatics Scientist at the Center for Biodiversity & Conservation at the American Museum of Natural History and now works as a Project Manager for Storke, LLC, a renewable energy company.
<br>
<img src="img/brianM.jpeg" alt="brianM" style="width: 100px;"/>
<a href="https://www.researchgate.net/profile/Brian-Maitner" target="_blank">Brian S. Maitner</a> (contributor, external partner) is a researcher at the Geography Department of the University at Buffalo, SUNY.
<br>
<img src="img/hannahO.jpeg" alt="hannahO" style="width: 100px;"/>
<a href="https://hannahlowens.weebly.com/" target="_blank">Hannah Owens</a> (contributor, external partner) is an assistant professor at the Center for Global Mountain Biodiversity & the Center for Macroecology, Evolution, and Climate; Section for Biodiversity; Globe Institute; at the University of Copenhagen.
<br>
<img src="img/saraV.jpeg" alt="saraV" style="width: 100px;"/>
<a href="https://paleobiogeography.org/" target="_blank">Sara Varela</a> (contributor, external partner) is a Principal Investigator at the MAPAS Lab at the University of Vigo in Spain.
<br>
## Past Developers
<img src="img/bob.png" alt="bob" style="width: 100px;"/>
<a href="https://bobmuscarella.weebly.com/index.html" target="_blank">Robert Muscarella</a> (contributor, past developer) is an Associate Professor at Uppsala University in Sweden.
<br>
<img src="img/bruno.png" alt="bruno" style="width: 100px;"/>
<a href="https://bvilela.weebly.com/" target="_blank">Bruno Vilela</a> (contributor, past developer) is a professor at Universidade Federal da Bahia in Brazil.
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/text_team.Rmd
|
---
title: Wallace Session `r Sys.Date()`
---
```{r, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
knitr::opts_chunk$set(message = FALSE, warning = FALSE, eval = FALSE)
```
Please find below the R code history from your *Wallace* v2.1.2 session.
You can reproduce your session results by running this R Markdown file in RStudio.
Each code block is called a "chunk", and you can run them either one-by-one or all at once by choosing an option in the "Run" menu at the top-right corner of the "Source" pane in RStudio.
For more detailed information see <http://rmarkdown.rstudio.com>).
### Package installation
Wallace uses the following R packages that must be installed and loaded before starting.
```{r}
library(spocc)
library(spThin)
library(dismo)
library(sf)
library(ENMeval)
library(wallace)
```
The *Wallace* session code .Rmd file is composed of a chain of module functions that are internal to *Wallace*. Each of these functions corresponds to a single module that the user ran during the session. To see the internal code for these module functions, click on the links in the .Rmd file. Users are encouraged to write custom code in the .Rmd directly to modify their analysis, and even modify the module function code to further customize. To see the source code for any module function, just type its name into the R console and press Return.
```{r}
# example:
# just type the function name and press Return to see its source code
# paste this code into a new script to edit it
occs_queryDb
```
Your analyses are below.
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/userReport_intro.Rmd
|
---
params:
multAbr: ""
spName1: ""
spName2: ""
child_rmds: ""
---
```{r, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
knitr::opts_chunk$set(message = FALSE, warning = FALSE, eval = FALSE)
```
-------------------------------------------------------------------------------
## ESPACE analysis for *`r params$spName1`* and *`r params$spName2`* (`r params$multAbr`)
```{r, comment='', echo=FALSE, message=FALSE, warning=FALSE, eval=TRUE, results="asis"}
for (component_rmds in params$child_rmds) {
for (rmd in component_rmds) {
cat(knitr::knit_child(rmd, quiet = TRUE))
}
}
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/userReport_multSpecies.Rmd
|
---
params:
spName: ""
spAbr: ""
child_rmds: ""
---
```{r, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
knitr::opts_chunk$set(message = FALSE, warning = FALSE, eval = FALSE)
```
-------------------------------------------------------------------------------
## Analysis for *`r params$spName`* (`r params$spAbr`)
```{r, comment='', echo=FALSE, message=FALSE, warning=FALSE, eval=TRUE, results="asis"}
for (component_rmds in params$child_rmds) {
for (rmd in component_rmds) {
cat(knitr::knit_child(rmd, quiet = TRUE))
}
}
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/Rmd/userReport_species.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# global.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
library(wallace)
library(glue)
MB <- 1024^2
UPLOAD_SIZE_MB <- 5000
options(shiny.maxRequestSize = UPLOAD_SIZE_MB*MB)
SAVE_SESSION_SIZE_MB_WARNING <- 100
source("helpers.R")
# Load all Wallace base modules (old format)
# TODO this should not exist after moving all modules to the new format
base_module_files <- list.files('modules', pattern = "\\.R$", full.names = TRUE)
for (file in base_module_files) source(file, local = TRUE)
# The components that have modules. These names must match the values of the
# tabs of the components in the UI.
COMPONENTS <- c("occs", "envs", "poccs", "penvs", "espace", "part", "model",
"vis", "xfer", "rep")
# Information about modules that various parts of the app need access to
COMPONENT_MODULES <- list()
# Load all Wallace base modules
base_module_configs <- c(
"modules/occs_queryDb.yml",
# "modules/occs_paleoDb.yml",
"modules/occs_userOccs.yml",
"modules/envs_worldclim.yml",
"modules/envs_ecoclimate.yml",
"modules/envs_userEnvs.yml",
"modules/poccs_selectOccs.yml",
"modules/poccs_removeByID.yml",
"modules/poccs_thinOccs.yml",
"modules/penvs_bgExtent.yml",
"modules/penvs_drawBgExtent.yml",
"modules/penvs_userBgExtent.yml",
"modules/espace_pca.yml",
"modules/espace_occDens.yml",
"modules/espace_nicheOv.yml",
"modules/part_nonSpat.yml",
"modules/part_spat.yml",
"modules/model_maxent.yml",
"modules/model_bioclim.yml",
"modules/vis_mapPreds.yml",
"modules/vis_maxentEvalPlot.yml",
"modules/vis_responsePlot.yml",
"modules/vis_bioclimPlot.yml",
"modules/xfer_area.yml",
"modules/xfer_time.yml",
"modules/xfer_user.yml",
"modules/xfer_mess.yml",
"modules/rep_markdown.yml",
"modules/rep_rmms.yml",
"modules/rep_refPackages.yml"
)
# Load user-defined modules
user_module_configs <- getOption("wallace_module_configs")
all_module_configs <- c(base_module_configs, user_module_configs)
for (module_config_file in all_module_configs) {
# Read each user-defined module config file
module_config <- yaml::read_yaml(module_config_file)
config_dir <- dirname(module_config_file)
id <- tools::file_path_sans_ext(basename(module_config_file))
module_config$id <- id
# Perform lots of error checking to ensure the module was written properly
required_fields <- c("component", "short_name", "long_name", "authors", "package")
if (id == "main") {
stop("A module cannot be named `main`", call. = FALSE)
}
if (!grepl("^[A-Za-z0-9_]+$", id)) {
stop("Module {id}: The id can only contain English characters, digits, and underscores",
call. = FALSE)
}
missing <- required_fields[!required_fields %in% names(module_config)]
if (length(missing) > 0) {
stop(glue("Module {id}: Some required fields are missing: {join(missing)}"),
call. = FALSE)
}
if (!module_config$component %in% COMPONENTS) {
stop(glue("Module {id}: Invalid component `{module_config$component}` ",
"(options are: {join(COMPONENTS)})"), call. = FALSE)
}
module_config$instructions <- suppressWarnings(
normalizePath(file.path(config_dir, glue("{id}.md")))
)
if (!file.exists(module_config$instructions)) {
stop(glue("Module {id}: Instructions file `{module_config$instructions}` was expected but not found"), call. = FALSE)
}
rmd_file <- suppressWarnings(
normalizePath(file.path(config_dir, glue("{id}.Rmd")))
)
if (file.exists(rmd_file)) {
module_config$rmd_file <- rmd_file
}
module_config$file <- suppressWarnings(
normalizePath(file.path(config_dir, glue("{id}.R")))
)
if (!file.exists(module_config$file)) {
stop(glue("Module {id}: Source file `{module_config$file}` was expected but not found"), call. = FALSE)
}
temp_env <- new.env()
source(module_config$file, local = temp_env)
ui_function <- glue("{id}_module_ui")
if (!exists(ui_function, envir = temp_env) || !is.function(get(ui_function, envir = temp_env))) {
stop(glue("Module {id}: Could not find a UI function named `{ui_function}`"),
call. = FALSE)
}
server_function <- glue("{id}_module_server")
if (!exists(server_function, envir = temp_env) || !is.function(get(server_function, envir = temp_env))) {
stop(glue("Module {id}: Could not find a server function named `{server_function}`"),
call. = FALSE)
}
# Save the module's UI and server
module_config$ui_function <- ui_function
module_config$server_function <- server_function
# Save the module's result and map code and Rmd variables if they exist
result_function <- glue("{id}_module_result")
if (exists(result_function, envir = temp_env) && is.function(get(result_function, envir = temp_env))) {
module_config$result_function <- result_function
}
map_function <- glue("{id}_module_map")
if (exists(map_function, envir = temp_env) && is.function(get(map_function, envir = temp_env))) {
module_config$map_function <- map_function
}
rmd_function <- glue("{id}_module_rmd")
if (exists(rmd_function, envir = temp_env) && is.function(get(rmd_function, envir = temp_env))) {
module_config$rmd_function <- rmd_function
}
# Save the module information
COMPONENT_MODULES[[module_config$component]][[id]] <- module_config
# Load the module's code
source(module_config$file, local = TRUE)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/global.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# helpers.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
uiTop <- function(mod_INFO) {
modID <- mod_INFO$modID
modName <- mod_INFO$modName
pkgName <- mod_INFO$pkgName
ls <- list(div(paste("Module: ", modName), class = "mod"),
actionLink(paste0(modID, "Help"),
label = "", icon = icon("circle-question"),
class = "modHelpButton"),
br())
ls <- c(ls, list(span("R packages:", class = "rpkg"),
span(paste(pkgName, collapse = ", "), class = "pkgDes"),
br()))
# for (i in seq_along(pkgName)) {
# ls <- c(ls, list(span(pkgName[i], class = "rpkg"),
# span(paste(':', pkgTitl[i]), class = "pkgDes"),
# br()))
# }
ls <- c(ls, list(HTML('<hr>')))
ls
}
uiBottom <- function(mod_INFO) {
modAuts <- mod_INFO$modAuts
pkgName <- mod_INFO$pkgName
pkgAuts <- mod_INFO$pkgAuts
pkgTitl <- mod_INFO$pkgTitl
ls <- list(span('Module Developers:', class = "rpkg"),
span(modAuts, class = "pkgDes"), br(), br())
for (i in seq_along(pkgName)) {
ls <- c(ls, list(
span(pkgName[i], class = "rpkg"),
"references", br(),
div(paste(pkgTitl[i]), class = "pkgTitl"),
div(paste('Package Developers:', pkgAuts[i]), class = "pkgDes"),
a("CRAN", href = file.path("http://cran.r-project.org/web/packages",
pkgName[i], "index.html"), target = "_blank"), " | ",
a("documentation", href = file.path("https://cran.r-project.org/web/packages",
pkgName[i], paste0(pkgName[i], ".pdf")), target = "_blank"), br()
))
}
ls
}
ui_top <- function(pkgName, modName, modAuts, modID) {
uiTop(infoGenerator(pkgName, modName, modAuts, modID))
}
ui_bottom <- function(pkgName, modName, modAuts, modID) {
uiBottom(infoGenerator(pkgName, modName, modAuts, modID))
}
infoGenerator <- function(pkgName, modName, modAuts, modID) {
# Use installed package only (some packages are Suggested)
pkgName <- pkgName[vapply(pkgName, requireNamespace, TRUE, quietly = TRUE)]
pkgInfo <- sapply(pkgName, packageDescription, simplify = FALSE)
pkgTitl <- sapply(pkgInfo, function(x) x$Title)
# remove square brackets and spaces before commas
pkgAuts <- sapply(pkgInfo, function(x) gsub("\\s+,", ",", gsub("\n|\\[.*?\\]", "", x$Author)))
# remove parens and spaces before commas
pkgAuts <- sapply(pkgAuts, function(x) gsub("\\s+,", ",", gsub("\\(.*?\\)", "", x)))
list(modID = modID,
modName = modName,
modAuts = modAuts,
pkgName = pkgName,
pkgTitl = pkgTitl,
pkgAuts = pkgAuts)
}
# Join a string vector into a single string separated by commas
join <- function(v) paste(v, collapse = ", ")
# Add radio buttons for all modules in a component
insert_modules_options <- function(component) {
unlist(setNames(
lapply(COMPONENT_MODULES[[component]], `[[`, "id"),
lapply(COMPONENT_MODULES[[component]], `[[`, "short_name")
))
}
# Add the UI for a module
insert_modules_ui <- function(component) {
lapply(COMPONENT_MODULES[[component]], function(module) {
conditionalPanel(
glue("input.{component}Sel == '{module$id}'"),
ui_top(
modID = module$id,
modName = module$long_name,
modAuts = module$authors,
pkgName = module$package
),
do.call(module$ui_function, list(module$id)),
tags$hr(),
ui_bottom(
modID = module$id,
modName = module$long_name,
modAuts = module$authors,
pkgName = module$package
)
)
})
}
# Add the results section UI of all modules in a component
insert_modules_results <- function(component) {
lapply(COMPONENT_MODULES[[component]], function(module) {
if (is.null(module$result_function)) return()
conditionalPanel(
glue("input.{component}Sel == '{module$id}'"),
do.call(module$result_function, list(module$id))
)
})
}
# Add helper button for component
help_comp_ui <- function(name) {
actionLink(name, label = "", icon = icon("circle-question"),
class = "compHelpButton")
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/helpers.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# envs_ecoclimate.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
envs_ecoclimate_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
# UI
tags$div(title = 'Select AOGCM',
selectInput(ns("bcAOGCM"),
label = "Select the Atmospheric Oceanic General Circulation Model you want to use",
choices = list("Select AOGCMs" = "",
"CCSM" = "CCSM",
"CNRM" = "CNRM",
"MIROC" = "MIROC",
"FGOALS" = "FGOALS",
"GISS" = "GISS",
"IPSL" = "IPSL",
"MRI" = "MRI",
"MPI" = "MPI")
)),
tags$div(title = 'Select Scenario',
selectInput(ns("bcScenario"),
label = "select the temporal scenario that you want to use",
choices = list("Select Scenario" = "",
"Present" = "Present",
"Holocene (6,000 years ago)" = "Holo",
"LGM (21,000 years ago)" = "LGM")
)),
shinyWidgets::pickerInput(
"ecoClimSel",
label = "Select bioclimatic variables",
choices = setNames(as.list(1:19),
paste0('bio', sprintf("%02d", 1:19))),
multiple = TRUE,
selected = 1:19,
options = list(`actions-box` = TRUE)),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
em("ecoClimate layers have a resolution of 0.5 degrees"), br(), br(),
actionButton(ns("goEcoClimData"), "Load Env Data")
)
}
envs_ecoclimate_module_server <- function(input, output, session, common) {
logger <- common$logger
ecoClimSel <- common$ecoClimSel
occs <- common$occs
spp <- common$spp
curSp <- common$curSp
allSp <- common$allSp
envs.global <- common$envs.global
observeEvent(input$goEcoClimData, {
# WARNING ####
if (is.null(curSp())) {
logger %>% writeLog(type = 'error',
paste0("Before obtaining environmental variables, ",
"obtain occurrence data in 'Occ Data' component."))
return()
}
# Specify more than 2 variables
if (length(ecoClimSel()) < 2) {
logger %>%
writeLog(
type = 'error',
"Select more than two variables.")
return()
}
# FUNCTION CALL ####
ecoClims <- envs_ecoClimate(input$bcAOGCM, input$bcScenario,
as.numeric(ecoClimSel()), logger)
req(ecoClims)
nmEcoClimate <- paste0("ecoClimate_", input$bcAOGCM, "_", input$bcScenario)
envs.global[[nmEcoClimate]] <- ecoClims
# LOAD INTO SPP ####
# loop over all species if batch is on
if (input$batch == FALSE) spLoop <- curSp() else spLoop <- allSp()
# PROCESSING ####
for (sp in spLoop) {
# remove occurrences with NA values for variables
withProgress(
message = paste0("Extracting environmental values for occurrences of ",
spName(sp), "..."), {
occsEnvsVals <- as.data.frame(
raster::extract(ecoClims,
spp[[sp]]$occs[, c('longitude', 'latitude')],
cellnumbers = TRUE))
})
# remove occurrence records with NA environmental values
remOccs <- remEnvsValsNA(spp[[sp]]$occs, occsEnvsVals, sp, logger)
if (!is.null(remOccs)) {
spp[[sp]]$occs <- remOccs$occs
occsEnvsVals <- remOccs$occsEnvsVals
} else {
# When remOccs is null, means that all localities have NAs
return()
}
logger %>% writeLog(hlSpp(sp), "EcoClimate variables ready to use.")
# LOAD INTO SPP ####
spp[[sp]]$envs <- nmEcoClimate
# add columns for env variable values for each occurrence record
if (!any(names(occsEnvsVals) %in% names(spp[[sp]]$occs))) {
spp[[sp]]$occs <- cbind(spp[[sp]]$occs, occsEnvsVals)
} else {
shaEnvNames <- names(occsEnvsVals)[names(occsEnvsVals) %in% names(spp[[sp]]$occs)]
spp[[sp]]$occs <- spp[[sp]]$occs %>% dplyr::mutate(occsEnvsVals[shaEnvNames])
}
# METADATA ####
spp[[sp]]$rmm$data$environment$variableNames <- names(ecoClims)
spp[[sp]]$rmm$data$environment$resolution <- paste(round(raster::res(ecoClims)[1] * 60, digits = 2), "minutes")
spp[[sp]]$rmm$data$environment$extent <- as.character(raster::extent(ecoClims))
spp[[sp]]$rmm$data$environment$sources <- nmEcoClimate
spp[[sp]]$rmm$data$environment$projection <- as.character(raster::crs(ecoClims))
spp[[sp]]$rmm$code$wallace$bcAOGCM <- input$bcAOGCM
spp[[sp]]$rmm$code$wallace$bcScenario <- input$bcScenario
spp[[sp]]$rmm$code$wallace$ecoClimSel <- ecoClimSel()
}
common$update_component(tab = "Results")
})
output$envsPrint <- renderPrint({
req(curSp(), spp[[curSp()]]$envs)
envs.global[[spp[[curSp()]]$envs]]
})
return(list(
save = function() {
# Save any values that should be saved when the current session is saved
list(
bcAOGCM = input$bcAOGCM,
bcScenario = input$bcScenario,
ecoClimSel = ecoClimSel()
)
},
load = function(state) {
# Load
updateSelectInput(session, "bcAOGCM", selected = state$bcAOGCM)
updateSelectInput(session, "bcScenario", selected = state$bcScenario)
shinyWidgets::updatePickerInput(session, "ecoClimSel",
selected = state$ecoClimSel)
}
))
}
envs_ecoclimate_module_result <- function(id) {
ns <- NS(id)
# Result UI
verbatimTextOutput(ns("envsPrint"))
}
envs_ecoclimate_module_map <- function(map, common) {
occs <- common$occs
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
}
envs_ecoclimate_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
envs_ecoclimate_knit = !is.null(species$rmm$code$wallace$bcAOGCM),
bcAOGCM_rmd = species$rmm$code$wallace$bcAOGCM,
bcScenario_rmd = species$rmm$code$wallace$bcScenario,
ecoClimSel_rmd = printVecAsis(as.numeric(species$rmm$code$wallace$ecoClimSel))
##Alternative using rmm instead of RMD object but not working
#grepl("ecoClimate",species$rmm$data$environment$sources)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/envs_ecoclimate.R
|
```{asis, echo = {{envs_ecoclimate_knit}}, eval = {{envs_ecoclimate_knit}}, include = {{envs_ecoclimate_knit}}}
### Obtain environmental data
Using Ecoclimate (http://www.ecoclimate.org) dataset at resolution of 0.5 degrees.
```
```{r, echo = {{envs_ecoclimate_knit}}, include = {{envs_ecoclimate_knit}}}
# R code to get environmental data from Ecoclimate
envs_{{spAbr}} <- envs_ecoClimate(
bcAOGCM = "{{bcAOGCM_rmd}}",
bcScenario = "{{bcScenario_rmd}}",
ecoClimSel = {{ecoClimSel_rmd}})
##Add envrionmental values to occurrences table
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
occs_vals_{{spAbr}} <- as.data.frame(raster::extract(envs_{{spAbr}}, occs_xy_{{spAbr}}, cellnumbers = TRUE))
# Remove duplicated same cell values
occs_{{spAbr}} <- occs_{{spAbr}}[!duplicated(occs_vals_{{spAbr}}[, 1]), ]
occs_vals_{{spAbr}} <- occs_vals_{{spAbr}}[!duplicated(occs_vals_{{spAbr}}[, 1]), -1]
# remove occurrence records with NA environmental values
occs_{{spAbr}} <- occs_{{spAbr}}[!(rowSums(is.na(occs_vals_{{spAbr}})) >= 1), ]
# also remove variable value rows with NA environmental values
occs_vals_{{spAbr}} <- na.omit(occs_vals_{{spAbr}})
# add columns for env variable values for each occurrence record
occs_{{spAbr}} <- cbind(occs_{{spAbr}}, occs_vals_{{spAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/envs_ecoclimate.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# envs_userEnvs.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
envs_userEnvs_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
checkboxInput(
ns("doBrick"),
label = "Save to memory for faster processing and save/load option",
value = FALSE), # Check default (value = FALSE)
fileInput(ns("userEnvs"), label = "Input rasters",
accept = c(".tif", ".asc"), multiple = TRUE),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns('goUserEnvs'), 'Load Env Data')
)
}
envs_userEnvs_module_server <- function(input, output, session, common) {
logger <- common$logger
occs <- common$occs
spp <- common$spp
allSp <- common$allSp
curSp <- common$curSp
envs.global <- common$envs.global
observeEvent(input$goUserEnvs, {
# ERRORS ####
if (is.null(curSp())) {
logger %>% writeLog(type = 'error', "Before obtaining environmental variables,
obtain occurrence data in 'Occ Data' component.")
return()
}
if (is.null(input$userEnvs)) {
logger %>% writeLog(type = 'error', "Raster files not uploaded.")
return()
}
# Specify more than 2 variables
if (length(input$userEnvs$name) < 2) {
logger %>%
writeLog(
type = 'error',
"Select more than two variables.")
return()
}
userEnvs <- envs_userEnvs(rasPath = input$userEnvs$datapath,
rasName = input$userEnvs$name,
doBrick = input$doBrick,
logger)
smartProgress(logger, message = "Checking NA values...", {
checkNA <- terra::global(terra::rast(userEnvs),
fun = "isNA")
})
if (length(unique(checkNA$isNA)) != 1) {
logger %>% writeLog(
type = "error",
'Input rasters have unmatching NAs pixel values.')
return()
}
# loop over all species if batch is on
if (input$batch == TRUE) {
spLoop <- allSp()
envs.global[["user"]] <- userEnvs
} else {
spLoop <- curSp()
envs.global[[paste0("user_", curSp())]] <- userEnvs
}
for (sp in spLoop) {
# get environmental variable values per occurrence record
withProgress(
message = paste0("Extracting environmental values for occurrences of ",
sp, "..."), {
occsEnvsVals <-
as.data.frame(
raster::extract(userEnvs,
spp[[sp]]$occs[, c('longitude', 'latitude')],
cellnumbers = TRUE))
})
# remove occurrence records with NA environmental values
remOccs <- remEnvsValsNA(spp[[sp]]$occs, occsEnvsVals, sp, logger)
if (!is.null(remOccs)) {
spp[[sp]]$occs <- remOccs$occs
occsEnvsVals <- remOccs$occsEnvsVals
} else {
# When remOccs is null, means that all localities have NAs
return()
}
logger %>% writeLog(hlSpp(sp), "User specified variables (",
paste(names(userEnvs), collapse = ", "),
") ready to use.")
# LOAD INTO SPP ####
if (input$batch == TRUE) {
spp[[sp]]$envs <- "user"
} else {
spp[[sp]]$envs <- paste0("user_", sp)
}
# add columns for env variable values for each occurrence record
if (!any(names(occsEnvsVals) %in% names(spp[[sp]]$occs))) {
spp[[sp]]$occs <- cbind(spp[[sp]]$occs, occsEnvsVals)
} else {
shaEnvNames <- names(occsEnvsVals)[names(occsEnvsVals) %in% names(spp[[sp]]$occs)]
spp[[sp]]$occs <- spp[[sp]]$occs %>% dplyr::mutate(occsEnvsVals[shaEnvNames])
}
# METADATA ####
spp[[sp]]$rmm$data$environment$variableNames <- names(userEnvs)
spp[[sp]]$rmm$data$environment$resolution <- raster::res(userEnvs)
spp[[sp]]$rmm$data$environment$sources <- 'user'
spp[[sp]]$rmm$data$environment$extent <- as.character(raster::extent(userEnvs))
spp[[sp]]$rmm$data$environment$projection <- as.character(raster::crs(userEnvs))
spp[[sp]]$rmm$code$wallace$userRasName <- input$userEnvs$name
spp[[sp]]$rmm$code$wallace$userBrick <- input$doBrick
}
common$update_component(tab = "Results")
common$disable_module(component = "xfer", module = "xferTime")
})
output$envsPrint <- renderPrint({
req(curSp(), spp[[curSp()]]$envs)
envs.global[[spp[[curSp()]]$envs]]
})
}
envs_userEnvs_module_result <- function(id) {
ns <- NS(id)
# Result UI
verbatimTextOutput(ns("envsPrint"))
}
envs_userEnvs_module_map <- function(map, common) {
occs <- common$occs
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
}
envs_userEnvs_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
envs_userEnvs_knit = !is.null(species$rmm$code$wallace$userRasName),
userRasName_rmd = printVecAsis(species$rmm$code$wallace$userRasName),
userBrick_rmd = species$rmm$code$wallace$userBrick
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/envs_userEnvs.R
|
```{asis, echo = {{envs_userEnvs_knit}}, eval = {{envs_userEnvs_knit}}, include = {{envs_userEnvs_knit}}}
### Obtain environmental data
Using user-specified variables.
```
```{r, echo = {{envs_userEnvs_knit}}, include = {{envs_userEnvs_knit}}}
## Specify the directory with the environmental variables
dir_envs_{{spAbr}} <- ""
envs_path <- file.path(dir_envs_{{spAbr}}, {{userRasName_rmd}})
# Create environmental object
envs_{{spAbr}} <- envs_userEnvs(
rasPath = envs_path,
rasName = {{userRasName_rmd}},
doBrick = {{userBrick_rmd}})
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
occs_vals_{{spAbr}} <- as.data.frame(raster::extract(envs_{{spAbr}}, occs_xy_{{spAbr}}, cellnumbers = TRUE))
# Remove duplicated same cell values
occs_{{spAbr}} <- occs_{{spAbr}}[!duplicated(occs_vals_{{spAbr}}[, 1]), ]
occs_vals_{{spAbr}} <- occs_vals_{{spAbr}}[!duplicated(occs_vals_{{spAbr}}[, 1]), -1]
# remove occurrence records with NA environmental values
occs_{{spAbr}} <- occs_{{spAbr}}[!(rowSums(is.na(occs_vals_{{spAbr}})) >= 1), ]
# also remove variable value rows with NA environmental values
occs_vals_{{spAbr}} <- na.omit(occs_vals_{{spAbr}})
# add columns for env variable values for each occurrence record
occs_{{spAbr}} <- cbind(occs_{{spAbr}}, occs_vals_{{spAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/envs_userEnvs.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# envs_worldclim.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
envs_worldclim_module_ui <- function(id) {
ns <- NS(id)
tagList(
tags$div(
title = paste0('Approximate lengths at equator: 10 arcmin = ~20 km, ',
'5 arcmin = ~10 km, 2.5 arcmin = ~5 km, 30 arcsec = ~1 km. ',
'Exact length varies based on latitudinal position.'),
selectInput(ns("wcRes"),
label = "Select WorldClim bioclimatic variable resolution",
choices = list("Select resolution" = "",
"30 arcsec" = 0.5,
"2.5 arcmin" = 2.5,
"5 arcmin" = 5,
"10 arcmin" = 10))), # Check default (No selected parameter)
checkboxInput(
ns("doBrick"),
label = "Save to memory for faster processing and save/load option",
value = FALSE), # Check default (value = FALSE)
shinyWidgets::pickerInput(
"bcSel",
label = "Select bioclim variables",
choices = setNames(as.list(paste0('bio', sprintf("%02d", 1:19))),
paste0('bio', sprintf("%02d", 1:19))),
multiple = TRUE,
selected = paste0('bio', sprintf("%02d", 1:19)),
options = list(`actions-box` = TRUE)),
conditionalPanel(
sprintf("input['%s'] != '0.5'", ns("wcRes")),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
)
),
conditionalPanel(
sprintf("input['%s'] == '0.5'", ns("wcRes")),
em("Batch option not available for 30 arcsec resolution."), br(), br(),
strong(
paste0("Coordinates centroid as reference for tile download. ",
"You can vizualize the tile in the bottomleft corner on ",
"the map. All occurrence outside of the purple polygon will ",
"be removed")), br(), br(),
textOutput(ns("ctrLatLon"))
),
br(),
actionButton(ns("goEnvData"), "Load Env Data")
)
}
envs_worldclim_module_server <- function(input, output, session, common) {
logger <- common$logger
bcSel <- common$bcSel
occs <- common$occs
spp <- common$spp
allSp <- common$allSp
curSp <- common$curSp
envs.global <- common$envs.global
mapCntr <- common$mapCntr
observeEvent(input$goEnvData, {
# ERRORS ####
if (is.null(curSp())) {
logger %>% writeLog(type = 'error',
"Before obtaining environmental variables, obtain occurrence data in 'Occ Data' component.")
return()
}
# Specify more than 2 variables
if (length(bcSel()) < 2) {
logger %>%
writeLog(
type = 'error',
"Select more than two variables.")
return()
}
# loop over all species if batch is on
if (input$batch == FALSE) spLoop <- curSp() else spLoop <- allSp()
# PROCESSING ####
for (sp in spLoop) {
# FUNCTION CALL ####
if (input$wcRes != 0.5) {
wcbc <- envs_worldclim(input$wcRes, bcSel(), doBrick = input$doBrick,
logger = logger)
req(wcbc)
envs.global[[paste0("wcbc_", sp)]] <- wcbc
} else {
wcbc <- envs_worldclim(input$wcRes, bcSel(), mapCntr(), input$doBrick, logger)
req(wcbc)
envs.global[[paste0("wcbc_", sp)]] <- wcbc
}
# get environmental variable values per occurrence record
withProgress(message = paste0("Extracting environmental values for occurrences of ",
spName(sp), "..."), {
occs.xy <- spp[[sp]]$occs[, c('longitude', 'latitude')]
occsEnvsVals <- as.data.frame(raster::extract(wcbc, occs.xy, cellnumbers = TRUE))
})
# remove occurrence records with NA environmental values
remOccs <- remEnvsValsNA(spp[[sp]]$occs, occsEnvsVals, sp, logger)
if (!is.null(remOccs)) {
spp[[sp]]$occs <- remOccs$occs
occsEnvsVals <- remOccs$occsEnvsVals
} else {
# When remOccs is null, means that all localities have NAs
return()
}
logger %>% writeLog(hlSpp(sp), "Worldclim variables ready to use.")
# LOAD INTO SPP ####
# add reference to WorldClim bioclim data
spp[[sp]]$envs <- paste0("wcbc_", sp)
# add columns for env variable values for each occurrence record
if (!any(names(occsEnvsVals) %in% names(spp[[sp]]$occs))) {
spp[[sp]]$occs <- cbind(spp[[sp]]$occs, occsEnvsVals)
} else {
shaEnvNames <- names(occsEnvsVals)[names(occsEnvsVals) %in% names(spp[[sp]]$occs)]
spp[[sp]]$occs <- spp[[sp]]$occs %>% dplyr::mutate(occsEnvsVals[shaEnvNames])
}
# METADATA ####
spp[[sp]]$rmm$data$environment$variableNames <- names(wcbc)
spp[[sp]]$rmm$data$environment$yearMin <- 1960
spp[[sp]]$rmm$data$environment$yearMax <- 1990
spp[[sp]]$rmm$data$environment$resolution <- paste(round(raster::res(wcbc)[1] * 60, digits = 2), "minutes")
spp[[sp]]$rmm$data$environment$extent <- as.character(raster::extent(wcbc))
spp[[sp]]$rmm$data$environment$sources <- 'WorldClim 1.4'
spp[[sp]]$rmm$data$environment$projection <- as.character(raster::crs(wcbc))
spp[[sp]]$rmm$code$wallace$wcRes <- input$wcRes
spp[[sp]]$rmm$code$wallace$bcSel <- bcSel()
spp[[sp]]$rmm$code$wallace$mapCntr <- mapCntr()
spp[[sp]]$rmm$code$wallace$wcBrick <- input$doBrick
}
common$update_component(tab = "Results")
})
# text showing the current map center
output$ctrLatLon <- renderText({
req(curSp(), occs())
glue::glue('Using coordinate centroid {join(mapCntr())}')
})
output$envsPrint <- renderPrint({
req(curSp(), spp[[curSp()]]$envs)
envs.global[[spp[[curSp()]]$envs]]
})
return(list(
save = function() {
list(
wcRes = input$wcRes,
wcBrick = input$doBrick,
bcSel = bcSel()
)
},
load = function(state) {
updateSelectInput(session, "wcRes", selected = state$wcRes)
updateCheckboxInput(session, "doBrick", value = state$doBrick)
shinyWidgets::updatePickerInput(session, "bcSel", selected = state$bcSel)
}
))
}
envs_worldclim_module_result <- function(id) {
ns <- NS(id)
# Result UI
verbatimTextOutput(ns("envsPrint"))
}
envs_worldclim_module_map <- function(map, common) {
# Map logic
occs <- common$occs
mapCntr <- c(mean(occs()$longitude), mean(occs()$latitude))
lon_tile <- seq(-180, 180, 30)
lat_tile <- seq(-60, 90, 30)
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
addRectangles(lng1 = lon_tile[sum(lon_tile <= mapCntr[1])],
lng2 = lon_tile[sum(lon_tile <= mapCntr[1])] + 30,
lat1 = lat_tile[sum(lat_tile <= mapCntr[2])],
lat2 = lat_tile[sum(lat_tile <= mapCntr[2])] + 30,
color = "purple", group = "30 arcsec tile") %>%
hideGroup("30 arcsec tile") %>%
addLayersControl(overlayGroups = "30 arcsec tile", position = "bottomleft",
options = layersControlOptions(collapsed = FALSE))
}
envs_worldclim_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
envs_worldclim_knit = !is.null(species$rmm$code$wallace$wcRes),
wcRes_rmd = species$rmm$code$wallace$wcRes,
bcSel_rmd = printVecAsis(species$rmm$code$wallace$bcSel),
mapCntr_rmd = printVecAsis(species$rmm$code$wallace$mapCntr),
wcBrick_rmd = species$rmm$code$wallace$wcBrick
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/envs_worldclim.R
|
```{asis, echo = {{envs_worldclim_knit}}, eval = {{envs_worldclim_knit}}, include = {{envs_worldclim_knit}}}
### Obtain environmental data
Using WorldClim (http://www.worldclim.org/) bioclimatic dataset at resolution of `r {{wcRes_rmd}}` arcmin.
```
```{r, echo = {{envs_worldclim_knit}}, include = {{envs_worldclim_knit}}}
# Download environmental data
envs_{{spAbr}} <- envs_worldclim(
bcRes = {{wcRes_rmd}},
bcSel = {{bcSel_rmd}},
mapCntr = {{mapCntr_rmd}}, # Mandatory for 30 arcsec resolution
doBrick = {{wcBrick_rmd}})
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
occs_vals_{{spAbr}} <- as.data.frame(raster::extract(envs_{{spAbr}}, occs_xy_{{spAbr}}, cellnumbers = TRUE))
# Remove duplicated same cell values
occs_{{spAbr}} <- occs_{{spAbr}}[!duplicated(occs_vals_{{spAbr}}[, 1]), ]
occs_vals_{{spAbr}} <- occs_vals_{{spAbr}}[!duplicated(occs_vals_{{spAbr}}[, 1]), -1]
# remove occurrence records with NA environmental values
occs_{{spAbr}} <- occs_{{spAbr}}[!(rowSums(is.na(occs_vals_{{spAbr}})) >= 1), ]
# also remove variable value rows with NA environmental values
occs_vals_{{spAbr}} <- na.omit(occs_vals_{{spAbr}})
# add columns for env variable values for each occurrence record
occs_{{spAbr}} <- cbind(occs_{{spAbr}}, occs_vals_{{spAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/envs_worldclim.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# espace_nicheOv.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
espace_nicheOv_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
actionButton(ns("goNicheOv"), "Run")
)
}
espace_nicheOv_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
curSp <- common$curSp
observeEvent(input$goNicheOv, {
if (length(curSp()) != 2) {
logger %>% writeLog(
type = "error",
"Please select two species to run the niche overlap module."
)
return()
}
mspName <- paste(curSp(), collapse = ".")
if (is.null(spp[[mspName]])) {
logger %>% writeLog(
type = "error",
paste0("Please run PCA and occurrence density with two species before",
" running the niche overlap module.")
)
return()
}
# if a multispecies analysis has been run, but not occDens
if (is.null(spp[[mspName]]$occDens)) {
logger %>% writeLog(
type = "error",
paste0("Please run occurrence density with two species before running",
" the niche overlap module.")
)
return()
}
# FUNCTION CALL ####
sp1 <- curSp()[1]
sp2 <- curSp()[2]
z1 <- spp[[mspName]]$occDens[[sp1]]
z2 <- spp[[mspName]]$occDens[[sp2]]
nicheOv <- espace_nicheOv(z1, z2, logger = logger)
if (is.null(nicheOv)) return()
# LOAD INTO SPP ####
spp[[mspName]]$nicheOv <- nicheOv
# REFERENCES
knitcitations::citep(citation("ecospat"))
common$update_component(tab = "Results")
})
output$nicheOvText <- renderUI({
if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
sp1 <- curSp()[1]
sp2 <- curSp()[2]
} else {
mSp <- curSp()
}
req(spp[[mSp]]$nicheOv)
HTML(
paste(
"Overlap D = ", round(spp[[mSp]]$nicheOv$overlap$D, 2),
" | Sp1 only :", round(spp[[mSp]]$nicheOv$USE[3], 2),
" | Sp2 only :", round(spp[[mSp]]$nicheOv$USE[1], 2),
" | Both :", round(spp[[mSp]]$nicheOv$USE[2], 2)
)
)
})
output$nicheOvPlot <- renderPlot({
if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
sp1 <- curSp()[1]
sp2 <- curSp()[2]
} else {
mSp <- curSp()
}
req(spp[[mSp]]$nicheOv)
graphics::par(mfrow = c(1, 2))
ecospat::ecospat.plot.niche.dyn(
spp[[mSp]]$occDens[[sp1]],
spp[[mSp]]$occDens[[sp2]],
0.5,
title = mSp,
col.unf = "blue",
col.exp = "red",
col.stab = "purple",
colZ1 = "blue",
colZ2 = "red",
transparency = 25
)
box()
# if (!is.null(spp[[mSp]]$nicheOv$equiv))
# ecospat::ecospat.plot.overlap.test(spp[[mSp]]$nicheOv$equiv,
# "D", "Equivalency test")
if (!is.null(spp[[mSp]]$nicheOv$simil))
ecospat::ecospat.plot.overlap.test(spp[[mSp]]$nicheOv$simil,
"D", "Similarity test")
graphics::par(mfrow = c(1, 1))
})
}
espace_nicheOv_module_result <- function(id) {
ns <- NS(id)
# Result UI
tagList(
htmlOutput(ns("nicheOvText")), br(), br(),
plotOutput(ns("nicheOvPlot"))
)
}
espace_nicheOv_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
espace_nicheOv_knit = !is.null(species$nicheOv),
simil_rmd = !is.null(species$nicheOv$simil),
equiv_rmd = !is.null(species$nicheOv$equiv)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/espace_nicheOv.R
|
```{asis, echo = {{espace_nicheOv_knit}}, eval = {{espace_nicheOv_knit}}, include = {{espace_nicheOv_knit}}}
### Environmental space
Evaluating niche overlap between *`r "{{spName1}}"`* & *`r "{{spName2}}"`* for which the occurrence density grid was computed. Running equivalence test ({{equiv_rmd}}) and similarity test {{simil_rmd}}
```
```{r, echo = {{espace_nicheOv_knit}}, include = {{espace_nicheOv_knit}}}
## Run tests
espace_nicheOv_{{multAbr}} <- espace_nicheOv(
z1 = espace_occDens_{{multAbr}}[["{{spName1}}"]],
z2 = espace_occDens_{{multAbr}}[["{{spName2}}"]],
iter = 100,
similarity = {{simil_rmd}})
# Plots
layout(matrix(c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3), 4, 3, byrow = FALSE))
ecospat::ecospat.plot.niche.dyn(
espace_occDens_{{multAbr}}[["{{spName1}}"]],
espace_occDens_{{multAbr}}[["{{spName2}}"]],
0.5,
title = "{{spName1}}_{{spName2}}",
col.unf = "blue",
col.exp = "red",
col.stab = "purple",
colZ1 = "blue",
colZ2 = "red",
transparency = 25
)
# Plot
ecospat::ecospat.plot.overlap.test(espace_nicheOv_{{multAbr}}$simil,
"D", "Similarity test")
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/espace_nicheOv.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# espace_occDens.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
espace_occDens_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
# UI
actionButton(ns("goOccDens"), "Run")
)
}
espace_occDens_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
curSp <- common$curSp
observeEvent(input$goOccDens, {
# ERRORS ####
if (length(curSp()) != 2) {
logger %>% writeLog(
type = "error",
"Please select two species to run the occurrence density grid module."
)
return()
}
# if no multispecies analysis has been run yet
mspName <- paste(curSp(), collapse = ".")
if (is.null(spp[[mspName]])) {
logger %>% writeLog(
type = "error",
"Please run PCA with two species before running the occurrence density grid module."
)
return()
}
# if a multispecies analysis has been run, but not PCA
if (is.null(spp[[mspName]]$pca)) {
logger %>% writeLog(
type = "error",
"Please run PCA with two species before running the occurrence density grid module."
)
return()
}
# FUNCTION CALL ####
sp1 <- curSp()[1]
sp2 <- curSp()[2]
occDens <- espace_occDens(sp1, sp2, spp[[mspName]]$pca, logger)
# LOAD INTO SPP ####
req(occDens)
spp[[mspName]]$occDens <- occDens
# REFERENCES
knitcitations::citep(citation("adehabitatHR"))
knitcitations::citep(citation("ecospat"))
common$update_component(tab = "Results")
})
# PLOTS ####
output$occDensPlot <- renderPlot({
graphics::par(mfrow = c(1,2))
if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
sp1 <- curSp()[1]
sp2 <- curSp()[2]
} else {
mSp <- curSp()
}
req(spp[[mSp]]$occDens)
ecospat.plot.nicheDEV(spp[[mSp]]$occDens[[sp1]], title = spName(sp1))
ecospat.plot.nicheDEV(spp[[mSp]]$occDens[[sp2]], title = spName(sp2))
})
}
espace_occDens_module_result <- function(id) {
ns <- NS(id)
# Result UI
plotOutput(ns("occDensPlot"))
}
espace_occDens_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
espace_occDens_knit = !is.null(species$occDens)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/espace_occDens.R
|
```{asis, echo = {{espace_occDens_knit}}, eval = {{espace_occDens_knit}}, include = {{espace_occDens_knit}}}
### Environmental space
Calculating the part of environmental space more densly populated by species & the availability of environmental conditions in the background for *`r "{{spName1}}"`* & *`r "{{spName2}}"`*
```
```{r, echo = {{espace_occDens_knit}}, include = {{espace_occDens_knit}}}
# Create density grid
espace_occDens_{{multAbr}} <- espace_occDens(
sp.name1 = "{{spName1}}",
sp.name2 = "{{spName2}}",
pca = espace_pca_{{multAbr}})
# Plots
graphics::par(mfrow = c(1,2))
ecospat.plot.nicheDEV(espace_occDens_{{multAbr}}[["{{spName1}}"]],
title = "{{spName1}}")
ecospat.plot.nicheDEV(espace_occDens_{{multAbr}}[["{{spName2}}"]],
title = "{{spName2}}")
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/espace_occDens.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# espace_pca.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
espace_pca_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
uiOutput(ns("pcaSel")),
selectInput(ns("pcaPlotSel"), "Plot selection:",
choices = list("None selected" = "",
"Occurrences only" = "occs",
"Occurrences + Background" = "occsBg")),
uiOutput(ns("pcaControls")),
actionButton(ns("goPCA"), "Run")
)
}
espace_pca_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
curSp <- common$curSp
envs.global <- common$envs.global
envs <- common$envs
output$pcaSel <- renderUI({
ns <- session$ns
req(curSp())
if (length(curSp()) == 1) {
shiny::tagList(
shiny::em("Select two species in species menu"),
br()
)
} else if (length(curSp()) == 2) {
sp1 <- curSp()[1]
sp2 <- curSp()[2]
if (is.null(spp[[sp1]]$envs)) return()
if (is.null(spp[[sp2]]$envs)) return()
sp1.envNames <- names(envs.global[[spp[[sp1]]$envs]])
sp2.envNames <- names(envs.global[[spp[[sp2]]$envs]])
shared_Names <- intersect(sp1.envNames, sp2.envNames)
shiny::tagList(
shinyWidgets::pickerInput(
ns("pcaSel"),
label = "Select variables available for both species",
choices = setNames(as.list(shared_Names), shared_Names),
multiple = TRUE,
selected = shared_Names,
options = list(`actions-box` = TRUE))
)
}
})
observeEvent(input$goPCA, {
# ERRORS ####
if (length(curSp()) != 2) {
logger %>% writeLog(
type = "error",
"Please select two species to run the PCA module."
)
return()
}
for(sp in curSp()) {
if (is.null(spp[[sp]]$procEnvs$bgMask)) {
logger %>% writeLog(
type = 'error', hlSpp(sp),
"Before partitioning occurrences, mask your ",
"environmental variables by your background extent.")
return()
}
}
# ERRORS ####
if(input$pcaPlotSel == "") {
logger %>% writeLog(type = "error", "Please choose a PCA plotting type.")
return()
}
# PROCESSING ####
sp1 <- curSp()[1]
sp1.envNames <- names(envs.global[[spp[[sp1]]$envs]])
sp2 <- curSp()[2]
sp2.envNames <- names(envs.global[[spp[[sp2]]$envs]])
pcaSel <- input$pcaSel
if (is.null(pcaSel)) {
logger %>% writeLog(
type = "error", hlSpp(paste0(curSp()[1], " and ", curSp()[2])),
" must have the same environmental variables."
)
return()
}
sp1.occsVals <- spp[[sp1]]$occs[pcaSel]
sp1.bgVals <- spp[[sp1]]$bg[pcaSel]
sp2.occsVals <- spp[[sp2]]$occs[pcaSel]
sp2.bgVals <- spp[[sp2]]$bg[pcaSel]
# FUNCTION CALL ####
pca <- espace_pca(sp1, sp2,
sp1.occsVals,
sp2.occsVals,
sp1.bgVals,
sp2.bgVals,
logger)
req(pca)
# LOAD INTO SPP ####
# this name concatenates the species names when there are two,
# and returns the same name when there is only one species name
mspName <- paste(curSp(), collapse = ".")
if (is.null(spp[[mspName]])) {
spp[[mspName]] <- list(pca = pca)
} else {
spp[[mspName]]$pca <- pca
}
spp[[mspName]]$pcaSel <- pcaSel
spp[[mspName]]$pcaPlotSel <- input$pcaPlotSel
###Save inputs for PCA
spp[[mspName]]$pc1 <- input$pc1
spp[[mspName]]$pc2 <- input$pc2
common$update_component(tab = "Results")
# REFERENCES
knitcitations::citep(citation("ade4"))
})
output$pcaControls <- renderUI({
tagList(
numericInput(session$ns("pc1"), "X-axis Component",
value = 1, min = 1, max = length(input$pcaSel)),
numericInput(session$ns("pc2"), "Y-axis Component",
value = 2, min = 1, max = length(input$pcaSel))
)
})
# PLOTS ####
output$pcaResults <- renderUI({
output$pcaScatter <- renderPlot({
if (length(curSp()) == 1) {
mSp <- curSp()
} else if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
}
req(spp[[mSp]]$pca)
if (input$pcaPlotSel == "occs") {
x <- spp[[mSp]]$pca$scores[spp[[mSp]]$pca$scores$bg == 'sp', ]
x.f <- factor(x$sp)
} else if (input$pcaPlotSel == "occsBg") {
x <- spp[[mSp]]$pca$scores[spp[[mSp]]$pca$scores$sp == 'bg', ]
x.f <- factor(x$bg)
}
ade4::s.class(x, x.f, xax = input$pc1, yax = input$pc2,
col = c("red", "blue"), cstar = 0, cpoint = 0.1, sub = "",
possub = "topright")
title(xlab = paste0("PC", input$pc1), ylab = paste0("PC", input$pc2))
})
output$pcaCorCircle <- renderPlot({
if (length(curSp()) == 1) {
mSp <- curSp()
} else if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
}
req(spp[[mSp]]$pca)
ade4::s.corcircle(spp[[mSp]]$pca$co, xax = input$pc1, yax = input$pc2,
lab = input$pcaSel, full = FALSE, box = TRUE)
title(xlab = paste0("PC", input$pc1), ylab = paste0("PC", input$pc2))
})
output$pcaScree <- renderPlot({
if (length(curSp()) == 1) {
mSp <- curSp()
} else if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
}
req(spp[[mSp]]$pca)
stats::screeplot(spp[[mSp]]$pca, main = NULL)
})
output$pcaOut <- renderPrint({
if (length(curSp()) == 1) {
mSp <- curSp()
} else if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
}
req(spp[[mSp]]$pca)
k <- round(100 * spp[[mSp]]$pca$eig / sum(spp[[mSp]]$pca$eig), 2)
names(k) <- paste0("PC", 1:length(spp[[mSp]]$pca$eig), "(%)")
j <- spp[[mSp]]$pca$c1
names(j) <- paste0("PC", 1:length(spp[[mSp]]$pca$eig))
cat(c("Variance explained:",
capture.output(k), "",
"Loadings:",
capture.output(j), "",
capture.output(summary(spp[[mSp]]$pca))),
sep = "\n")
})
tabsetPanel(
tabPanel("PCA scatter plot",
tagList(
plotOutput(session$ns('pcaScatter'))
)),
tabPanel("PCA correlation circle",
tagList(
plotOutput(session$ns('pcaCorCircle'))
)),
tabPanel("PCA screeplot",
tagList(
plotOutput(session$ns('pcaScree'))
)),
tabPanel("PCA results summary",
tagList(
verbatimTextOutput(session$ns("pcaOut"))
))
)
})
return(list(
save = function() {
list(
pcaSel = input$pcaSel,
pcaPlotSel = input$pcaPlotSel
)
},
load = function(state) {
shinyWidgets::updatePickerInput(session, "pcaSel", selected = state$pcaSel)
updateSelectInput(session, "pcaPlotSel", selected = state$pcaPlotSel)
}
))
updateSelectInput(session, "curSp", selected = curSp())
}
espace_pca_module_result <- function(id) {
ns <- NS(id)
# Result UI
uiOutput(ns('pcaResults'))
}
espace_pca_module_rmd <- function(species) {
list(
espace_pca_knit = !is.null(species$pca),
pcaSel_rmd = printVecAsis(species$pcaSel),
pcaPlotSel_rmd = species$pcaPlotSel,
pc1_rmd = species$pc1,
pc2_rmd = species$pc2
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/espace_pca.R
|
```{asis, echo = {{espace_pca_knit}}, eval = {{espace_pca_knit}}, include = {{espace_pca_knit}}}
### Environmental space
Performing and plotting principal component analysis to reduce dimensionality of environmental space for *`r "{{spName1}}"`* & *`r "{{spName2}}"`*. PCA done for {{pcaPlotSel_rmd}}.
```
```{r, echo = {{espace_pca_knit}}, include = {{espace_pca_knit}}}
# Determine the variables to use
pcaSel_{{multAbr}} <- {{pcaSel_rmd}}
# Run the pca
espace_pca_{{multAbr}} <- espace_pca(
sp.name1 = "{{spName1}}",
sp.name2 = "{{spName2}}",
occs.z1 = occs_{{spAbr1}}[,pcaSel_{{multAbr}}],
occs.z2 = occs_{{spAbr2}}[,pcaSel_{{multAbr}}],
bgPts.z1 = bgEnvsVals_{{spAbr1}}[,pcaSel_{{multAbr}}],
bgPts.z2 = bgEnvsVals_{{spAbr2}}[,pcaSel_{{multAbr}}])
## Generate plots
# PCA Scatter Plot
if ("{{pcaPlotSel_rmd}}" == "occs") {
x <- espace_pca_{{multAbr}}$scores[espace_pca_{{multAbr}}$scores$bg == 'sp', ]
x.f <- factor(x$sp)
} else if ("{{pcaPlotSel_rmd}}" == "occsBg") {
x <- espace_pca_{{multAbr}}$scores[espace_pca_{{multAbr}}$scores$sp == 'bg', ]
x.f <- factor(x$bg)
}
ade4::s.class(x, x.f, xax = {{pc1_rmd}}, yax = {{pc2_rmd}},
col = c("red", "blue"), cstar = 0, cpoint = 0.1)
title(xlab = paste0("PC", {{pc1_rmd}}), ylab = paste0("PC", {{pc2_rmd}}))
# PCA Correlation circle
ade4::s.corcircle(espace_pca_{{multAbr}}$co, xax = {{pc1_rmd}}, yax = {{pc2_rmd}},
lab = pcaSel_{{multAbr}}, full = FALSE, box = TRUE)
title(xlab = paste0("PC", {{pc1_rmd}}),
ylab = paste0("PC", {{pc2_rmd}}))
# PCA screeplot
screeplot(espace_pca_{{multAbr}}, main = NULL)
# Print PCA summary of results
summary(espace_pca_{{multAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/espace_pca.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# model_bioclim.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
model_bioclim_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns('goBIOCLIM'), 'Run')
)
}
model_bioclim_module_server <- function(input, output, session, common) {
allSp <- common$allSp
curSp <- common$curSp
spp <- common$spp
logger <- common$logger
observeEvent(input$goBIOCLIM, {
# loop over all species if batch is on
if(input$batch == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for(sp in spLoop) {
# ERRORS ####
if(is.null(spp[[sp]]$occs$partition)) {
logger %>% writeLog(
type = 'error', hlSpp(sp),
"Before building a model, please partition occurrences for cross-validation.")
return()
}
user_grp <- list(occs.grp = spp[[sp]]$occs$partition,
bg.grp = spp[[sp]]$bg$partition)
# FUNCTION CALL ####
m.bioclim <- model_bioclim(occs = spp[[sp]]$occs,
bg = spp[[sp]]$bg,
user.grp = user_grp,
bgMsk = spp[[sp]]$procEnvs$bgMask,
logger,
spN = sp)
req(m.bioclim)
# LOAD INTO SPP ####
spp[[sp]]$evalOut <- m.bioclim
# REFERENCES
knitcitations::citep(citation("dismo"))
knitcitations::citep(citation("ENMeval", auto = TRUE))
# METADATA ####
spp[[sp]]$rmm$model$algorithms <- "BIOCLIM"
spp[[sp]]$rmm$model$algorithm$bioclim$notes <- "ENMeval/dismo package implementation"
}
common$update_component(tab = "Results")
})
output$evalTblsBioclim <- renderUI({
req(spp[[curSp()]]$rmm$model$algorithms)
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
req(spp[[curSp()]]$evalOut)
res <- spp[[curSp()]]$evalOut@results
res.grp <- spp[[curSp()]][email protected]
res.round <- cbind(round(res[, 1:11], digits = 3))
res.grp.round <- round(res.grp[, 2:6], digits = 3)
# define contents for both evaluation tables
options <- list(scrollX = TRUE, sDom = '<"top">rtp<"bottom">')
output$evalTbl <- DT::renderDataTable(res.round, options = options)
output$evalTblBins <- DT::renderDataTable(res.grp.round, options = options)
tagList(br(),
span("Evaluation statistics: full model and partition averages",
class = "stepText"), br(), br(),
DT::dataTableOutput(session$ns('evalTbl')), br(),
span("Evaluation statistics: individual partitions",
class = "stepText"), br(), br(),
DT::dataTableOutput(session$ns('evalTblBins')))
}
})
}
model_bioclim_module_result <- function(id) {
ns <- NS(id)
# Result UI
uiOutput(ns('evalTblsBioclim'))
}
model_bioclim_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
model_bioclim_knit = if (!is.null(species$rmm$model$algorithms)) {
species$rmm$model$algorithms == "BIOCLIM"} else {FALSE}
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/model_bioclim.R
|
```{asis, echo = {{model_bioclim_knit}}, eval = {{model_bioclim_knit}}, include = {{model_bioclim_knit}}}
### Build and Evaluate Niche Model
Generating a species distribution model using the bioclim alogorithm as implemented in ENMeval V2.0.
```
```{r, echo = {{model_bioclim_knit}}, include = {{model_bioclim_knit}}}
# Run bioclim model for the selected species
model_{{spAbr}} <- model_bioclim(
occs = occs_{{spAbr}},
bg = bgEnvsVals_{{spAbr}},
user.grp = groups_{{spAbr}},
bgMsk = bgMask_{{spAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/model_bioclim.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# model_maxent.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
model_maxent_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
htmlOutput('maxentJar'), "(",
HTML("<font color='blue'><b>NOTE</b></font>"),
": see module guidance for troubleshooting tips if you are experiencing problems.)",
tags$hr(),
strong("Select algorithm"), br(),
tags$div(title = 'text',
radioButtons(ns("algMaxent"), label = '',
choices = list("maxnet", "maxent.jar"), inline = TRUE)),
strong("Select feature classes "),
strong(em("(flexibility of modeled response)")), br(),
"key: ", strong("L"), "inear, ", strong("Q"), "uadratic, ",
strong("H"), "inge, ", strong("P"), "roduct",
tags$div(title = paste0('Feature combinations to be explored. Features are ',
'constructed using different relationships within and ',
'among the environmental predictors, and are used to ',
'constrain the computed probability distribution. ',
'In short, more features = more potential model ',
'complexity.'),
checkboxGroupInput(ns("fcs"), label = '',
choices = list("L", "LQ", "H", "LQH", "LQHP"),
inline = TRUE)), # Check default (no selected param)
strong("Select regularization multipliers "),
strong(em("(penalty against complexity)")),
tags$div(title = paste0('Range of regularization multipliers to explore. ',
'Greater values of the regularization multiplier lead ',
'to increased penalty against overly complex and/or ',
'overfit models. A value of 0 results in no ',
'regularization.'),
sliderInput(ns("rms"), label = "",
min = 0.5, max = 10, step = 0.5, value = c(1, 2))),
tags$div(title = paste0('Value used to step through regularization multiplier ',
'range (e.g. range of 1-3 with step 0.5 results in ',
'[1, 1.5, 2, 2.5, 3]).'),
numericInput(ns("rmsStep"), label = "Multiplier step value",
value = 1)),
strong("Are you using a categorical variable?"),
tags$div(title = '',
selectInput(ns("categSel"), label = '',
choices = list("NO", "YES")),
conditionalPanel(sprintf("input['%s'] == 'YES'", ns("categSel")),
uiOutput('catEnvs'))),
strong("Clamping?"),
tags$div(title = 'Clamp model predictions?',
selectInput(ns("clamp"), label = '',
choices = list("None selected" = '',
"TRUE" = "TRUE",
"FALSE" = "FALSE"))),
strong("Parallel?"),
tags$div(
title = 'Use parallel option for quicker analysis?',
selectInput(ns("parallel"), label = '',
choices = list("None selected" = '',
"TRUE" = "TRUE",
"FALSE" = "FALSE")),
conditionalPanel(
sprintf("input['%s'] == 'TRUE'", ns("parallel")),
numericInput(
ns("numCores"),
label = paste0("Specify the number of cores (max. ", parallel::detectCores(), ")"),
value = parallel::detectCores() - 1, min = 1,
max = parallel::detectCores(), step = 1
))),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goMaxent"), "Run")
)
}
model_maxent_module_server <- function(input, output, session, common) {
allSp <- common$allSp
curSp <- common$curSp
spp <- common$spp
logger <- common$logger
curModel <- common$curModel
selCatEnvs <- common$selCatEnvs
updateSelectInput(session, "clamp", selected = "") # Check default (selected = "")
observeEvent(input$goMaxent, {
if(is.null(input$fcs)) {
logger %>% writeLog(type = 'error', "No feature classes selected.")
return()
}
if(input$clamp == "") {
logger %>% writeLog(type = 'error', "Please specify clamping setting.")
return()
}
if(input$parallel == "") {
logger %>% writeLog(type = 'error', "Please specify parallel setting.")
return()
}
if(input$rmsStep <= 0) {
logger %>% writeLog(type = 'error', "Please specify a positive multiplier step value that is greater than 0.")
return()
}
# loop over all species if batch is on
if (input$batch == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for(sp in spLoop) {
# ERRORS ####
if (is.null(spp[[sp]]$occs$partition)) {
logger %>% writeLog(type = 'error', hlSpp(sp),
"Before building a model, please partition ",
"occurrences for cross-validation.")
return()
}
# Define vector of categorical variables if they exits
if (input$categSel == 'NO') {
catEnvs <- NULL
} else if (input$categSel == 'YES') {
catEnvs <- selCatEnvs()
}
user_grp <- list(occs.grp = spp[[sp]]$occs$partition,
bg.grp = spp[[sp]]$bg$partition)
# FUNCTION CALL ####
res.maxent <- model_maxent(spp[[sp]]$occs,
spp[[sp]]$bg,
user_grp,
spp[[sp]]$procEnvs$bgMask,
input$rms,
input$rmsStep,
input$fcs,
as.logical(input$clamp),
input$algMaxent,
catEnvs,
input$parallel,
input$numCores,
logger,
spN = sp)
req(res.maxent)
# LOAD INTO SPP ####
spp[[sp]]$evalOut <- res.maxent
# METADATA ####
# Metadata obtained from ENMeval RMM object
spp[[sp]]$rmm$model$algorithm <- res.maxent@rmm$model$algorithm
spp[[sp]]$rmm$model$tuneSettings <- res.maxent@rmm$model$tuneSettings
spp[[sp]]$rmm$assessment <- res.maxent@rmm$assessment
# Overwrite metadata
spp[[sp]]$rmm$model$algorithms <- input$algMaxent
spp[[sp]]$rmm$model$algorithm$maxent$clamping <- as.logical(input$clamp)
spp[[sp]]$rmm$model$algorithm$maxent$regularizationMultiplierSet <- input$rms
spp[[sp]]$rmm$model$algorithm$maxent$featureSet <- input$fcs
spp[[sp]]$rmm$model$algorithm$maxent$regularizationRule <- paste("increment by",
input$rmsStep)
spp[[sp]]$rmm$model$algorithm$maxent$categorical <- catEnvs
spp[[sp]]$rmm$model$algorithm$maxent$parallel <- input$parallel
spp[[sp]]$rmm$model$algorithm$maxent$nCores <- input$numCores
}
# REFERENCES
if (input$algMaxent == "maxent.jar") knitcitations::citep(citation("dismo"))
if (input$algMaxent == "maxnet") knitcitations::citep(citation("maxnet"))
knitcitations::citep(citation("ENMeval", auto = TRUE))
common$update_component(tab = "Results")
})
output$evalTbls <- renderUI({
req(spp[[curSp()]]$rmm$model$algorithms)
if (spp[[curSp()]]$rmm$model$algorithms == "maxnet" |
spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
req(spp[[curSp()]]$evalOut)
res <- spp[[curSp()]]$evalOut@results
res.grp <- spp[[curSp()]][email protected]
tuned.n <- ncol(spp[[curSp()]][email protected])
if(tuned.n > 0) {
res.round <- cbind(res[,seq(1, tuned.n)],
round(res[,seq(tuned.n+1, ncol(res))], digits = 3))
res.grp.round <- cbind(res.grp[, 1:2],
round(res.grp[, 3:6], digits = 3))
} else {
res.round <- cbind(round(res[, 1:13], digits = 3))
res.grp.round <- cbind(fold = res.grp[, 1],
round(res.grp[, 2:6], digits = 3))
}
# define contents for both evaluation tables
options <- list(scrollX = TRUE, sDom = '<"top">rtp<"bottom">')
output$evalTbl <- DT::renderDataTable(res.round, options = options)
output$evalTblBins <- DT::renderDataTable(res.grp.round, options = options)
output$lambdas <- renderPrint({
req(spp[[curSp()]]$evalOut)
if(spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
spp[[curSp()]]$evalOut@models[[curModel()]]$betas
} else if(spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
spp[[curSp()]]$evalOut@models[[curModel()]]@lambdas
}
})
tabsetPanel(
tabPanel("Evaluation",
tagList(br(),
span("Evaluation statistics: full model and partition averages",
class = "stepText"), br(), br(),
DT::dataTableOutput(session$ns('evalTbl')), br(),
span("Evaluation statistics: individual partitions",
class = "stepText"), br(), br(),
DT::dataTableOutput(session$ns('evalTblBins')))
),
tabPanel("Lambdas",
br(),
span("Maxent Lambdas File", class = "stepText"), br(), br(),
verbatimTextOutput(session$ns("lambdas"))
)
)
}
})
return(list(
save = function() {
list(
algMaxent = input$algMaxent,
fcs = input$fcs,
rms = input$rms,
rmsStep = input$rmsStep,
categSel = input$categSel,
clamp = input$clamp,
parallel = input$parallel,
numCores = input$numCores
)
# Save any values that should be saved when the current session is saved
},
load = function(state) {
updateRadioButtons(session, "algMaxent", selected = state$algMaxent)
updateCheckboxGroupInput(session, "fcs", selected = state$fcs)
updateSliderInput(session, "rms", value = state$rms)
updateNumericInput(session, "rmsStep", value = state$rmsStep)
updateSelectInput(session, "categSel", selected = state$categSel)
updateSelectInput(session, "clamp", selected = state$clamp)
updateSelectInput(session, "parallel", selected = state$parallel)
updateNumericInput(session, "numCores", value = state$numCores)
}
))
}
model_maxent_module_result <- function(id) {
ns <- NS(id)
# Result UI
uiOutput(ns('evalTbls'))
}
model_maxent_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
model_maxent_knit =
if (!is.null(species$rmm$model$algorithms)) {
species$rmm$model$algorithms != "BIOCLIM"
} else {FALSE},
rms_rmd = printVecAsis(species$rmm$model$algorithm$maxent$regularizationMultiplierSet),
rmsStep_rmd = gsub("increment by", "", species$rmm$model$algorithm$maxent$regularizationRule),
fcs_rmd = printVecAsis(species$rmm$model$algorithm$maxent$featureSet),
clampSel_rmd = species$rmm$model$algorithm$maxent$clamping,
algMaxent_rmd = species$rmm$model$algorithms,
parallel_rmd = species$rmm$model$algorithm$maxent$parallel,
numCores_rmd = print(species$rmm$model$algorithm$maxent$nCores),
cat_envs_knit = !is.null(species$rmm$model$algorithm$maxent$categorical),
catEnvs_rmd = if(!is.null(species$rmm$model$algorithm$maxent$categorical)){species$rmm$model$algorithm$maxent$categorical} else {NULL},
catEnvsNum_rmd = if(!is.null(species$rmm$model$algorithm$maxent$categorical)){
length(species$rmm$model$algorithm$maxent$categorical)} else {0}
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/model_maxent.R
|
```{asis, echo = {{model_maxent_knit}}, eval = {{model_maxent_knit & !cat_envs_knit}}, include = {{model_maxent_knit & !cat_envs_knit}}}
### Build and Evaluate Niche Model
Generating a species distribution model using the `r '{{algMaxent_rmd}}'` algorithm as implemented in ENMeval V2.0 (with clamping = `r {{clampSel_rmd}}`).
For tuning using `r {{fcs_rmd}}` feature classes and regularization multipliers in the `r {{rms_rmd}}` range increasing by `r {{rmsStep_rmd}}`. Not using any categorical predictor variables.
```
```{r, echo = {{model_maxent_knit & !cat_envs_knit}}, include = {{model_maxent_knit & !cat_envs_knit}}}
# Run maxent model for the selected species
model_{{spAbr}} <- model_maxent(
occs = occs_{{spAbr}},
bg = bgEnvsVals_{{spAbr}},
user.grp = groups_{{spAbr}},
bgMsk = bgMask_{{spAbr}},
rms = {{rms_rmd}},
rmsStep = {{rmsStep_rmd}},
fcs = {{fcs_rmd}},
clampSel = {{clampSel_rmd}},
algMaxent = "{{algMaxent_rmd}}",
parallel = {{parallel_rmd}},
numCores = {{numCores_rmd}})
```
```{asis, echo = {{model_maxent_knit & cat_envs_knit}}, eval = {{model_maxent_knit & cat_envs_knit}}, include = {{model_maxent_knit & cat_envs_knit}}}
### Build and Evaluate Niche Model
Generating a species distribution model using the `r '{{algMaxent_rmd}}'` algorithm as implemented in ENMeval V2.0 (with clamping = `r {{clampSel_rmd}}`).
For tuning using `r {{fcs_rmd}}` feature classes and regularization multipliers in the `r {{rms_rmd}}` range increasing by `r {{rmsStep_rmd}}`. Using a total of `r {{catEnvsNum_rmd}}` categorical predictor variables.
```
```{r, echo = {{model_maxent_knit & cat_envs_knit}}, include = {{model_maxent_knit & cat_envs_knit}}}
# Run maxent model for the selected species
model_{{spAbr}} <- model_maxent(
occs = occs_{{spAbr}},
bg = bgEnvsVals_{{spAbr}},
user.grp = groups_{{spAbr}},
bgMsk = bgMask_{{spAbr}},
rms = {{rms_rmd}},
rmsStep = {{rmsStep_rmd}},
fcs = {{fcs_rmd}},
clampSel = {{clampSel_rmd}},
algMaxent = "{{algMaxent_rmd}}",
catEnvs = "{{catEnvs_rmd}}",
parallel = {{parallel_rmd}},
numCores = {{numCores_rmd}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/model_maxent.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# occs_paleoDb.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
# occs_paleoDb_module_ui <- function(id) {
# ns <- shiny::NS(id)
# tagList(
# shinyWidgets::pickerInput(
# ns("timeInterval"),
# label = "Select interval",
# choices = setNames(as.list(c('Quaternary', 'Holocene', 'Pleistocene',
# 'Late Pleistocene', 'Middle Pleistocene',
# 'Calabrian', 'Gelasian')),
# c('Quaternary [0 - 2.588]',
# '-- Holocene [0 - 0.0117]',
# '-- Pleistocene [0.0117 - 2.588]',
# '---- Late Pleistocene [0.0117 - 0.126]',
# '---- Middle Pleistocene [0.126 - 0.781]',
# '---- Calabrian [0.781 - 1.806]',
# '---- Gelasian [1.806 - 2.588]')),
# multiple = FALSE),
# tags$div(title = 'Examples: Canis lupus, Crocuta crocuta',
# textInput(ns("spNamePB"), label = "Enter species scientific name",
# placeholder = 'format: Genus species')),
# tags$div(title = paste0('Maximum number of occurrences recovered from',
# ' databases. Downloaded records are not sorted',
# ' randomly: rows are always consistent between',
# ' downloads.'),
# numericInput(ns("occsNumPB"), "Set maximum number of occurrences",
# value = 0, min = 0, max = 500)),
# actionButton(ns("goPaleoDbOccs"), "Query Database")
# )
# }
#
# occs_paleoDb_module_server <- function(input, output, session, common) {
# logger <- common$logger
# spp <- common$spp
#
# observeEvent(input$goPaleoDbOccs, {
# # WARNING ####
# if (input$occsNumPB < 1) {
# logger %>% writeLog(type = 'warning', "Enter a non-zero number of ocurrences.")
# return()
# }
#
# # FUNCTION CALL ####
# occsTbls <- occs_paleoDb(input$spNamePB, input$occsNumPB, input$timeInterval,
# logger)
#
# req(occsTbls)
#
# # LOAD INTO SPP ####
# occsOrig <- occsTbls$orig
# occs <- occsTbls$cleaned
# sp <- fmtSpN(input$spNamePB)
# sp <- paste0(toupper(substring(sp, 1, 1)), substring(sp, 2, nchar(sp)))
# # if species name is already in list, overwrite it
# if (!is.null(spp[[sp]])) spp[[sp]] <- NULL
# # add two copies of occs dataset -- "occs" will be altered during session,
# # while "occsOrig" will be preserved in this state
# # rmm is the range model metadata object
# spp[[sp]] <- list(occs = occs,
# occData = list(occsOrig = occsOrig,
# occsCleaned = occs),
# rmm = rangeModelMetadata::rmmTemplate(),
# rmd = list())
#
# # REFERENCES ####
# knitcitations::citep(citation("paleobioDB"))
#
# # METADATA ####
# spp[[sp]]$rmm$data$occurrence$taxon <- sp
# spp[[sp]]$rmm$data$occurrence$dataType <- "presence only"
# spp[[sp]]$rmm$data$occurrence$presenceSampleSize <- nrow(occs)
# spp[[sp]]$rmm$data$occurrence$yearMin <- paste(min(occs$late_age), "mya")
# spp[[sp]]$rmm$data$occurrence$yearMax <- paste(max(occs$early_age), "mya")
# spp[[sp]]$rmm$code$wallace$occsNum <- input$occsNumPB
# spp[[sp]]$rmm$code$wallace$occsRemoved <- nrow(occsOrig) - nrow(occs)
# spp[[sp]]$rmm$data$occurrence$sources <- "paleobioDb"
# spp[[sp]]$rmm$code$wallace$timeInterval <- input$timeInterval
#
# common$update_component(tab = "Map")
# })
#
# return(list(
# save = function() {
# list(
# spNamePB = input$spNamePB,
# occsNumPB = input$occsNumPB,
# timeInterval = input$timeInterval
# )
# },
# load = function(state) {
# updateTextInput(session, "spNamePB", value = state$spNamePB)
# updateNumericInput(session, "occsNumPB", value = state$occsNumPB)
# shinyWidgets::updatePickerInput(session, "timeInterval",
# selected = input$timeInterval)
# }
# ))
#
# }
#
# occs_paleoDb_module_map <- function(map, common) {
# spp <- common$spp
# curSp <- common$curSp
# occs <- spp[[curSp()]]$occData$occsCleaned
# map %>% clearAll() %>%
# addCircleMarkers(data = occs, lat = ~latitude, lng = ~longitude,
# radius = 5, color = 'red', fill = TRUE, fillColor = "red",
# fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
# zoom2Occs(occs)
# }
#
# occs_paleoDb_module_rmd <- function(species) {
# # Variables used in the module's Rmd code
# list(
# occs_paleoDb_knit = species$rmm$data$occurrence$sources == "paleobioDb",
# occsNumPB_rmd = species$rmm$code$wallace$occsNum,
# timeInterval_rmd = species$rmm$code$wallace$timeInterval
# )
# }
#
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/occs_paleoDb.R
|
```{asis, echo = {{occs_paleoDb_knit}}, eval = {{occs_paleoDb_knit}}, include = {{occs_paleoDb_knit}}}
### Obtain Occurrence Data
You searched the paleobioDB database for *`r "{{spName}}"`*, limited to `r {{occsNumPB_rmd}}` records in the {{timeInterval_rmd}}.
```
```{r, echo = {{occs_paleoDb_knit}}, include = {{occs_paleoDb_knit}}}
# Query selected database for occurrence records
paleoDb_{{spAbr}}<-occs_paleoDb(
spName = "{{spName}}",
occNum = {{occsNumPB_rmd}},
timeInterval = "{{timeInterval_rmd}}")
occs_{{spAbr}} <- paleoDb_{{spAbr}}$cleaned
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/occs_paleoDb.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# occs_queryDb.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
occs_queryDb_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
tags$div(title = "text",
radioButtons(ns("occsDb"), label = "Choose Database",
choices = c("GBIF" = 'gbif',
"VertNet" = 'vertnet',
# "BISON" = 'bison',
"BIEN" = 'bien'),
inline = TRUE)),
tags$div(
title = "Check to get only occurrences with uncertainty information",
checkboxInput(ns("uncertainty"),
label = strong("Keep only occurrences with uncertainty values"),
value = FALSE)
),
conditionalPanel(
sprintf("input['%s'] == 'gbif'", ns("occsDb")),
checkboxInput(ns("doCitations"),
label = 'Include Data Source Citations',
value = FALSE),
conditionalPanel(
sprintf("input['%1$s'] == 'gbif' &
input['%2$s'] == true",
ns("occsDb"), ns("doCitations")),
splitLayout(textInput(ns('gbifUser'),
'GBIF User ID',
value = NULL),
textInput(ns('gbifEmail'),
'GBIF email',
value = NULL),
passwordInput(ns('gbifPW'),
'GBIF password',
value = NULL))
)
),
tags$div(title = 'Examples: Felis catus, Canis lupus, Nyctereutes procyonoides',
textInput(ns("spNames"), label = "Enter species scientific name",
placeholder = 'format: Genus species',
value = "")), # Check default
conditionalPanel(
sprintf(
"(input['%1$s'] == 'gbif' & input['%2$s'] == false) | input['%1$s'] == 'vertnet'" ,
ns("occsDb"), ns("doCitations")),
tags$div(
title = paste0('Maximum number of occurrences recovered from ',
'databases. Downloaded records are not sorted randomly: ',
'rows are always consistent between downloads.'),
numericInput(ns("occsNum"), "Set maximum number of occurrences",
value = 0, min = 0))
),
actionButton(ns("goDbOccs"), "Query Database")
)
}
occs_queryDb_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
observeEvent(input$goDbOccs, {
# WARNING ####
if (input$occsDb != "bien") {
if (input$occsDb != "gbif" & input$occsNum < 1) {
logger %>% writeLog(type = 'warning',
"Enter a non-zero number of occurrences.")
return()
}
if (input$occsDb == "gbif" & input$occsNum < 1 &
input$doCitations == FALSE) {
logger %>% writeLog(type = 'warning',
"Enter a non-zero number of occurrences.")
return()
}
}
# FUNCTION CALL ####
occsList <- occs_queryDb(input$spNames, input$occsDb, input$occsNum,
input$doCitations, input$gbifUser, input$gbifEmail,
input$gbifPW, input$uncertainty, logger)
req(occsList)
for (sp in names(occsList)) {
# LOAD INTO SPP ####
# if species name is already in list, overwrite it
if (!is.null(spp[[sp]])) spp[[sp]] <- NULL
# add two copies of occs dataset -- higher level occs will be
# altered during session, while occData$occsCleaned is preserved in the
# post-download cleaned state; occsOrig is the raw download
# rmm is the range model metadata object
spp[[sp]] <- list(occs = occsList[[sp]]$cleaned,
occData = list(occsOrig = occsList[[sp]]$orig,
occsCleaned = occsList[[sp]]$cleaned),
rmm = rangeModelMetadata::rmmTemplate(),
rmd = list())
# REFERENCES ####
if (input$occsDb == "bien") {
knitcitations::citep(citation("BIEN"))
} else {
if (input$doCitations) {
knitcitations::citep(citation("occCite"))
} else {
knitcitations::citep(citation("spocc"))
}
}
# METADATA ####
spp[[sp]]$rmm$data$occurrence$taxon <- sp
spp[[sp]]$rmm$data$occurrence$dataType <- "presence only"
spp[[sp]]$rmm$data$occurrence$presenceSampleSize <- nrow(occsList[[sp]]$cleaned)
spp[[sp]]$rmm$data$occurrence$yearMin <- min(occsList[[sp]]$cleaned$year)
spp[[sp]]$rmm$data$occurrence$yearMax <- max(occsList[[sp]]$cleaned$year)
spp[[sp]]$rmm$code$wallace$occsNum <- input$occsNum
spp[[sp]]$rmm$code$wallace$uncertainty <- input$uncertainty
if (input$doCitations | input$occsDb == 'bien') {
spp[[sp]]$rmm$code$wallace$occsNum <- nrow(occsList[[sp]]$orig)
}
spp[[sp]]$rmm$code$wallace$occsRemoved <- input$occsNum - nrow(occsList[[sp]]$cleaned)
# Store DOI citations
if (input$doCitations) {
spp[[sp]]$rmm$data$occurrence$sources <- input$occsDb
spp[[sp]]$rmm$code$wallace$gbifDOI <- occsList[[sp]]$citation
spp[[sp]]$rmm$code$wallace$gbifUser <- input$gbifUser
spp[[sp]]$rmm$code$wallace$gbifEmail <- input$gbifEmail
spp[[sp]]$rmm$code$wallace$doCitations <- input$doCitations
} else {
spp[[sp]]$rmm$data$occurrence$sources <- input$occsDb
}
}
common$update_component(tab = "Map")
})
return(list(
save = function() {
list(
spNames = input$spNames,
occsNum = input$occsNum
)
},
load = function(state) {
updateTextInput(session, "spNames", value = state$spNames)
updateNumericInput(session, "occsNum", value = state$occsNum)
}
))
}
occs_queryDb_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
occs <- spp[[curSp()]]$occData$occsCleaned
map %>% clearAll() %>%
addCircleMarkers(data = occs, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
zoom2Occs(occs)
}
occs_queryDb_module_rmd <- function(species) {
list(
occs_queryDb_knit = species$rmm$data$occurrence$sources == 'gbif' |
species$rmm$data$occurrence$sources == 'vernet' |
# species$rmm$data$occurrence$sources == 'bison' |
species$rmm$data$occurrence$sources == 'bien',
occs_citation_knit = !is.null(species$rmm$code$wallace$gbifDOI),
occDb_rmd = species$rmm$data$occurrence$sources,
occNum_rmd = species$rmm$code$wallace$occsNum,
doCitations_rmd = species$rmm$code$wallace$doCitations,
gbifUser_rmd = species$rmm$code$wallace$gbifUser,
gbifEmail_rmd = species$rmm$code$wallace$gbifEmail,
uncertainty_rmd = species$rmm$code$wallace$uncertainty
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/occs_queryDb.R
|
```{asis, echo = {{occs_queryDb_knit & !occs_citation_knit}}, eval = {{occs_queryDb_knit & !occs_citation_knit}}, include = {{occs_queryDb_knit & !occs_citation_knit}}}
### Obtain Occurrence Data
You searched the `r "{{occDb_rmd}}"` database for *`r "{{spName}}"`*, limited to `r {{occNum_rmd}}` records. You decided to remove occurrences without uncertainty information? `r {{uncertainty_rmd}}`
```
```{asis, echo = {{occs_queryDb_knit & occs_citation_knit}}, eval = {{occs_queryDb_knit & occs_citation_knit}}, include = {{occs_queryDb_knit & occs_citation_knit}}}
### Obtain Occurrence Data
You searched the `r "{{occDb_rmd}}"` database for *`r "{{spName}}"`*, limited to `r {{occNum_rmd}}` records, using the citation option. You decided to remove occurrences without uncertainty information? `r {{uncertainty_rmd}}`
```
```{r, echo = {{occs_queryDb_knit & !occs_citation_knit}}, include = {{occs_queryDb_knit & !occs_citation_knit}}}
# Query selected database for occurrence records
queryDb_{{spAbr}} <- occs_queryDb(
spNames = "{{spName}}",
occDb = "{{occDb_rmd}}",
occNum = {{occNum_rmd}},
RmUncertain = {{uncertainty_rmd}})
occs_{{spAbr}} <- queryDb_{{spAbr}}${{sp}}$cleaned
```
```{r, echo = {{occs_queryDb_knit & occs_citation_knit}}, include = {{occs_queryDb_knit & occs_citation_knit}}}
# Query selected database for occurrence records
queryDb_{{spAbr}} <- occs_queryDb(
spNames = "{{spName}}",
occDb = "{{occDb_rmd}}",
doCitations = {{doCitations_rmd}},
gbifUser = "{{gbifUser_rmd}}",
gbifEmail = "{{gbifEmail_rmd}}",
# Please type your GBIF password
gbifPW = "",
RmUncertain = {{uncertainty_rmd}})
occs_{{spAbr}} <- queryDb_{{spAbr}}${{sp}}$cleaned
# Print DOI and date of your search
queryDb_{{spAbr}}${{sp}}$citation
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/occs_queryDb.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# occs_userOccs.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
occs_userOccs_module_ui <- function(id) {
ns <- NS(id)
tagList(
fileInput(ns("userCSV"), label = "Upload Occurrence CSV", accept = ".csv"),
checkboxInput(
ns("noCSV"), value = FALSE,
label = "Do you want to define delimiter-separated and decimal values?"),
conditionalPanel(
sprintf("input['%s'] == 1", ns("noCSV")),
textInput(ns("sepCSV"), label = "Define delimiter-separator", value = ","),
textInput(ns("decCSV"), label = "Define decimal-separator", value = ".")
),
actionButton(ns("goUserOccs"), "Load Occurrences")
)
}
occs_userOccs_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
observeEvent(input$goUserOccs, {
# FUNCTION CALL ####
if (input$noCSV == 0 | is.null(input$noCSV)) {
occsList <- occs_userOccs(input$userCSV$datapath, input$userCSV$name,
",", ".", logger)
} else {
occsList <- occs_userOccs(input$userCSV$datapath, input$userCSV$name,
input$sepCSV, input$decCSV, logger)
}
if (is.null(occsList)) return()
# LOAD INTO SPP ####
# if species name is already in list, overwrite it
for(sp in names(occsList)) {
occs <- occsList[[sp]]$cleaned
occsOrig <- occsList[[sp]]$orig
if(!is.null(spp[[sp]])) spp[[sp]] <- NULL
spp[[sp]] <- list(occs = occs,
occData = list(occsOrig = occsOrig, occsCleaned = occs),
rmm = rangeModelMetadata::rmmTemplate(),
rmd = list())
if(!is.null(occsList[[sp]]$bg)) spp[[sp]]$bg <- occsList[[sp]]$bg
# METADATA ####
spp[[sp]]$rmm$data$occurrence$taxon <- unique(occs$scientific_name)
spp[[sp]]$rmm$data$occurrence$dataType <- "presence only"
spp[[sp]]$rmm$data$occurrence$presenceSampleSize <- nrow(occs)
spp[[sp]]$rmm$data$occurrence$sources <- "user"
spp[[sp]]$rmm$code$wallace$userCSV <- input$userCSV$name
spp[[sp]]$rmm$code$wallace$occsNum <- nrow(occs)
spp[[sp]]$rmm$code$wallace$occsRemoved <- nrow(occs) - nrow(occsOrig)
spp[[sp]]$rmm$code$wallace$sepCSV <- ifelse(input$noCSV == 0 | is.null(input$noCSV),
",", input$sepCSV)
spp[[sp]]$rmm$code$wallace$decCSV <- ifelse(input$noCSV == 0 | is.null(input$noCSV),
".", input$decCSV)
}
common$update_component(tab = "Map")
})
return(list(
save = function() {
list(
noCSV = input$noCSV,
sepCSV = input$sepCSV,
decCSV = input$decCSV
)
},
load = function(state) {
updateCheckboxInput(session, "noCSV", value = state$noCSV)
updateTextInput(session, "sepCSV", value = state$sepCSV)
updateTextInput(session, "decCSV", value = state$decCSV)
}
))
}
occs_userOccs_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
occs <- spp[[curSp()]]$occData$occsCleaned
map %>% clearAll() %>%
addCircleMarkers(data = occs, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
zoom2Occs(occs)
}
occs_userOccs_module_rmd <- function(species) {
list(
occs_userOccs_knit = species$rmm$data$occurrence$sources == 'user',
userCSV_rmd = species$rmm$code$wallace$userCSV,
sepCSV_rmd = species$rmm$code$wallace$sepCSV,
decCSV_rmd = species$rmm$code$wallace$decCSV
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/occs_userOccs.R
|
```{asis, echo = {{occs_userOccs_knit}}, eval = {{occs_userOccs_knit}}, include = {{occs_userOccs_knit}}}
User CSV path with occurrence data. If the CSV file is not in the current workspace, change to the correct file path (e.g. "/Users/darwin/Documents/occs/").
```
```{r, echo = {{occs_userOccs_knit}}}
# NOTE: provide the folder path of the .csv file
occs_path <- ""
occs_path <- file.path(occs_path, "{{userCSV_rmd}}")
# get a list of species occurrence data
userOccs_{{spAbr}} <- occs_userOccs(
txtPath = occs_path,
txtName = "{{userCSV_rmd}}",
txtSep = "{{sepCSV_rmd}}",
txtDec = "{{decCSV_rmd}}")
occs_{{spAbr}} <- userOccs_{{spAbr}}${{sp}}$cleaned
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/occs_userOccs.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# part_nonSpat.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
part_nonSpat_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
selectInput(ns("partNspSel"), "Options Available:",
choices = list("None selected" = '',
"Jackknife (k = n)" = "jack",
"Random k-fold" = "rand")),
conditionalPanel(sprintf("input['%s'] == 'rand'", ns("partNspSel")),
numericInput(ns("kfolds"), label = "Number of Folds",
value = 2, min = 2)),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goPartitionNonSpat"), "Partition")
)
}
part_nonSpat_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
allSp <- common$allSp
curSp <- common$curSp
bgMask <- common$bgMask
observeEvent(input$goPartitionNonSpat, {
# loop over all species if batch is on
if(input$batch == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for(sp in spLoop) {
if (is.null(bgMask())) {
logger %>% writeLog(
type = 'error', hlSpp(sp),
"Before partitioning occurrences, mask your ",
"environmental variables by your background extent."
)
return()
}
#### FUNCTION CALL
group.data <- part_partitionOccs(spp[[sp]]$occs, spp[[sp]]$bg,
input$partNspSel, kfolds = input$kfolds,
bgMask = NULL, aggFact = NULL, logger,
spN = sp)
req(group.data)
# LOAD INTO SPP ####
spp[[sp]]$occs$partition <- group.data$occs.grp
spp[[sp]]$bg$partition <- group.data$bg.grp
# REFERENCES
knitcitations::citep(citation("ENMeval", auto = TRUE))
# METADATA ####
spp[[sp]]$rmm$code$wallace$partition_code <- input$partNspSel
spp[[sp]]$rmm$model$partition$NonSpatial <- 'Non-spatial'
if(input$partNspSel == 'jack') {
spp[[sp]]$rmm$model$partition$numberFolds <- nrow(spp[[sp]]$occs)
spp[[sp]]$rmm$model$partition$partitionRule <- 'jackknife'
}
if(input$partNspSel == 'rand') {
spp[[sp]]$rmm$model$partition$numberFolds <- input$kfolds
spp[[sp]]$rmm$model$partition$partitionRule <- 'random k-fold'
}
}
common$update_component(tab = "Map")
})
return(list(
save = function() {
list(
partNspSel = input$partNspSel,
kfolds = input$kfolds
)
},
load = function(state) {
updateSelectInput(session, "partNspSel", selected = state$partNspSel)
updateNumericInput(session, "kfolds", value = state$kfolds)
}
))
}
part_nonSpat_module_map <- function(map, common) {
occs <- common$occs
# Map logic
if (!is.null(occs()$partition)) {
occsGrp <- occs()$partition
# colors for partition symbology
if (max(occsGrp) < 3) {
newColors <- RColorBrewer::brewer.pal(n = 3, "Set2")[1:max(occsGrp)]
} else if (max(occsGrp) < 9) {
newColors <- RColorBrewer::brewer.pal(n = max(occsGrp), "Set2")
} else if (max(occsGrp) < 12) {
newColors <- RColorBrewer::brewer.pal(n = max(occsGrp), "RdYlBu")
} else {
newColors <- grDevices::colorRampPalette(RColorBrewer::brewer.pal(n = 11, "RdYlBu"))(max(occsGrp))
}
partsFill <- newColors[occsGrp]
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE,
fillColor = partsFill, fillOpacity = 1, weight = 2,
popup = ~pop) %>%
addLegend("bottomright", colors = newColors,
title = "Partition Groups", labels = sort(unique(occsGrp)),
opacity = 1)
} else {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
zoom2Occs(occs())
}
}
part_nonSpat_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
part_nonSpat_knit = !is.null(species$rmm$model$partition$NonSpatial),
k_folds_rmd = species$rmm$model$partition$numberFolds,
method_rmd = species$rmm$model$partition$partitionRule,
method_code_rmd = species$rmm$code$wallace$partition_code
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/part_nonSpat.R
|
```{asis, echo = {{part_nonSpat_knit}}, eval = {{part_nonSpat_knit}}, include = {{part_nonSpat_knit}}}
### Partition occurrence data
Partition occurrences and background points for model training and validation using `r "{{method_rmd}}"`, a non-spatial partition method.
```
```{r, echo = {{part_nonSpat_knit}}, include = {{part_nonSpat_knit}}}
# R code to get partitioned data
groups_{{spAbr}} <- part_partitionOccs(
occs = occs_{{spAbr}} ,
bg = bgSample_{{spAbr}},
method = "{{method_code_rmd}}",
kfolds = {{k_folds_rmd}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/part_nonSpat.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# part_spat.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
part_spat_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
selectInput(ns("partitionSpatSel"), "Options Available:",
choices = list("None selected" = '',
"Block (k = 4)" = "block",
"Checkerboard 1 (k = 2)" = "cb1",
"Checkerboard 2 (k = 4)" = "cb2")), # Check default (no selected)
conditionalPanel(sprintf("input['%1$s'] == 'cb1' | input['%1$s'] == 'cb2'",
ns("partitionSpatSel")),
numericInput(ns("aggFact"), label = "Aggregation Factor",
value = 2, min = 2)),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goPartitionSpat"), "Partition")
)
}
part_spat_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
allSp <- common$allSp
curSp <- common$curSp
bgMask <- common$bgMask
observeEvent(input$goPartitionSpat, {
# loop over all species if batch is on
if(input$batch == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for(sp in spLoop) {
if (is.null(bgMask())) {
logger %>% writeLog(
type = 'error', hlSpp(sp),
"Before partitioning occurrences, mask your ",
"environmental variables by your background extent.")
return()
}
# FUNCTION CALL ####
group.data <- part_partitionOccs(spp[[sp]]$occs, spp[[sp]]$bg,
input$partitionSpatSel, kfolds = NULL,
bgMask = spp[[sp]]$procEnvs$bgMask,
aggFact = input$aggFact, logger,
spN = sp)
req(group.data)
# LOAD INTO SPP ####
spp[[sp]]$occs$partition <- group.data$occs.grp
spp[[sp]]$bg$partition <- group.data$bg.grp
spp[[sp]]$rmm$code$wallace$partition_code <- input$partitionSpatSel
spp[[sp]]$rmm$code$wallace$partition_agg <- input$aggFact
# REFERENCES
knitcitations::citep(citation("ENMeval", auto = TRUE))
# METADATA ####
spp[[sp]]$rmm$model$partition$Spatial <- 'Spatial'
if(input$partitionSpatSel == 'block') {
spp[[sp]]$rmm$model$partition$numberFolds <- 4
spp[[sp]]$rmm$model$partition$partitionRule <- 'spatial block'
}
if(input$partitionSpatSel == 'cb1') {
spp[[sp]]$rmm$model$partition$numberFolds <- 2
spp[[sp]]$rmm$model$partition$partitionRule <- 'checkerboard'
}
if(input$partitionSpatSel == 'cb2') {
spp[[sp]]$rmm$model$partition$numberFolds <- 4
spp[[sp]]$rmm$model$partition$partitionRule <- 'hierarchical checkerboard'
spp[[sp]]$rmm$model$partition$notes <- paste('aggregation factor =',
input$aggFact)
}
}
common$update_component(tab = "Map")
})
return(list(
save = function() {
list(
partitionSpatSel = input$partitionSpatSel,
aggFact = input$aggFact
)
},
load = function(state) {
updateSelectInput(session, "partitionSpatSel", selected = state$partitionSpatSel)
updateNumericInput(session, "aggFact", value = state$aggFact)
}
))
}
part_spat_module_map <- function(map, common) {
occs <- common$occs
# Map logic
if (!is.null(occs()$partition)) {
occsGrp <- occs()$partition
# colors for partition symbology
if (max(occsGrp) < 3) {
newColors <- RColorBrewer::brewer.pal(n = 3, "Set2")[1:max(occsGrp)]
} else if (max(occsGrp) < 9) {
newColors <- RColorBrewer::brewer.pal(n = max(occsGrp), "Set2")
} else if (max(occsGrp) < 12) {
newColors <- RColorBrewer::brewer.pal(n = max(occsGrp), "RdYlBu")
} else {
newColors <- grDevices::colorRampPalette(RColorBrewer::brewer.pal(n = 11, "RdYlBu"))(max(occsGrp))
}
partsFill <- newColors[occsGrp]
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE,
fillColor = partsFill, fillOpacity = 1, weight = 2,
popup = ~pop) %>%
addLegend("bottomright", colors = newColors,
title = "Partition Groups", labels = sort(unique(occsGrp)),
opacity = 1)
} else {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
zoom2Occs(occs())
}
}
part_spat_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
part_spat_knit = !is.null(species$rmm$model$partition$Spatial)&is.null(species$rmm$code$wallace$partition_agg),
method_rmd = species$rmm$model$partition$partitionRule,
method_code_rmd = species$rmm$code$wallace$partition_code,
part_spat_aggreg_knit = !is.null(species$rmm$code$wallace$partition_agg),
aggFact_rmd = species$rmm$code$wallace$partition_agg
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/part_spat.R
|
```{asis, echo = {{part_spat_knit}}, eval = {{part_spat_knit}}, include = {{part_spat_knit}}}
### Partition occurrence data
Partition occurrences and background points for model training and validation using "{{method_rmd}}", a spatial partition method with 4 partitions.
```
```{asis, echo = {{part_spat_aggreg_knit}}, eval = {{ part_spat_aggreg_knit }}, include = {{part_spat_aggreg_knit}}}
### Partition occurrence data
Partition occurrences and background points for model training and validation using "{{method_rmd}}", a spatial partition method with an aggregation factor of {{aggFact_rmd}}.
```
```{r, echo = {{part_spat_knit}}, include = {{part_spat_knit}}}
# R code to get partitioned data
groups_{{spAbr}} <- part_partitionOccs(
occs = occs_{{spAbr}} ,
bg = bgSample_{{spAbr}},
method = "{{method_code_rmd}}")
```
```{r, echo = {{part_spat_aggreg_knit}}, include = {{part_spat_aggreg_knit}}}
# R code to get partitioned data
groups_{{spAbr}} <- part_partitionOccs(
occs = occs_{{spAbr}} ,
bg = bgSample_{{spAbr}},
method = "{{method_code_rmd}}",
bgMask = bgMask_{{spAbr}},
aggFact = {{aggFact_rmd}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/part_spat.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# penvs_bgExtent.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
penvs_bgExtent_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
span("Step 1:", class = "step"),
span("Choose Background Extent", class = "stepText"), br(), br(),
radioButtons(ns("bgSel"), "Background Extents:",
choices = list("bounding box",
"minimum convex polygon",
"point buffers")),
tags$div(title = paste0('Buffer area in degrees (1 degree = ~111 km). ',
'Exact length varies based on latitudinal position.'),
numericInput(ns("bgBuf"),
label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5)), # Check default (value = 0)
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch1"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goBgExt"), "Select"),
tags$hr(class = "hrDotted"),
span("Step 2:", class = "step"),
span("Sample Background Points", class = "stepText"), br(), br(),
strong(paste0('Mask predictor rasters by background extent and sample',
' background points')), br(), br(),
numericInput(ns("bgPtsNum"), label = "No. of background points",
value = 10000, min = 1, step = 1), # Check default (value = 10000)
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch2"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goBgMask"), "Sample"),
tags$hr(class = "hrDashed"),
actionButton(ns("goReset_penvs"), "Reset", class = 'butReset'),
strong(" background")
)
}
penvs_bgExtent_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
allSp <- common$allSp
curSp <- common$curSp
envs.global <- common$envs.global
envs <- common$envs
bgExt <- common$bgExt
occs <- common$occs
observeEvent(input$goBgExt, {
common$update_component(tab = "Map")
req(curSp(), occs())
# loop over all species if batch is on
if (input$batch1 == TRUE) spLoop <- allSp() else spLoop <- curSp()
for (sp in spLoop) {
# ERRORS ####
if (is.null(spp[[sp]]$envs)) {
logger %>% writeLog(
type = 'error',
hlSpp(sp),
'Environmental variables missing. Obtain them in component 3.')
return()
}
# FUNCTION CALL ####
bgExt <- penvs_bgExtent(spp[[sp]]$occs, input$bgSel, input$bgBuf, logger,
spN = sp)
req(bgExt)
# LOAD INTO SPP ####
spp[[sp]]$procEnvs$bgExt <- bgExt
# REFERENCES ####
knitcitations::citep(citation("sf"))
knitcitations::citep(citation("sp"))
# METADATA ####
spp[[sp]]$rmm$data$occurrence$backgroundSampleSizeRule <-
paste0(input$bgSel, ', ', input$bgBuf, ' degree buffer')
##Creating these to facilitate RMD generation
spp[[sp]]$rmm$code$wallace$bgSel <- input$bgSel
spp[[sp]]$rmm$code$wallace$bgBuf <- input$bgBuf
# spp[[sp]]$rmm$wallace$bgSel <- input$bgSel
# spp[[sp]]$rmm$wallace$bgBuf <- input$bgBuf
}
})
observeEvent(input$goBgMask, {
# WARNING ####
if (input$bgPtsNum < 1) {
logger %>% writeLog(type = 'warning',
"Enter a non-zero number of background points.")
return()
}
req(bgExt())
# loop over all species if batch is on
if (input$batch2 == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for (sp in spLoop) {
# FUNCTION CALL ####
bgMask <- penvs_bgMask(spp[[sp]]$occs, envs.global[[spp[[sp]]$envs]],
spp[[sp]]$procEnvs$bgExt, logger, spN = sp)
req(bgMask)
bgNonNA <- raster::ncell(bgMask) - raster::freq(bgMask, value = NA)[[1]]
if ((bgNonNA + 1) < input$bgPtsNum) {
logger %>%
writeLog(
type = "error", hlSpp(sp),
"Number of requested background points (n = ", input$bgPtsNum, ") is ",
"higher than the maximum points available on the background extent ",
"(n = ", bgNonNA, "). Please reduce the number of requested points.")
return()
}
bgPts <- penvs_bgSample(spp[[sp]]$occs, bgMask, input$bgPtsNum, logger,
spN = sp)
req(bgPts)
withProgress(
message = paste0("Extracting background values for ", spName(sp), "..."), {
bgEnvsVals <- as.data.frame(raster::extract(bgMask, bgPts))
})
NApoints <- sum(rowSums(is.na(raster::extract(bgMask, spp[[sp]]$occs[ , c("longitude", "latitude")]))))
if (NApoints > 0) {
logger %>%
writeLog(type = "error", hlSpp(sp),
"One or more occurrence points have NULL raster values.",
" This can sometimes happen for points on the margin of the study extent.",
" Please increase the buffer slightly to include them.")
return()
}
# LOAD INTO SPP ####
spp[[sp]]$procEnvs$bgMask <- bgMask
# add columns for env variables beginning with "envs_" to bg tbl
spp[[sp]]$bg <- cbind(scientific_name = paste0("bg_", sp), bgPts,
country = NA, state_province = NA, locality = NA,
year = NA, record_type = NA, catalog_number = NA,
institution_code = NA, elevation = NA,
uncertainty = NA, bgEnvsVals)
# sample background points
spp[[sp]]$bgPts <- bgPts
# METADATA ####
spp[[sp]]$rmm$data$occurrence$backgroundSampleSizeSet <- input$bgPtsNum
}
common$update_component(tab = "Map")
})
# reset background button functionality
observeEvent(input$goReset_penvs, {
req(curSp())
spp[[curSp()]]$procEnvs$bgExt <- NULL
spp[[curSp()]]$procEnvs$bgMask <- NULL
spp[[curSp()]]$bg <- NULL
spp[[curSp()]]$bgPts <- NULL
spp[[curSp()]]$rmm$data$occurrence$backgroundSampleSizeSet <- NULL
logger %>% writeLog(
hlSpp(curSp()), "Reset background extent and background points.")
})
return(list(
save = function() {
list(
bgSel = input$bgSel,
bgBuf = input$bgBuf,
bgPtsNum = input$bgPtsNum
)
},
load = function(state) {
# Load
updateRadioButtons(session, "bgSel", selected = state$bgSel)
updateNumericInput(session, "bgBuf", value = state$bgBuf)
updateNumericInput(session, "bgPtsNum", value = state$bgPtsNum)
}
))
common$update_component(tab = "Map")
}
penvs_bgExtent_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
occs <- common$occs
if (is.null(spp[[curSp()]]$procEnvs$bgExt)) {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
} else {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
polys <- spp[[curSp()]]$procEnvs$bgExt@polygons[[1]]@Polygons
if (length(polys) == 1) {
xy <- list(polys[[1]]@coords)
} else {
xy <- lapply(polys, function(x) x@coords)
}
for (shp in xy) {
map %>%
addPolygons(lng = shp[, 1], lat = shp[, 2], weight = 4, color = "gray",
group = 'bgShp')
}
bb <- spp[[curSp()]]$procEnvs$bgExt@bbox
map %>% fitBounds(bb[1], bb[2], bb[3], bb[4])
}
}
## Original idea for RMD
# bgExtent_RMD <- function(sp) {
# list(bgSel = spp[[sp]]$rmm$wallace$bgSel,
# bgBuf = spp[[sp]]$rmm$wallace$bgBuf)
# }
penvs_bgExtent_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
penvs_bgExtent_knit = !is.null(species$rmm$code$wallace$bgSel),
# penvs_bgExtent_knit = species$rmm$code$wallace$someFlag,
bgPtsNum_rmd = species$rmm$data$occurrence$backgroundSampleSizeSet,
bgSel_rmd = species$rmm$code$wallace$bgSel,
bgBuf_rmd = species$rmm$code$wallace$bgBuf
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/penvs_bgExtent.R
|
```{asis, echo = {{penvs_bgExtent_knit}}, eval = {{penvs_bgExtent_knit}}, include = {{penvs_bgExtent_knit}}}
### Process environmental data
Sampling of {{bgPtsNum_rmd}} background points and corresponding environmental data using a "{{bgSel_rmd}}" method with a {{bgBuf_rmd}} degree buffer.
```
```{r, echo = {{penvs_bgExtent_knit}}, include = {{penvs_bgExtent_knit}}}
# Generate background extent
bgExt_{{spAbr}} <- penvs_bgExtent(
occs = occs_{{spAbr}},
bgSel = "{{bgSel_rmd}}",
bgBuf = {{bgBuf_rmd}})
# Mask environmental data to provided extent
bgMask_{{spAbr}} <- penvs_bgMask(
occs = occs_{{spAbr}},
envs = envs_{{spAbr}},
bgExt = bgExt_{{spAbr}})
# Sample background points from the provided area
bgSample_{{spAbr}} <- penvs_bgSample(
occs = occs_{{spAbr}},
bgMask = bgMask_{{spAbr}},
bgPtsNum = {{bgPtsNum_rmd}})
# Extract values of environmental layers for each background point
bgEnvsVals_{{spAbr}} <- as.data.frame(raster::extract(bgMask_{{spAbr}}, bgSample_{{spAbr}}))
##Add extracted values to background points table
bgEnvsVals_{{spAbr}} <- cbind(scientific_name = paste0("bg_", "{{spName}}"), bgSample_{{spAbr}},
occID = NA, year = NA, institution_code = NA, country = NA,
state_province = NA, locality = NA, elevation = NA,
record_type = NA, bgEnvsVals_{{spAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/penvs_bgExtent.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# penvs_drawBgExtent.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
penvs_drawBgExtent_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
span("Step 1:", class = "step"),
span("Draw Background Extent", class = "stepText"), br(), br(),
"Draw a polygon and select buffer distance", br(), br(),
tags$p(paste0('Buffer area in degrees (1 degree = ~111 km). Exact length',
' varies based on latitudinal position.')),
numericInput(ns("drawBgBuf"), label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch1"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns('goDrawBg'), "Create"),
tags$hr(class = "hrDotted"),
span("Step 2:", class = "step"),
span("Sample Background Points", class = "stepText"), br(), br(),
strong(paste0('Mask predictor rasters by background extent and sample',
' background points')), br(), br(),
numericInput(ns("bgPtsNum"), label = "No. of background points",
value = 10000, min = 1, step = 1), # Check default (value = 10000)
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch2"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goBgMask"), "Sample"),
tags$hr(class = "hrDashed"),
actionButton(ns("goReset_penvs"), "Reset", class = 'butReset'),
strong(" background")
)
}
penvs_drawBgExtent_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
allSp <- common$allSp
curSp <- common$curSp
envs.global <- common$envs.global
envs <- common$envs
bgExt <- common$bgExt
observeEvent(input$goDrawBg, {
if (is.null(spp[[curSp()]]$polyExtXY)) {
logger %>% writeLog(
type = 'error',
paste0("The polygon has not been drawn and finished. Please use the ",
"draw toolbar on the left-hand of the map to complete ",
"the polygon.")
)
return()
}
drawExtXY <- spp[[curSp()]]$polyExtXY
drawExtID <- spp[[curSp()]]$polyExtID
# loop over all species if batch is on
if (input$batch1 == TRUE) spLoop <- allSp() else spLoop <- curSp()
for (sp in spLoop) {
# ERRORS ####
if (is.null(spp[[sp]]$envs)) {
logger %>% writeLog(
type = 'error',
hlSpp(sp),
'Environmental variables missing. Obtain them in component 3.')
return()
}
# FUNCTION CALL ####
drawBgExt <- penvs_drawBgExtent(drawExtXY, drawExtID, input$drawBgBuf,
spp[[sp]]$occs, logger, spN = sp)
# LOAD INTO SPP ####
spp[[sp]]$procEnvs$bgExt <- drawBgExt
# METADATA ####
##Record buffer size
spp[[sp]]$rmm$code$wallace$bgBuf <- input$drawBgBuf
polyX <- printVecAsis(round(spp[[curSp()]]$polyExtXY[, 1], digits = 4))
polyY <- printVecAsis(round(spp[[curSp()]]$polyExtXY[, 2], digits = 4))
spp[[curSp()]]$rmm$code$wallace$drawExtPolyCoords <-
paste0('Draw Polygon (X: ', polyX, ', Y: ', polyY, ')')
spp[[sp]]$rmm$data$occurrence$backgroundSampleSizeRule <-
paste0('Draw Polygon, ', input$bgBuf, ' degree buffer')
}
})
observeEvent(input$goBgMask, {
# WARNING ####
if (input$bgPtsNum < 1) {
logger %>% writeLog(type = 'warning',
"Enter a non-zero number of background points.")
return()
}
req(bgExt())
# loop over all species if batch is on
if (input$batch2 == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for (sp in spLoop) {
# FUNCTION CALL ####
bgMask <- penvs_bgMask(spp[[sp]]$occs,
envs.global[[spp[[sp]]$envs]],
spp[[sp]]$procEnvs$bgExt,
logger,
spN = sp)
req(bgMask)
bgNonNA <- raster::ncell(bgMask) - raster::freq(bgMask, value = NA)[[1]]
if ((bgNonNA + 1) < input$bgPtsNum) {
logger %>%
writeLog(
type = "error", hlSpp(sp),
"Number of requested background points (n = ", input$bgPtsNum, ") is ",
"higher than the maximum points available on the background extent ",
"(n = ", bgNonNA, "). Please reduce the number of requested points.")
return()
}
bgPts <- penvs_bgSample(spp[[sp]]$occs,
bgMask,
input$bgPtsNum,
logger,
spN = sp)
req(bgPts)
withProgress(message = paste0("Extracting background values for ",
spName(sp), "..."), {
bgEnvsVals <- as.data.frame(raster::extract(bgMask, bgPts))
})
if (sum(rowSums(is.na(raster::extract(bgMask, spp[[sp]]$occs[ , c("longitude", "latitude")])))) > 0) {
logger %>%
writeLog(type = "error", hlSpp(sp),
"One or more occurrence points have NULL raster values.",
" This can sometimes happen for points on the margin of the study extent.",
" Please increase the buffer slightly to include them.")
return()
}
# LOAD INTO SPP ####
spp[[sp]]$procEnvs$bgMask <- bgMask
# add columns for env variables beginning with "envs_" to bg tbl
spp[[sp]]$bg <- cbind(scientific_name = paste0("bg_", sp), bgPts,
country = NA, state_province = NA, locality = NA,
year = NA, record_type = NA, catalog_number = NA,
institution_code = NA, elevation = NA,
uncertainty = NA, bgEnvsVals)
# sample background points
spp[[sp]]$bgPts <- bgPts
# METADATA ####
spp[[sp]]$rmm$data$occurrence$backgroundSampleSizeSet <- input$bgPtsNum
}
})
# reset background button functionality
observeEvent(input$goReset_penvs, {
req(curSp())
spp[[curSp()]]$procEnvs$bgExt <- NULL
spp[[curSp()]]$procEnvs$bgMask <- NULL
spp[[curSp()]]$bg <- NULL
spp[[curSp()]]$bgPts <- NULL
spp[[curSp()]]$rmm$data$occurrence$backgroundSampleSizeSet <- NULL
logger %>% writeLog(
hlSpp(curSp()), "Reset background extent and background points.")
})
return(list(
save = function() {
list(
drawBgBuf = input$drawBgBuf,
bgPtsNum = input$bgPtsNum
)
},
load = function(state) {
# Load
updateNumericInput(session, "drawBgBuf", value = state$drawBgBuf)
updateNumericInput(session, "bgPtsNum", value = state$bgPtsNum)
}
))
common$update_component(tab = "Map")
}
penvs_drawBgExtent_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
occs <- common$occs
map %>% leaflet.extras::addDrawToolbar(
targetGroup = 'draw',
polylineOptions = FALSE,
rectangleOptions = FALSE,
circleOptions = FALSE,
markerOptions = FALSE,
circleMarkerOptions = FALSE,
editOptions = leaflet.extras::editToolbarOptions()
)
if (is.null(spp[[curSp()]]$procEnvs$bgExt)) {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
} else {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
polys <- spp[[curSp()]]$procEnvs$bgExt@polygons[[1]]@Polygons
if (length(polys) == 1) {
xy <- list(polys[[1]]@coords)
} else {
xy <- lapply(polys, function(x) x@coords)
}
for (shp in xy) {
map %>%
addPolygons(lng = shp[, 1], lat = shp[, 2], weight = 4, color = "gray",
group = 'bgShp')
}
}
}
penvs_drawBgExtent_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
penvs_drawBgExtent_knit = !is.null(species$rmm$code$wallace$drawExtPolyCoords),
polyExtXY_rmd = printVecAsis(species$polyExtXY),
polyExtID_rmd = species$polyExtID,
drawBgBuf_rmd = species$rmm$code$wallace$bgBuf,
bgPtsNum_rmd = species$rmm$data$occurrence$backgroundSampleSizeSet
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/penvs_drawBgExtent.R
|
```{asis, echo = {{penvs_drawBgExtent_knit}}, eval = {{penvs_drawBgExtent_knit}}, include = {{penvs_drawBgExtent_knit}}}
### Process environmental data
Sampling of {{bgPtsNum_rmd}} background points and corresponding environmental data using a user drawn background extent with a {{drawBgBuf_rmd}} degree buffer.
```
```{r, echo = {{penvs_drawBgExtent_knit}}, include = {{penvs_drawBgExtent_knit}}}
# Create a background extent based on user drawn polygon
bgExt_{{spAbr}} <- penvs_drawBgExtent(
polyExtXY = matrix({{polyExtXY_rmd}},ncol=2,byrow=FALSE),
polyExtID = {{polyExtID_rmd}},
drawBgBuf = {{drawBgBuf_rmd}},
occs = occs_{{spAbr}})
# Mask environmental data to provided extent
bgMask_{{spAbr}} <- penvs_bgMask(
occs = occs_{{spAbr}},
envs = envs_{{spAbr}},
bgExt = bgExt_{{spAbr}})
# Sample background points from the provided area
bgSample_{{spAbr}} <- penvs_bgSample(
occs = occs_{{spAbr}},
bgMask = bgMask_{{spAbr}},
bgPtsNum = {{bgPtsNum_rmd}})
# Extract values of environmental layers for each background point
bgEnvsVals_{{spAbr}} <- as.data.frame(raster::extract(bgMask_{{spAbr}}, bgSample_{{spAbr}}))
##Add extracted values to background points table
bgEnvsVals_{{spAbr}} <- cbind(scientific_name = paste0("bg_", "{{spName}}"), bgSample_{{spAbr}},
occID = NA, year = NA, institution_code = NA, country = NA,
state_province = NA, locality = NA, elevation = NA,
record_type = NA, bgEnvsVals_{{spAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/penvs_drawBgExtent.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# penvs_userBgExtent.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
penvs_userBgExtent_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
span("Step 1:", class = "step"),
span("Choose Background Extent", class = "stepText"), br(), br(),
fileInput(ns("userBgShp"),
label = paste0('Upload polygon in shapefile (.shp, .shx, .dbf) ',
'or CSV file with field order (longitude, latitude)'),
accept = c(".csv", ".dbf", ".shx", ".shp"), multiple = TRUE),
tags$div(title = paste0('Buffer area in degrees (1 degree = ~111 km). Exact',
' length varies based on latitudinal position.'),
numericInput(ns("userBgBuf"),
label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5)),
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch1"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goUserBg"), "Load"),
tags$hr(class = "hrDotted"),
span("Step 2:", class = "step"),
span("Sample Background Points", class = "stepText"), br(), br(),
strong(paste0('Mask predictor rasters by background extent and sample',
' background points')), br(), br(),
numericInput(ns("bgPtsNum"), label = "No. of background points",
value = 10000, min = 1, step = 1), # Check default (value = 10000)
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch2"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goBgMask"), "Sample"),
tags$hr(class = "hrDashed"),
actionButton(ns("goReset_penvs"), "Reset", class = 'butReset'),
strong(" background")
)
}
penvs_userBgExtent_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
allSp <- common$allSp
curSp <- common$curSp
envs.global <- common$envs.global
envs <- common$envs
bgExt <- common$bgExt
occs <- common$occs
observeEvent(input$goUserBg, {
# ERRORS ####
if (is.null(input$userBgShp)) {
logger %>%
writeLog(type = 'error',
'Background extent files not uploaded.')
return()
}
# loop over all species if batch is on
if (input$batch1 == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for (sp in spLoop) {
# ERRORS ####
if (is.null(spp[[sp]]$envs)) {
logger %>% writeLog(
type = 'error',
hlSpp(sp),
'Environmental variables missing. Obtain them in component 3.')
return()
}
# FUNCTION CALL ####
userBgExt <- penvs_userBgExtent(input$userBgShp$datapath,
input$userBgShp$name,
input$userBgBuf,
spp[[sp]]$occs,
logger,
spN = sp)
# LOAD INTO SPP ####
spp[[sp]]$procEnvs$bgExt <- userBgExt
# METADATA ####
##Record buffer size
spp[[sp]]$rmm$code$wallace$bgBuf <- input$userBgBuf
##Record name of user provided background extent
spp[[sp]]$rmm$data$occurrence$backgroundSampleSizeRule <- input$userBgShp$name
# get extensions of all input files
spp[[sp]]$rmm$rmm$code$wallace$userBgName <-input$userBgShp$name
paste0('User Polygon, ', input$bgBuf, ' degree buffer')
exts <- sapply(strsplit(input$userBgShp$name, '\\.'),
FUN = function(x) x[2])
if ('csv' %in% exts) {
spp[[sp]]$rmm$code$wallace$userBgExt <- 'csv'
spp[[sp]]$rmm$code$wallace$userBgPath <- input$userBgShp$datapath
}
else if ('shp' %in% exts) {
spp[[sp]]$rmm$code$wallace$userBgExt <- 'shp'
spp[[sp]]$rmm$code$wallace$userBgPath <- input$userBgShp$datapath
# get index of .shp
i <- which(exts == 'shp')
shpName <- strsplit(input$userBgShp$name[i], '\\.')[[1]][1]
spp[[sp]]$rmm$code$wallace$userBgShpParams <-
list(dsn = input$userBgShp$datapath[i], layer = shpName)
}
}
})
observeEvent(input$goBgMask, {
# WARNING ####
if (input$bgPtsNum < 1) {
logger %>% writeLog(type = 'warning',
"Enter a non-zero number of background points.")
return()
}
req(bgExt())
# loop over all species if batch is on
if (input$batch2 == TRUE) spLoop <- allSp() else spLoop <- curSp()
# PROCESSING ####
for (sp in spLoop) {
# FUNCTION CALL ####
bgMask <- penvs_bgMask(spp[[sp]]$occs,
envs.global[[spp[[sp]]$envs]],
spp[[sp]]$procEnvs$bgExt,
logger,
spN = sp)
req(bgMask)
bgNonNA <- raster::ncell(bgMask) - raster::freq(bgMask, value = NA)[[1]]
if ((bgNonNA + 1) < input$bgPtsNum) {
logger %>%
writeLog(
type = "error", hlSpp(sp),
"Number of requested background points (n = ", input$bgPtsNum, ") is ",
"higher than the maximum points available on the background extent ",
"(n = ", bgNonNA, "). Please reduce the number of requested points.")
return()
}
bgPts <- penvs_bgSample(spp[[sp]]$occs,
bgMask,
input$bgPtsNum,
logger,
spN = sp)
req(bgPts)
withProgress(message = paste0("Extracting background values for ",
spName(sp), "..."), {
bgEnvsVals <- as.data.frame(raster::extract(bgMask, bgPts))
})
if (sum(rowSums(is.na(raster::extract(bgMask, spp[[sp]]$occs[ , c("longitude", "latitude")])))) > 0) {
logger %>%
writeLog(type = "error", hlSpp(sp),
"One or more occurrence points have NULL raster values.",
" This can sometimes happen for points on the margin of the study extent.",
" Please increase the buffer slightly to include them.")
return()
}
# LOAD INTO SPP ####
spp[[sp]]$procEnvs$bgMask <- bgMask
# add columns for env variables beginning with "envs_" to bg tbl
spp[[sp]]$bg <- cbind(scientific_name = paste0("bg_", sp), bgPts,
country = NA, state_province = NA, locality = NA,
year = NA, record_type = NA, catalog_number = NA,
institution_code = NA, elevation = NA,
uncertainty = NA, bgEnvsVals)
# sample background points
spp[[sp]]$bgPts <- bgPts
# METADATA ####
spp[[sp]]$rmm$data$occurrence$backgroundSampleSizeSet <- input$bgPtsNum
}
})
# reset background button functionality
observeEvent(input$goReset_penvs, {
req(curSp())
spp[[curSp()]]$procEnvs$bgExt <- NULL
spp[[curSp()]]$procEnvs$bgMask <- NULL
spp[[curSp()]]$bg <- NULL
spp[[curSp()]]$bgPts <- NULL
spp[[curSp()]]$rmm$data$occurrence$backgroundSampleSizeSet <- NULL
logger %>% writeLog(
hlSpp(curSp()), "Reset background extent and background points.")
})
return(list(
save = function() {
list(
userBgBuf = input$userBgBuf,
bgPtsNum = input$bgPtsNum
)
},
load = function(state) {
# Load
updateNumericInput(session, "userBgBuf", value = state$userBgBuf)
updateNumericInput(session, "bgPtsNum", value = state$bgPtsNum)
}
))
common$update_component(tab = "Map")
}
penvs_userBgExtent_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
occs <- common$occs
if (is.null(spp[[curSp()]]$procEnvs$bgExt)) {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
} else {
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop)
polys <- spp[[curSp()]]$procEnvs$bgExt@polygons[[1]]@Polygons
if (length(polys) == 1) {
xy <- list(polys[[1]]@coords)
} else {
xy <- lapply(polys, function(x) x@coords)
}
for (shp in xy) {
map %>%
addPolygons(lng = shp[, 1], lat = shp[, 2], weight = 4, color = "gray",
group = 'bgShp')
}
bb <- spp[[curSp()]]$procEnvs$bgExt@bbox
map %>% fitBounds(bb[1], bb[2], bb[3], bb[4])
}
}
penvs_userBgExtent_module_rmd <- function(species) {
list(
# Variables used in the module's Rmd code
penvs_userBgExtent_knit = !is.null(species$rmm$code$wallace$userBgExt),
bgShp_name_rmd = species$rmm$code$wallace$userBgShpParams[["layer"]],
userBgBuf_rmd = species$rmm$code$wallace$bgBuf,
bgPtsNum_rmd = species$rmm$data$occurrence$backgroundSampleSizeSet
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/penvs_userBgExtent.R
|
```{asis, echo = {{penvs_userBgExtent_knit}}, eval = {{penvs_userBgExtent_knit}}, include = {{penvs_userBgExtent_knit}}}
### Process environmental data
Sampling of {{bgPtsNum_rmd}} background points and corresponding environmental data using a user provided background extent with a {{userBgBuf_rmd}} degree buffer.
```
```{r, echo = {{penvs_userBgExtent_knit}}, include = {{penvs_userBgExtent_knit}}}
# Load the user provided shapefile or csv file with the desired extent.
##User must input the path to shapefile or csv file and the file name
# Define path
bgPath_{{spAbr}} <- ""
bgExt_{{spAbr}} <- penvs_userBgExtent(
bgShp_path = paste0(bgPath_{{spAbr}}, "{{bgShp_name_rmd}}", ".shp"),
bgShp_name = paste0("{{bgShp_name_rmd}}", c(".shp", ".shx", ".dbf")),
userBgBuf = {{userBgBuf_rmd}},
occs = occs_{{spAbr}})
# Mask environmental data to provided extent
bgMask_{{spAbr}} <- penvs_bgMask(
occs = occs_{{spAbr}},
envs = envs_{{spAbr}},
bgExt = bgExt_{{spAbr}})
# Sample background points from the provided area
bgSample_{{spAbr}} <- penvs_bgSample(
occs = occs_{{spAbr}},
bgMask = bgMask_{{spAbr}},
bgPtsNum = {{bgPtsNum_rmd}})
# Extract values of environmental layers for each background point
bgEnvsVals_{{spAbr}} <- as.data.frame(raster::extract(bgMask_{{spAbr}}, bgSample_{{spAbr}}))
##Add extracted values to background points table
bgEnvsVals_{{spAbr}} <- cbind(scientific_name = paste0("bg_", "{{spName}}"), bgSample_{{spAbr}},
occID = NA, year = NA, institution_code = NA, country = NA,
state_province = NA, locality = NA, elevation = NA,
record_type = NA, bgEnvsVals_{{spAbr}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/penvs_userBgExtent.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# poccs_removeByID.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
poccs_removeByID_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
numericInput(ns("removeID"), label = "Enter the record ID to be removed",
value = 0),
actionButton(ns("goRemoveByID"), "Remove Occurrence"),
tags$hr(class = "hrDashed"),
actionButton(ns("goResetOccs"), "Reset", class = 'butReset'),
strong(" to original occurrence")
)
}
poccs_removeByID_module_server <- function(input, output, session, common) {
logger <- common$logger
occs <- common$occs
spp <- common$spp
curSp <- common$curSp
observeEvent(input$goRemoveByID, {
# FUNCTION CALL ####
occs.rem <- poccs_removeByID(occs(),
input$removeID,
logger,
spN = curSp())
req(occs.rem)
# LOAD INTO SPP ####
spp[[curSp()]]$occs <- occs.rem
# REFERENCES ####
knitcitations::citep(citation("leaflet.extras"))
# METADATA ####
# if no removeIDs are recorded yet, make a list to record them
# if at least one exists, add to the list
if (is.null(spp[[curSp()]]$rmm$code$wallace$removedIDs)) {
spp[[curSp()]]$rmm$code$wallace$removedIDs <- input$removeID
} else {
spp[[curSp()]]$rmm$code$wallace$removedIDs <-
c(spp[[curSp()]]$rmm$code$wallace$removedIDs, input$removeID)
}
common$update_component(tab = "Map")
})
# reset occurrences button functionality
observeEvent(input$goResetOccs, {
req(curSp())
spp[[curSp()]]$occs <- spp[[curSp()]]$occData$occsCleaned
spp[[curSp()]]$rmm$code$wallace$occsSelPolyCoords <- NULL
spp[[curSp()]]$procOccs$occsThin <- NULL
spp[[curSp()]]$rmm$code$wallace$removedIDs <- NULL
logger %>% writeLog(
hlSpp(curSp()), "Reset to original occurrences (n = ",
nrow(spp[[curSp()]]$occs), ").")
})
return(list(
save = function() {
list(
removeID = input$removeID
)
},
load = function(state) {
updateNumericInput(session, "removeID", value = state$removeID)
}
))
}
poccs_removeByID_module_map <- function(map, common) {
occs <- common$occs
# Map logic
map %>% leaflet.extras::removeDrawToolbar() %>%
clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
zoom2Occs(occs())
}
poccs_removeByID_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
poccs_removeByID_knit = !is.null(species$rmm$code$wallace$removedIDs),
removeByID_id_rmd = printVecAsis(species$rmm$code$wallace$removedIDs)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/poccs_removeByID.R
|
```{asis, echo = {{poccs_removeByID_knit}}, eval = {{poccs_removeByID_knit}}, include = {{poccs_removeByID_knit}}}
### Process Occurrence Data
Remove the occurrence localities by ID.
```
```{r, echo = {{poccs_removeByID_knit}}, include = {{poccs_removeByID_knit}}}
# remove the rows that match the occIDs selected
occs_{{spAbr}} <- poccs_removeByID(
occs = occs_{{spAbr}} ,
removeID = {{removeByID_id_rmd}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/poccs_removeByID.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# poccs_selectOccs.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
poccs_selectOccs_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
strong("Select occurrences intersecting drawn polygon"), br(),
"(", HTML("<font color='blue'><b>NOTE</b></font>"),
': to begin drawing, click hexagon icon on map toolbar,
and when complete, press "Finish" and then the "Select Occurrences" button)', br(), br(),
actionButton(ns("goSelectOccs"), "Select Occurrences"),
tags$hr(class = "hrDashed"),
actionButton(ns("goResetOccs"), "Reset", class = 'butReset'),
strong(" to original occurrence")
)
}
poccs_selectOccs_module_server <- function(input, output, session, common) {
logger <- common$logger
occs <- common$occs
spp <- common$spp
curSp <- common$curSp
observeEvent(input$goSelectOccs, {
occs.sel <- poccs_selectOccs(occs(),
spp[[curSp()]]$polySelXY,
spp[[curSp()]]$polySelID,
logger,
spN = curSp())
req(occs.sel)
# LOAD INTO SPP ####
spp[[curSp()]]$occs <- occs.sel
# REFERENCES ####
knitcitations::citep(citation("leaflet.extras"))
# METADATA ####
polyX <- printVecAsis(round(spp[[curSp()]]$polySelXY[,1], digits = 4))
polyY <- printVecAsis(round(spp[[curSp()]]$polySelXY[,2], digits = 4))
spp[[curSp()]]$rmm$code$wallace$occsSelPolyCoords <- paste0('X: ', polyX, ', Y: ', polyY)
common$update_component(tab = "Map")
})
# reset occurrences button functionality
observeEvent(input$goResetOccs, {
req(curSp())
spp[[curSp()]]$occs <- spp[[curSp()]]$occData$occsCleaned
spp[[curSp()]]$rmm$code$wallace$occsSelPolyCoords <- NULL
spp[[curSp()]]$procOccs$occsThin <- NULL
spp[[curSp()]]$rmm$code$wallace$removedIDs <- NULL
logger %>% writeLog(
hlSpp(curSp()), "Reset to original occurrences (n = ",
nrow(spp[[curSp()]]$occs), ").")
})
}
poccs_selectOccs_module_map <- function(map, common) {
occs <- common$occs
# Map logic
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
zoom2Occs(occs()) %>%
leaflet.extras::addDrawToolbar(targetGroup='draw', polylineOptions = FALSE,
rectangleOptions = FALSE, circleOptions = FALSE,
markerOptions = FALSE, circleMarkerOptions = FALSE,
editOptions = leaflet.extras::editToolbarOptions())
}
poccs_selectOccs_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
poccs_selectByID_knit = !is.null(species$rmm$code$wallace$occsSelPolyCoords),
selectByID_xy_rmd = printVecAsis(species$polySelXY),
selectByID_id_rmd = species$polySelID
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/poccs_selectOccs.R
|
```{asis, echo = {{poccs_selectByID_knit}}, eval = {{poccs_selectByID_knit}}, include = {{poccs_selectByID_knit}}}
### Process Occurrence Data
Remove occurrences outside of user drawn polygon
```
```{r, echo = {{poccs_selectByID_knit}}, include = {{poccs_selectByID_knit}}}
occs_{{spAbr}} <- poccs_selectOccs(
occs = occs_{{spAbr}},
polySelXY = matrix({{selectByID_xy_rmd}}, ncol = 2, byrow = FALSE),
polySelID = {{selectByID_id_rmd}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/poccs_selectOccs.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# poccs_thinOccs.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
poccs_thinOccs_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
tags$p(
paste0('The minimum distance between occurrence locations (nearest ',
'neighbor distance) in km for resulting thinned dataset. Ideally ',
'based on species biology (e.g., home-range size).')
),
numericInput(ns("thinDist"), label = "Thinning distance (km)",
value = 0), # Check default (value = 0)
tags$div(
title = "Apply selection to ALL species loaded",
checkboxInput(ns("batch"), label = strong("Batch"), value = FALSE) # Check default (value = FALSE)
),
actionButton(ns("goThinOccs"), "Thin Occurrences"),
tags$hr(class = "hrDashed"),
actionButton(ns("goResetOccs"), "Reset", class = 'butReset'),
strong(" to original occurrence")
)
}
poccs_thinOccs_module_server <- function(input, output, session, common) {
logger <- common$logger
spp <- common$spp
curSp <- common$curSp
allSp <- common$allSp
observeEvent(input$goThinOccs, {
# loop over all species if batch is on
if (input$batch == TRUE) spLoop <- allSp() else spLoop <- curSp()
for (sp in spLoop) {
# FUNCTION CALL ####
occs.thin <- poccs_thinOccs(spp[[sp]]$occs,
input$thinDist,
logger,
spN = sp)
req(occs.thin)
# LOAD INTO SPP ####
# record present occs before thinning (this may be different from occData$occOrig)
spp[[sp]]$procOccs$occsPreThin <- spp[[sp]]$occs
spp[[sp]]$occs <- occs.thin
spp[[sp]]$procOccs$occsThin <- occs.thin
# REFERENCES ####
knitcitations::citep(citation("spThin"))
# METADATA ####
# perhaps there should be a thinDist metadata field?
spp[[sp]]$rmm$code$wallace$thinDistKm <- input$thinDist
}
common$update_component(tab = "Map")
})
# reset occurrences button functionality
observeEvent(input$goResetOccs, {
req(curSp())
spp[[curSp()]]$occs <- spp[[curSp()]]$occData$occsCleaned
spp[[curSp()]]$rmm$code$wallace$occsSelPolyCoords <- NULL
spp[[curSp()]]$procOccs$occsThin <- NULL
spp[[curSp()]]$rmm$code$wallace$removedIDs <- NULL
logger %>% writeLog(
hlSpp(curSp()), "Reset to original occurrences (n = ",
nrow(spp[[curSp()]]$occs), ").")
})
return(list(
save = function() {
list(thinDist = input$thinDist)
},
load = function(state) {
updateNumericInput(session, "thinDist", value = state$thinDist)
}
))
}
poccs_thinOccs_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
occs <- common$occs
# Map logic
# if you've thinned already, map thinned points blue
# and kept points red
if (!is.null(spp[[curSp()]]$procOccs$occsThin)) {
occs.preThin <- spp[[curSp()]]$procOccs$occsPreThin
map %>% clearAll() %>%
addCircleMarkers(data = occs.preThin, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "blue",
fillOpacity = 1, weight = 2, popup = ~pop) %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 1, weight = 2, popup = ~pop) %>%
zoom2Occs(occs()) %>%
addLegend("bottomright", colors = c('red', 'blue'), title = "Occ Records",
labels = c('retained', 'removed'), opacity = 1)
} else {
# if you haven't thinned, map all points red
map %>% clearAll() %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
zoom2Occs(occs()) %>%
leaflet.extras::removeDrawToolbar(clearFeatures = TRUE)
}
}
poccs_thinOccs_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
poccs_thinOccs_knit = !is.null(species$rmm$code$wallace$thinDistKm),
thinDist_rmd = species$rmm$code$wallace$thinDistKm
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/poccs_thinOccs.R
|
```{asis, echo = {{poccs_thinOccs_knit}}, eval = {{poccs_thinOccs_knit}}, include = {{poccs_thinOccs_knit}}}
### Process Occurrence Data
Thinning the occurrences to `r "{{thinDist_rmd}}"` km
```
```{r, echo = {{poccs_thinOccs_knit}}, include = {{poccs_thinOccs_knit}}}
# Thin occurrences
occs_{{spAbr}} <- poccs_thinOccs(
occs = occs_{{spAbr}},
thinDist = {{thinDist_rmd}})
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/poccs_thinOccs.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# rep_markdown.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
rep_markdown_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
# UI
strong("Select download file type"),
selectInput('rmdFileType', label = "",
choices = list("Rmd", "PDF", "HTML", "Word")),
downloadButton('dlRMD', 'Download Session Code')
)
}
rep_markdown_module_server <- function(input, output, session, common) {}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/rep_markdown.R
|
---
title: "sessionCode"
output: html_document
---
Here, the user can download documented code that corresponds to the analyses run in the current session of *Wallace* in multiple formats (.Rmd [R Markdown], .pdf, .html, or .doc). The .Rmd format is an executable R script file that will reproduce the analysis when run in an R session, and is composed of plain text and R code "chunks". Extended functionality for R Markdown files exists in RStudio. Simply open the .Rmd in RStudio, click on "Run" in the upper-right corner, and run chunk by chunk or all at once. To learn more details, check out the RStudio [tutorial](http://rmarkdown.rstudio.com/lesson-1.html).
The *Wallace* session code .Rmd file is composed of a chain of module functions that are internal to *Wallace*. Each of these functions corresponds to a single module that the user ran during the session. To see the internal code for these module functions, click on the links in the .Rmd file. Users are encouraged to write custom code in the .Rmd directly to modify their analysis, and even modify the module function code to further customize.
#### Notes
To generate a PDF of your session code, it is essential you have a working version of TeX installed. For Mac OS, download MacTeX [here](http://www.tug.org/mactex/). For Windows, please perform the following steps:
1. Download and Install MiKTeX [here](http://miktex.org/2.9/setup/).
2. Run `Sys.getenv("PATH")` in RStudio. This command returns the path where RStudio is trying to find pdflatex.exe. In Windows (64-bit), it should return `C:\Program Files\MiKTeX 2.9\miktex\bin\x64\pdflatex.exe`. If pdflatex.exe is not located in this location, RStudio gives the error code "41".
3. To set the path variable, run the following in RStudio:
`d <- "C:/Program Files/MiKTeX 2.9/miktex/bin/x64/"`
`Sys.setenv(PATH=paste(Sys.getenv("PATH"), d, sep=";"))`
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/rep_markdown.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# rep_refPackages.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
rep_refPackages_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
# UI
strong("Download List of References"), br(), br(),
strong("Select download file type"),
selectInput('refFileType', label = "",
choices = list("PDF", "HTML", "Word")),
downloadButton('dlrefPackages', 'Download References')
)
}
rep_refPackages_module_server <- function(input, output, session, common) {}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/rep_refPackages.R
|
---
title: "refPackages"
output: html_document
---
Add text here
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/rep_refPackages.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# rep_rmms.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
rep_rmms_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
# UI
strong("Download metadata CSV file"), br(), br(),
downloadButton('dlRMM', 'Download Metadata')
)
}
rep_rmms_module_server <- function(input, output, session, common) {}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/rep_rmms.R
|
---
title: "rangeModelMetadata"
output: html_document
---
Add text here
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/rep_rmms.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# vis_bioclimPlot.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
vis_bioclimPlot_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
"Pick a bioclimatic variable number for each axis",
numericInput(ns("bc1"), "Axis 1", value = 1, min = 1, max = 19),
numericInput(ns("bc2"), "Axis 2", value = 2, min = 1, max = 19),
numericInput(ns("bcProb"), "Set threshold", value = 0.9, min = 0.75,
max = 1, step = 0.05)
)
}
vis_bioclimPlot_module_server <- function(input, output, session, common) {
spp <- common$spp
curSp <- common$curSp
curModel <- common$curModel
evalOut <- common$evalOut
observe({
req(curSp())
if (length(curSp()) == 1) {
req(evalOut())
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$bcPlotSettings <-
list(bc1 = input$bc1, bc2 = input$bc2, p = input$bcProb)
}
}
})
output$bioclimPlot <- renderPlot({
req(curSp(), evalOut())
if (spp[[curSp()]]$rmm$model$algorithms != "BIOCLIM") {
graphics::par(mar = c(0,0,0,0))
plot(c(0, 1), c(0, 1), ann = FALSE, bty = 'n', type = 'n', xaxt = 'n', yaxt = 'n')
graphics::text(x = 0.25, y = 1, "Bioclim plots module requires a Bioclim model",
cex = 1.2, col = "#641E16")
} else if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
# FUNCTION CALL ####
vis_bioclimPlot(evalOut()@models[[curModel()]],
input$bc1,
input$bc2,
input$bcProb)
}
}, width = 700, height = 700)
return(list(
save = function() {
list(
bc1 = input$bc1,
bc2 = input$bc2,
bcProb = input$bcProb
)
},
load = function(state) {
updateNumericInput(session, "bc1", value = state$bc1)
updateNumericInput(session, "bc2", value = state$bc2)
updateNumericInput(session, "bcProb", value = state$bcProb)
}
))
}
vis_bioclimPlot_module_result <- function(id) {
ns <- NS(id)
# Result UI
imageOutput(ns('bioclimPlot'))
}
vis_bioclimPlot_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
vis_bioclimPlot_knit = !is.null(species$rmm$code$wallace$bcPlotSettings),
a_rmd = unlist(species$rmm$code$wallace$bcPlotSettings)[1],
b_rmd = unlist(species$rmm$code$wallace$bcPlotSettings)[2],
p_rmd = unlist(species$rmm$code$wallace$bcPlotSettings)[3]
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_bioclimPlot.R
|
```{asis, echo = {{vis_bioclimPlot_knit}}, eval = {{vis_bioclimPlot_knit}}, include = {{vis_bioclimPlot_knit}}}
### Visualize
Visualize bivariate plot of bioclim model for environmental layers `r {{a_rmd}}` & ,
`r {{b_rmd}}` and a percentile distribution of `r {{p_rmd}}`
```
```{r, echo = {{vis_bioclimPlot_knit}}, include = {{vis_bioclimPlot_knit}}}
# Generate a bioclim plot
vis_bioclimPlot_{{spAbr}} <- vis_bioclimPlot(
x = model_{{spAbr}}@models$bioclim,
a = {{a_rmd}},
b = {{b_rmd}},
p = {{p_rmd}})
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_bioclimPlot.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# vis_mapPreds.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
vis_mapPreds_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
tags$div(
title = paste0('Create binary map of predicted presence/absence assuming',
' all values above threshold value represent presence.',
' Also can be interpreted as a "potential distribution"',
'(see guidance).'),
selectInput(ns('threshold'), label = "Set threshold",
choices = list("No threshold" = 'none',
"Minimum Training Presence" = 'mtp',
"10 Percentile Training Presence" = 'p10',
"Quantile of Training Presences" = 'qtp'))),
conditionalPanel(
sprintf("input['%s'] == 'qtp'", ns("threshold")),
sliderInput(ns("trainPresQuantile"), "Set quantile",
min = 0, max = 1, value = .05)
),
conditionalPanel(paste0("input['", ns("threshold"), "'] == 'none'"),
uiOutput(ns("maxentPredType"))),
actionButton(ns("goMapPreds"), "Plot")
)
}
vis_mapPreds_module_server <- function(input, output, session, common) {
spp <- common$spp
evalOut <- common$evalOut
curSp <- common$curSp
allSp <- common$allSp
curModel <- common$curModel
bgMask <- common$bgMask
occs <- common$occs
logger <- common$logger
bgShpXY <- common$bgShpXY
output$maxentPredType <- renderUI({
ns <- session$ns
req(curSp(), evalOut())
if (spp[[curSp()]]$rmm$model$algorithms != "BIOCLIM") {
tags$div(
title = 'Please see guidance for an explanation of different Maxent output types.',
radioButtons(ns('maxentPredType'), label = "Prediction output",
choices = list("cloglog", "logistic", "raw"),
inline = TRUE))
}
})
observeEvent(input$goMapPreds, {
# ERRORS ####
if(is.null(evalOut())) {
logger %>% writeLog(
type = 'error',
"Models must be run before visualizing model predictions.")
return()
}
if(is.na(input$threshold)) {
logger %>% writeLog(
type = 'error', "Please select a thresholding rule.")
return()
}
# pick the prediction that matches the model selected
predSel <- evalOut()@predictions[[curModel()]]
raster::crs(predSel) <- raster::crs(bgMask())
if(is.na(raster::crs(predSel))) {
logger %>% writeLog(
type = "error",
paste0("Model prediction raster has undefined coordinate reference ",
"system (CRS), and thus cannot be mapped. This is likely due to",
" undefined CRS for input rasters. Please see guidance text for",
" module 'User-specified Environmental Data' in component",
" 'Obtain Environmental Data' for more details."))
return()
}
# PROCESSING ####
# define predType based on model type
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
predType <- "BIOCLIM"
m <- evalOut()@models[[curModel()]]
predSel <- dismo::predict(m, bgMask(), useC = FALSE)
# define crs
raster::crs(predSel) <- raster::crs(bgMask())
# define predSel name
names(predSel) <- curModel()
} else if (spp[[curSp()]]$rmm$model$algorithms %in% c("maxent.jar", "maxnet")) {
if (is.null(input$maxentPredType)) {
predType <- "cloglog"
} else {
predType <- input$maxentPredType
}
# if selected prediction type is not raw, transform
# transform and redefine predSel
smartProgress(
logger,
message = paste0("Generating ", input$maxentPredType,
" prediction for model ", curModel(), "..."), {
m <- evalOut()@models[[curModel()]]
clamping <- spp[[curSp()]]$rmm$model$algorithm$maxent$clamping
if (spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
if (predType == "raw") predType <- "exponential"
predSel <- predictMaxnet(m, bgMask(),
type = predType,
clamp = FALSE)
} else if (spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
outputFormat <- paste0("outputformat=", predType)
if (clamping == TRUE) {
doClamp <- "doclamp=true"
} else {
doClamp <- "doclamp=false"
}
predSel <- dismo::predict(m, bgMask(),
args = c(outputFormat, doClamp),
na.rm = TRUE)
}
})
# define crs
raster::crs(predSel) <- raster::crs(bgMask())
# define predSel name
names(predSel) <- curModel()
}
# generate binary prediction based on selected thresholding rule
# (same for all Maxent prediction types because they scale the same)
# find predicted values for occurrences for selected model
# extract the suitability values for all occurrences
occs.xy <- occs()[c('longitude', 'latitude')]
# determine the threshold based on the current, not projected, prediction
occPredVals <- raster::extract(predSel, occs.xy)
# get all thresholds
# get the chosen threshold value
if (input$threshold != 'none') {
if (input$threshold == 'mtp') {
thr.sel <- stats::quantile(occPredVals, probs = 0)
} else if (input$threshold == 'p10') {
thr.sel <- stats::quantile(occPredVals, probs = 0.1)
} else if (input$threshold == 'qtp'){
thr.sel <- stats::quantile(occPredVals, probs = input$trainPresQuantile)
}
predSel.thr <- predSel > thr.sel
# rename prediction raster if thresholded
names(predSel.thr) <- paste0(curModel(), '_', predType)
nameAlg <- ifelse(spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM",
"",
paste0(" ", spp[[curSp()]]$rmm$model$algorithms, " "))
logger %>% writeLog(hlSpp(curSp()),
input$threshold, ' threshold selected for ', nameAlg, predType,
' (', formatC(thr.sel, format = "e", 2), ').')
} else {
predSel.thr <- predSel
}
# write to log box
if (predType == 'BIOCLIM') {
logger %>% writeLog(
hlSpp(curSp()), "BIOCLIM model prediction plotted.")
} else if (input$threshold != 'none'){
logger %>% writeLog(
hlSpp(curSp()), spp[[curSp()]]$rmm$model$algorithms,
" model prediction plotted.")
} else if (input$threshold == 'none'){
logger %>% writeLog(
hlSpp(curSp()), spp[[curSp()]]$rmm$model$algorithms, " ",
predType, " model prediction plotted.")
}
# LOAD INTO SPP ####
spp[[curSp()]]$visualization$occPredVals <- occPredVals
if (input$threshold != 'none') {
spp[[curSp()]]$visualization$thresholds <- thr.sel # were you recording multiple before?
}
spp[[curSp()]]$visualization$mapPred <- predSel.thr
spp[[curSp()]]$visualization$mapPredVals <- getRasterVals(predSel.thr, predType)
# METADATA ####
spp[[curSp()]]$rmd$vis_curModel <- curModel()
spp[[curSp()]]$rmm$prediction$Type <- predType
spp[[curSp()]]$rmm$prediction$binary$thresholdRule <- input$threshold
if (input$threshold != 'none') {
spp[[curSp()]]$rmm$prediction$binary$thresholdSet <- thr.sel
if (input$threshold == 'qtp') {
spp[[curSp()]]$rmm$code$wallace$trainPresQuantile <- input$trainPresQuantile
} else {
spp[[curSp()]]$rmm$code$wallace$trainPresQuantile <- 0
}
} else {
spp[[curSp()]]$rmm$prediction$binary$thresholdSet <- NULL
spp[[curSp()]]$rmm$prediction$continuous$minVal <- min(occPredVals)
spp[[curSp()]]$rmm$prediction$continuous$maxVal <- max(occPredVals)
}
spp[[curSp()]]$rmm$prediction$notes <- predType
# REFERENCES
knitcitations::citep(citation("dismo"))
common$update_component(tab = "Map")
})
return(list(
save = function() {
list(
threshold = input$threshold,
trainPresQuantile = input$trainPresQuantile
)
},
load = function(state) {
updateSelectInput(session, "threshold", selected = state$threshold)
updateSliderInput(session, 'trainPresQuantile', value = state$trainPresQuantile)
}
))
}
vis_mapPreds_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
mapPred <- common$mapPred
rmm <- common$rmm
occs <- common$occs
bgShpXY <- common$bgShpXY
# Map logic
req(mapPred())
mapPredVals <- spp[[curSp()]]$visualization$mapPredVals
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if threshold specified
if (rmm()$prediction$binary$thresholdRule != 'none') {
rasPal <- c('gray', 'blue')
map %>% clearAll() %>%
addLegend("bottomright", colors = c('gray', 'blue'),
title = "Thresholded Suitability<br>(Training)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = "train")
} else {
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols), mapPredVals, na.color = 'transparent')
rasPal <- colorNumeric(rasCols, mapPredVals, na.color = 'transparent')
map %>% clearAll() %>%
addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Training)",
values = mapPredVals, layerId = "train",
labFormat = reverseLabel(2, reverse_order = TRUE))
}
# function to map all background polygons
mapBgPolys <- function(map, bgShpXY) {
for (shp in bgShpXY) {
map %>%
addPolygons(lng = shp[,1], lat = shp[,2], fill = FALSE,
weight = 4, color = "blue", group = 'proj')
}
}
# map model prediction raster
map %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = 'red',
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
addRasterImage(mapPred(), colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
# add background polygon(s)
mapBgPolys(bgShpXY())
}
vis_mapPreds_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
vis_mapPreds_knit = !is.null(species$visualization$mapPred),
vis_map_threshold_knit = !is.null(species$rmm$prediction$binary$thresholdSet),
vis_map_maxnet_knit = if(!is.null(species$rmm$model$algorithms)){
species$rmm$model$algorithms == "maxnet"} else {FALSE},
vis_map_maxent_knit = if(!is.null(species$rmm$model$algorithms)){
species$rmm$model$algorithms == "maxent.jar"} else {FALSE},
vis_map_bioclim_knit = if(!is.null(species$rmm$model$algorithms)){
species$rmm$model$algorithms == "BIOCLIM"} else {FALSE},
alg_rmd = if(!is.null(species$rmm$model$algorithms)){species$rmm$model$algorithms} else {NULL},
curModel_rmd = if(!is.null(species$rmd$vis_curModel)){species$rmd$vis_curModel} else {NULL},
clamp_rmd = species$rmm$model$algorithm$maxent$clamping,
predType_rmd = species$rmm$prediction$Type,
threshold_rmd = if (!is.null(species$rmm$prediction$binary$thresholdSet)) {
species$rmm$prediction$binary$thresholdSet} else {0},
thresholdRule_rmd = species$rmm$prediction$binary$thresholdRule,
probQuantile_rmd = species$rmm$code$wallace$trainPresQuantile
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_mapPreds.R
|
```{asis, echo = {{vis_mapPreds_knit & vis_map_bioclim_knit & !vis_map_threshold_knit}}, eval = {{vis_mapPreds_knit & vis_map_bioclim_knit & !vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_bioclim_knit & !vis_map_threshold_knit}}}
### Visualize
Generate a map of the Bioclim generated model with no threshold
```
```{r, echo = {{vis_mapPreds_knit & vis_map_bioclim_knit & !vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_bioclim_knit & !vis_map_threshold_knit}}}
# Select current model and obtain raster prediction
m_{{spAbr}} <- model_{{spAbr}}@models[["{{curModel_rmd}}"]]
predSel_{{spAbr}} <- dismo::predict(m_{{spAbr}}, bgMask_{{spAbr}}, useC = FALSE)
#Get values of prediction
mapPredVals_{{spAbr}} <- getRasterVals(predSel_{{spAbr}}, "{{predType_rmd}}")
#Define colors and legend
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
legendPal <- colorNumeric(rev(rasCols), mapPredVals_{{spAbr}}, na.color = 'transparent')
rasPal <- colorNumeric(rasCols, mapPredVals_{{spAbr}}, na.color = 'transparent')
#Generate map
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Training)",
values = mapPredVals_{{spAbr}}, layerId = "train",
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
#add occurrence data
addCircleMarkers(data = occs_{{spAbr}}, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
##Add model prediction
addRasterImage(predSel_{{spAbr}}, colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
##add background polygons
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'proj')
```
```{asis, echo = {{vis_mapPreds_knit & vis_map_bioclim_knit & vis_map_threshold_knit}}, eval = {{vis_mapPreds_knit & vis_map_bioclim_knit & vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_bioclim_knit & vis_map_threshold_knit}}}
### Visualize
Generate a map of the Bioclim generated model with a "{{thresholdRule_rmd}}" threshold rule of {{threshold_rmd}}.
```
```{r, echo = {{vis_mapPreds_knit & vis_map_bioclim_knit & vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_bioclim_knit & vis_map_threshold_knit}}}
# Select current model and obtain raster prediction
m_{{spAbr}} <- model_{{spAbr}}@models[["{{curModel_rmd}}"]]
predSel_{{spAbr}} <- dismo::predict(m_{{spAbr}}, bgMask_{{spAbr}}, useC = FALSE)
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
thresProb_{{spAbr}} <- switch("{{thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{probQuantile_rmd}})
# Define threshold value
thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}},
probs = thresProb_{{spAbr}})
# Applied selected threshold
predSel_{{spAbr}} <- predSel_{{spAbr}} > thres_{{spAbr}}
# Get values of prediction
mapPredVals_{{spAbr}} <- getRasterVals(predSel_{{spAbr}}, "{{predType_rmd}}")
# Define colors and legend
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
legendPal <- colorNumeric(rev(rasCols), mapPredVals_{{spAbr}}, na.color = 'transparent')
rasPal <- c('gray', 'blue')
# Generate map
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
leaflet::addLegend("bottomright", colors = c('gray', 'blue'),
title = "Thresholded Suitability<br>(Training)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = "train") %>%
# add occurrence data
addCircleMarkers(data = occs_{{spAbr}}, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
## Add model prediction
addRasterImage(predSel_{{spAbr}}, colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
##add background polygons
addPolygons(data = bgExt_{{spAbr}},fill = FALSE,
weight = 4, color = "blue", group = 'proj')
```
```{asis, echo = {{vis_mapPreds_knit & vis_map_maxent_knit & !vis_map_threshold_knit}}, eval = {{vis_mapPreds_knit & vis_map_maxent_knit & !vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxent_knit & !vis_map_threshold_knit}}}
### Visualize
Generate a map of the Maxent generated model with no threshold
```
```{r, echo = {{vis_mapPreds_knit & vis_map_maxent_knit & !vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxent_knit & !vis_map_threshold_knit}}}
# Select current model and obtain raster prediction
m_{{spAbr}} <- model_{{spAbr}}@models[["{{curModel_rmd}}"]]
predSel_{{spAbr}} <- dismo::predict(
m_{{spAbr}}, bgMask_{{spAbr}},
args = c(paste0("outputformat=", "{{predType_rmd}}"),
paste0("doclamp=", tolower(as.character({{clamp_rmd}})))),
na.rm = TRUE)
#Get values of prediction
mapPredVals_{{spAbr}} <- getRasterVals(predSel_{{spAbr}}, "{{predType_rmd}}")
#Define colors and legend
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
legendPal <- colorNumeric(rev(rasCols), mapPredVals_{{spAbr}}, na.color = 'transparent')
rasPal <- colorNumeric(rasCols, mapPredVals_{{spAbr}}, na.color = 'transparent')
#Generate map
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Training)",
values = mapPredVals_{{spAbr}}, layerId = "train",
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
#add occurrence data
addCircleMarkers(data = occs_{{spAbr}}, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
##Add model prediction
addRasterImage(predSel_{{spAbr}}, colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
##add background polygons
addPolygons(data = bgExt_{{spAbr}},fill = FALSE,
weight = 4, color = "blue", group = 'proj')
```
```{asis, echo = {{vis_mapPreds_knit & vis_map_maxent_knit & vis_map_threshold_knit}}, eval = {{vis_mapPreds_knit & vis_map_maxent_knit & vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxent_knit & vis_map_threshold_knit}}}
### Visualize
Generate a map of the Maxent generated model with a "{{thresholdRule_rmd}}" threshold rule of {{threshold_rmd}}.
```
```{r, echo = {{vis_mapPreds_knit & vis_map_maxent_knit & vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxent_knit & vis_map_threshold_knit}}}
# Select current model and obtain raster prediction
m_{{spAbr}} <- model_{{spAbr}}@models[["{{curModel_rmd}}"]]
predSel_{{spAbr}} <- dismo::predict(
m_{{spAbr}}, bgMask_{{spAbr}},
args = c(paste0("outputformat=", "{{predType_rmd}}"),
paste0("doclamp=", tolower(as.character({{clamp_rmd}})))),
na.rm = TRUE)
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
thresProb_{{spAbr}} <- switch("{{thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{probQuantile_rmd}})
# Define threshold value
thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}}, probs = thresProb_{{spAbr}})
# Applied selected threshold
predSel_{{spAbr}} <- predSel_{{spAbr}} > thres_{{spAbr}}
#Get values of prediction
mapPredVals_{{spAbr}} <- getRasterVals(predSel_{{spAbr}}, "{{predType_rmd}}")
#Define colors and legend
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
legendPal <- colorNumeric(rev(rasCols), mapPredVals_{{spAbr}}, na.color = 'transparent')
rasPal <- c('gray', 'blue')
# Generate map
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
leaflet::addLegend("bottomright", colors = c('gray', 'blue'),
title = "Thresholded Suitability<br>(Training)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = "train") %>%
#add occurrence data
addCircleMarkers(data = occs_{{spAbr}}, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
##Add model prediction
addRasterImage(predSel_{{spAbr}}, colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
##add background polygons
addPolygons(data = bgExt_{{spAbr}},fill = FALSE,
weight = 4, color = "blue", group = 'proj')
```
```{asis, echo = {{vis_mapPreds_knit & vis_map_maxnet_knit & !vis_map_threshold_knit}}, eval = {{vis_mapPreds_knit & vis_map_maxnet_knit & !vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxnet_knit & !vis_map_threshold_knit}}}
### Visualize
Generate a map of the maxnet generated model with no threshold
```
```{r, echo = {{vis_mapPreds_knit & vis_map_maxnet_knit & !vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxnet_knit & !vis_map_threshold_knit}}}
# Select current model and obtain raster prediction
m_{{spAbr}} <- model_{{spAbr}}@models[["{{curModel_rmd}}"]]
predSel_{{spAbr}} <- predictMaxnet(m_{{spAbr}}, bgMask_{{spAbr}},
type = "{{predType_rmd}}",
clamp = {{clamp_rmd}})
#Get values of prediction
mapPredVals_{{spAbr}} <- getRasterVals(predSel_{{spAbr}}, "{{predType_rmd}}")
#Define colors and legend
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
legendPal <- colorNumeric(rev(rasCols), mapPredVals_{{spAbr}}, na.color = 'transparent')
rasPal <- colorNumeric(rasCols, mapPredVals_{{spAbr}}, na.color = 'transparent')
#Generate map
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Training)",
values = mapPredVals_{{spAbr}}, layerId = "train",
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
#add occurrence data
addCircleMarkers(data = occs_{{spAbr}}, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
##Add model prediction
addRasterImage(predSel_{{spAbr}}, colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
##add background polygons
addPolygons(data = bgExt_{{spAbr}},fill = FALSE,
weight = 4, color = "blue", group = 'proj')
```
```{asis, echo = {{vis_mapPreds_knit & vis_map_maxnet_knit & vis_map_threshold_knit}}, eval = {{vis_mapPreds_knit & vis_map_maxnet_knit & vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxnet_knit & vis_map_threshold_knit}}}
### Visualize
Generate a map of the maxnet generated model with with a "{{thresholdRule_rmd}}" threshold rule of {{threshold_rmd}}.
```
```{r, echo = {{vis_mapPreds_knit & vis_map_maxnet_knit & vis_map_threshold_knit}}, include = {{vis_mapPreds_knit & vis_map_maxnet_knit & vis_map_threshold_knit}}}
# Select current model and obtain raster prediction
m_{{spAbr}} <- model_{{spAbr}}@models[["{{curModel_rmd}}"]]
predSel_{{spAbr}} <- predictMaxnet(m_{{spAbr}}, bgMask_{{spAbr}},
type = "{{predType_rmd}}",
clamp = {{clamp_rmd}})
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
thresProb_{{spAbr}} <- switch("{{thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{probQuantile_rmd}})
# Define threshold value
thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}}, probs = thresProb_{{spAbr}})
# Applied selected threshold
predSel_{{spAbr}} <- predSel_{{spAbr}} > thres_{{spAbr}}
# Get values of prediction
mapPredVals_{{spAbr}} <- getRasterVals(predSel_{{spAbr}}, "{{predType_rmd}}")
# Define colors and legend
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
legendPal <- colorNumeric(rev(rasCols), mapPredVals_{{spAbr}}, na.color = 'transparent')
rasPal <- c('gray', 'blue')
# Generate map
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
leaflet::addLegend("bottomright", colors = c('gray', 'blue'),
title = "Thresholded Suitability<br>(Training)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = "train") %>%
#add occurrence data
addCircleMarkers(data = occs_{{spAbr}}, lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = "red",
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
##Add model prediction
addRasterImage(predSel_{{spAbr}}, colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
##add background polygons
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'proj')
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_mapPreds.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# vis_maxentEvalPlot.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
vis_maxentEvalPlot_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
selectInput(ns('maxentEvalSel'), label = "Select evaluation statistic",
choices = list("Select Stat..." = '',
"average AUC test" = 'auc.val',
"average AUC diff" = 'auc.diff',
"average OR mtp" = 'or.mtp',
"average OR 10%" = 'or.10p',
"delta AICc" = 'delta.AICc'),
selected = 'auc.val'),
h6("Maxent evaluation plots display automatically in 'Results' tab")
)
}
vis_maxentEvalPlot_module_server <- function(input, output, session, common) {
spp <- common$spp
curSp <- common$curSp
curModel <- common$curModel
evalOut <- common$evalOut
observe({
req(curSp())
if (length(curSp()) == 1) {
req(evalOut())
if (spp[[curSp()]]$rmm$model$algorithms == "maxent.jar" |
spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
# ERRORS ####
if (is.null(input$maxentEvalSel)) {
logger %>% writeLog(type = 'error', "Please choose a statistic to plot.")
return()
}
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$maxentEvalPlotSel <- input$maxentEvalSel
}
}
})
observeEvent(input$maxentEvalSel,{
req(curSp())
spp[[curSp()]]$rmm$code$wallace$maxentEvalPlot <- TRUE
})
output$maxentEvalPlot <- renderPlot({
req(curSp(), evalOut())
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
graphics::par(mar = c(0,0,0,0))
plot(c(0, 1), c(0, 1), ann = FALSE, bty = 'n', type = 'n', xaxt = 'n', yaxt = 'n')
graphics::text(x = 0.25, y = 1, "Evaluation plot module requires a Maxent model",
cex = 1.2, col = "#641E16")
} else if (spp[[curSp()]]$rmm$model$algorithms == "maxent.jar" |
spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
# FUNCTION CALL ####
if (!is.null(input$maxentEvalSel)) {
ENMeval::evalplot.stats(evalOut(), input$maxentEvalSel, "rm", "fc")
}
}
}, width = 700, height = 700)
return(list(
save = function() {
list(maxentEvalSel = input$maxentEvalSel)
},
load = function(state) {
updateSelectInput(session, "maxentEvalSel", selected = state$maxentEvalSel)
}
))
}
vis_maxentEvalPlot_module_result <- function(id) {
ns <- NS(id)
# Result UI
imageOutput(ns('maxentEvalPlot'))
}
vis_maxentEvalPlot_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
vis_maxentEvalPlot_knit = !is.null(species$rmm$code$wallace$maxentEvalPlot),
evalPlot_rmd = species$rmm$code$wallace$maxentEvalPlotSel
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_maxentEvalPlot.R
|
```{asis, echo = {{vis_maxentEvalPlot_knit}}, eval = {{vis_maxentEvalPlot_knit}}, include = {{vis_maxentEvalPlot_knit}}}
### Visualize
Generate a Maxent evaluation plot using "{{evalPlot_rmd}}" as evaluation statistic.
```
```{r, echo = {{vis_maxentEvalPlot_knit}}, include = {{vis_maxentEvalPlot_knit}}}
# Generate an evaluation plot
maxentEvalPlot_{{spAbr}} <- ENMeval::evalplot.stats(
model_{{spAbr}},
"{{evalPlot_rmd}}",
"rm",
"fc")
#plot
maxentEvalPlot_{{spAbr}}
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_maxentEvalPlot.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# vis_responsePlot.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
vis_responsePlot_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
uiOutput(ns("curEnvUI")),
h5("Reponse curves are displayed automatically in 'Results' tab")
)
}
vis_responsePlot_module_server <- function(input, output, session, common) {
spp <- common$spp
envs <- common$envs
curSp <- common$curSp
curModel <- common$curModel
curEnv <- common$curEnv
evalOut <- common$evalOut
observeEvent(input,{
req(curSp())
req(curModel())
req(evalOut())
#for rmd
spp[[curSp()]]$rmd$vis_responsePlot <- TRUE
if (spp[[curSp()]]$rmm$model$algorithms == "maxnet" | spp[[curSp()]]$rmm$model$algorithms == "maxent.jar"){
spp[[curSp()]]$rmd$vis_curModel <- curModel()
}
})
# ui that populates with the names of environmental predictors used
output$curEnvUI <- renderUI({
# ensure envs entity is within spp
req(curSp(), evalOut(), curModel())
if (spp[[curSp()]]$rmm$model$algorithms != "BIOCLIM") {
if (spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
n <- mxNonzeroCoefs(evalOut()@models[[curModel()]], "maxnet")
} else if (spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
n <- mxNonzeroCoefs(evalOut()@models[[curModel()]], "maxent.jar")
}
envsNameList <- c(setNames(as.list(n), n))
selectizeInput("curEnv", label = "Select variable" ,
choices = envsNameList, multiple = FALSE, selected = n[1],
options = list(maxItems = 1))
}
})
output$responsePlot <- renderPlot({
req(curSp(), evalOut())
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
graphics::par(mar = c(0,0,0,0))
plot(c(0, 1), c(0, 1), ann = FALSE, bty = 'n', type = 'n', xaxt = 'n', yaxt = 'n')
graphics::text(x = 0.25, y = 1, "Response curves module requires a Maxent model",
cex = 1.2, col = "#641E16")
} else if (spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
req(curEnv())
suppressWarnings(
maxnet::response.plot(evalOut()@models[[curModel()]], v = curEnv(), type = "cloglog")
)
} else if (spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
dismo::response(evalOut()@models[[curModel()]], var = curEnv())
}
}, width = 700, height = 700)
}
vis_responsePlot_module_result <- function(id) {
ns <- NS(id)
imageOutput(ns('responsePlot'))
}
vis_responsePlot_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
vis_responsePlot_knit = !is.null(species$rmd$vis_responsePlot),
vis_maxnet_knit = if(!is.null(species$rmm$model$algorithms)){
species$rmm$model$algorithms == "maxnet"} else {FALSE},
alg_rmd = if(!is.null(species$rmm$model$algorithms)){species$rmm$model$algorithms} else {NULL},
curModel_rmd = if(!is.null(species$rmd$vis_curModel)){species$rmd$vis_curModel} else {NULL}
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_responsePlot.R
|
```{asis, echo = {{vis_responsePlot_knit & vis_maxnet_knit}}, eval = {{vis_responsePlot_knit & vis_maxnet_knit}}, include = {{vis_responsePlot_knit & vis_maxnet_knit}}}
### Visualize
Visualize response curves from "{{alg_rmd}}" model.
```
```{r, echo = {{vis_responsePlot_knit & vis_maxnet_knit}}, include = {{vis_responsePlot_knit & vis_maxnet_knit}}}
# Create response curves
maxnet::response.plot(
model_{{spAbr}}@models[["{{curModel_rmd}}"]],
v = names(bgMask_{{spAbr}}),
type = "cloglog")
```
```{asis, echo = {{vis_responsePlot_knit & !vis_maxnet_knit}}, eval = {{vis_responsePlot_knit & !vis_maxnet_knit}}, include = {{vis_responsePlot_knit & !vis_maxnet_knit}}}
### Visualize
Visualize response curves from "{{alg_rmd}}" model.
```
```{r, echo = {{vis_responsePlot_knit & !vis_maxnet_knit }}, include = {{vis_responsePlot_knit & !vis_maxnet_knit}}}
# Create response curves
dismo::response(
model_{{spAbr}}@models[["{{curModel_rmd}}"]],
var = names(bgMask_{{spAbr}}))
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/vis_responsePlot.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_area.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
xfer_area_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
span("Step 1:", class = "step"),
span("Choose Study Region", class = "stepText"), br(), br(),
selectInput(ns('xferExt'), label = "Select method",
choices = list("Draw polygon" = 'xfDraw',
"User-specified polygon" = 'xfUser')),
conditionalPanel(sprintf("input['%s'] == 'xfUser'", ns("xferExt")),
fileInput(ns("userXfShp"),
label = paste0('Upload polygon in shapefile (.shp, .shx, .dbf) or ',
'CSV file with field order (longitude, latitude)'),
accept = c(".csv", ".dbf", ".shx", ".shp"), multiple = TRUE),
tags$div(title = paste0('Buffer area in degrees (1 degree = ~111 km). Exact',
' length varies based on latitudinal position.'),
numericInput(ns("userXfBuf"), label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5))),
conditionalPanel(sprintf("input['%s'] == 'xfDraw'", ns("xferExt")),
p("Draw a polygon and select buffer distance"),
tags$div(title = paste0('Buffer area in degrees (1 degree = ~111 km). Exact',
' length varies based on latitudinal position.'),
numericInput(ns("drawXfBuf"), label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5))),
actionButton(ns("goxferExtArea"), "Create"), br(),
tags$hr(class = "hrDotted"),
span("Step 2:", class = "step"),
span("Transfer", class = "stepText"), br(),
p("Transfer model to transfer extent (red) "),
tags$div(
title = paste0(
'Create binary map of predicted presence/absence assuming ',
'all values above threshold value represent presence. Also ',
'can be interpreted as a "potential distribution" (see ',
'guidance).'),
selectInput(ns('threshold'), label = "Set threshold",
choices = list("No threshold" = 'none',
"Minimum Training Presence" = 'mtp',
"10 Percentile Training Presence" = 'p10',
"Quantile of Training Presences" = 'qtp'))),
conditionalPanel(sprintf("input['%s'] == 'qtp'", ns("threshold")),
sliderInput(ns("trainPresQuantile"), "Set quantile",
min = 0, max = 1, value = .05)),
conditionalPanel(paste0("input['", ns("threshold"), "'] == 'none'"),
uiOutput(ns("noThrs"))),
actionButton(ns('goTransferArea'), "Transfer"),
tags$hr(class = "hrDashed"),
actionButton(ns("goResetXfer"), "Reset", class = 'butReset'),
strong(" transfer extent ")
)
}
xfer_area_module_server <- function(input, output, session, common) {
spp <- common$spp
evalOut <- common$evalOut
envs <- common$envs
envs.global <- common$envs.global
rmm <- common$rmm
curSp <- common$curSp
curModel <- common$curModel
logger <- common$logger
output$noThrs <- renderUI({
ns <- session$ns
req(curSp(), evalOut())
if (spp[[curSp()]]$rmm$model$algorithms != "BIOCLIM") {
h5("Prediction output is the same than Visualize component ")
}
})
observeEvent(input$goxferExtArea, {
# ERRORS ####
if (is.null(spp[[curSp()]]$visualization$mapPred)) {
logger %>% writeLog(type = 'error',
'Calculate a model prediction in model component before transfering.')
return()
}
if (input$xferExt == 'xfDraw') {
if (is.null(spp[[curSp()]]$polyXfXY)) {
logger %>% writeLog(type = 'error',
paste0("The polygon has not been drawn and finished. Please use the ",
"draw toolbar on the left-hand of the map to complete the ",
"polygon."))
return()
}
}
if (input$xferExt == 'xfUser') {
if (is.null(input$userXfShp$datapath)) {
logger %>% writeLog(type = 'error', "Specified filepath(s) ")
return()
}
}
# FUNCTION CALL ####
if (input$xferExt == 'xfDraw') {
polyXf <- xfer_draw(spp[[curSp()]]$polyXfXY, spp[[curSp()]]$polyXfID,
input$drawXfBuf, logger, spN = curSp())
if (input$drawXfBuf == 0 ) {
logger %>% writeLog(
hlSpp(curSp()), 'Draw polygon without buffer.')
} else {
logger %>% writeLog(
hlSpp(curSp()), 'Draw polygon with buffer of ', input$drawXfBuf,
' degrees.')
}
# METADATA ####
polyX <- printVecAsis(round(spp[[curSp()]]$polyXfXY[, 1], digits = 4))
polyY <- printVecAsis(round(spp[[curSp()]]$polyXfXY[, 2], digits = 4))
spp[[curSp()]]$rmm$code$wallace$drawExtPolyXfCoords <-
paste0('X: ', polyX, ', Y: ', polyY)
spp[[curSp()]]$rmm$code$wallace$XfBuff <- input$drawXfBuf
}
if (input$xferExt == 'xfUser') {
polyXf <- xfer_userExtent(input$userXfShp$datapath, input$userXfShp$name,
input$userXfBuf, logger, spN = curSp())
# ERRORS ####
# Check that the extents of raster and transfer extent intersects
polyXf_sfc <- sf::st_as_sfc(polyXf) #convert poly to sfc
envs_ext <- methods::as(raster::extent(envs()),'SpatialPolygons')
envs_sfc <- sf::st_as_sfc(envs_ext) #convert envs to sfc
#set crs to match
if (sf::st_crs(polyXf_sfc) != sf::st_crs(envs_sfc)) {
sf::st_crs(polyXf_sfc) <- sf::st_crs(envs_sfc)
logger %>%
writeLog(type = 'error', 'CRS was automatically set to match environmental variables.')
return()
}
if (!sf::st_intersects(polyXf_sfc, envs_sfc, sparse = FALSE)[1,1]) {
logger %>%
writeLog(type = 'error', 'Extents do not overlap.')
return()
}
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$XfBuff <- input$userXfBuf
# get extensions of all input files
exts <- sapply(strsplit(input$userXfShp$name, '\\.'),
FUN = function(x) x[2])
if('csv' %in% exts) {
spp[[curSp()]]$rmm$code$wallace$userXfExt <- 'csv'
spp[[curSp()]]$rmm$code$wallace$userXfPath <- input$userXfShp$datapath
}
else if('shp' %in% exts) {
spp[[curSp()]]$rmm$code$wallace$userXfExt <- 'shp'
# get index of .shp
i <- which(exts == 'shp')
shpName <- strsplit(input$userXfShp$name[i], '\\.')[[1]][1]
spp[[curSp()]]$rmm$code$wallace$userXfShpParams <-
list(dsn = input$userXfShp$datapath[i], layer = shpName)
}
}
# LOAD INTO SPP ####
spp[[curSp()]]$transfer$xfExt <- polyXf
common$update_component(tab = "Map")
})
observeEvent(input$goTransferArea, {
# ERRORS ####
if (is.null(spp[[curSp()]]$visualization$mapPred)) {
logger %>%
writeLog(type = 'error',
'Calculate a model prediction in model component before transfering.')
return()
}
if (is.null(spp[[curSp()]]$transfer$xfExt)) {
logger %>% writeLog(type = 'error', 'Select transfer extent first.')
return()
}
# Check that the extents of raster and transfer extent intersects
Xfer_sfc <- sf::st_as_sfc(spp[[curSp()]]$transfer$xfExt) #convert xfrExt to sfc
envs_ext <- methods::as(raster::extent(envs()),'SpatialPolygons')
envs_sfc <- sf::st_as_sfc(envs_ext) #convert envs to sfc
if (!sf::st_intersects(Xfer_sfc, envs_sfc, sparse = FALSE)[1,1]) {
logger %>%
writeLog(type = 'error', 'Extents do not overlap.')
return()
}
if (is.null(envs())) {
logger %>%
writeLog(
type = 'error',
'Environmental variables missing. Obtain them in component 3.')
return()
} else {
diskRast <- raster::fromDisk(envs.global[[spp[[curSp()]]$envs]])
if (diskRast) {
if (class(envs.global[[spp[[curSp()]]$envs]]) == "RasterStack") {
diskExist <- !file.exists(envs.global[[spp[[curSp()]]$envs]]@layers[[1]]@file@name)
} else if (class(envs.global[[spp[[curSp()]]$envs]]) == "RasterBrick") {
diskExist <- !file.exists(envs.global[[spp[[curSp()]]$envs]]@file@name)
}
if (diskExist) {
logger %>%
writeLog(
type = 'error',
'Environmental variables missing. Please upload again.')
return()
}
}
}
# FUNCTION CALL ####
predType <- rmm()$prediction$notes
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
xferArea.out <- xfer_area(evalOut = evalOut(),
curModel = curModel(),
envs = envs(),
xfExt = spp[[curSp()]]$transfer$xfExt,
alg = spp[[curSp()]]$rmm$model$algorithms,
logger,
spN = curSp())
} else {
xferArea.out <- xfer_area(evalOut = evalOut(),
curModel = curModel(),
envs = envs(),
xfExt = spp[[curSp()]]$transfer$xfExt,
alg = spp[[curSp()]]$rmm$model$algorithms,
outputType = predType,
clamp = rmm()$model$algorithm$maxent$clamping,
logger,
spN = curSp())
}
xferExt <- xferArea.out$xferExt
xferArea <- xferArea.out$xferArea
# PROCESSING ####
# generate binary prediction based on selected thresholding rule
# (same for all Maxent prediction types because they scale the same)
occPredVals <- spp[[curSp()]]$visualization$occPredVals
if(!(input$threshold == 'none')) {
if (input$threshold == 'mtp') {
thr <- stats::quantile(occPredVals, probs = 0)
} else if (input$threshold == 'p10') {
thr <- stats::quantile(occPredVals, probs = 0.1)
} else if (input$threshold == 'qtp'){
thr <- stats::quantile(occPredVals, probs = input$trainPresQuantile)
}
xferAreaThr <- xferArea > thr
logger %>% writeLog(hlSpp(curSp()), "Transfer of model to new area with threshold ",
input$threshold, ' (', formatC(thr, format = "e", 2), ').')
} else {
xferAreaThr <- xferArea
logger %>% writeLog(hlSpp(curSp()), "Transfer of model to new area with ",
predType, ' output.')
}
raster::crs(xferAreaThr) <- raster::crs(envs())
# rename
names(xferAreaThr) <- paste0(curModel(), '_thresh_', predType)
# LOAD INTO SPP ####
spp[[curSp()]]$transfer$xfEnvs <- xferExt
spp[[curSp()]]$transfer$mapXfer <- xferAreaThr
spp[[curSp()]]$transfer$mapXferVals <- getRasterVals(xferAreaThr, predType)
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$transfer_curModel <- curModel()
spp[[curSp()]]$rmm$code$wallace$transfer_area <- TRUE
spp[[curSp()]]$rmm$data$transfer$environment1$minVal <-
printVecAsis(raster::cellStats(xferExt, min), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$maxVal <-
printVecAsis(raster::cellStats(xferExt, max), asChar = TRUE)
if (spp[[curSp()]]$rmm$data$environment$sources == 'WorldClim 1.4') {
spp[[curSp()]]$rmm$data$transfer$environment1$yearMin <- 1960
spp[[curSp()]]$rmm$data$transfer$environment1$yearMax <- 1990
}
spp[[curSp()]]$rmm$data$transfer$environment1$resolution <-
paste(round(raster::res(xferExt)[1] * 60, digits = 2), "degrees")
spp[[curSp()]]$rmm$data$transfer$environment1$extentSet <-
printVecAsis(as.vector(xferExt@extent), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$extentRule <-
"transfer to user-selected new area"
spp[[curSp()]]$rmm$data$transfer$environment1$sources <-
spp[[curSp()]]$rmm$data$environment$sources
spp[[curSp()]]$rmm$prediction$transfer$environment1$units <-
ifelse(predType == "raw", "relative occurrence rate", predType)
spp[[curSp()]]$rmm$prediction$transfer$environment1$minVal <-
printVecAsis(raster::cellStats(xferAreaThr, min), asChar = TRUE)
spp[[curSp()]]$rmm$prediction$transfer$environment1$maxVal <-
printVecAsis(raster::cellStats(xferAreaThr, max), asChar = TRUE)
if(!(input$threshold == 'none')) {
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdSet <- thr
if (input$threshold == 'qtp') {
spp[[curSp()]]$rmm$code$wallace$transferQuantile <- input$trainPresQuantile
} else {
spp[[curSp()]]$rmm$code$wallace$transferQuantile <- 0
}
} else {
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdSet <- NULL
}
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdRule <- input$threshold
if (!is.null(spp[[curSp()]]$rmm$model$algorithm$maxent$clamping)) {
spp[[curSp()]]$rmm$prediction$transfer$environment1$extrapolation <-
spp[[curSp()]]$rmm$model$algorithm$maxent$clamping
}
spp[[curSp()]]$rmm$prediction$transfer$notes <- NULL
common$update_component(tab = "Map")
})
# Reset Transfer Extent button functionality
observeEvent(input$goResetXfer, {
spp[[curSp()]]$polyXfXY <- NULL
spp[[curSp()]]$polyXfID <- NULL
spp[[curSp()]]$transfer <- NULL
logger %>% writeLog("Reset transfer extent.")
})
return(list(
save = function() {
list(
xferExt = input$xferExt,
userXfBuf = input$userXfBuf,
drawXfBuf = input$drawXfBuf,
threshold = input$threshold,
trainPresQuantile = input$trainPresQuantile
)
},
load = function(state) {
updateSelectInput(session, 'xferExt', selected = state$xferExt)
updateNumericInput(session, 'userXfBuf', value = state$userXfBuf)
updateNumericInput(session, 'drawXfBuf', value = state$drawXfBuf)
updateSelectInput(session, 'threshold', selected = state$threshold)
updateSliderInput(session, 'trainPresQuantile', value = state$trainPresQuantile)
}
))
}
xfer_area_module_map <- function(map, common) {
spp <- common$spp
evalOut <- common$evalOut
curSp <- common$curSp
rmm <- common$rmm
mapXfer <- common$mapXfer
# Map logic
map %>% leaflet.extras::addDrawToolbar(
targetGroup = 'draw', polylineOptions = FALSE, rectangleOptions = FALSE,
circleOptions = FALSE, markerOptions = FALSE, circleMarkerOptions = FALSE,
editOptions = leaflet.extras::editToolbarOptions()
)
# Add just transfer Polygon
req(spp[[curSp()]]$transfer$xfExt)
polyXfXY <- spp[[curSp()]]$transfer$xfExt@polygons[[1]]@Polygons
if(length(polyXfXY) == 1) {
shp <- list(polyXfXY[[1]]@coords)
} else {
shp <- lapply(polyXfXY, function(x) x@coords)
}
bb <- spp[[curSp()]]$transfer$xfExt@bbox
bbZoom <- polyZoom(bb[1, 1], bb[2, 1], bb[1, 2], bb[2, 2], fraction = 0.05)
map %>% clearAll() %>% removeImage('xferRas') %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4])
for (poly in shp) {
map %>% addPolygons(lng = poly[, 1], lat = poly[, 2], weight = 4,
color = "red",group = 'bgShp')
}
req(evalOut(), spp[[curSp()]]$transfer$xfEnvs)
mapXferVals <- spp[[curSp()]]$transfer$mapXferVals
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if threshold specified
if(rmm()$prediction$transfer$environment1$thresholdRule != 'none') {
rasPal <- c('gray', 'red')
map %>% removeControl("xfer") %>%
addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')
} else {
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols), mapXferVals, na.color = 'transparent')
rasPal <- colorNumeric(rasCols, mapXferVals, na.color = 'transparent')
map %>% removeControl("xfer") %>%
addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE))
}
# map model prediction raster and transfer polygon
map %>% clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(mapXfer(), colors = rasPal, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb")
for (poly in shp) {
map %>% addPolygons(lng = poly[, 1], lat = poly[, 2], weight = 4,
color = "red", group = 'xfer', fill = FALSE)
}
}
xfer_area_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
xfer_area_knit = !is.null(species$rmm$code$wallace$transfer_area),
curModel_rmd = species$rmm$code$wallace$transfer_curModel,
outputType_rmd = species$rmm$prediction$notes,
alg_rmd = species$rmm$model$algorithms,
clamp_rmd = species$rmm$model$algorithm$maxent$clamping,
###arguments for creating extent
polyXfXY_rmd = if(!is.null(species$rmm$code$wallace$drawExtPolyXfCoords)){
printVecAsis(species$polyXfXY)} else {NULL},
polyXfID_rmd = if(!is.null(species$rmm$code$wallace$drawExtPolyXfCoords)){
species$polyXfID} else {0},
BgBuf_rmd = species$rmm$code$wallace$XfBuff,
##Determine the type of transfer extent to use correct RMD function
xfer_area_extent_knit = !is.null(species$rmm$code$wallace$userXfShpParams),
##Use of threshold for transfer
xfer_area_threshold_knit = !is.null(species$rmm$prediction$transfer$environment1$thresholdSet),
xfer_thresholdRule_rmd = species$rmm$prediction$transfer$environment1$thresholdRule,
xfer_threshold_rmd = if (!is.null(species$rmm$prediction$transfer$environment1$thresholdSet)){
species$rmm$prediction$transfer$environment1$thresholdSet} else {0},
xfer_probQuantile_rmd = species$rmm$code$wallace$transferQuantile
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_area.R
|
```{asis, echo = {{xfer_area_knit & !xfer_area_extent_knit & xfer_area_threshold_knit}}, eval = {{xfer_area_knit & !xfer_area_extent_knit & !xfer_area_threshold_knit}}, include = {{xfer_area_knit & !xfer_area_extent_knit & !xfer_area_threshold_knit}}}
## Transfer model
Transfering the model to a new user drawn area
```
```{r, echo = {{xfer_area_knit & !xfer_area_extent_knit & !xfer_area_threshold_knit}}, include = {{xfer_area_knit & !xfer_area_extent_knit & !xfer_area_threshold_knit}}}
# First must generate the transfer area according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <-xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}},ncol=2,byrow=FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Create object of transfer variables
xferAreaEnvs_{{spAbr}} <- envs_{{spAbr}}
# Generate a transfer of the model to the desired area
xfer_area_{{spAbr}} <- xfer_area(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferAreaEnvs_{{spAbr}} ,
outputType = "{{outputType_rmd}}",
alg = "{{alg_rmd}}",
clamp = {{clamp_rmd}},
xfExt = xfer_draw_{{spAbr}})
# store the cropped transfer variables
xferExt_{{spAbr}} <- xfer_area_{{spAbr}}$xferExt
#map result
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_area_{{spAbr}}$xferArea,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and transfer polygon
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_area_{{spAbr}}$xferArea, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add transfer polygon (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_area_knit & !xfer_area_extent_knit & xfer_area_threshold_knit}}, eval = {{xfer_area_knit & !xfer_area_extent_knit & xfer_area_threshold_knit}}, include = {{xfer_area_knit & !xfer_area_extent_knit & xfer_area_threshold_knit}}}
## Transfer model
Transfering the model to a new user drawn area using a "{{xfer_thresholdRule_rmd}}" threshold of {{xfer_threshold_rmd}}.
```
```{r, echo = {{xfer_area_knit & !xfer_area_extent_knit & xfer_area_threshold_knit}}, include = {{xfer_area_knit & !xfer_area_extent_knit & xfer_area_threshold_knit}}}
# First must generate the transfer area according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <-xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}},ncol=2,byrow=FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Create object of transfer variables
xferAreaEnvs_{{spAbr}} <- envs_{{spAbr}}
# Generate a transfer of the model to the desired area
xfer_area_{{spAbr}} <- xfer_area(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferAreaEnvs_{{spAbr}} ,
outputType = "{{outputType_rmd}}",
alg = "{{alg_rmd}}",
clamp = {{clamp_rmd}},
xfExt = xfer_draw_{{spAbr}})
#store the cropped transfer variables
xferExt_{{spAbr}} <- xfer_area_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Define threshold value
xfer_thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}},
probs = xfer_thresProb_{{spAbr}})
# Add threshold if specified
xfer_area_{{spAbr}} <- xfer_area_{{spAbr}}$xferArea > xfer_thres_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_area_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and transfer polygon
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_area_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add transfer polygon (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_area_knit & xfer_area_extent_knit}} , eval = {{xfer_area_knit & xfer_area_extent_knit }}, include = {{xfer_area_knit & xfer_area_extent_knit}}}
## Transfer model
Transfering the model to a new user provided area
```
```{r, echo = {{xfer_area_knit & xfer_area_extent_knit}}, include = {{xfer_area_knit & xfer_area_extent_knit}}}
# First must generate the transfer area based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Create object of transfer variables
xferAreaEnvs_{{spAbr}} <- envs_{{spAbr}}
# Generate a transfer of the model to the desired area
xfer_area_{{spAbr}} <- xfer_area(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferAreaEnvs_{{spAbr}} ,
outputType = "{{outputType_rmd}}",
alg = "{{alg_rmd}}",
clamp = {{clamp_rmd}},
xfExt = xfer_userExt_{{spAbr}})
#store the cropped transfer variables
xferExt_{{spAbr}} <- xfer_area_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_area_{{spAbr}}$xferArea,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and transfer polygon
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_area_{{spAbr}}$xferArea, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add transfer polygon (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_area_knit & xfer_area_extent_knit & xfer_area_threshold_knit}} , eval = {{xfer_area_knit & xfer_area_extent_knit & xfer_area_threshold_knit}}, include = {{xfer_area_knit & xfer_area_extent_knit & xfer_area_threshold_knit}}}
## Transfer model
Transfering the model to a new user provided area using a "{{xfer_thresholdRule_rmd}}" threshold of {{xfer_threshold_rmd}}.
```
```{r, echo = {{xfer_area_knit & xfer_area_extent_knit & xfer_area_threshold_knit}}, include = {{xfer_area_knit & xfer_area_extent_knit & xfer_area_threshold_knit}}}
# First must generate the transfer area based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Create object of transfer variables
xferAreaEnvs_{{spAbr}} <- envs_{{spAbr}}
# Generate a transfer of the model to the desired area
xfer_area_{{spAbr}} <- xfer_area(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferAreaEnvs_{{spAbr}} ,
outputType = "{{outputType_rmd}}",
alg = "{{alg_rmd}}",
clamp = {{clamp_rmd}},
xfExt = xfer_userExt_{{spAbr}})
# store the cropped transfer variables
xferExt_{{spAbr}} <- xfer_area_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Define threshold value
xfer_thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}},
probs = xfer_thresProb_{{spAbr}})
# Add threshold if specified
xfer_area_{{spAbr}} <- xfer_area_{{spAbr}}$xferArea > xfer_thresProb_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_area_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and transfer polygon
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_area_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add transfer polygon (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_area.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_mess.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
xfer_mess_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
strong("Calculate MESS for current extent"), br(), br(),
actionButton(ns('goEnvSimilarity'), "Calculate MESS")
)
}
xfer_mess_module_server <- function(input, output, session, common) {
spp <- common$spp
curSp <- common$curSp
mapXfer <- common$mapXfer
occs <- common$occs
bg <- common$bg
bgMask <- common$bgMask
logger <- common$logger
observeEvent(input$goEnvSimilarity, {
# ERRORS ####
if (is.null(mapXfer())) {
logger %>% writeLog(type = 'error', 'Transfer to new area or time first.')
return()
}
if (is.null(spp[[curSp()]]$transfer$xfExt)) {
logger %>%
writeLog(
type = 'error',
"The polygon has not been finished. Please define a polygon."
)
return()
}
# FUNCTION CALL ####
xferYr <- spp[[curSp()]]$rmm$data$transfer$environment1$yearMax
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
mss <- xfer_mess(occs(), bg = NULL, bgMask(), spp[[curSp()]]$transfer$xfEnvs,
logger, spN = curSp())
} else {
mss <- xfer_mess(occs(), bg(), bgMask(), spp[[curSp()]]$transfer$xfEnvs,
logger, spN = curSp())
}
# LOAD INTO SPP ####
spp[[curSp()]]$transfer$mess <- mss
spp[[curSp()]]$transfer$messVals <- getRasterVals(mss)
spp[[curSp()]]$rmm$code$wallace$MESS <- TRUE
spp[[curSp()]]$rmm$code$wallace$MESSTime <- time
# REFERENCES
knitcitations::citep(citation("dismo"))
# METADATA
spp[[curSp()]]$rmm$prediction$uncertainty$extrapolation <-
"MESS (multivariate environmental similarity surface)"
common$update_component(tab = "Map")
})
return(list(
save = function() {
# Save any values that should be saved when the current session is saved
},
load = function(state) {
# Load
}
))
}
xfer_mess_module_map <- function(map, common) {
spp <- common$spp
curSp <- common$curSp
occs <- common$occs
bgShpXY <- common$bgShpXY
req(spp[[curSp()]]$transfer$mess, spp[[curSp()]]$transfer$xfExt)
polyXfXY <- spp[[curSp()]]$transfer$xfExt@polygons[[1]]@Polygons
if(length(polyXfXY) == 1) {
shp <- list(polyXfXY[[1]]@coords)
} else {
shp <- lapply(polyXfXY, function(x) x@coords)
}
mess <- spp[[curSp()]]$transfer$mess
rasVals <- spp[[curSp()]]$transfer$messVals
# define colorRamp for mess
if (max(rasVals) > 0 & min(rasVals) < 0) {
rc1 <- colorRampPalette(colors = rev(RColorBrewer::brewer.pal(n = 3, name = 'Reds')),
space = "Lab")(abs(min(rasVals)))
rc2 <- colorRampPalette(colors = RColorBrewer::brewer.pal(n = 3, name = 'Blues'),
space = "Lab")(max(rasVals))
rasCols <- c(rc1, rc2)
} else if (max(rasVals) < 0 & min(rasVals) < 0) {
rasCols <- colorRampPalette(colors = rev(RColorBrewer::brewer.pal(n = 3, name = 'Reds')),
space = "Lab")(abs(min(rasVals)))
} else if (max(rasVals) > 0 & min(rasVals) > 0) {
rasCols <- colorRampPalette(colors = RColorBrewer::brewer.pal(n = 3, name = 'Blues'),
space = "Lab")(max(rasVals))
}
legendPal <- colorNumeric(rev(rasCols), rasVals, na.color='transparent')
rasPal <- colorNumeric(rasCols, rasVals, na.color='transparent')
map %>% removeControl("xfer") %>%
addLegend("bottomright", pal = legendPal, title = "MESS Values",
values = rasVals, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order=TRUE))
# map model prediction raster and transfer polygon
map %>% clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(mess, colors = rasPal, opacity = 0.9,
layerId = 'xferRas', group = 'xfer', method = "ngb")
for (poly in shp) {
map %>% addPolygons(lng = poly[, 1], lat = poly[, 2], weight = 4,
color = "red", group = 'xfer', fill = FALSE)
}
}
xfer_mess_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
xfer_mess_knit = !is.null(species$rmm$code$wallace$MESS),
time_rmd = species$rmm$code$wallace$MESSTime
# polyXfXY_rmd <- printVecAsis(species$transfer$xfExt@polygons[[1]]@Polygons)
# xfer_mess_knit = species$rmm$code$wallace$someFlag,
# var1 = species$rmm$code$wallace$someSetting1,
# var2 = species$rmm$code$wallace$someSetting2
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_mess.R
|
```{asis, echo = {{xfer_mess_knit}}, eval = {{xfer_mess_knit}}, include = {{xfer_mess_knit}}}
Generate a MESS map for the transferring variables given the variables used for modelling
```
```{r, echo = {{xfer_mess_knit}}, include = {{xfer_mess_knit}}}
# R code to generate MESS raster
xferMess_{{spAbr}} <- xfer_mess(
occs = occs_{{spAbr}},
bg = bgEnvsVals_{{spAbr}} ,
bgMsk = bgMask_{{spAbr}},
xferExtRas = xferExt_{{spAbr}})
# Generate MESS map
rasVals_{{spAbr}} <- getRasterVals(xferMess_{{spAbr}})
# define colorRamp for mess
if (max(rasVals_{{spAbr}}) > 0 & min(rasVals_{{spAbr}}) < 0) {
rc1 <- colorRampPalette(colors = rev(RColorBrewer::brewer.pal(n = 3, name = 'Reds')),
space = "Lab")(abs(min(rasVals_{{spAbr}})))
rc2 <- colorRampPalette(colors = RColorBrewer::brewer.pal(n = 3, name = 'Blues'),
space = "Lab")(max(rasVals_{{spAbr}}))
rasCols_{{spAbr}} <- c(rc1, rc2)
} else if (max(rasVals_{{spAbr}}) < 0 & min(rasVals_{{spAbr}}) < 0) {
rasCols_{{spAbr}} <- colorRampPalette(colors = rev(RColorBrewer::brewer.pal(n = 3, name = 'Reds')),
space = "Lab")(abs(min(rasVals)))
} else if (max(rasVals_{{spAbr}}) > 0 & min(rasVals_{{spAbr}}) > 0) {
rasCols{{spAbr}} <- colorRampPalette(colors = RColorBrewer::brewer.pal(n = 3, name = 'Blues'),
space = "Lab")(max(rasVals_{{spAbr}}))
}
legendPal_{{spAbr}} <- colorNumeric(rev(rasCols_{{spAbr}}), rasVals_{{spAbr}}, na.color='transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, rasVals_{{spAbr}}, na.color='transparent')
#Create map
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
leaflet::addLegend("bottomright", pal = legendPal_{{spAbr}}, title = "MESS Values",
values = rasVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order=TRUE)) %>%
# map model prediction raster and transferring polygon
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xferMess_{{spAbr}}, colors = rasPal_{{spAbr}} , opacity = 0.9,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add transferring polygon: this we need to fix for now please replace bgExt_{{spAbr}} for the name of your transferring polygon.
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_mess.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_time.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
xfer_time_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
span("Step 1:", class = "step"),
span("Choose Study Region", class = "stepText"), br(), br(),
selectInput(ns('xferExt'), label = "Select method",
choices = list("Draw polygon" = 'xfDraw',
"Same extent" = 'xfCur',
"User-specified polygon" = 'xfUser')),
conditionalPanel(sprintf("input['%s'] == 'xfUser'", ns("xferExt")),
fileInput(
ns("userXfShp"),
label = paste0(
'Upload polygon in shapefile (.shp, .shx, .dbf) or ',
'CSV file with field order (longitude, latitude)'),
accept = c(".csv", ".dbf", ".shx", ".shp"),
multiple = TRUE),
tags$div(
title = paste0(
'Buffer area in degrees (1 degree = ~111 km). Exact',
' length varies based on latitudinal position.'),
numericInput(ns("userXfBuf"),
label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5)
)),
conditionalPanel(sprintf("input['%s'] == 'xfDraw'", ns("xferExt")),
p("Draw a polygon and select buffer distance"),
tags$div(
title = paste0(
'Buffer area in degrees (1 degree = ~111 km). Exact',
' length varies based on latitudinal position.'
),
numericInput(
ns("drawXfBuf"),
label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5)
)),
conditionalPanel(sprintf("input['%s'] == 'xfCur'", ns("xferExt")),
p('You will use the same extent')),
actionButton(ns("goXferExtTime"), "Create"), br(),
tags$hr(class = "hrDotted"),
span("Step 2:", class = "step"),
span("Transfer", class = "stepText"), br(),
p("Transfer model to extent (red) "),
radioButtons(ns('selTimeVar'), label = "Select source of variables",
choices = list("WorldClim" = "worldclim",
"ecoClimate" = "ecoclimate"),
inline = TRUE),
conditionalPanel(sprintf("input['%s'] == 'worldclim'", ns("selTimeVar")),
selectInput(ns("selTime"), label = "Select time period",
choices = list("Select period" = "",
"2050" = 50,
"2070" = 70)),
uiOutput(ns('selGCMui')),
selectInput(ns('selRCP'), label = "Select RCP",
choices = list("Select RCP" = "",
'2.6' = 26,
'4.5' = 45,
'6.0' = 60,
'8.5' = 85))),
conditionalPanel(sprintf("input['%s'] == 'ecoclimate'", ns("selTimeVar")),
tags$div(title = 'Select AOGCM',
selectInput(ns("xfAOGCM"),
label = "Select the Atmospheric Oceanic General Circulation Model you want to use",
choices = list("Select AOGCMs" = "",
"CCSM" = "CCSM",
"CNRM" = "CNRM",
"MIROC" = "MIROC",
"FGOALS" = "FGOALS",
"GISS" = "GISS",
"IPSL" = "IPSL",
"MRI" = "MRI",
"MPI" = "MPI")
)),
tags$div(title = 'Select Scenario',
selectInput(ns("xfScenario"),
label = "select the temporal scenario that you want to use",
choices = list("Select Scenario" = "",
"2080-2100 RCP 2.6" = "Future 2.6",
"2080-2100 RCP 4.5" = "Future 4.5",
"2080-2100 RCP 6" = "Future 6",
"2080-2100 RCP 8.5" = "Future 8.5",
"Holocene (6,000 years ago)" = "Holo",
"LGM (21,000 years ago)" = "LGM")
))),
tags$div(title = paste0('Create binary map of predicted presence/absence ',
'assuming all values above threshold value represent ',
'presence. Also can be interpreted as a "potential ',
'distribution" (see guidance).'),
selectInput(ns('threshold'), label = "Set threshold",
choices = list("No threshold" = 'none',
"Minimum Training Presence" = 'mtp',
"10 Percentile Training Presence" = 'p10',
"Quantile of Training Presences" = 'qtp'))),
conditionalPanel(sprintf("input['%s'] == 'qtp'", ns("threshold")),
sliderInput(ns("trainPresQuantile"), "Set quantile",
min = 0, max = 1, value = .05)),
conditionalPanel(paste0("input['", ns("threshold"), "'] == 'none'"),
uiOutput(ns("noThrs"))),
actionButton(ns('goTransferTime'), "Transfer"),
tags$hr(class = "hrDashed"),
actionButton(ns("goResetXfer"), "Reset", class = 'butReset'),
strong(" extent of transfer")
)
}
xfer_time_module_server <- function(input, output, session, common) {
spp <- common$spp
evalOut <- common$evalOut
envs <- common$envs
rmm <- common$rmm
curSp <- common$curSp
curModel <- common$curModel
logger <- common$logger
output$noThrs <- renderUI({
ns <- session$ns
req(curSp(), evalOut())
if (spp[[curSp()]]$rmm$model$algorithms != "BIOCLIM") {
h5("Prediction output is the same as Visualize component")
}
})
GCMlookup <- c(AC = "ACCESS1-0", BC = "BCC-CSM1-1", CC = "CCSM4",
CE = "CESM1-CAM5-1-FV2", CN = "CNRM-CM5", GF = "GFDL-CM3",
GD = "GFDL-ESM2G", GS = "GISS-E2-R", HD = "HadGEM2-AO",
HG = "HadGEM2-CC", HE = "HadGEM2-ES", IN = "INMCM4",
IP = "IPSL-CM5A-LR", ME = "MPI-ESM-P", MI = "MIROC-ESM-CHEM",
MR = "MIROC-ESM", MC = "MIROC5", MP = "MPI-ESM-LR",
MG = "MRI-CGCM3", NO = "NorESM1-M")
# dynamic ui for GCM selection: choices differ depending on choice of time period
output$selGCMui <- renderUI({
ns <- session$ns
if (input$selTime == 'lgm') {
gcms <- c('CC', 'MR', 'MC')
} else if (input$selTime == 'mid') {
gcms <- c("BC", "CC", "CE", "CN", "HG", "IP", "MR", "ME", "MG")
} else {
gcms <- c("AC", "BC", "CC", "CE", "CN", "GF", "GD", "GS", "HD",
"HG", "HE", "IN", "IP", "MI", "MR", "MC", "MP", "MG", "NO")
}
names(gcms) <- GCMlookup[gcms]
gcms <- as.list(c("Select GCM" = "", gcms))
selectInput(ns("selGCM"), label = "Select global circulation model",
choices = gcms)
})
observeEvent(input$goXferExtTime, {
# ERRORS ####
if (is.null(spp[[curSp()]]$visualization$mapPred)) {
logger %>%
writeLog(
type = 'error',
'Calculate a model prediction in model component before transferring.'
)
return()
}
if (input$xferExt == 'xfDraw') {
if (is.null(spp[[curSp()]]$polyXfXY)) {
logger %>%
writeLog(
type = 'error',
paste0("The polygon has not been drawn and finished. Please use the ",
"draw toolbar on the left-hand of the map to complete the ",
"polygon.")
)
return()
}
}
if (input$xferExt == 'xfUser') {
if (is.null(input$userXfShp$datapath)) {
logger %>% writeLog(type = 'error', paste0("Specified filepath(s) "))
return()
}
}
# FUNCTION CALL ####
if (input$xferExt == 'xfDraw') {
polyXf <- xfer_draw(spp[[curSp()]]$polyXfXY, spp[[curSp()]]$polyXfID,
input$drawXfBuf, logger, spN = curSp())
if (input$drawXfBuf == 0 ) {
logger %>% writeLog(
hlSpp(curSp()), 'Draw polygon without buffer.')
} else {
logger %>% writeLog(
hlSpp(curSp()), 'Draw polygon with buffer of ', input$drawXfBuf,
' degrees.')
}
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$XfBuff <- input$drawXfBuf
polyX <- printVecAsis(round(spp[[curSp()]]$polyXfXY[, 1], digits = 4))
polyY <- printVecAsis(round(spp[[curSp()]]$polyXfXY[, 2], digits = 4))
spp[[curSp()]]$rmm$code$wallace$drawExtPolyXfCoords <-
paste0('X: ', polyX, ', Y: ', polyY)
}
if (input$xferExt == 'xfUser') {
polyXf <- xfer_userExtent(input$userXfShp$datapath, input$userXfShp$name,
input$userXfBuf, logger, spN = curSp())
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$XfBuff <- input$userXfBuf
# get extensions of all input files
exts <- sapply(strsplit(input$userXfShp$name, '\\.'),
FUN = function(x) x[2])
if('csv' %in% exts) {
spp[[curSp()]]$rmm$code$wallace$userXfExt <- 'csv'
spp[[curSp()]]$rmm$code$wallace$userXfPath <- input$userXfShp$datapath
}
else if('shp' %in% exts) {
spp[[curSp()]]$rmm$code$wallace$userXfExt <- 'shp'
# get index of .shp
i <- which(exts == 'shp')
shpName <- strsplit(input$userXfShp$name[i], '\\.')[[1]][1]
spp[[curSp()]]$rmm$code$wallace$userXfShpParams <-
list(dsn = input$userXfShp$datapath[i], layer = shpName)
}
}
if (input$xferExt == 'xfCur') {
polyXf <- spp[[curSp()]]$procEnvs$bgExt
logger %>% writeLog(
hlSpp(curSp()),
'Transfer extent equal to current extent region.')
}
# LOAD INTO SPP ####
spp[[curSp()]]$transfer$xfExt <- polyXf
common$update_component(tab = "Map")
})
observeEvent(input$goTransferTime, {
# ERRORS ####
if (is.null(spp[[curSp()]]$visualization$mapPred)) {
logger %>%
writeLog(
type = 'error',
'Calculate a model prediction in visualization component before transferring.')
return()
}
if (is.null(spp[[curSp()]]$transfer$xfExt)) {
logger %>% writeLog(type = 'error', 'Select extent of transfer first.')
return()
}
envsRes <- raster::res(envs())[1]
if (envsRes < 0.01) {
logger %>%
writeLog(type = 'error',
paste0('Transfer to New Time currently only available with ',
'resolutions >30 arc seconds.'))
return()
}
if(!all(names(envs()) %in% paste0('bio', sprintf("%02d", 1:19)))) {
nonBios <- names(envs())[!names(envs()) %in% paste0('bio', sprintf("%02d", 1:19))]
logger %>%
writeLog(type = 'error', hlSpp(curSp()),
"Your model is using non-bioclimatic variables or non-conventional",
" names (i.e., ", paste0(nonBios, collapse = ", "),
"). You can not transfer to a New Time.")
return()
}
#BAJ
if (input$selTimeVar == 'worldclim') {
# warnings for wc selections
if(input$selTime == "") {
logger %>% writeLog(type = 'error', "Please select transfer time period.")
return()
}
if(input$selGCM == "") {
logger %>% writeLog(type = 'error', "Please select global circulation model.")
return()
}
if(input$selRCP == "") {
logger %>% writeLog(type = 'error', "Please select RCP.")
return()
}
} else if (input$selTimeVar == 'ecoclimate') {
# warnings for ecoclimate selections
if(input$xfAOGCM == "") {
logger %>% writeLog(type = 'error', "Please select transfer AOGCM.")
return()
}
if(input$xfScenario == "") {
logger %>% writeLog(type = 'error', "Please select transfer temporal scenario.")
return()
}
}
# DATA ####
if (input$selTimeVar == 'worldclim') {
# code taken from dismo getData() function to catch if user is trying to
# download a missing combo of gcm / rcp
gcms <- c('AC', 'BC', 'CC', 'CE', 'CN', 'GF', 'GD', 'GS', 'HD', 'HG', 'HE',
'IN', 'IP', 'MI', 'MR', 'MC', 'MP', 'MG', 'NO')
rcps <- c(26, 45, 60, 85)
m <- matrix(c(0,1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,0,1,1,0,0,1,0,1,1,1,0,0,1,1,1,1,0,1,1,1,1,1,0,1,
0,1,1,1,1,1,1,1,1,1,1,1,1,1), ncol = 4)
i <- m[which(input$selGCM == gcms), which(input$selRCP == rcps)]
if (!i) {
logger %>%
writeLog(type = 'error',
paste0('This combination of GCM and RCP is not available. Please ',
'make a different selection.'))
return()
}
smartProgress(
logger,
message = paste("Retrieving WorldClim data for", input$selTime,
input$selRCP, "..."),
{
xferTimeEnvs <-
raster::getData('CMIP5', var = "bio", res = round(envsRes * 60, 1),
rcp = input$selRCP, model = input$selGCM,
year = input$selTime)
names(xferTimeEnvs) <- paste0('bio', c(paste0('0',1:9), 10:19))
# in case user subsetted bioclims
xferTimeEnvs <- xferTimeEnvs[[names(envs())]]
}
)
} else if (input$selTimeVar == 'ecoclimate') {
smartProgress(
logger,
message = paste0("Retrieving ecoClimate data of GCM ", input$xfAOGCM,
" for ", input$xfScenario, "..."),
{
xferTimeEnvs <- envs_ecoClimate(input$xfAOGCM, input$xfScenario,
as.numeric(gsub("bio", "", names(envs()))),
logger)
}
)
}
# ERRORS ####
# Check that the extents of raster and extent of transfer intersects
Xfer_sfc <- sf::st_as_sfc(spp[[curSp()]]$transfer$xfExt) #convert poly to sfc
xferTimeEnvs_sp <- methods::as(raster::extent(xferTimeEnvs),'SpatialPolygons')
xferTimeEnvs_sfc <- sf::st_as_sfc(xferTimeEnvs_sp) #convert xfer envs to sfc
if (!sf::st_intersects(Xfer_sfc, xferTimeEnvs_sfc, sparse = FALSE)[1,1]) {
logger %>%
writeLog(type = 'error', 'Extents do not overlap.')
return()
}
# FUNCTION CALL ####
req(xferTimeEnvs)
predType <- rmm()$prediction$notes
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
xferTime.out <- xfer_time(evalOut = evalOut(),
curModel = curModel(),
envs = xferTimeEnvs,
xfExt = spp[[curSp()]]$transfer$xfExt,
alg = spp[[curSp()]]$rmm$model$algorithms,
logger,
spN = curSp())
} else {
xferTime.out <- xfer_time(evalOut = evalOut(),
curModel = curModel(),
envs = xferTimeEnvs,
xfExt = spp[[curSp()]]$transfer$xfExt,
alg = spp[[curSp()]]$rmm$model$algorithms,
outputType = predType,
clamp = rmm()$model$algorithm$maxent$clamping,
logger,
spN = curSp())
}
xferExt <- xferTime.out$xferExt
xferTime <- xferTime.out$xferTime
# PROCESSING ####
# generate binary prediction based on selected thresholding rule
# (same for all Maxent prediction types because they scale the same)
occPredVals <- spp[[curSp()]]$visualization$occPredVals
if(!(input$threshold == 'none')) {
# use threshold from present-day model training area
if (input$threshold == 'mtp') {
thr <- stats::quantile(occPredVals, probs = 0)
} else if (input$threshold == 'p10') {
thr <- stats::quantile(occPredVals, probs = 0.1)
} else if (input$threshold == 'qtp'){
thr <- stats::quantile(occPredVals, probs = input$trainPresQuantile)
}
xferTimeThr <- xferTime > thr
if (input$selTimeVar == 'worldclim') {
logger %>% writeLog(hlSpp(curSp()), "Transfer of model to ", paste0('20', input$selTime),
' with threshold ', input$threshold, ' (',
formatC(thr, format = "e", 2), ") for GCM ",
GCMlookup[input$selGCM], " under RCP ",
as.numeric(input$selRCP)/10.0, ".")
} else if (input$selTimeVar == 'ecoclimate') {
logger %>% writeLog(hlSpp(curSp()), "Transfer of model to ", input$xfScenario,
' with threshold ', input$threshold, ' (',
formatC(thr, format = "e", 2), ") for GCM ",
input$xfAOGCM, ".")
}
} else {
xferTimeThr <- xferTime
if (input$selTimeVar == 'worldclim') {
logger %>% writeLog(hlSpp(curSp()), "Transfer of model to ", paste0('20', input$selTime),
' with ', predType, " output for GCM ", GCMlookup[input$selGCM],
" under RCP ", as.numeric(input$selRCP)/10.0, ".")
} else if (input$selTimeVar == 'ecoclimate') {
logger %>% writeLog(hlSpp(curSp()), "Transfer of model to ", input$xfScenario,
' with ', predType, " output for GCM ", input$xfAOGCM, ".")
}
}
raster::crs(xferTimeThr) <- raster::crs(envs())
# rename
names(xferTimeThr) <- paste0(curModel(), '_thresh_', predType)
# LOAD INTO SPP ####
spp[[curSp()]]$transfer$xfEnvs <- xferExt
spp[[curSp()]]$transfer$xferTimeEnvs <- xferTimeEnvs
spp[[curSp()]]$transfer$mapXfer <- xferTimeThr
spp[[curSp()]]$transfer$mapXferVals <- getRasterVals(xferTimeThr, predType)
if (input$selTimeVar == "worldclim") {
spp[[curSp()]]$transfer$xfEnvsDl <- paste0('CMIP5_', envsRes * 60, "min_RCP",
input$selRCP, "_", input$selGCM,
"_", input$selTime)
} else if (input$selTimeVar == "ecoclimate") {
spp[[curSp()]]$transfer$xfEnvsDl <- paste0('ecoClimate_', input$xfScenario,
'_', input$xfAOGCM)
}
# REFERENCES
knitcitations::citep(citation("dismo"))
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$transfer_curModel <- curModel()
spp[[curSp()]]$rmm$code$wallace$transfer_time <- TRUE
spp[[curSp()]]$rmm$data$transfer$environment1$minVal <-
printVecAsis(raster::cellStats(xferExt, min), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$maxVal <-
printVecAsis(raster::cellStats(xferExt, max), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$resolution <-
paste(round(raster::res(xferExt)[1] * 60, digits = 2), "degrees")
spp[[curSp()]]$rmm$data$transfer$environment1$extentSet <-
printVecAsis(as.vector(xferExt@extent), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$extentRule <-
"transfer to user-selected new time"
if (input$selTimeVar == "worldclim") {
xferYr <- paste0('20', input$selTime)
###For RMD only
spp[[curSp()]]$rmm$code$wallace$transfer_worldclim <- TRUE
spp[[curSp()]]$rmm$code$wallace$transfer_GCM <- input$selGCM
spp[[curSp()]]$rmm$code$wallace$transfer_RCP <- input$selRCP
spp[[curSp()]]$rmm$code$wallace$transfer_Time <- input$selTime
spp[[curSp()]]$rmm$data$transfer$environment1$yearMin <- xferYr
spp[[curSp()]]$rmm$data$transfer$environment1$yearMax <- xferYr
spp[[curSp()]]$rmm$data$transfer$environment1$sources <- "WorldClim 1.4"
spp[[curSp()]]$rmm$data$transfer$environment1$notes <-
paste("transfer to year", xferYr, "for GCM",
GCMlookup[input$selGCM], "under RCP",
as.numeric(input$selRCP)/10.0)
} else if (input$selTimeVar == "ecoclimate") {
spp[[curSp()]]$rmm$code$wallace$transfer_ecoclimate <- TRUE
spp[[curSp()]]$rmm$code$wallace$transfer_AOGCM <- input$xfAOGCM
spp[[curSp()]]$rmd$transfer_Scenario <- input$xfScenario
spp[[curSp()]]$rmm$data$transfer$environment1$sources <- "ecoClimate"
spp[[curSp()]]$rmm$data$transfer$environment1$notes <-
paste("transfer to", input$xfScenario, "for GCM", input$xfAOGCM)
if (input$xfScenario == "LGM") {
spp[[curSp()]]$rmm$data$transfer$environment1$yearMin <- -21000
spp[[curSp()]]$rmm$data$transfer$environment1$yearMax <- -21000
} else if (input$xfScenario == "Holo") {
spp[[curSp()]]$rmm$data$transfer$environment1$yearMin <- -6000
spp[[curSp()]]$rmm$data$transfer$environment1$yearMax <- -6000
} else {
spp[[curSp()]]$rmm$data$transfer$environment1$yearMin <- 2080
spp[[curSp()]]$rmm$data$transfer$environment1$yearMax <- 2100
}
}
spp[[curSp()]]$rmm$prediction$transfer$environment1$units <-
ifelse(predType == "raw", "relative occurrence rate", predType)
spp[[curSp()]]$rmm$prediction$transfer$environment1$minVal <-
printVecAsis(raster::cellStats(xferTimeThr, min), asChar = TRUE)
spp[[curSp()]]$rmm$prediction$transfer$environment1$maxVal <-
printVecAsis(raster::cellStats(xferTimeThr, max), asChar = TRUE)
if(!(input$threshold == 'none')) {
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdSet <- thr
if (input$threshold == 'qtp') {
spp[[curSp()]]$rmm$code$wallace$transferQuantile <- input$trainPresQuantile
} else {
spp[[curSp()]]$rmm$code$wallace$transferQuantile <- 0
}
} else {
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdSet <- NULL
}
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdRule <- input$threshold
if (!is.null(spp[[curSp()]]$rmm$model$algorithm$maxent$clamping)) {
spp[[curSp()]]$rmm$prediction$transfer$environment1$extrapolation <-
spp[[curSp()]]$rmm$model$algorithm$maxent$clamping
}
spp[[curSp()]]$rmm$prediction$transfer$notes <- NULL
common$update_component(tab = "Map")
})
# Reset Transfer Extent button functionality
observeEvent(input$goResetXfer, {
spp[[curSp()]]$polyXfXY <- NULL
spp[[curSp()]]$polyXfID <- NULL
spp[[curSp()]]$transfer <- NULL
logger %>% writeLog("Reset extent of transfer.")
})
return(list(
save = function() {
list(
xferExt = input$xferExt,
userXfBuf = input$userXfBuf,
drawXfBuf = input$drawXfBuf,
selTimeVar = input$selTimeVar,
selTime = input$selTime,
selRCP = input$selRCP,
xfAOGCM = input$xfAOGCM,
xfScenario = input$xfScenario,
threshold = input$threshold,
trainPresQuantile = input$trainPresQuantile
)
},
load = function(state) {
updateSelectInput(session, 'xferExt', selected = state$xferExt)
updateNumericInput(session, 'userXfBuf', value = state$userXfBuf)
updateNumericInput(session, 'drawXfBuf', value = state$drawXfBuf)
updateSelectInput(session, 'selTime', selected = state$selTime)
updateSelectInput(session, 'selRCP', selected = state$selRCP)
updateSelectInput(session, 'xfAOGCM', selected = state$xfAOGCM)
updateSelectInput(session, 'xfScenario', selected = state$xfScenario)
updateSelectInput(session, 'threshold', selected = state$threshold)
updateSliderInput(session, 'trainPresQuantile', value = state$trainPresQuantile)
}
))
}
xfer_time_module_map <- function(map, common) {
spp <- common$spp
evalOut <- common$evalOut
curSp <- common$curSp
rmm <- common$rmm
mapXfer <- common$mapXfer
# Map logic
map %>% leaflet.extras::addDrawToolbar(
targetGroup = 'draw', polylineOptions = FALSE, rectangleOptions = FALSE,
circleOptions = FALSE, markerOptions = FALSE, circleMarkerOptions = FALSE,
editOptions = leaflet.extras::editToolbarOptions()
)
# Add just transfer Polygon
req(spp[[curSp()]]$transfer$xfExt)
polyXfXY <- spp[[curSp()]]$transfer$xfExt@polygons[[1]]@Polygons
if(length(polyXfXY) == 1) {
shp <- list(polyXfXY[[1]]@coords)
} else {
shp <- lapply(polyXfXY, function(x) x@coords)
}
bb <- spp[[curSp()]]$transfer$xfExt@bbox
bbZoom <- polyZoom(bb[1, 1], bb[2, 1], bb[1, 2], bb[2, 2], fraction = 0.05)
map %>% clearAll() %>% removeImage('xferRas') %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4])
for (poly in shp) {
map %>% addPolygons(lng = poly[, 1], lat = poly[, 2], weight = 4,
color = "red",group = 'bgShp')
}
req(evalOut(), spp[[curSp()]]$transfer$xfEnvs)
mapXferVals <- spp[[curSp()]]$transfer$mapXferVals
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if threshold specified
if(rmm()$prediction$transfer$environment1$thresholdRule != 'none') {
rasPal <- c('gray', 'red')
map %>% removeControl("xfer") %>%
addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')
} else {
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols), mapXferVals, na.color = 'transparent')
rasPal <- colorNumeric(rasCols, mapXferVals, na.color = 'transparent')
map %>% removeControl("xfer") %>%
addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE))
}
# map model prediction raster and transfer polygon
map %>% clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(mapXfer(), colors = rasPal, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb")
for (poly in shp) {
map %>% addPolygons(lng = poly[, 1], lat = poly[, 2], weight = 4,
color = "red", group = 'xfer', fill = FALSE)
}
}
xfer_time_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
xfer_time_knit = !is.null(species$rmm$code$wallace$transfer_time),
curModel_rmd = species$rmm$code$wallace$transfer_curModel,
outputType_rmd = species$rmm$prediction$notes,
alg_rmd = species$rmm$model$algorithms,
clamp_rmd = species$rmm$model$algorithm$maxent$clamping,
##Determine the type of extent of transfer to use correct RMD function
xfer_time_user_knit = !is.null(species$rmm$code$wallace$userXfShpParams),
xfer_time_drawn_knit = !is.null(species$rmm$code$wallace$drawExtPolyXfCoords),
###arguments for creating extent
polyXfXY_rmd = if(!is.null(species$rmm$code$wallace$drawExtPolyXfCoords)){
printVecAsis(species$polyXfXY)} else {NULL},
polyXfID_rmd = if(!is.null(species$rmm$code$wallace$drawExtPolyXfCoords)){
species$polyXfID} else {0},
BgBuf_rmd = species$rmm$code$wallace$XfBuff,
polyXf_rmd = if(is.null(species$rmm$code$wallace$drawExtPolyXfCoords) & is.null(species$rmm$code$wallace$userXfShpParams)){
species$procEnvs$bgExt} else {NULL},
##Use of threshold for transferring
xfer_time_threshold_knit = !is.null(species$rmm$prediction$transfer$environment1$thresholdSet),
xfer_thresholdRule_rmd = species$rmm$prediction$transfer$environment1$thresholdRule,
xfer_threshold_rmd = if (!is.null(species$rmm$prediction$transfer$environment1$thresholdSet)){
species$rmm$prediction$transfer$environment1$thresholdSet} else {0},
xfer_probQuantile_rmd = species$rmm$code$wallace$transferQuantile,
###for guidance text
##name of environmental variables used
envs_name_rmd = species$rmm$data$transfer$environment1$sources,
yearMin_rmd = species$rmm$data$transfer$environment1$yearMin,
yearMax_rmd = species$rmm$data$transfer$environment1$yearMax,
###for getting the right environmental variables
xfer_time_worldclim_knit = !is.null(species$rmm$code$wallace$transfer_worldclim),
model_rmd = if (!is.null(species$rmm$code$wallace$transfer_worldclim)){
species$rmm$code$wallace$transfer_GCM} else {NULL},
rcp_rmd = if (!is.null(species$rmm$code$wallace$transfer_worldclim)){
species$rmm$code$wallace$transfer_RCP} else {0},
year_rmd = if (!is.null(species$rmm$code$wallace$transfer_worldclim)){
species$rmm$code$wallace$transfer_Time} else {0},
xfAOGCM_rmd = if(!is.null(species$rmm$code$wallace$transfer_ecoclimate)){
species$rmm$code$wallace$transfer_AOGCM} else {NULL},
xfScenario_rmd = if(!is.null(species$rmm$code$wallace$transfer_ecoclimate)){
species$rmd$transfer_Scenario} else {NULL}
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_time.R
|
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to the same modelling area with no threshold rule. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} using a "{{model_rmd}}" GCM and an RCP of *`r {{rcp_rmd}}/10`*.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
#Download variables for transferring
xferTimeEnvs_{{spAbr}} <- raster::getData(
'CMIP5',
var = "bio",
res = round((raster::res(bgMask_{{spAbr}}) * 60)[1],1),
rcp = {{rcp_rmd}},
model = "{{model_rmd}}",
year = {{year_rmd}})
names(xferTimeEnvs_{{spAbr}}) <- paste0('bio', c(paste0('0',1:9), 10:19))
# Select variables for transferring to match variables used for modelling
xferTimeEnvs_{{spAbr}} <- xferTimeEnvs_{{spAbr}}[[names(bgMask_{{spAbr}})]]
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = bgExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}}$xferTime,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}$xferTime, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (same modeling area)
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to the same modelling area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} using a "{{model_rmd}}" GCM and an RCP of *`r {{rcp_rmd}}/10`*.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
#Download variables for transferring
xferTimeEnvs_{{spAbr}} <- raster::getData(
'CMIP5',
var = "bio",
res = round((raster::res(bgMask_{{spAbr}}) * 60)[1],1),
rcp = {{rcp_rmd}},
model = "{{model_rmd}}",
year = {{year_rmd}})
names(xferTimeEnvs_{{spAbr}}) <- paste0('bio', c(paste0('0',1:9), 10:19))
# Select variables for transferring to match variables used for modelling
xferTimeEnvs_{{spAbr}} <- xferTimeEnvs_{{spAbr}}[[names(bgMask_{{spAbr}})]]
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = bgExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Add threshold if specified
xfer_time_{{spAbr}} <- xfer_time_{{spAbr}}$xferTime > xfer_thresProb_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (same modeling area)
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user drawn area with no threshold. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} using a "{{model_rmd}}" GCM and an RCP of *`r {{rcp_rmd}}/10`*.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
#Download variables for transferring
xferTimeEnvs_{{spAbr}} <- raster::getData(
'CMIP5',
var = "bio",
res = round((raster::res(bgMask_{{spAbr}}) * 60)[1],1),
rcp = {{rcp_rmd}},
model = "{{model_rmd}}",
year = {{year_rmd}})
names(xferTimeEnvs_{{spAbr}}) <- paste0('bio', c(paste0('0',1:9), 10:19))
# Select variables for transferring to match variables used for modelling
xferTimeEnvs_{{spAbr}} <- xferTimeEnvs_{{spAbr}}[[names(bgMask_{{spAbr}})]]
# Generate the area of transfer according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <-xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}}, ncol = 2, byrow = FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_draw_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
#store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}}$xferTime,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}$xferTime, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user drawn area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} using a "{{model_rmd}}" GCM and an RCP of *`r {{rcp_rmd}}/10`*.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
#Download variables for transferring
xferTimeEnvs_{{spAbr}} <- raster::getData(
'CMIP5',
var = "bio",
res = round((raster::res(bgMask_{{spAbr}}) * 60)[1],1),
rcp = {{rcp_rmd}},
model = "{{model_rmd}}",
year = {{year_rmd}})
names(xferTimeEnvs_{{spAbr}}) <- paste0('bio', c(paste0('0',1:9), 10:19))
# Select variables for transferring to match variables used for modelling
xferTimeEnvs_{{spAbr}} <- xferTimeEnvs_{{spAbr}}[[names(bgMask_{{spAbr}})]]
# Generate the area of transfer according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <-xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}},ncol=2,byrow=FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_draw_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Add threshold if specified
xfer_time_{{spAbr}} <- xfer_time_{{spAbr}}$xferTime > xfer_thresProb_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer') %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user provided area area with no threshold. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} using a "{{model_rmd}}" GCM and an RCP of *`r {{rcp_rmd}}/10`*.
```
```{r, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
# Download variables for transferring
xferTimeEnvs_{{spAbr}} <- raster::getData(
'CMIP5',
var = "bio",
res = round((raster::res(bgMask_{{spAbr}}) * 60)[1],1),
rcp = {{rcp_rmd}},
model = "{{model_rmd}}",
year = {{year_rmd}})
names(xferTimeEnvs_{{spAbr}}) <- paste0('bio', c(paste0('0',1:9), 10:19))
# Select variables for transferring to match variables used for modelling
xferTimeEnvs_{{spAbr}} <- xferTimeEnvs_{{spAbr}}[[names(bgMask_{{spAbr}})]]
# Generate the area of transfer based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_userExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}}$xferTime,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}},
na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}},
na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}$xferTime, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user provided area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} using a "{{model_rmd}}" GCM and an RCP of *`r {{rcp_rmd}}/10`*.
```
```{r, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & xfer_time_worldclim_knit}}}
# Download variables for transferring from Worldclim
xferTimeEnvs_{{spAbr}} <- raster::getData(
'CMIP5',
var = "bio",
res = round((raster::res(bgMask_{{spAbr}}) * 60)[1],1),
rcp = {{rcp_rmd}},
model = "{{model_rmd}}",
year = {{year_rmd}})
names(xferTimeEnvs_{{spAbr}}) <- paste0('bio', c(paste0('0',1:9), 10:19))
# Select variables for transferring to match variables used for modelling
xferTimeEnvs_{{spAbr}} <- xferTimeEnvs_{{spAbr}}[[names(bgMask_{{spAbr}})]]
# Generate the area of transfer based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_userExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Add threshold if specified
xfer_time_{{spAbr}} <- xfer_time_{{spAbr}}$xferTime > xfer_thresProb_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to the same modelling area with no threshold rule. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} to {{yearMax_rmd}} using a "{{xfAOGCM_rmd}}" GCM and a "{{xfScenario_rmd}}" scenario.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
#Download data from ecoClimate for transferring
xferTimeEnvs_{{spAbr}} <- envs_ecoClimate(
"{{xfAOGCM_rmd}}",
"{{xfScenario_rmd}}",
as.numeric(gsub("bio", "", names(bgMask_{{spAbr}}))))
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}} ,
xfExt = bgExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
#store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}}$xferTime,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}},
na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}},
na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}$xferTime, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (same modeling area)
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to the same modelling area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} to {{yearMax_rmd}} using a "{{xfAOGCM_rmd}}" GCM and a "{{xfScenario_rmd}}" scenario.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
#Download data from ecoClimate for transferring
xferTimeEnvs_{{spAbr}} <- envs_ecoClimate(
"{{xfAOGCM_rmd}}",
"{{xfScenario_rmd}}",
as.numeric(gsub("bio", "", names(bgMask_{{spAbr}}))))
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}} ,
xfExt = bgExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Add threshold if specified
xfer_time_{{spAbr}} <- xfer_time_{{spAbr}}$xferTime > xfer_thresProb_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer') %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (same modeling area)
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user drawn area with no threshold rule. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} to {{yearMax_rmd}} using a "{{xfAOGCM_rmd}}" GCM and a "{{xfScenario_rmd}}" scenario.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
#Download data from ecoClimate for transferring
xferTimeEnvs_{{spAbr}} <- envs_ecoClimate(
"{{xfAOGCM_rmd}}",
"{{xfScenario_rmd}}",
as.numeric(gsub("bio", "", names(bgMask_{{spAbr}}))))
# Generate the area of transfer according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <-xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}},ncol=2,byrow=FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_draw_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# Store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}}$xferTime,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}$xferTime, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user drawn area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} to {{yearMax_rmd}} using a "{{xfAOGCM_rmd}}" GCM and a "{{xfScenario_rmd}}" scenario.
```
```{r, echo = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & !xfer_time_user_knit & xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
#Download data from ecoClimate for transferring
xferTimeEnvs_{{spAbr}} <- envs_ecoClimate(
"{{xfAOGCM_rmd}}",
"{{xfScenario_rmd}}",
as.numeric(gsub("bio", "", names(bgMask_{{spAbr}}))))
# Generate the area of transfer according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <-xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}},ncol=2,byrow=FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_draw_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Add threshold if specified
xfer_time_{{spAbr}} <- xfer_time_{{spAbr}}$xferTime > xfer_thresProb_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user provided area with no threshold rule. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} to {{yearMax_rmd}} using a "{{xfAOGCM_rmd}}" GCM and a "{{xfScenario_rmd}}" scenario.
```
```{r, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & !xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
#Download data from ecoClimate for transferring
xferTimeEnvs_{{spAbr}} <- envs_ecoClimate(
"{{xfAOGCM_rmd}}",
"{{xfScenario_rmd}}",
as.numeric(gsub("bio", "", names(bgMask_{{spAbr}}))))
# Generate the area of transfer based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_userExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}}$xferTime,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}},
na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}},
na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}$xferTime, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, eval = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
### Transfer model
Transferring the model to a user provided area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. New time based on "{{envs_name_rmd}}" variables for {{yearMin_rmd}} to {{yearMax_rmd}} using a "{{xfAOGCM_rmd}}" GCM and a "{{xfScenario_rmd}}" scenario.
```
```{r, echo = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}, include = {{xfer_time_knit & xfer_time_user_knit & !xfer_time_drawn_knit & xfer_time_threshold_knit & !xfer_time_worldclim_knit}}}
#Download data from ecoClimate for transferring
xferTimeEnvs_{{spAbr}} <- envs_ecoClimate(
"{{xfAOGCM_rmd}}",
"{{xfScenario_rmd}}",
as.numeric(gsub("bio", "", names(bgMask_{{spAbr}}))))
# Generate the area of transfer based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Generate a transfer of the model to the desired area and time
xfer_time_{{spAbr}} <-xfer_time(
evalOut = model_{{spAbr}},
curModel = "{{curModel_rmd}}",
envs = xferTimeEnvs_{{spAbr}},
xfExt = xfer_userExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_time_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Add threshold if specified
xfer_time_{{spAbr}} <- xfer_time_{{spAbr}}$xferTime > xfer_thresProb_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_time_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_time_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_time.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# xfer_user.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
xfer_user_module_ui <- function(id) {
ns <- shiny::NS(id)
tagList(
span("Step 1:", class = "step"),
span("Choose Study Region", class = "stepText"), br(), br(),
selectInput(ns('xferExt'), label = "Select method",
choices = list("Draw polygon" = 'xfDraw',
"Same extent" = 'xfCur',
"User-specified polygon" = 'xfUser')),
conditionalPanel(sprintf("input['%s'] == 'xfUser'", ns("xferExt")),
fileInput(
ns("userXfShp"),
label = paste0(
'Upload polygon in shapefile (.shp, .shx, .dbf) or ',
'CSV file with field order (longitude, latitude)'),
accept = c(".csv", ".dbf", ".shx", ".shp"),
multiple = TRUE),
tags$div(
title = paste0(
'Buffer area in degrees (1 degree = ~111 km). Exact',
' length varies based on latitudinal position.'),
numericInput(ns("userXfBuf"),
label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5)
)),
conditionalPanel(sprintf("input['%s'] == 'xfDraw'", ns("xferExt")),
p("Draw a polygon and select buffer distance"),
tags$div(
title = paste0(
'Buffer area in degrees (1 degree = ~111 km). Exact',
' length varies based on latitudinal position.'
),
numericInput(
ns("drawXfBuf"),
label = "Study region buffer distance (degree)",
value = 0, min = 0, step = 0.5)
)),
conditionalPanel(sprintf("input['%s'] == 'xfCur'", ns("xferExt")),
p('You will use the same extent')),
actionButton(ns("goXferExtUser"), "Create"), br(),
tags$hr(class = "hrDotted"),
span("Step 2:", class = "step"),
span("Transfer", class = "stepText"), br(),
p("Transfer model to extent of transfer (red) "),
uiOutput(ns("xferUserNames")),
fileInput(ns("userXferEnvs"),
label = paste0('Input rasters in single-file format (i.e. .tif, ',
'.asc). All rasters must have the same extent and ',
'resolution (cell size).'),
accept = c(".asc", ".tif"), multiple = TRUE),
tags$div(title = paste0('Create binary map of predicted presence/absence ',
'assuming all values above threshold value represent ',
'presence. Also can be interpreted as a "potential ',
'distribution" (see guidance).'),
selectInput(ns('threshold'), label = "Set threshold",
choices = list("No threshold" = 'none',
"Minimum Training Presence" = 'mtp',
"10 Percentile Training Presence" = 'p10',
"Quantile of Training Presences" = 'qtp'))),
conditionalPanel(sprintf("input['%s'] == 'qtp'", ns("threshold")),
sliderInput(ns("trainPresQuantile"), "Set quantile",
min = 0, max = 1, value = .05)),
conditionalPanel(paste0("input['", ns("threshold"), "'] == 'none'"),
uiOutput(ns("noThrs"))),
actionButton(ns('goTransferUser'), "Transfer"),
tags$hr(class = "hrDashed"),
actionButton(ns("goResetXfer"), "Reset", class = 'butReset'),
strong(" extent of transfer")
)
}
xfer_user_module_server <- function(input, output, session, common) {
spp <- common$spp
evalOut <- common$evalOut
envs <- common$envs
envs.global <- common$envs.global
rmm <- common$rmm
curSp <- common$curSp
curModel <- common$curModel
logger <- common$logger
output$noThrs <- renderUI({
ns <- session$ns
req(curSp(), evalOut())
if (spp[[curSp()]]$rmm$model$algorithms != "BIOCLIM") {
h5("Prediction output is the same than Visualize component")
}
})
# Render a text with filenames for user-specified rasters of transfer
output$xferUserNames <- renderUI({
req(curSp())
sp <- curSp()[1]
if(is.null(spp[[sp]]$envs)) return()
envNames <- names(envs.global[[spp[[sp]]$envs]])
tagList(
tags$em("Your files must be named as: "),
tags$p(paste(spp[[curSp()]]$rmm$data$environment$variableNames,
collapse = ", "))
)
})
observeEvent(input$goXferExtUser, {
# ERRORS ####
if (is.null(spp[[curSp()]]$visualization$mapPred)) {
logger %>%
writeLog(
type = 'error',
'Calculate a model prediction in model component before transferring.'
)
return()
}
if (input$xferExt == 'xfDraw') {
if (is.null(spp[[curSp()]]$polyXfXY)) {
logger %>%
writeLog(
type = 'error',
paste0("The polygon has not been drawn and finished. Please use the ",
"draw toolbar on the left-hand of the map to complete the ",
"polygon.")
)
return()
}
}
if (input$xferExt == 'xfUser') {
if (is.null(input$userXfShp$datapath)) {
logger %>% writeLog(type = 'error', paste0("Specified filepath(s)"))
return()
}
}
# FUNCTION CALL ####
if (input$xferExt == 'xfDraw') {
polyXf <- xfer_draw(spp[[curSp()]]$polyXfXY, spp[[curSp()]]$polyXfID,
input$drawXfBuf, logger, spN = curSp())
if (input$drawXfBuf == 0 ) {
logger %>% writeLog(
hlSpp(curSp()), 'Draw polygon without buffer.')
} else {
logger %>% writeLog(
hlSpp(curSp()), 'Draw polygon with buffer of ', input$drawXfBuf,
' degrees.')
}
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$XfBuff <- input$drawXfBuf
polyX <- printVecAsis(round(spp[[curSp()]]$polyXfXY[, 1], digits = 4))
polyY <- printVecAsis(round(spp[[curSp()]]$polyXfXY[, 2], digits = 4))
spp[[curSp()]]$rmm$code$wallace$drawExtPolyXfCoords <-
paste0('X: ', polyX, ', Y: ', polyY)
}
if (input$xferExt == 'xfUser') {
polyXf <- xfer_userExtent(input$userXfShp$datapath, input$userXfShp$name,
input$userXfBuf, logger, spN = curSp())
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$XfBuff <- input$userXfBuf
# get extensions of all input files
exts <- sapply(strsplit(input$userXfShp$name, '\\.'),
FUN = function(x) x[2])
if('csv' %in% exts) {
spp[[curSp()]]$rmm$code$wallace$userXfExt <- 'csv'
spp[[curSp()]]$rmm$code$wallace$userXfPath <- input$userXfShp$datapath
}
else if('shp' %in% exts) {
spp[[curSp()]]$rmm$code$wallace$userXfExt <- 'shp'
# get index of .shp
i <- which(exts == 'shp')
shpName <- strsplit(input$userXfShp$name[i], '\\.')[[1]][1]
spp[[curSp()]]$rmm$code$wallace$userXfShpParams <-
list(dsn = input$userXfShp$datapath[i], layer = shpName)
}
}
if (input$xferExt == 'xfCur') {
polyXf <- spp[[curSp()]]$procEnvs$bgExt
logger %>% writeLog(
hlSpp(curSp()),
'Extent of transfer equal to current extent region.')
}
# LOAD INTO SPP ####
spp[[curSp()]]$transfer$xfExt <- polyXf
common$update_component(tab = "Map")
})
observeEvent(input$goTransferUser, {
# ERRORS ####
if (is.null(spp[[curSp()]]$visualization$mapPred)) {
logger %>%
writeLog(type = 'error',
'Calculate a model prediction in visualize component before transferring.')
return()
}
if (is.null(spp[[curSp()]]$transfer$xfExt)) {
logger %>% writeLog(type = 'error', 'Select extent of transfer first.')
return()
}
if (is.null(input$userXferEnvs)) {
logger %>% writeLog(type = 'error', "Raster files not uploaded.")
return()
}
# Check the number of selected files
if (length(input$userXferEnvs$name) !=
length(spp[[curSp()]]$rmm$data$environment$variableNames)) {
logger %>%
writeLog(type = 'error', "Number of files are not the same that the ",
"enviromental variables")
return()
}
# Check if the filesnames are the same that envs()
if (!identical(tools::file_path_sans_ext(sort(input$userXferEnvs$name)),
sort(spp[[curSp()]]$rmm$data$environment$variableNames))) {
logger %>%
writeLog(type = 'error',
paste0("Raster files don't have same names. You must name your",
" files as: "),
em(paste(spp[[curSp()]]$rmm$data$environment$variableNames,
collapse = ", ")), ".")
return()
}
# Load raster ####
userXferEnvs <- envs_userEnvs(rasPath = input$userXferEnvs$datapath,
rasName = input$userXferEnvs$name)
# ERRORS ####
# Check that the extents of raster and extent of transfer intersects
Xfer_sfc <- sf::st_as_sfc(spp[[curSp()]]$transfer$xfExt) #convert poly to sfc
userXferEnvs_sp <- methods::as(raster::extent(userXferEnvs),'SpatialPolygons')
userXferEnvs_sfc <- sf::st_as_sfc(userXferEnvs_sp) #convert user envs to sfc
if (!sf::st_intersects(Xfer_sfc, userXferEnvs_sfc, sparse = FALSE)[1,1]) {
logger %>%
writeLog(type = 'error', 'Extents do not overlap.')
return()
}
# FUNCTION CALL ####
predType <- rmm()$prediction$notes
if (spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
xferUser.out <- xfer_userEnvs(evalOut = evalOut(),
curModel = curModel(),
envs = userXferEnvs,
xfExt = spp[[curSp()]]$transfer$xfExt,
alg = spp[[curSp()]]$rmm$model$algorithms,
logger,
spN = curSp())
} else {
xferUser.out <- xfer_userEnvs(evalOut = evalOut(),
curModel = curModel(),
envs = userXferEnvs,
xfExt = spp[[curSp()]]$transfer$xfExt,
alg = spp[[curSp()]]$rmm$model$algorithms,
outputType = predType,
clamp = rmm()$model$algorithm$maxent$clamping,
logger,
spN = curSp())
}
xferExt <- xferUser.out$xferExt
xferUser <- xferUser.out$xferUser
# PROCESSING ####
# generate binary prediction based on selected thresholding rule
# (same for all Maxent prediction types because they scale the same)
occPredVals <- spp[[curSp()]]$visualization$occPredVals
if(!(input$threshold == 'none')) {
if (input$threshold == 'mtp') {
thr <- stats::quantile(occPredVals, probs = 0)
} else if (input$threshold == 'p10') {
thr <- stats::quantile(occPredVals, probs = 0.1)
} else if (input$threshold == 'qtp'){
thr <- stats::quantile(occPredVals, probs = input$trainPresQuantile)
}
xferUserThr <- xferUser > thr
logger %>% writeLog(
hlSpp(curSp()), "Transferring of model to user-specified files",
'with threshold ', input$threshold, ' (',
formatC(thr, format = "e", 2), ').')
} else {
xferUserThr <- xferUser
logger %>% writeLog(hlSpp(curSp()), "Transferring of model to user-specified files",
'with ', predType, ' output.')
}
raster::crs(xferUserThr) <- raster::crs(envs())
# rename
names(xferUserThr) <- paste0(curModel(), '_thresh_', predType)
# LOAD INTO SPP ####
spp[[curSp()]]$transfer$xfEnvs <- xferExt
spp[[curSp()]]$transfer$mapXfer <- xferUserThr
spp[[curSp()]]$transfer$mapXferVals <- getRasterVals(xferUserThr, predType)
# METADATA ####
spp[[curSp()]]$rmm$code$wallace$transfer_curModel <- curModel()
spp[[curSp()]]$rmd$transfer_user <-TRUE
spp[[curSp()]]$rmm$data$transfer$environment1$minVal <-
printVecAsis(raster::cellStats(xferExt, min), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$maxVal <-
printVecAsis(raster::cellStats(xferExt, max), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$resolution <-
paste(round(raster::res(xferExt)[1] * 60, digits = 2), "degrees")
spp[[curSp()]]$rmm$data$transfer$environment1$extentSet <-
printVecAsis(as.vector(xferExt@extent), asChar = TRUE)
spp[[curSp()]]$rmm$data$transfer$environment1$extentRule <-
"transfer to user-specified files"
spp[[curSp()]]$rmm$data$transfer$environment1$sources <- "user"
spp[[curSp()]]$rmm$prediction$transfer$environment1$units <-
ifelse(predType == "raw", "relative occurrence rate", predType)
spp[[curSp()]]$rmm$prediction$transfer$environment1$minVal <-
printVecAsis(raster::cellStats(xferUserThr, min), asChar = TRUE)
spp[[curSp()]]$rmm$prediction$transfer$environment1$maxVal <-
printVecAsis(raster::cellStats(xferUserThr, max), asChar = TRUE)
if(!(input$threshold == 'none')) {
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdSet <- thr
if (input$threshold == 'qtp') {
spp[[curSp()]]$rmm$code$wallace$transferQuantile <- input$trainPresQuantile
} else {
spp[[curSp()]]$rmm$code$wallace$transferQuantile <- 0
}
} else {
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdSet <- NULL
}
spp[[curSp()]]$rmm$prediction$transfer$environment1$thresholdRule <- input$threshold
if (!is.null(spp[[curSp()]]$rmm$model$algorithm$maxent$clamping)) {
spp[[curSp()]]$rmm$prediction$transfer$environment1$extrapolation <-
spp[[curSp()]]$rmm$model$algorithm$maxent$clamping
}
spp[[curSp()]]$rmm$prediction$transfer$notes <- NULL
spp[[curSp()]]$rmm$code$wallace$userXfName <- input$userXferEnvs$name
})
# Reset extent of transfer button functionality
observeEvent(input$goResetXfer, {
spp[[curSp()]]$polyXfXY <- NULL
spp[[curSp()]]$polyXfID <- NULL
spp[[curSp()]]$transfer <- NULL
logger %>% writeLog("Reset extent of transfer.")
})
return(list(
save = function() {
list(
xferExt = input$xferExt,
userXfBuf = input$userXfBuf,
drawXfBuf = input$drawXfBuf,
threshold = input$threshold,
trainPresQuantile = input$trainPresQuantile
)
},
load = function(state) {
updateSelectInput(session, 'xferExt', selected = state$xferExt)
updateNumericInput(session, 'userXfBuf', value = state$userXfBuf)
updateNumericInput(session, 'drawXfBuf', value = state$drawXfBuf)
updateSelectInput(session, 'threshold', selected = state$threshold)
updateSliderInput(session, 'trainPresQuantile', value = state$trainPresQuantile)
}
))
}
xfer_user_module_map <- function(map, common) {
spp <- common$spp
evalOut <- common$evalOut
curSp <- common$curSp
rmm <- common$rmm
mapXfer <- common$mapXfer
# Map logic
map %>% leaflet.extras::addDrawToolbar(
targetGroup = 'draw', polylineOptions = FALSE, rectangleOptions = FALSE,
circleOptions = FALSE, markerOptions = FALSE, circleMarkerOptions = FALSE,
editOptions = leaflet.extras::editToolbarOptions()
)
# Add just Polygon of transfer
req(spp[[curSp()]]$transfer$xfExt)
polyXfXY <- spp[[curSp()]]$transfer$xfExt@polygons[[1]]@Polygons
if(length(polyXfXY) == 1) {
shp <- list(polyXfXY[[1]]@coords)
} else {
shp <- lapply(polyXfXY, function(x) x@coords)
}
bb <- spp[[curSp()]]$transfer$xfExt@bbox
bbZoom <- polyZoom(bb[1, 1], bb[2, 1], bb[1, 2], bb[2, 2], fraction = 0.05)
map %>% clearAll() %>% removeImage('xferRas') %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4])
for (poly in shp) {
map %>% addPolygons(lng = poly[, 1], lat = poly[, 2], weight = 4,
color = "red",group = 'bgShp')
}
req(evalOut(), spp[[curSp()]]$transfer$xfEnvs)
mapXferVals <- spp[[curSp()]]$transfer$mapXferVals
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
if(rmm()$prediction$transfer$environment1$thresholdRule != 'none') {
rasPal <- c('gray', 'red')
map %>% removeControl("xfer") %>%
addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')
} else {
# if threshold specified
legendPal <- colorNumeric(rev(rasCols), mapXferVals, na.color = 'transparent')
rasPal <- colorNumeric(rasCols, mapXferVals, na.color = 'transparent')
map %>% removeControl("xfer") %>%
addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE))
}
# map model prediction raster and polygon of transfer
map %>% clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(mapXfer(), colors = rasPal, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb")
for (poly in shp) {
map %>% addPolygons(lng = poly[, 1], lat = poly[, 2], weight = 4,
color = "red", group = 'xfer', fill = FALSE)
}
}
xfer_user_module_rmd <- function(species) {
# Variables used in the module's Rmd code
list(
xfer_user_knit = !is.null(species$rmd$transfer_user),
curModel_rmd = species$rmm$code$wallace$transfer_curModel,
outputType_rmd = species$rmm$prediction$notes,
alg_rmd = species$rmm$model$algorithms,
clamp_rmd = species$rmm$model$algorithm$maxent$clamping,
userXfName_rmd = printVecAsis(species$rmm$code$wallace$userXfName),
##Use of threshold for transferring
xfer_user_threshold_knit = !is.null(species$rmm$prediction$transfer$environment1$thresholdSet),
xfer_thresholdRule_rmd = species$rmm$prediction$transfer$environment1$thresholdRule,
xfer_threshold_rmd = if (!is.null(species$rmm$prediction$transfer$environment1$thresholdSet)){
species$rmm$prediction$transfer$environment1$thresholdSet} else {0},
xfer_probQuantile_rmd = species$rmm$code$wallace$transferQuantile,
##Determine the type of extent of transfer to use correct RMD function
xfer_user_user_knit = !is.null(species$rmm$code$wallace$userXfShpParams),
xfer_user_drawn_knit = !is.null(species$rmm$code$wallace$drawExtPolyXfCoords),
###arguments for creating extent
polyXfXY_rmd = if(!is.null(species$rmm$code$wallace$drawExtPolyXfCoords)){
printVecAsis(species$polyXfXY)} else {NULL},
polyXfID_rmd = if(!is.null(species$rmm$code$wallace$drawExtPolyXfCoords)){
species$polyXfID} else {0},
BgBuf_rmd = species$rmm$code$wallace$XfBuff,
polyXf_rmd = if(is.null(species$rmm$code$wallace$drawExtPolyXfCoords) & is.null(species$rmm$code$wallace$userXfShpParams)){
species$procEnvs$bgExt} else {NULL}
)
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_user.R
|
```{asis, echo = {{xfer_user_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}, eval = {{xfer_user_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}, include = {{xfer_user_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}}
### Transfer model
Transferring the model to the same modelling area with no threshold rule. Environmental layers for transferring are user provided.
```
```{r, echo = {{xfer_user_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}, include = {{xfer_user_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}}
## Specify the directory with the environmental variables
dir_envsXf_{{spAbr}} <- ""
envsXf_path <- file.path(dir_envsXf_{{spAbr}}, {{userXfName_rmd}})
# Load user environmental variables
xferUserEnvs_{{spAbr}} <- envs_userEnvs(
rasPath = envsXf_path,
rasName = {{userXfName_rmd}}
)
# Transfer model
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs(
evalOut = model_{{spAbr}},
curModel= "{{curModel_rmd}}",
envs = xferUserEnvs_{{spAbr}} ,
xfExt = bgExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_userEnvs_{{spAbr}}$xferUser, "{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_userEnvs_{{spAbr}}$xferUser, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (same modeling area)
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_user_knit & xfer_user_threshold_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}, eval = {{xfer_user_knit & xfer_user_threshold_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}, include = {{xfer_user_knit & xfer_user_threshold_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}}
### Transfer model
Transferring the model to the same modelling area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. Environmental layers for transferring are user provided.
```
```{r, echo = {{xfer_user_knit & xfer_user_threshold_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}, include = {{xfer_user_knit & xfer_user_threshold_knit & !xfer_user_user_knit & !xfer_user_drawn_knit}}}
## Specify the directory with the environmental variables
dir_envsXf_{{spAbr}} <- ""
envsXf_path <- file.path(dir_envsXf_{{spAbr}}, {{userXfName_rmd}})
# Load user environmental variables
xferUserEnvs_{{spAbr}} <- envs_userEnvs(
rasPath = envsXf_path,
rasName = {{userXfName_rmd}}
)
# Transfer model
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs(
evalOut = model_{{spAbr}},
curModel= "{{curModel_rmd}}",
envs = xferUserEnvs_{{spAbr}} ,
xfExt = bgExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Define threshold value
xfer_thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}},
probs = xfer_thresProb_{{spAbr}})
# Add threshold if specified
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferUser > xfer_thres_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_userEnvs_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_userEnvs_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (same modeling area)
addPolygons(data = bgExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit}}, eval = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit}}, include = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit }}}
### Transfer model
Transferring the model to a user drawn area with no threshold rule. Environmental layers for transferring are user provided.
```
```{r, echo = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit}}, include = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit}}}
## Specify the directory with the environmental variables
dir_envsXf_{{spAbr}} <- ""
envsXf_path <- file.path(dir_envsXf_{{spAbr}}, {{userXfName_rmd}})
# Load user environmental variables
xferUserEnvs_{{spAbr}} <- envs_userEnvs(
rasPath = envsXf_path,
rasName = {{userXfName_rmd}}
)
# Generate the area of transfer according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <- xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}}, ncol = 2, byrow = FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Transfer model
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs(
evalOut = model_{{spAbr}},
curModel= "{{curModel_rmd}}",
envs = xferUserEnvs_{{spAbr}} ,
xfExt = xfer_draw_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
#store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals( xfer_userEnvs_{{spAbr}}$xferUser,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_userEnvs_{{spAbr}}$xferUser, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit & xfer_user_threshold_knit}}, eval = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit & xfer_user_threshold_knit}}, include = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit & xfer_user_threshold_knit }}}
### Transfer model
Transferring the model to a user drawn area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. Environmental layers for transferring are user provided.
```
```{r, echo = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit & xfer_user_threshold_knit}}, include = {{xfer_user_knit & !xfer_user_user_knit & xfer_user_drawn_knit & xfer_user_threshold_knit}}}
## Specify the directory with the environmental variables
dir_envsXf_{{spAbr}} <- ""
envsXf_path <- file.path(dir_envsXf_{{spAbr}}, {{userXfName_rmd}})
# Load user environmental variables
xferUserEnvs_{{spAbr}} <- envs_userEnvs(
rasPath = envsXf_path,
rasName = {{userXfName_rmd}}
)
# Generate the area of transfer according to the drawn polygon in the GUI
xfer_draw_{{spAbr}} <-xfer_draw(
polyXfXY = matrix({{polyXfXY_rmd}}, ncol = 2, byrow = FALSE),
polyXfID = {{polyXfID_rmd}},
drawXfBuf = {{BgBuf_rmd}})
# Transfer model
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs(
evalOut = model_{{spAbr}},
curModel= "{{curModel_rmd}}",
envs = xferUserEnvs_{{spAbr}} ,
xfExt = xfer_draw_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Define threshold value
xfer_thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}},
probs = xfer_thresProb_{{spAbr}})
# Add threshold if specified
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferUser > xfer_thres_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_userEnvs_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_userEnvs_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user drawn area)
addPolygons(data = xfer_draw_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit}}, eval = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit}}, include = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit }}}
### Transfer model
Transferring the model to a user provided area with no threshold rule. Environmental layers for transferring are user provided.
```
```{r, echo = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit}}, include = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit}}}
## Specify the directory with the environmental variables
dir_envsXf_{{spAbr}} <- ""
envsXf_path <- file.path(dir_envsXf_{{spAbr}}, {{userXfName_rmd}})
# Load user environmental variables
xferUserEnvs_{{spAbr}} <- envs_userEnvs(
rasPath = envsXf_path,
rasName = {{userXfName_rmd}}
)
# Generate the area of transfer based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Transfer model
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs(
evalOut = model_{{spAbr}},
curModel= "{{curModel_rmd}}",
envs = xferUserEnvs_{{spAbr}} ,
xfExt = xfer_userExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferExt
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_userEnvs_{{spAbr}}$xferUser,"{{outputType_rmd}}")
rasCols_{{spAbr}} <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
# if no threshold specified
legendPal <- colorNumeric(rev(rasCols_{{spAbr}}), mapXferVals_{{spAbr}}, na.color = 'transparent')
rasPal_{{spAbr}} <- colorNumeric(rasCols_{{spAbr}}, mapXferVals_{{spAbr}}, na.color = 'transparent')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", pal = legendPal,
title = "Predicted Suitability<br>(Transferred)",
values = mapXferVals_{{spAbr}}, layerId = 'xfer',
labFormat = reverseLabel(2, reverse_order = TRUE)) %>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_userEnvs_{{spAbr}}$xferUser, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
```{asis, echo = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit & xfer_user_threshold_knit}}, eval = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit & xfer_user_threshold_knit}}, include = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit & xfer_user_threshold_knit }}}
### Transfer model
Transferring the model to a user provided area with a "{{xfer_thresholdRule_rmd}}" threshold rule of {{xfer_threshold_rmd}}. Environmental layers for transferring are user provided.
```
```{r, echo = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit & xfer_user_threshold_knit}}, include = {{xfer_user_knit & xfer_user_user_knit & !xfer_user_drawn_knit & xfer_user_threshold_knit}}}
## Specify the directory with the environmental variables
dir_envsXf_{{spAbr}} <- ""
envsXf_path <- file.path(dir_envsXf_{{spAbr}}, {{userXfName_rmd}})
# Load user environmental variables
xferUserEnvs_{{spAbr}} <- envs_userEnvs(
rasPath = envsXf_path,
rasName = {{userXfName_rmd}}
)
# Generate the area of transfer based on user provided files
##User must input the path to shapefile or csv file and the file name
xfer_userExt_{{spAbr}} <- xfer_userExtent(
bgShp_path = "Input path here",
bgShp_name = "Input file name here",
userBgBuf = {{BgBuf_rmd}})
# Transfer model
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs(
evalOut = model_{{spAbr}},
curModel= "{{curModel_rmd}}",
envs = xferUserEnvs_{{spAbr}} ,
xfExt = xfer_userExt_{{spAbr}},
alg = "{{alg_rmd}}",
outputType = "{{outputType_rmd}}",
clamp = {{clamp_rmd}}
)
# store the cropped variables of transfer
xferExt_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferExt
# extract the suitability values for all occurrences
occs_xy_{{spAbr}} <- occs_{{spAbr}}[c('longitude', 'latitude')]
# determine the threshold based on the current prediction
occPredVals_{{spAbr}} <- raster::extract(predSel_{{spAbr}}, occs_xy_{{spAbr}})
# Define probability of quantile based on selected threshold
xfer_thresProb_{{spAbr}} <- switch("{{xfer_thresholdRule_rmd}}",
"mtp" = 0, "p10" = 0.1, "qtp" = {{xfer_probQuantile_rmd}})
# Define threshold value
xfer_thres_{{spAbr}} <- stats::quantile(occPredVals_{{spAbr}},
probs = xfer_thresProb_{{spAbr}})
# Add threshold if specified
xfer_userEnvs_{{spAbr}} <- xfer_userEnvs_{{spAbr}}$xferUser > xfer_thres_{{spAbr}}
##Make map
###Make map of transfer
bb_{{spAbr}} <- bgExt_{{spAbr}}@bbox
bbZoom <- polyZoom(bb_{{spAbr}}[1, 1], bb_{{spAbr}}[2, 1], bb_{{spAbr}}[1, 2],
bb_{{spAbr}}[2, 2], fraction = 0.05)
mapXferVals_{{spAbr}} <- getRasterVals(xfer_userEnvs_{{spAbr}},"{{outputType_rmd}}")
# if threshold specified
rasPal_{{spAbr}} <- c('gray', 'red')
m <- leaflet() %>% addProviderTiles(providers$Esri.WorldTopoMap)
m %>%
fitBounds(bbZoom[1], bbZoom[2], bbZoom[3], bbZoom[4]) %>%
leaflet::addLegend("bottomright", colors = c('gray', 'red'),
title = "Thresholded Suitability<br>(Transferred)",
labels = c("predicted absence", "predicted presence"),
opacity = 1, layerId = 'xfer')%>%
# map model prediction raster and polygon of transfer
clearMarkers() %>% clearShapes() %>% removeImage('xferRas') %>%
addRasterImage(xfer_userEnvs_{{spAbr}}, colors = rasPal_{{spAbr}}, opacity = 0.7,
layerId = 'xferRas', group = 'xfer', method = "ngb") %>%
##add polygon of transfer (user provided area)
addPolygons(data = xfer_userExt_{{spAbr}}, fill = FALSE,
weight = 4, color = "blue", group = 'xfer')
```
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/modules/xfer_user.Rmd
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# server.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
function(input, output, session) {
########################## #
# REACTIVE VALUES LISTS ####
########################## #
# single species list of lists
spp <- reactiveValues()
envs.global <- reactiveValues()
# Variable to keep track of current log message
initLogMsg <- function() {
intro <- '***WELCOME TO WALLACE***'
brk <- paste(rep('------', 14), collapse = '')
expl <- 'Please find messages for the user in this log window.'
logInit <- gsub('.{4}$', '', paste(intro, brk, expl, brk, '', sep = '<br>'))
logInit
}
logger <- reactiveVal(initLogMsg())
# Write out logs to the log Window
observeEvent(logger(), {
shinyjs::html(id = "logHeader", html = logger(), add = FALSE)
shinyjs::js$scrollLogger()
})
# tab and module-level reactives
component <- reactive({
input$tabs
})
observe({
if (component() == "_stopapp") {
shinyjs::runjs("window.close();")
stopApp()
}
})
module <- reactive({
if (component() == "intro") "intro"
else input[[glue("{component()}Sel")]]
})
######################## #
### GUIDANCE TEXT ####
######################## #
# UI for component guidance text
output$gtext_component <- renderUI({
file <- file.path('Rmd', glue("gtext_{component()}.Rmd"))
if (!file.exists(file)) return()
includeMarkdown(file)
})
# UI for module guidance text
output$gtext_module <- renderUI({
req(module())
file <- COMPONENT_MODULES[[component()]][[module()]]$instructions
if (is.null(file)) return()
includeMarkdown(file)
})
# Help Component
help_components <- c("occs", "envs", "poccs", "penvs", "espace", "part", "model", "vis", "xfer")
lapply(help_components, function(component) {
btn_id <- paste0(component, "Help")
observeEvent(input[[btn_id]], updateTabsetPanel(session, "main", "Component Guidance"))
})
# Help Module
observeEvent(input$occs_queryDbHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$occs_paleoDbHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$occs_userOccsHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$envs_worldclimHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$envs_ecoclimateHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$envs_userEnvsHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$poccs_selectOccsHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$poccs_removeByIDHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$poccs_thinOccsHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$penvs_bgExtentHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$penvs_drawBgExtentHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$penvs_userBgExtentHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$espace_pcaHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$espace_occDensHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$espace_nicheOvHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$part_nonSpatHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$part_spatHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$model_maxentHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$model_bioclimHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$vis_mapPredsHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$vis_maxentEvalPlotHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$vis_responsePlotHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$vis_bioclimPlotHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$xfer_areaHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$xfer_timeHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$xfer_userHelp, updateTabsetPanel(session, "main", "Module Guidance"))
observeEvent(input$xfer_messHelp, updateTabsetPanel(session, "main", "Module Guidance"))
######################## #
### MAPPING LOGIC ####
######################## #
# create map
output$map <- renderLeaflet(
leaflet() %>%
setView(0, 0, zoom = 2) %>%
addProviderTiles('Esri.WorldTopoMap') %>%
leafem::addMouseCoordinates()
)
# create map proxy to make further changes to existing map
map <- leafletProxy("map")
# change provider tile option
observe({
map %>% addProviderTiles(input$bmap)
})
# logic for recording the attributes of drawn polygon features
observeEvent(input$map_draw_new_feature, {
req(curSp())
coords <- unlist(input$map_draw_new_feature$geometry$coordinates)
xy <- matrix(c(coords[c(TRUE,FALSE)], coords[c(FALSE,TRUE)]), ncol=2)
colnames(xy) <- c('longitude', 'latitude')
id <- input$map_draw_new_feature$properties$`_leaflet_id`
if(component() == 'poccs') {
spp[[curSp()]]$polySelXY <- xy
spp[[curSp()]]$polySelID <- id
}
if(component() == 'penvs') {
spp[[curSp()]]$polyExtXY <- xy
spp[[curSp()]]$polyExtID <- id
}
if(component() == 'xfer') {
spp[[curSp()]]$polyXfXY <- xy
spp[[curSp()]]$polyXfID <- id
}
# UI CONTROLS - for some reason, curSp() disappears here unless input is updated
updateSelectInput(session, "curSp", selected = curSp())
})
# Call the module-specific map function for the current module
observe({
# must have one species selected and occurrence data
req(length(curSp()) == 1, occs(), module())
map_fx <- COMPONENT_MODULES[[component()]][[module()]]$map_function
if (!is.null(map_fx)) {
do.call(map_fx, list(map, common = common))
}
})
######################## #
### BUTTONS LOGIC ####
######################## #
# Enable/disable buttons
observe({
shinyjs::toggleState("goLoad_session", !is.null(input$load_session$datapath))
req(length(curSp()) == 1)
shinyjs::toggleState("dlDbOccs", !is.null(occs()))
shinyjs::toggleState("dlOccs", !is.null(occs()))
shinyjs::toggleState("dlAllOccs", length(allSp()) > 1)
shinyjs::toggleState("dlRMD", !is.null(occs()))
shinyjs::toggleState("dlGlobalEnvs", !is.null(spp[[curSp()]]$envs))
shinyjs::toggleState("dlProcOccs",
!is.null(spp[[curSp()]]$rmm$code$wallace$occsSelPolyCoords) |
!is.null(spp[[curSp()]]$procOccs$occsThin) |
!is.null(spp[[curSp()]]$rmm$code$wallace$removedIDs))
shinyjs::toggleState("dlMskEnvs", !is.null(spp[[curSp()]]$procEnvs$bgMask))
shinyjs::toggleState("dlBgPts", !is.null(spp[[curSp()]]$bgPts))
shinyjs::toggleState("dlBgShp", !is.null(spp[[curSp()]]$procEnvs$bgExt))
shinyjs::toggleState("dlPcaResults", !is.null(spp[[curSp()]]$pca))
shinyjs::toggleState("dlPart", ("partition" %in% colnames(spp[[curSp()]]$occs)))
shinyjs::toggleState("dlEvalTbl", !is.null(evalOut()))
shinyjs::toggleState("dlEvalTblBins", !is.null(evalOut()))
shinyjs::toggleState("dlVisBioclim", !is.null(spp[[curSp()]]$rmm$model$algorithm$bioclim$notes))
shinyjs::toggleState("dlMaxentPlots", !is.null(spp[[curSp()]]$rmm$model$algorithm$maxent$notes))
shinyjs::toggleState("dlRespCurves", !is.null(spp[[curSp()]]$rmm$model$algorithm$maxent$notes))
shinyjs::toggleState("dlPred", !is.null(spp[[curSp()]]$visualization$occPredVals))
shinyjs::toggleState("dlXfShp", !is.null(spp[[curSp()]]$transfer$xfExt))
shinyjs::toggleState("dlXferEnvs", !is.null(spp[[curSp()]]$transfer$xfEnvsDl))
shinyjs::toggleState("dlXfer", !is.null(spp[[curSp()]]$transfer$xfEnvs))
shinyjs::toggleState("dlMess", !is.null(spp[[curSp()]]$transfer$messVals))
# shinyjs::toggleState("dlWhatever", !is.null(spp[[curSp()]]$whatever))
})
observe({
req(length(curSp()) == 2)
shinyjs::toggleState("dlPcaResults", !is.null(spp[[paste0(curSp()[1],".",curSp()[2])]]$pca))
shinyjs::toggleState("dlOccDens", !is.null(spp[[paste0(curSp()[1],".",curSp()[2])]]$occDens))
shinyjs::toggleState("dlNicheOvPlot", !is.null(spp[[paste0(curSp()[1],".",curSp()[2])]]$nicheOv))
})
# # # # # # # # # # # # # # # # # #
# OBTAIN OCCS: other controls ####
# # # # # # # # # # # # # # # # # #
output$curSpUI <- renderUI({
# check that a species is in the list already -- if not, don't proceed
req(length(reactiveValuesToList(spp)) > 0)
# get the species names
n <- names(spp)[order(names(spp))]
# remove multispecies names from list
n <- n[!grepl(".", n, fixed = TRUE)]
# if no current species selected, select the first name
# NOTE: this line is necessary to retain the selection after selecting different tabs
if(!is.null(curSp())) selected <- curSp() else selected <- n[1]
# if espace component, allow for multiple species selection
if(component() == 'espace') options <- list(maxItems = 2) else options <- list(maxItems = 1)
# make a named list of their names
sppNameList <- c(list("Current species" = ""), setNames(as.list(n), n))
# generate a selectInput ui that lists the available species
if (is.null(module())) {
span("...Select a module...", class = "step")
} else {
selectizeInput('curSp', label = "Species menu", choices = sppNameList,
multiple = TRUE, selected = selected, options = options)
}
})
curSp <- reactive(input$curSp)
# vector of all species with occurrence data loaded
allSp <- reactive(sort(names(reactiveValuesToList(spp))[!grepl("\\.", names(reactiveValuesToList(spp)))]))
# vector of all species with occurrence data loaded
multSp <- reactive(sort(names(reactiveValuesToList(spp))[grepl("\\.", names(reactiveValuesToList(spp)))]))
# convenience function for occurrence table for current species
occs <- reactive(spp[[curSp()]]$occs)
# convenience function for metadata list for current species
rmm <- reactive(spp[[curSp()]]$rmm)
# TABLE
# options <- list(autoWidth = TRUE, columnDefs = list(list(width = '40%', targets = 7)),
# scrollX=TRUE, scrollY=400)
output$occTbl <- DT::renderDataTable({
# check if spp has species in it
req(length(reactiveValuesToList(spp)) > 0)
occs() %>%
dplyr::mutate(occID = as.numeric(occID),
longitude = round(as.numeric(longitude), digits = 2),
latitude = round(as.numeric(latitude), digits = 2)) %>%
dplyr::select(-pop) %>%
dplyr::arrange(occID)
}, rownames = FALSE, options = list(scrollX = TRUE))
# DOWNLOAD: current species occurrence data table
output$dlOccs <- downloadHandler(
filename = function() {
n <- fmtSpN(curSp())
source <- rmm()$data$occurrence$sources
glue("{n}_{source}.csv")
},
content = function(file) {
tbl <- occs() %>%
dplyr::select(-c(pop, occID))
# if bg values are present, add them to table
if(!is.null(bg())) {
tbl <- rbind(tbl, bg())
}
write_csv_robust(tbl, file, row.names = FALSE)
}
)
# DOWNLOAD: all species occurrence data table
output$dlAllOccs <- downloadHandler(
filename = function(){"multispecies_ocurrence_table.csv"},
content = function(file) {
l <- lapply(allSp(), function(x) {
data.frame(spp[[x]]$occData$occsCleaned, stringsAsFactors = FALSE)
})
tbl <- dplyr::bind_rows(l)
tbl <- tbl %>% dplyr::select(-pop)
write_csv_robust(tbl, file, row.names = FALSE)
}
)
# DOWNLOAD: occsOrig
output$dlDbOccs <- downloadHandler(
filename = function() {
n <- fmtSpN(curSp())
source <- rmm()$data$occurrence$sources
glue("{n}_{source}_raw.csv")
},
content = function(file) {
write_csv_robust(spp[[curSp()]]$occData$occsOrig, file, row.names = FALSE)
}
)
############################################# #
### COMPONENT: OBTAIN ENVIRONMENTAL DATA ####
############################################# #
# # # # # # # # # # # # # # # # # #
# OBTAIN ENVS: other controls ####
# # # # # # # # # # # # # # # # # #
bcSel <- reactive(input$bcSel)
ecoClimSel <- reactive(input$ecoClimSel)
VarSelector <- reactive(input$VarSelector)
# shortcut to currently selected environmental variable, read from curEnvUI
curEnv <- reactive(input$curEnv)
# convenience function for environmental variables for current species
envs <- reactive({
req(curSp(), spp[[curSp()]]$envs)
envs.global[[spp[[curSp()]]$envs]]
})
# map center coordinates for 30 arcsec download
mapCntr <- reactive({
req(occs())
round(c(mean(occs()$longitude), mean(occs()$latitude)), digits = 3)
})
# CONSOLE PRINT
output$envsPrint <- renderPrint({
req(envs())
envs()
})
output$dlGlobalEnvs <- downloadHandler(
filename = function() paste0(spp[[curSp()]]$envs, '_envs.zip'),
content = function(file) {
withProgress(
message = paste0("Preparing ", paste0(spp[[curSp()]]$envs, '_envs.zip ...')), {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
type <- input$globalEnvsFileType
nm <- names(envs.global[[spp[[curSp()]]$envs]])
raster::writeRaster(envs.global[[spp[[curSp()]]$envs]], nm, bylayer = TRUE,
format = type, overwrite = TRUE)
ext <- switch(type, raster = 'grd', ascii = 'asc', GTiff = 'tif')
fs <- paste0(nm, '.', ext)
if (ext == 'grd') {
fs <- c(fs, paste0(nm, '.gri'))
}
zip::zipr(zipfile = file, files = fs)
if (file.exists(paste0(file, ".zip"))) file.rename(paste0(file, ".zip"), file)
})
},
contentType = "application/zip"
)
########################################### #
### COMPONENT: PROCESS OCCURRENCE DATA ####
########################################### #
# # # # # # # # # # # # # # # # # #
# PROCESS OCCS: other controls ####
# # # # # # # # # # # # # # # # # #
# DOWNLOAD: current processed occurrence data table
output$dlProcOccs <- downloadHandler(
filename = function() paste0(curSp(), "_processed_occs.csv"),
content = function(file) {
tbl <- occs() %>% dplyr::select(-pop)
write_csv_robust(tbl, file, row.names = FALSE)
}
)
############################################## #
### COMPONENT: PROCESS ENVIRONMENTAL DATA ####
############################################## #
# # # # # # # # # # # # # # # # # #
# PROCESS ENVS: other controls ####
# # # # # # # # # # # # # # # # # #
# convenience function for background points table for current species
bg <- reactive(spp[[curSp()]]$bg)
# convenience function for background polygon for current species
bgExt <- reactive(spp[[curSp()]]$procEnvs$bgExt)
# convenience function for environmental variable rasters masked to background for current species
bgMask <- reactive(spp[[curSp()]]$procEnvs$bgMask)
# get the coordinates of the current background extent shape
bgShpXY <- reactive({
req(bgExt())
polys <- bgExt()@polygons[[1]]@Polygons
if (length(polys) == 1) {
xy <- list(polys[[1]]@coords)
} else{
xy <- lapply(polys, function(x) x@coords)
}
return(xy)
})
# DOWNLOAD: masked environmental variable rasters
output$dlBgShp <- downloadHandler(
filename = function() paste0(curSp(), "_bgShp.zip"),
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
n <- curSp()
sf::st_write(obj = sf::st_as_sf(bgExt()),
dsn = tmpdir,
layer = paste0(n, '_bgShp'),
driver = "ESRI Shapefile",
append = FALSE)
exts <- c('dbf', 'shp', 'shx')
fs <- paste0(n, '_bgShp.', exts)
zip::zipr(zipfile = file, files = fs)
if (file.exists(paste0(file, ".zip"))) {
file.rename(paste0(file, ".zip"), file)}
},
contentType = "application/zip"
)
# DOWNLOAD: masked environmental variable rasters
output$dlMskEnvs <- downloadHandler(
filename = function() paste0(curSp(), '_mskEnvs.zip'),
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
type <- input$bgMskFileType
nm <- names(envs())
raster::writeRaster(bgMask(), nm, bylayer = TRUE,
format = type, overwrite = TRUE)
ext <- switch(type, raster = 'grd', ascii = 'asc', GTiff = 'tif')
fs <- paste0(nm, '.', ext)
if (ext == 'grd') {
fs <- c(fs, paste0(nm, '.gri'))
}
zip::zipr(zipfile = file, files = fs)
if (file.exists(paste0(file, ".zip"))) {file.rename(paste0(file, ".zip"), file)}
},
contentType = "application/zip"
)
# DOWNLOAD: background points table
output$dlBgPts <- downloadHandler(
filename = function() {
n <- curSp()
paste0(n, "_bgPoints.csv")
},
content = function(file) {
tbl <- as.data.frame(spp[[curSp()]]$bgPts)
write_csv_robust(tbl, file, row.names = FALSE)
}
)
############################################## #
### COMPONENT: ESPACE ####
############################################## #
output$dlPcaResults <- downloadHandler(
filename = function() {
mspName <- paste(curSp(), collapse = ".")
paste0(mspName, "_PcaResults.zip")
},
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
sp1 <- curSp()[1]
sp2 <- curSp()[2]
} else {
mSp <- curSp()
}
req(spp[[mSp]]$pca)
png(paste0("pcaScatterOccs.png"), width = 500, height = 500)
x <- spp[[mSp]]$pca$scores[spp[[mSp]]$pca$scores$bg == 'sp', ]
x.f <- factor(x$sp)
ade4::s.class(x, x.f, xax = spp[[mSp]]$pc1, yax = spp[[mSp]]$pc2,
col = c("red", "blue"), cstar = 0, cpoint = 0.1)
title(xlab = paste0("PC", spp[[mSp]]$pc1),
ylab = paste0("PC", spp[[mSp]]$pc2))
dev.off()
png(paste0("pcaScatterOccsBg.png"), width = 500, height = 500)
x <- spp[[mSp]]$pca$scores[spp[[mSp]]$pca$scores$sp == 'bg', ]
x.f <- factor(x$bg)
ade4::s.class(x, x.f, xax = spp[[mSp]]$pc1, yax = spp[[mSp]]$pc2,
col = c("red", "blue"), cstar = 0, cpoint = 0.1)
title(xlab = paste0("PC", spp[[mSp]]$pc1),
ylab = paste0("PC", spp[[mSp]]$pc2))
dev.off()
png(paste0("pcaCorCircle.png"), width = 500, height = 500)
ade4::s.corcircle(spp[[mSp]]$pca$co, xax = spp[[mSp]]$pc1,
yax = spp[[mSp]]$pc2, lab = input$pcaSel,
full = FALSE, box = TRUE)
title(xlab = paste0("PC", spp[[mSp]]$pc1),
ylab = paste0("PC", spp[[mSp]]$pc2))
dev.off()
png(paste0("pcaScree.png"), width = 500, height = 500)
screeplot(spp[[mSp]]$pca, main = NULL)
dev.off()
sink(paste0("pcaOut.txt"))
print(summary(spp[[mSp]]$pca))
sink()
fs <- c("pcaScatterOccs.png", "pcaScatterOccsBg.png",
"pcaCorCircle.png","pcaScree.png","pcaOut.txt")
zip::zipr(zipfile = file,
files = fs)
}
)
output$dlOccDens <- downloadHandler(
filename = function() {
mspName <- paste(curSp(), collapse = ".")
paste0(mspName, "_occDens.png")
},
content = function(file) {
png(file, width = 1000, height = 500)
graphics::par(mfrow=c(1,2))
if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
sp1 <- curSp()[1]
sp2 <- curSp()[2]
} else {
mSp <- curSp()
}
req(spp[[mSp]]$occDens)
ecospat.plot.nicheDEV(spp[[mSp]]$occDens[[sp1]], title = spName(sp1))
ecospat.plot.nicheDEV(spp[[mSp]]$occDens[[sp2]], title = spName(sp2))
dev.off()
}
)
output$dlNicheOvPlot <- downloadHandler(
filename = function() {
mSp <- paste(curSp(), collapse = ".")
paste0(mSp, "_nicheOvPlot.png")
},
content = function(file) {
png(file, width = 1000, height = 500)
graphics::par(mfrow = c(1, 2))
if (length(curSp()) == 2) {
mSp <- paste(curSp(), collapse = ".")
sp1 <- curSp()[1]
sp2 <- curSp()[2]
} else {
mSp <- curSp()
}
req(spp[[mSp]]$occDens)
ecospat::ecospat.plot.niche.dyn(
spp[[mSp]]$occDens[[sp1]],
spp[[mSp]]$occDens[[sp2]],
0.5,
title = mSp,
col.unf = "blue",
col.exp = "red",
col.stab = "purple",
colZ1 = "blue",
colZ2 = "red",
transparency = 25
)
box()
req(spp[[mSp]]$nicheOv)
# if (!is.null(spp[[mSp]]$nicheOv$equiv))
# ecospat::ecospat.plot.overlap.test(spp[[mSp]]$nicheOv$equiv,
# "D", "Equivalency test")
if (!is.null(spp[[mSp]]$nicheOv$simil))
ecospat::ecospat.plot.overlap.test(spp[[mSp]]$nicheOv$simil,
"D", "Similarity test")
ovMetrics <- paste(
"Overlap D = ", round(spp[[mSp]]$nicheOv$overlap$D, 2),
" | Sp1 only :", round(spp[[mSp]]$nicheOv$USE[3], 2),
" | Sp2 only :", round(spp[[mSp]]$nicheOv$USE[1], 2),
" | Both :", round(spp[[mSp]]$nicheOv$USE[2], 2)
)
graphics::mtext(ovMetrics, outer = TRUE, line = -1)
dev.off()
}
)
################################################## #
### COMPONENT: PARTITION OCCURRENCE DATA ####
################################################# #
# download for partitioned occurrence records csv
output$dlPart <- downloadHandler(
filename = function() paste0(curSp(), "_partitioned_occs.csv"),
content = function(file) {
bg.bind <- data.frame(rep('background',
nrow(spp[[curSp()]]$bgPts)), spp[[curSp()]]$bgPts)
names(bg.bind) <- c('scientific_name', 'longitude', 'latitude')
occs.bg.bind <- rbind(spp[[curSp()]]$occs[, 2:4], bg.bind)
all.bind <- cbind(occs.bg.bind, c(spp[[curSp()]]$occs$partition,
spp[[curSp()]]$bg$partition))
names(all.bind)[4] <- "group"
write_csv_robust(all.bind, file, row.names = FALSE)
}
)
######################### #
### COMPONENT: MODEL ####
######################### #
# # # # # # # # # # # # # # # # # #
# MODEL: other controls ####
# # # # # # # # # # # # # # # # # #
# convenience function for modeling results list for current species
evalOut <- reactive(spp[[curSp()]]$evalOut)
# ui that populates with the names of models that were run
output$curModelUI <- renderUI({
# do not display until both current species is selected and it has a model
req(curSp(), length(curSp()) == 1, evalOut())
# if
if(!is.null(evalOut())) {
n <- names(evalOut()@models)
} else {
n <- NULL
}
# NOTE: this line is necessary to retain the selection after selecting different tabs
if(!is.null(curModel())) selected <- curModel() else selected <- n[1]
modsNameList <- c(list("Current model" = ""), setNames(as.list(n), n))
options <- list(maxItems = 1)
if (!is.null(module())) {
selectizeInput('curModel', label = "Select model: " ,
choices = modsNameList, multiple = TRUE,
selected = selected, options = options)
}
})
# shortcut to currently selected model, read from modSelUI
curModel <- reactive(input$curModel)
# picker option to select categorical variables
output$catEnvs <- renderUI({
req(curSp(), occs(), envs())
if(!is.null(envs())) {
n <- c(names(envs()))
} else {
n <- NULL
}
envList <- setNames(as.list(n), n)
shinyWidgets::pickerInput(
"selCatEnvs",
label = "Select categorical variables",
choices = envList,
multiple = TRUE)
})
selCatEnvs <- reactive(input$selCatEnvs)
# download for partitioned occurrence records csv
output$dlEvalTbl <- downloadHandler(
filename = function() {
if(spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
paste0(curSp(), "_bioclim_evalTbl.csv")
} else if(spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
paste0(curSp(), "_maxent_evalTbl.csv")
} else if(spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
paste0(curSp(), "_maxnet_evalTbl.csv")
}
},
content = function(file) {
evalTbl <- spp[[curSp()]]$evalOut@results
write_csv_robust(evalTbl, file, row.names = FALSE)
}
)
# download for partitioned occurrence records csv
output$dlEvalTblBins <- downloadHandler(
filename = function() {
if(spp[[curSp()]]$rmm$model$algorithms == "BIOCLIM") {
paste0(curSp(), "_bioclim_evalTblBins.csv")
} else if(spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
paste0(curSp(), "_maxent_evalTblBins.csv")
} else if(spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
paste0(curSp(), "_maxnet_evalTblBins.csv")
}
},
content = function(file) {
evalTblBins <- spp[[curSp()]][email protected]
write_csv_robust(evalTblBins, file, row.names = FALSE)
}
)
########################################### #
### COMPONENT: VISUALIZE MODEL RESULTS ####
########################################### #
# # # # # # # # # # # # # # # # # #
# VISUALIZE: other controls ####
# # # # # # # # # # # # # # # # # #
# convenience function for mapped model prediction raster for current species
mapPred <- reactive(spp[[curSp()]]$visualization$mapPred)
# handle downloads for BIOCLIM Plots png
output$dlVisBioclim <- downloadHandler(
filename = function() {paste0(curSp(), "_bioClimPlot.png")},
content = function(file) {
png(file)
vis_bioclimPlot(evalOut()@models[[curModel()]],
spp[[curSp()]]$rmm$code$wallace$bcPlotSettings[['bc1']],
spp[[curSp()]]$rmm$code$wallace$bcPlotSettings[['bc2']],
spp[[curSp()]]$rmm$code$wallace$bcPlotSettings[['p']])
dev.off()
}
)
# handle downloads for Maxent Plots png
output$dlMaxentPlots <- downloadHandler(
filename = function() {paste0(curSp(), "_evalPlots.zip")},
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
parEval <- c('auc.val', 'auc.diff', 'or.mtp', 'or.10p', 'delta.AICc')
for (i in parEval) {
ENMeval::evalplot.stats(spp[[curSp()]]$evalOut, i, "rm", "fc")
ggplot2::ggsave(paste0(gsub("[[:punct:]]", "_", i), ".png"))
# dev.off()
}
fs <- paste0(gsub("[[:punct:]]", "_", parEval), ".png")
zip::zipr(zipfile = file,
files = fs)
}
)
# handle downloads for Response Curve Plots png
output$dlRespCurves <- downloadHandler(
filename = function() {paste0(curSp(), "_responseCurves.zip")},
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
if (spp[[curSp()]]$rmm$model$algorithms == "maxnet") {
namesEnvs <- mxNonzeroCoefs(evalOut()@models[[curModel()]], "maxnet")
for (i in namesEnvs) {
png(paste0(i, ".png"))
suppressWarnings(
maxnet::response.plot(evalOut()@models[[curModel()]], v = i,
type = "cloglog")
)
dev.off()
}
} else if (spp[[curSp()]]$rmm$model$algorithms == "maxent.jar") {
namesEnvs <- mxNonzeroCoefs(evalOut()@models[[curModel()]], "maxent.jar")
for (i in namesEnvs) {
png(paste0( i, ".png"))
dismo::response(evalOut()@models[[curModel()]], var = i)
dev.off()
}
}
fs <- paste0(namesEnvs, ".png")
zip::zipr(zipfile = file, files = fs)
}
)
# download for model predictions (restricted to background extent)
output$dlPred <- downloadHandler(
filename = function() {
ext <- switch(input$predFileType, raster = 'zip', ascii = 'asc',
GTiff = 'tif', png = 'png')
thresholdRule <- rmm()$prediction$binary$thresholdRule
predType <- rmm()$prediction$notes
if (thresholdRule == 'none') {
paste0(curSp(), "_", predType, '.', ext)
} else {
paste0(curSp(), "_", thresholdRule, '.', ext)
}
},
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
if(require(sf)) {
if (input$predFileType == 'png') {
req(mapPred())
if (!webshot::is_phantomjs_installed()) {
logger %>%
writeLog(type = "error", "To download PNG prediction, you're required to",
" install PhantomJS in your machine. You can use webshot::install_phantomjs()",
" in you are R console.")
return()
}
if (!requireNamespace("mapview")) {
logger %>%
writeLog(
type = "error",
"PNG option is available if you install the 'mapview' package ",
"(which is a suggested package for Wallace, not a required dependency). If you ",
"want to install it, close Wallace and run the following line in the ",
"R Console: ", em("install.packages('mapview')")
)
return()
}
if (rmm()$prediction$binary$thresholdRule != 'none') {
mapPredVals <- 0:1
rasPal <- c('gray', 'blue')
legendPal <- colorBin(rasPal, 0:1, bins = 2)
mapTitle <- "Thresholded Suitability<br>(Training)"
mapLabFormat <- function(type, cuts, p) {
n = length(cuts)
cuts[n] = "predicted presence"
for (i in 2:(n - 1)) {
cuts[i] = ""
}
cuts[1] = "predicted absence"
paste0(cuts[-n], cuts[-1])
}
mapOpacity <- 1
} else {
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
mapPredVals <- spp[[curSp()]]$visualization$mapPredVals
rasPal <- colorNumeric(rasCols, mapPredVals, na.color='transparent')
legendPal <- colorNumeric(rev(rasCols), mapPredVals, na.color='transparent')
mapTitle <- "Predicted Suitability<br>(Training)"
mapLabFormat <- reverseLabel(2, reverse_order=TRUE)
mapOpacity <- NULL
}
m <- leaflet() %>%
addLegend("bottomright", pal = legendPal, title = mapTitle,
labFormat = mapLabFormat, opacity = mapOpacity,
values = mapPredVals, layerId = "train") %>%
addProviderTiles(input$bmap) %>%
addCircleMarkers(data = occs(), lat = ~latitude, lng = ~longitude,
radius = 5, color = 'red', fill = TRUE, fillColor = 'red',
fillOpacity = 0.2, weight = 2, popup = ~pop) %>%
addRasterImage(mapPred(), colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapPred', method = "ngb") %>%
addPolygons(data = bgExt(), fill = FALSE, weight = 4, color = "blue",
group='xfer')
mapview::mapshot(m, file = file)
} else if (input$predFileType == 'raster') {
fileName <- curSp()
raster::writeRaster(mapPred(), file.path(tmpdir, fileName),
format = input$predFileType, overwrite = TRUE)
fs <- paste0(fileName, c('.grd', '.gri'))
zip::zipr(zipfile = file, files = fs)
} else {
r <- raster::writeRaster(mapPred(), file, format = input$predFileType,
overwrite = TRUE)
file.rename(r@file@name, file)
}
} else {
logger %>%
writeLog("Please install the sf package before downloading rasters.")
}
}
)
########################################### #
### COMPONENT: MODEL TRANSFER ####
########################################### #
# # # # # # # # # # # # # # # # # #
# TRANSFER: other controls ####
# # # # # # # # # # # # # # # # # #
# convenience function for mapped model prediction raster for current species
mapXfer <- reactive(spp[[curSp()]]$transfer$mapXfer)
# DOWNLOAD: Shapefile of extent of transfer
output$dlXfShp <- downloadHandler(
filename = function() paste0(curSp(), '_xferShp.zip'),
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
n <- curSp()
sf::st_write(obj = sf::st_as_sf(spp[[curSp()]]$transfer$xfExt),
dsn = tmpdir,
layer = paste0(n, '_xferShp'),
driver = "ESRI Shapefile",
append = FALSE)
exts <- c('dbf', 'shp', 'shx')
fs <- paste0(n, '_xferShp.', exts)
zip::zipr(zipfile = file, files = fs)
if (file.exists(paste0(file, ".zip"))) {file.rename(paste0(file, ".zip"), file)}
},
contentType = "application/zip"
)
# DOWNLOAD: Transferred envs
output$dlXferEnvs <- downloadHandler(
filename = function() paste0(spp[[curSp()]]$transfer$xfEnvsDl, '_xfEnvs.zip'),
content = function(file) {
withProgress(
message = paste0("Preparing ", paste0(spp[[curSp()]]$transfer$xfEnvsDl, '_xfEnvs.zip...')), {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
type <- input$xferEnvsFileType
nm <- names(spp[[curSp()]]$transfer$xferTimeEnvs)
raster::writeRaster(spp[[curSp()]]$transfer$xferTimeEnvs, nm, bylayer = TRUE,
format = type, overwrite = TRUE)
ext <- switch(type, raster = 'grd', ascii = 'asc', GTiff = 'tif')
fs <- paste0(nm, '.', ext)
if (ext == 'grd') {
fs <- c(fs, paste0(nm, '.gri'))
}
zip::zipr(zipfile = file, files = fs)
if (file.exists(paste0(file, ".zip"))) file.rename(paste0(file, ".zip"), file)
})
},
contentType = "application/zip"
)
# download for model predictions (restricted to background extent)
output$dlXfer <- downloadHandler(
filename = function() {
ext <- switch(input$xferFileType, raster = 'zip', ascii = 'asc',
GTiff = 'tif', png = 'png')
thresholdRule <- rmm()$prediction$transfer$environment1$thresholdRule
predType <- rmm()$prediction$notes
if (thresholdRule == 'none') {
paste0(curSp(), "_xfer_", predType, '.', ext)
} else {
paste0(curSp(), "_xfer_", thresholdRule, '.', ext)
}
},
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
if(require(sf)) {
if (input$xferFileType == 'png') {
req(mapXfer())
if (!webshot::is_phantomjs_installed()) {
logger %>%
writeLog(type = "error", "To download PNG prediction, you're required to",
" install PhantomJS in your machine. You can use webshot::install_phantomjs()",
" in you are R console.")
return()
}
if (!requireNamespace("mapview")) {
logger %>%
writeLog(
type = "error",
"PNG option is available if you install the 'mapview' package ",
"(which is a suggested package for Wallace, not a required dependency). If you ",
"want to install it, close Wallace and run the following line in the ",
"R Console: ", em("install.packages('mapview')")
)
return()
}
if (rmm()$prediction$transfer$environment1$thresholdRule != 'none') {
mapXferVals <- 0:1
rasPal <- c('gray', 'red')
legendPal <- colorBin(rasPal, 0:1, bins = 2)
mapTitle <- "Thresholded Suitability<br>(Transferred)"
mapLabFormat <- function(type, cuts, p) {
n = length(cuts)
cuts[n] = "predicted presence"
for (i in 2:(n - 1)) {
cuts[i] = ""
}
cuts[1] = "predicted absence"
paste0(cuts[-n], cuts[-1])
}
mapOpacity <- 1
} else {
rasCols <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c")
mapXferVals <- spp[[curSp()]]$transfer$mapXferVals
rasPal <- colorNumeric(rasCols, mapXferVals, na.color='transparent')
legendPal <- colorNumeric(rev(rasCols), mapXferVals, na.color='transparent')
mapTitle <- "Predicted Suitability<br>(Transferred)"
mapLabFormat <- reverseLabel(2, reverse_order=TRUE)
mapOpacity <- NULL
}
polyXfXY <- spp[[curSp()]]$transfer$xfExt@polygons[[1]]@Polygons
if(length(polyXfXY) == 1) {
shp <- polyXfXY[[1]]@coords
} else {
shp <- lapply(polyXfXY, function(x) x@coords)
}
m <- leaflet() %>%
addLegend("bottomright", pal = legendPal, title = mapTitle,
labFormat = mapLabFormat, opacity = mapOpacity,
values = mapXferVals, layerId = "train") %>%
addProviderTiles(input$bmap) %>%
addRasterImage(mapXfer(), colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapXfer', method = "ngb") %>%
addPolygons(lng = shp[, 1], lat = shp[, 2], fill = FALSE,
weight = 4, color = "red", group = 'xfer')
mapview::mapshot(m, file = file)
} else if (input$xferFileType == 'raster') {
fileName <- curSp()
raster::writeRaster(mapXfer(), file.path(tmpdir, fileName),
format = input$xferFileType, overwrite = TRUE)
fs <- paste0(fileName, c('.grd', '.gri'))
zip::zipr(zipfile = file, files = fs)
} else {
r <- raster::writeRaster(mapXfer(), file, format = input$xferFileType,
overwrite = TRUE)
file.rename(r@file@name, file)
}
} else {
logger %>% writeLog("Please install the sf package before downloading rasters.")
}
}
)
# download for mess (restricted to background extent)
output$dlMess <- downloadHandler(
filename = function() {
ext <- switch(input$messFileType, raster = 'zip', ascii = 'asc',
GTiff = 'tif', png = 'png')
paste0(curSp(), "_mess.", ext)
},
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
if(require(sf)) {
req(spp[[curSp()]]$transfer$mess, spp[[curSp()]]$transfer$xfExt)
mess <- spp[[curSp()]]$transfer$mess
if (input$messFileType == 'png') {
if (!webshot::is_phantomjs_installed()) {
logger %>%
writeLog(type = "error", "To download PNG prediction, you're required to",
" install PhantomJS in your machine. You can use webshot::install_phantomjs()",
" in you are R console.")
return()
}
if (!requireNamespace("mapview")) {
logger %>%
writeLog(
type = "error",
"PNG option is available if you install the 'mapview' package ",
"(which is a suggested package for Wallace, not a required dependency). If you ",
"want to install it, close Wallace and run the following line in the ",
"R Console: ", em("install.packages('mapview')")
)
return()
}
rasVals <- spp[[curSp()]]$transfer$messVals
polyXfXY <- spp[[curSp()]]$transfer$xfExt@polygons[[1]]@Polygons
if(length(polyXfXY) == 1) {
shp <- polyXfXY[[1]]@coords
} else {
shp <- lapply(polyXfXY, function(x) x@coords)
}
# define colorRamp for mess
if (max(rasVals) > 0 & min(rasVals) < 0) {
rc1 <- colorRampPalette(colors = rev(RColorBrewer::brewer.pal(n = 3, name = 'Reds')),
space = "Lab")(abs(min(rasVals)))
rc2 <- colorRampPalette(colors = RColorBrewer::brewer.pal(n = 3, name = 'Blues'),
space = "Lab")(max(rasVals))
rasCols <- c(rc1, rc2)
} else if (max(rasVals) < 0 & min(rasVals) < 0) {
rasCols <- colorRampPalette(colors = rev(RColorBrewer::brewer.pal(n = 3, name = 'Reds')),
space = "Lab")(abs(min(rasVals)))
} else if (max(rasVals) > 0 & min(rasVals) > 0) {
rasCols <- colorRampPalette(colors = RColorBrewer::brewer.pal(n = 3, name = 'Blues'),
space = "Lab")(max(rasVals))
}
legendPal <- colorNumeric(rev(rasCols), rasVals, na.color='transparent')
rasPal <- colorNumeric(rasCols, rasVals, na.color='transparent')
m <- leaflet() %>%
addLegend("bottomright", pal = legendPal, title = "MESS Values",
labFormat = reverseLabels(2, reverse_order=TRUE),
values = rasVals, layerId = "train") %>%
addProviderTiles(input$bmap) %>%
addRasterImage(mess, colors = rasPal, opacity = 0.7,
group = 'vis', layerId = 'mapXfer', method = "ngb") %>%
addPolygons(lng = shp[, 1], lat = shp[, 2], fill = FALSE,
weight = 4, color = "red", group = 'xfer')
mapview::mapshot(m, file = file)
} else if (input$messFileType == 'raster') {
fileName <- curSp()
raster::writeRaster(mess, file.path(tmpdir, fileName),
format = input$messFileType, overwrite = TRUE)
fs <- paste0(fileName, c('.grd', '.gri'))
zip::zipr(zipfile = file, files = fs)
} else {
r <- raster::writeRaster(mess, file, format = input$messFileType,
overwrite = TRUE)
file.rename(r@file@name, file)
}
} else {
logger %>% writeLog("Please install the sf package before downloading rasters.")
}
}
)
########################################### #
### RMARKDOWN FUNCTIONALITY ####
########################################### #
filetype_to_ext <- function(type = c("Rmd", "PDF", "HTML", "Word")) {
type <- match.arg(type)
switch(
type,
Rmd = '.Rmd',
PDF = '.pdf',
HTML = '.html',
Word = '.docx'
)
}
# handler for R Markdown download
output$dlRMD <- downloadHandler(
filename = function() {
paste0("wallace-session-", Sys.Date(), filetype_to_ext(input$rmdFileType))
},
content = function(file) {
spp <- common$spp
md_files <- c()
md_intro_file <- tempfile(pattern = "intro_", fileext = ".md")
rmarkdown::render("Rmd/userReport_intro.Rmd",
output_format = rmarkdown::github_document(html_preview = FALSE),
output_file = md_intro_file,
clean = TRUE,
encoding = "UTF-8")
md_files <- c(md_files, md_intro_file)
# Abbreviation for one species
spAbr <- plyr::alply(abbreviate(stringr::str_replace(allSp(), "_", " "),
minlength = 2),
.margins = 1, function(x) {x <- as.character(x)})
names(spAbr) <- allSp()
for (sp in allSp()) {
species_rmds <- NULL
for (component in names(COMPONENT_MODULES[names(COMPONENT_MODULES) != c("espace", "rep")])) {
for (module in COMPONENT_MODULES[[component]]) {
rmd_file <- module$rmd_file
rmd_function <- module$rmd_function
if (is.null(rmd_file)) next
if (is.null(rmd_function)) {
rmd_vars <- list()
} else {
rmd_vars <- do.call(rmd_function, list(species = spp[[sp]]))
}
knit_params <- c(
file = rmd_file,
spName = spName(sp),
sp = sp,
spAbr = spAbr[[sp]],
rmd_vars
)
module_rmd <- do.call(knitr::knit_expand, knit_params)
module_rmd_file <- tempfile(pattern = paste0(module$id, "_"),
fileext = ".Rmd")
writeLines(module_rmd, module_rmd_file)
species_rmds <- c(species_rmds, module_rmd_file)
}
}
species_md_file <- tempfile(pattern = paste0(sp, "_"),
fileext = ".md")
rmarkdown::render(input = "Rmd/userReport_species.Rmd",
params = list(child_rmds = species_rmds,
spName = spName(sp),
spAbr = spAbr[[sp]]),
output_format = rmarkdown::github_document(html_preview = FALSE),
output_file = species_md_file,
clean = TRUE,
encoding = "UTF-8")
md_files <- c(md_files, species_md_file)
}
if (!is.null(multSp())) {
for (sp in multSp()) {
namesMult <- unlist(strsplit(sp, "\\."))
multSpecies_rmds <- NULL
for (component in names(COMPONENT_MODULES[names(COMPONENT_MODULES) == "espace"])) {
for (module in COMPONENT_MODULES[[component]]) {
rmd_file <- module$rmd_file
rmd_function <- module$rmd_function
if (is.null(rmd_file)) next
if (is.null(rmd_function)) {
rmd_vars <- list()
} else {
rmd_vars <- do.call(rmd_function, list(species = spp[[sp]]))
}
knit_params <- c(
file = rmd_file,
spName1 = spName(namesMult[1]),
spName2 = spName(namesMult[2]),
sp1 = namesMult[1],
spAbr1 = spAbr[[namesMult[1]]],
sp2 = namesMult[2],
spAbr2 = spAbr[[namesMult[2]]],
multAbr = paste0(spAbr[[namesMult[1]]], "_", spAbr[[namesMult[2]]]),
rmd_vars
)
module_rmd <- do.call(knitr::knit_expand, knit_params)
module_rmd_file <- tempfile(pattern = paste0(module$id, "_"),
fileext = ".Rmd")
writeLines(module_rmd, module_rmd_file)
multSpecies_rmds <- c(multSpecies_rmds, module_rmd_file)
}
}
multSpecies_md_file <- tempfile(pattern = paste0(sp, "_"),
fileext = ".md")
rmarkdown::render(input = "Rmd/userReport_multSpecies.Rmd",
params = list(child_rmds = multSpecies_rmds,
spName1 = spName(namesMult[1]),
spName2 = spName(namesMult[2]),
multAbr = paste0(spAbr[[namesMult[1]]], "_",
spAbr[[namesMult[2]]])
),
output_format = rmarkdown::github_document(html_preview = FALSE),
output_file = multSpecies_md_file,
clean = TRUE,
encoding = "UTF-8")
md_files <- c(md_files, multSpecies_md_file)
}
}
combined_md <-
md_files %>%
lapply(readLines) %>%
# lapply(readLines, encoding = "UTF-8") %>%
lapply(paste, collapse = "\n") %>%
paste(collapse = "\n\n")
result_file <- tempfile(pattern = "result_", fileext = filetype_to_ext(input$rmdFileType))
if (input$rmdFileType == "Rmd") {
combined_rmd <- gsub('``` r', '```{r}', combined_md)
writeLines(combined_rmd, result_file, useBytes = TRUE)
} else {
combined_md_file <- tempfile(pattern = "combined_", fileext = ".md")
writeLines(combined_md, combined_md_file)
rmarkdown::render(
input = combined_md_file,
output_format =
switch(
input$rmdFileType,
"PDF" = rmarkdown::pdf_document(),
"HTML" = rmarkdown::html_document(),
"Word" = rmarkdown::word_document()
),
output_file = result_file,
clean = TRUE,
encoding = "UTF-8"
)
}
file.rename(result_file, file)
}
)
################################
### METADATA FUNCTIONALITY ####
################################
output$dlRMM <- downloadHandler(
filename = function() {paste0("wallace-metadata-", Sys.Date(), ".zip")},
content = function(file) {
tmpdir <- tempdir()
owd <- setwd(tmpdir)
on.exit(setwd(owd))
# REFERENCES ####
knitcitations::citep(citation("rangeModelMetadata"))
namesSpp <- allSp()
for (i in namesSpp) {
rangeModelMetadata::rmmToCSV(spp[[i]]$rmm, filename = paste0(i, "_RMM.csv"))
}
zip::zipr(zipfile = file, files = paste0(namesSpp, "_RMM.csv"))
})
################################
### REFERENCE FUNCTIONALITY ####
################################
output$dlrefPackages <- downloadHandler(
filename = function() {paste0("ref-packages-", Sys.Date(),
filetype_to_ext(input$refFileType))},
content = function(file) {
# Create BIB file
bib_file <- "Rmd/references.bib"
temp_bib_file <- tempfile(pattern = "ref_", fileext = ".bib")
# Package always cited
knitcitations::citep(citation("wallace"))
knitcitations::citep(citation("knitcitations"))
knitcitations::citep(citation("knitr"))
knitcitations::citep(citation("rmarkdown"))
knitcitations::citep(citation("raster"))
# Write BIBTEX file
knitcitations::write.bibtex(file = temp_bib_file)
# Replace NOTE fields with VERSION when R package
bib_ref <- readLines(temp_bib_file)
bib_ref <- gsub(pattern = "note = \\{R package version", replace = "version = \\{R package", x = bib_ref)
writeLines(bib_ref, con = temp_bib_file)
file.rename(temp_bib_file, bib_file)
# Render reference file
md_ref_file <- tempfile(pattern = "ref_", fileext = ".md")
rmarkdown::render("Rmd/references.Rmd",
output_format =
switch(
input$refFileType,
"PDF" = rmarkdown::pdf_document(),
"HTML" = rmarkdown::html_document(),
"Word" = rmarkdown::word_document()
),
output_file = file,
clean = TRUE,
encoding = "UTF-8")
})
################################
### COMMON LIST FUNTIONALITY ####
################################
# Create a data structure that holds variables and functions used by modules
common = list(
# Reactive variables to pass on to modules
logger = logger,
spp = spp,
curSp = curSp,
allSp = allSp,
multSp = multSp,
curEnv = curEnv,
curModel = curModel,
component = component,
module = module,
envs.global = envs.global,
mapCntr = mapCntr,
# Shortcuts to values nested inside spp
occs = occs,
envs = envs,
bcSel = bcSel,
ecoClimSel = ecoClimSel,
bg = bg,
bgExt = bgExt,
bgMask = bgMask,
bgShpXY = bgShpXY,
selCatEnvs = selCatEnvs,
evalOut = evalOut,
mapPred = mapPred,
mapXfer = mapXfer,
rmm = rmm,
# Switch to a new component tab
update_component = function(tab = c("Map", "Table", "Results", "Download")) {
tab <- match.arg(tab)
updateTabsetPanel(session, "main", selected = tab)
},
# Disable a specific module so that it will not be selectable in the UI
disable_module = function(component = COMPONENTS, module) {
component <- match.arg(component)
shinyjs::js$disableModule(component = component, module = module)
},
# Enable a specific module so that it will be selectable in the UI
enable_module = function(component = COMPONENTS, module) {
component <- match.arg(component)
shinyjs::js$enableModule(component = component, module = module)
}
)
# Initialize all modules
modules <- list()
lapply(names(COMPONENT_MODULES), function(component) {
lapply(COMPONENT_MODULES[[component]], function(module) {
return <- callModule(get(module$server_function), module$id, common = common)
if (is.list(return) &&
"save" %in% names(return) && is.function(return$save) &&
"load" %in% names(return) && is.function(return$load)) {
modules[[module$id]] <<- return
}
})
})
observe({
spp_size <- as.numeric(utils::object.size(reactiveValuesToList(spp)))
shinyjs::toggle("save_warning", condition = (spp_size >= SAVE_SESSION_SIZE_MB_WARNING * MB))
})
# Save the current session to a file
save_session <- function(file) {
state <- list()
spp_save <- reactiveValuesToList(spp)
# Save general data
state$main <- list(
version = as.character(packageVersion("wallace")),
spp = spp_save,
envs_global = reactiveValuesToList(envs.global),
cur_sp = input$curSp,
selected_module = sapply(COMPONENTS, function(x) input[[glue("{x}Sel")]], simplify = FALSE)
)
# Ask each module to save whatever data it wants
for (module_id in names(modules)) {
state[[module_id]] <- modules[[module_id]]$save()
}
saveRDS(state, file)
}
output$save_session <- downloadHandler(
filename = function() {
paste0("wallace-session-", Sys.Date(), ".rds")
},
content = function(file) {
save_session(file)
}
)
# Load a wallace session from a file
load_session <- function(file) {
if (tools::file_ext(file) != "rds") {
shinyalert::shinyalert("Invalid Wallace session file", type = "error")
return()
}
state <- readRDS(file)
if (!is.list(state) || is.null(state$main) || is.null(state$main$version)) {
shinyalert::shinyalert("Invalid Wallace session file", type = "error")
return()
}
# Load general data
new_version <- as.character(packageVersion("wallace"))
if (state$main$version != new_version) {
shinyalert::shinyalert(
glue("The input file was saved using Wallace v{state$main$version}, but you are using Wallace v{new_version}"),
type = "warning"
)
}
for (spname in names(state$main$spp)) {
spp[[spname]] <- state$main$spp[[spname]]
}
for (envname in names(state$main$envs_global)) {
envs.global[[envname]] <- state$main$envs_global[[envname]]
}
for (component in names(state$main$selected_module)) {
value <- state$main$selected_module[[component]]
updateRadioButtons(session, glue("{component}Sel"), selected = value)
}
updateSelectInput(session, "curSp", selected = state$main$cur_sp)
state$main <- NULL
# Ask each module to load its own data
for (module_id in names(state)) {
modules[[module_id]]$load(state[[module_id]])
}
}
observeEvent(input$goLoad_session, {
load_session(input$load_session$datapath)
# Select names of species in spp object
sppLoad <- grep("\\.", names(spp), value = TRUE, invert = TRUE)
# Storage species with no env data
noEnvsSpp <- NULL
for (i in sppLoad) {
# Check if envs.global object exists in spp
if (!is.null(spp[[i]]$envs)) {
diskRast <- raster::fromDisk(envs.global[[spp[[i]]$envs]])
if (diskRast) {
if (class(envs.global[[spp[[i]]$envs]]) == "RasterStack") {
diskExist <- !file.exists(envs.global[[spp[[i]]$envs]]@layers[[1]]@file@name)
} else if (class(envs.global[[spp[[i]]$envs]]) == "RasterBrick") {
diskExist <- !file.exists(envs.global[[spp[[i]]$envs]]@file@name)
}
if (diskExist) {
noEnvsSpp <- c(noEnvsSpp, i)
}
}
}
}
if (is.null(noEnvsSpp)) {
shinyalert::shinyalert(title = "Session loaded", type = "success")
} else {
msgEnvAgain <- paste0("Load variables again for: ",
paste0(noEnvsSpp, collapse = ", "))
shinyalert::shinyalert(title = "Session loaded", type = "warning",
text = msgEnvAgain)
}
})
}
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/server.R
|
# Wallace EcoMod: a flexible platform for reproducible modeling of
# species niches and distributions.
#
# ui.R
# File author: Wallace EcoMod Dev Team. 2023.
# --------------------------------------------------------------------------
# This file is part of the Wallace EcoMod application
# (hereafter “Wallace”).
#
# Wallace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Wallace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wallace. If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
#
resourcePath <- system.file("shiny", "www", package = "wallace")
shiny::addResourcePath("wallaceres", resourcePath)
tagList(
shinyjs::useShinyjs(),
shinyjs::extendShinyjs(
script = file.path("wallaceres", "js", "shinyjs-funcs.js"),
functions = c("scrollLogger", "disableModule", "enableModule")
),
navbarPage(
theme = bslib::bs_theme(version = 3,
bootswatch = "united"),
id = 'tabs',
collapsible = TRUE,
header = tagList(
tags$head(tags$link(href = "css/styles.css", rel = "stylesheet"))
),
title = img(src = "logo.png", height = '50', width = '50',
style = "margin-top: -15px"),
windowTitle = "#WallaceEcoMod",
tabPanel("Intro", value = 'intro'),
tabPanel("Occ Data", value = 'occs'),
tabPanel("Env Data", value = 'envs'),
tabPanel("Process Occs", value = 'poccs'),
tabPanel("Process Envs", value = 'penvs'),
tabPanel("Env Space", value = 'espace'),
tabPanel("Partition Occs", value = 'part'),
tabPanel("Model", value = 'model'),
tabPanel("Visualize", value = 'vis'),
tabPanel("Transfer", value = 'xfer'),
tabPanel("Reproduce", value = 'rep'),
navbarMenu("Support", icon = icon("life-ring"),
HTML('<a href="https://wallaceecomod.github.io/" target="_blank">Wallace Homepage</a>'),
HTML('<a href="https://groups.google.com/g/wallaceEcoMod" target="_blank">Google Group</a>'),
HTML('<a href="https://github.com/wallaceEcoMod/wallace/issues" target="_blank">GitHub Issues</a>'),
HTML('<a href="mailto: [email protected]" target="_blank">Send Email</a>')),
tabPanel(NULL, icon = icon("power-off"), value = "_stopapp")
),
tags$div(
class = "container-fluid",
fluidRow(
column(
4,
wellPanel(
conditionalPanel(
"input.tabs == 'intro'",
includeMarkdown("Rmd/text_intro_tab.Rmd")
),
# OBTAIN OCCS ####
conditionalPanel(
"input.tabs == 'occs'",
div("Component: Obtain Occurrence Data", class = "componentName"),
help_comp_ui("occsHelp"),
radioButtons(
"occsSel", "Modules Available:",
choices = insert_modules_options("occs"),
selected = character(0)
),
tags$hr(),
insert_modules_ui("occs")
),
# OBTAIN ENVS ####
conditionalPanel(
"input.tabs == 'envs'",
div("Component: Obtain Environmental Data", class = "componentName"),
help_comp_ui("envsHelp"),
radioButtons(
"envsSel", "Modules Available:",
choices = insert_modules_options("envs"),
selected = character(0)
),
tags$hr(),
insert_modules_ui("envs")
),
# PROCESS OCCS ####
conditionalPanel(
"input.tabs == 'poccs'",
div("Component: Process Occurrence Data", class = "componentName"),
help_comp_ui("poccsHelp"),
radioButtons(
"poccsSel", "Modules Available:",
choices = insert_modules_options("poccs"),
selected = character(0)
),
tags$hr(),
insert_modules_ui("poccs")
),
conditionalPanel(
"input.tabs == 'penvs'",
div("Component: Process Environmental Data", class = "componentName"),
help_comp_ui("penvsHelp"),
radioButtons(
"penvsSel", "Modules Available:",
choices = insert_modules_options("penvs"),
selected = character(0)
),
tags$hr(),
insert_modules_ui("penvs")
),
# ESPACE ####
conditionalPanel(
"input.tabs == 'espace'",
div("Component: Characterize Environmental Space", class = "componentName"),
help_comp_ui("espaceHelp"),
radioButtons(
"espaceSel", "Modules Available:",
choices = insert_modules_options("espace"),
selected = character(0)
),
tags$hr(),
insert_modules_ui("espace")
),
# PARTITION ####
conditionalPanel(
"input.tabs == 'part'",
div("Component: Partition Occurrence Data", class = "componentName"),
help_comp_ui("partHelp"),
radioButtons(
"partSel", "Modules Available:",
choices = insert_modules_options("part"),
selected = character(0)
),
tags$hr(),
insert_modules_ui("part")
),
# MODEL ####
conditionalPanel(
"input.tabs == 'model'",
div("Component: Build and Evaluate Niche Model", class = "componentName"),
help_comp_ui("modelHelp"),
radioButtons("modelSel", "Modules Available:",
choices = insert_modules_options("model"),
selected = character(0)),
tags$hr(),
insert_modules_ui("model")
),
# VISUALIZE ####
conditionalPanel(
"input.tabs == 'vis'",
div("Component: Visualize Model Results", class = "componentName"),
help_comp_ui("visHelp"),
radioButtons("visSel", "Modules Available:",
choices = insert_modules_options("vis"),
selected = character(0)),
tags$hr(),
insert_modules_ui("vis")
),
# TRANSFER ####
conditionalPanel(
"input.tabs == 'xfer'",
div("Component: Model Transfer", class = "componentName"),
help_comp_ui("xferHelp"),
radioButtons(
"xferSel", "Modules Available:",
choices = insert_modules_options("xfer"),
selected = character(0)),
tags$hr(),
insert_modules_ui("xfer")
),
# REPRODUCIBILITY
conditionalPanel(
"input.tabs == 'rep'",
div("Component: Reproduce", class = "componentName"),
radioButtons(
"repSel", "Modules Available:",
choices = insert_modules_options("rep"),
selected = character(0)
),
tags$hr(),
insert_modules_ui("rep")
)
)
),
# --- RESULTS WINDOW ---
column(
8,
conditionalPanel(
"input.tabs != 'intro' & input.tabs != 'rep'",
fixedRow(
column(
4,
absolutePanel(
div(style = "margin-top: -10px"),
uiOutput("curSpUI"),
div(style = "margin-top: -12px"),
uiOutput("curModelUI")
)
),
column(
2,
offset = 1,
align = "left",
div(style = "margin-top: -10px"),
strong("Log window"),
div(style = "margin-top: 5px"),
div(
id = "wallaceLog",
div(id = "logHeader", div(id = "logContent"))
)
)
)
),
br(),
conditionalPanel(
"input.tabs != 'intro' & input.tabs != 'rep'",
tabsetPanel(
id = 'main',
tabPanel(
'Map',
leaflet::leafletOutput("map", height = 700),
absolutePanel(
top = 160, right = 20, width = 150, draggable = TRUE,
selectInput("bmap", "",
choices = c('ESRI Topo' = "Esri.WorldTopoMap",
'Stamen Terrain' = "Stamen.Terrain",
'Open Topo' = "OpenTopoMap",
'ESRI Imagery' = "Esri.WorldImagery",
'ESRI Nat Geo' = 'Esri.NatGeoWorldMap'),
selected = "Esri.WorldTopoMap"
)
)
),
tabPanel(
'Occurrences', br(),
DT::dataTableOutput('occTbl')
),
tabPanel(
'Results',
lapply(COMPONENTS, function(component) {
conditionalPanel(
glue::glue("input.tabs == '{component}'"),
insert_modules_results(component)
)
})
),
tabPanel(
'Component Guidance', icon = icon("circle-info"),
uiOutput('gtext_component')
),
tabPanel(
'Module Guidance', icon = icon("circle-info", class = "mod_icon"),
uiOutput('gtext_module')
),
tabPanel(
'Save', icon = icon("floppy-disk", class = "save_icon"),
br(),
h5(em("Note: To save your session code or metadata, use the Reproduce component")),
wellPanel(
h4(strong("Save Session")),
p(paste0("By saving your session into an RDS file, you can resume ",
"working on it at a later time or you can share the file",
" with a collaborator.")),
shinyjs::hidden(p(
id = "save_warning",
icon("triangle-exclamation"),
paste0("The current session data is large, which means the ",
"downloaded file may be large and the download might",
" take a long time.")
)),
downloadButton("save_session", "Save Session"),
br()
),
wellPanel(
h4(strong("Download Data")),
p(paste0("Download data/results from analyses from currently selected module")),
## save module data BEGIN ##
# save occs #
conditionalPanel(
"input.tabs == 'occs'",
br(),
fluidRow(
column(3, h5("Download original occurrence data")),
column(2, shinyjs::disabled(downloadButton('dlDbOccs', "CSV file")))
),
br(),
fluidRow(
column(3, h5("Download current table")),
column(2, shinyjs::disabled(downloadButton('dlOccs', "CSV file")))
),
br(),
fluidRow(
column(3, h5("Download all data")),
column(2, shinyjs::disabled(downloadButton('dlAllOccs', "CSV file")))
)
),
# save envs #
conditionalPanel(
"input.tabs == 'envs'",
br(),
fluidRow(
column(3, h5("Download environmental variables (Select download file type)")),
column(2, selectInput('globalEnvsFileType',
label = NULL,
choices = list("GeoTIFF" = 'GTiff',
"GRD" = 'raster',
"ASCII" = 'ascii'))),
column(2, shinyjs::disabled(downloadButton('dlGlobalEnvs', "ZIP file")))
)
),
# save poccs #
conditionalPanel(
"input.tabs == 'poccs'",
br(),
fluidRow(
column(3, h5("Download processed occurence table")),
column(2, shinyjs::disabled(downloadButton('dlProcOccs', "CSV file")))
)
),
# save penvs #
conditionalPanel(
"input.tabs == 'penvs'",
br(),
fluidRow(
column(3, h5("Download shapefile of background extent")),
column(2, shinyjs::disabled(downloadButton('dlBgShp', "ZIP file")))
),
br(),
fluidRow(
column(3, h5("Download predictor rasters masked to background extent (Select download file type)")),
column(2, selectInput('bgMskFileType',
label = NULL,
choices = list("GeoTIFF" = 'GTiff',
"GRD" = 'raster',
"ASCII" = 'ascii'))),
column(2, shinyjs::disabled(downloadButton('dlMskEnvs', "ZIP file")))
),
br(),
fluidRow(
column(3, h5("Download sample background points")),
column(2, shinyjs::disabled(downloadButton('dlBgPts', "CSV file")))
)
),
# save espace #
conditionalPanel(
"input.tabs == 'espace'",
br(),
fluidRow(
column(3, h5("Download PCA results")),
column(2, shinyjs::disabled(downloadButton('dlPcaResults', "ZIP file")))
),
br(),
fluidRow(
column(3, h5("Download Occurence density grid")),
column(2, shinyjs::disabled(downloadButton('dlOccDens', "PNG file")))
),
br(),
fluidRow(
column(3, h5("Download Niche Overlap plot")),
column(2, shinyjs::disabled(downloadButton('dlNicheOvPlot', "PNG file")))
)
),
# save part #
conditionalPanel(
"input.tabs == 'part'",
br(),
fluidRow(
column(3, h5("Download occurrence and background localities with partition values")),
column(2, shinyjs::disabled(downloadButton('dlPart', "CSV file")))
)
),
# save model #
conditionalPanel(
"input.tabs == 'model'",
br(),
fluidRow(
column(3, h5("Download evaluation table")),
column(2, shinyjs::disabled(downloadButton('dlEvalTbl', "CSV file")))
), br(),
fluidRow(
column(3, h5("Download evaluation groups table")),
column(2, shinyjs::disabled(downloadButton('dlEvalTblBins', "CSV file")))
)
),
# save vis #
conditionalPanel(
"input.tabs == 'vis'",
br(),
fluidRow(
column(3, h5("Download Bioclim plot")),
column(2, shinyjs::disabled(downloadButton('dlVisBioclim', "PNG file")))
),
br(),
fluidRow(
column(3, h5("Download Maxent plots")),
column(2, shinyjs::disabled(downloadButton('dlMaxentPlots', "ZIP file")))
),
br(),
fluidRow(
column(3, h5("Download Response plots")),
column(2, shinyjs::disabled(downloadButton('dlRespCurves', "ZIP file")))
),
br(),
fluidRow(
column(3, h5("Download current prediction (Select download file type**)")),
column(2, selectInput('predFileType',
label = NULL,
choices = list("GeoTIFF" = 'GTiff',
"GRD" = 'raster',
"ASCII" = 'ascii',
"PNG" = 'png'))),
column(2, shinyjs::disabled(downloadButton('dlPred', "Prediction file")))
)
),
# save xfer #
conditionalPanel(
"input.tabs == 'xfer'",
br(),
fluidRow(
column(3, h5("Download shapefile of extent of transfer")),
column(2, shinyjs::disabled(downloadButton('dlXfShp', "ZIP file")))
),
br(),
fluidRow(
column(3, h5("Download environmental variables of transfer (Select download file type)")),
column(2, selectInput('xferEnvsFileType',
label = NULL,
choices = list("GeoTIFF" = 'GTiff',
"GRD" = 'raster',
"ASCII" = 'ascii'))),
column(2, shinyjs::disabled(downloadButton('dlXferEnvs', "ZIP file")))
),
br(),
fluidRow(
column(3, h5("Download transfer (Select download file type**)")),
column(2, selectInput('xferFileType',
label = NULL,
choices = list("GeoTIFF" = 'GTiff',
"GRD" = 'raster',
"ASCII" = 'ascii',
"PNG" = 'png'))),
column(2, shinyjs::disabled(downloadButton('dlXfer', "Transfer file")))
),
br(),
fluidRow(
column(3, h5("Download MESS (Select download file type**)")),
column(2, selectInput('messFileType',
label = NULL,
choices = list("GeoTIFF" = 'GTiff',
"GRD" = 'raster',
"ASCII" = 'ascii',
"PNG" = 'png'))),
column(2, shinyjs::disabled(downloadButton('dlMess', "MESS file")))
)
)
)
)
)
),
## save module data END ##
conditionalPanel(
"input.tabs == 'rep' & input.repSel == null",
column(8,
includeMarkdown("Rmd/gtext_rep.Rmd")
)
),
conditionalPanel(
"input.tabs == 'rep' & input.repSel == 'rep_markdown'",
column(8,
includeMarkdown("modules/rep_markdown.md")
)
),
conditionalPanel(
"input.tabs == 'rep' & input.repSel == 'rep_rmms'",
column(8,
includeMarkdown("modules/rep_rmms.md")
)
),
conditionalPanel(
"input.tabs == 'rep' & input.repSel == 'rep_refPackages'",
column(8,
includeMarkdown("modules/rep_refPackages.md")
)
),
conditionalPanel(
"input.tabs == 'intro'",
tabsetPanel(
id = 'introTabs',
tabPanel(
'About',
includeMarkdown("Rmd/text_about.Rmd")
),
tabPanel(
'Team',
fluidRow(
column(8, includeMarkdown("Rmd/text_team.Rmd")
)
)
),
tabPanel(
'How To Use',
includeMarkdown("Rmd/text_how_to_use.Rmd")
),
tabPanel(
'Load Prior Session',
h4("Load session"),
includeMarkdown("Rmd/text_loadsesh.Rmd"),
fileInput("load_session", "", accept = ".rds"),
actionButton('goLoad_session', 'Load RDS')
)
)
)
)
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/wallace/inst/shiny/ui.R
|
# Main Author for this function: Paul Blanche
# Description :
#
# This function generates 'M' new data sets from NPMLE under the constraint
# that the cumulative incidence function of event 1 is 'pstar' at 'tstar'
GenCRDataAJCons <- function (tstar, pstar, M = 1000, data, myseed=140786)
{
old <- .Random.seed
# {{{ set seed
set.seed(myseed)
# }}}
# number of observations to generate
n <- nrow(data)
# {{{ To generate time to event and cause of event
# CR fit with and without constraint
x <- AJconstrained(tstar, pstar, data)
survTimes <- c(x$time, Inf)
Surv <- 1 - x$CIF1c - x$CIF2c
Survminus <- c(1,Surv[-length(Surv)])
dSurv <- -diff(c(1, Surv))
dSurv <- abs(c(dSurv, 1 - sum(dSurv))) # absolute to avoid problems without long doubles
diffcumInc1 <- diff(c(0,x$CIF1c))
diffcumInc2 <- diff(c(0,x$CIF2c))
lambda1 <- diffcumInc1/Survminus
lambda2 <- diffcumInc2/Survminus
lambda <- lambda1 + lambda2
## cbind(survTimes,c(Surv,0),dSurv,c(0,x$CIF1c),c(0,x$CIF2c)) #diffcumInc1,diffcumInc2)
# }}}
## browser()
# {{{ to generate censoring
# fit KM for censoring
if(sum(data$status==0)>=1){ # only if there is censoring
fitcens <- prodlim(Hist(time,status)~1,data=data,reverse=TRUE)
# censored observation times
censTimes <- sort(unique(data$time[data$status==0]))
# compute probability with which the observed times are drawn
survCens <- predict(fitcens,times=censTimes,type="surv")
censTimes <- c(censTimes, max(data$time) + 1)
dCens <- -diff(c(1, survCens))
dCens <- abs(c(dCens, 1 - sum(dCens))) # absolute to avoid problems without long doubles
}
# }}}
# {{{ function to generate new data
ftoloop <- function(i){
## browser()
if(sum(data$status==0)>=1){ # if there are censored observations
Ci <- sample(censTimes, n, prob = dCens, replace = TRUE)
}
else{
Ci <- rep(max(data$time) + 1, n)
}
# {{{ generate time and cause of event
# first generate the random number of times that each observed time is selected
HowMany <- rmultinom(1, size=n, prob=dSurv)
# then create the vector of observed times by repeated each observed time the suitable number of times
Ti <- rep(survTimes,times=HowMany)
# generate cause
probtogenevent <- rep(c((lambda2/(lambda1 + lambda2)),0.5),times=HowMany) # 0.5 because it does not matter after time point of interest
events <- rbinom(length(Ti),size=1,prob=probtogenevent ) + 1
# }}}
Time <- pmin(Ti,Ci)
Status <- as.numeric(Ti<=Ci)*events
d <- data.frame(time=Time,
status=Status,
event=events,
eventtime=Ti,
censtime=Ci
)
d <- d[order(d$time),]
d
}
## browser()
## ftoloop(1)
# }}}
# {{{ output
out <- list(l=lapply(1:M,ftoloop),x=x)
# }}}
.Random.seed <<- old
out
}
|
/scratch/gouwar.j/cran-all/cranData/wally/R/AJ-constrained-bootstrap.R
|
# Main Author for this function: Paul Blanche
# Description :
#
# This function generates NPMLE under the constraint
# that the cumulative incidence function of event 1 is 'pstar'
# at 'tstar'.
# This current version assumes there are no ties !
AJconstrained <- function (tstar, CIF1star, data, mytol=10^(-5), plotUNBUG = FALSE)
{
# {{{ data management steps (just fo rme)
data <- data[order(data$time),]
time <- data$time
status <- data$status
# {{{ help for unbugging
## plot(prodlim(Hist(time,status)~1,data=data))
## plot(prodlim(Hist(time,status)~1,data=data),cause=2,col="red",add=TRUE)
## abline(v=tstar,lty=2)
# }}}
# }}}
# {{{ STOP : if ties
if(length(unique(time))!=length(time)){
stop("This function does not handle ties to compute the constrained version of the Aalen-Johansen estimates.")
}
# }}}
# {{{ handle the case where no main event is observed
if(sum(data$time<=tstar & data$status==1)==0){
# we should had an observed event in that case to allow a jump of the CIF at that time !
# first we check if an observed time corresponds to tstar, if yes, we had an event.
# If no, we add a time to the data
if(!(tstar %in% data$time)){
time <- c(time,tstar)
status <- c(status,1)
status <- status[order(time)]
time <- time[order(time)]
## cbind(time,status)
}else{
status[which(tstar==time)] <- 1
}
# Be careful, when compute for lambda=0, then we want the original data !
}
## browser()
# }}}
# {{{ useful quantities
N <- length(time)
## tab <- table(time, status)
tab <- table(time,factor(status,levels=c(0,1,2)))
d1i <- tab[, 2]
d2i <- tab[, 3]
ci <- tab[, 1]
ti <- as.numeric(dimnames(tab)[[1]])
k <- length(ti)
ni <- c(N, N - cumsum(ci)[-k] - cumsum(d1i)[-k] - cumsum(d2i)[-k])
# keep only for ti before tstar
II <- ti <= tstar
nj <- ni[II]
d1j <- d1i[II]
d2j <- d2i[II]
cj <- ci[II]
kj <- sum(II)
## cbind(ti[II],nj,d1j,d2j,cj)
## browser()
# }}}
# {{{ function to compute estimates given lamda
CIFlambda <- function(lambda) {
if(kj==0){
out <- list(forRoot=0,
Surv=1,
a=0,
a1=0,
a2=0,
CIF1=0,
CIF2=0,
alla1a2Positive=TRUE,
alla1Positive=TRUE,
alla2Positive=TRUE,
allOK=TRUE)
return(out)
}
# initialize vectors
a1 <- rep(0,kj) # cause-1-specific hazard
a2 <- rep(0,kj) # cause-2-specific hazard
a <- rep(0,kj) # all-causes hazard
Surv <- rep(1,kj) # survival : P(T > t_i)
CIF1 <- rep(0,kj) # CIF 1: P(T<=t_i, eta=1)
CIF2 <- rep(0,kj) # CIF 1: P(T<=t_i, eta=2)
# loop over ti
for (i in 1:kj) {
if(i==1){
if(d1j[i]>0){
# event at ti is event 1
a1[i] <- 1/(nj[i] + lambda*(1-0-CIF1star) )
}else{
if(d2j[i]>0){
# event at ti is event 2
a2[i] <- 1/(nj[i] + lambda*(0-CIF1star))
}
} # else, i.e. if event at ti is censoring, then we keep a2[i]=a1[i]=0
a[i] <- a1[i] + a2[i]
Surv[i] <- 1*(1- a[i])
CIF1[i] <- 0 + 1*a1[i]
CIF2[i] <- 0 + 1*a2[i]
}else{
if(d1j[i]>0){
# event at ti is event 1
a1[i] <- 1/(nj[i] + lambda*(1 - CIF2[i-1] - CIF1star) )
}else{
if(d2j[i]>0){
# event at ti is event 2
a2[i] <- 1/(nj[i] + lambda*(CIF1[i-1] - CIF1star))
}
}
# else, i.e. if event at ti is censoring, then we keep a2[i]=a1[i]=0
a[i] <- a1[i] + a2[i]
Surv[i] <- Surv[i-1]*(1-a[i])
CIF1[i] <- CIF1[i-1] + Surv[i-1]*a1[i]
CIF2[i] <- CIF2[i-1] + Surv[i-1]*a2[i]
}
}
# output
out <- list(forRoot=CIF1[kj],
Surv=Surv,
a=a,
a1=a1,
a2=a2,
CIF1=CIF1,
CIF2=CIF2,
alla1a2Positive=all(c(a1>=0,a2>=0)),
alla1Positive=all(a1>=0),
alla2Positive=all(a2>=0),
allOK=all(c(a1>=0,
a2>=0,
CIF1<=1,
CIF1>=0,
CIF2<=1,
CIF2>=0,
CIF1 + CIF2<=1
))
)
out
}
# }}}
# {{{ find lambda
## browser()
# {{{ we find interval for lambda with positive values for all aki in which to use uniroot
## print(paste("lambda.min : start"))
thelambdamin <- -N*1000
try(thelambdamin <- uniroot(f=function(l){as.numeric(CIFlambda(l)$allOK) - 0.5},
lower=-N*1000, # How to choose that ????
upper=0,
tol=mytol)$root,silent=TRUE)
## browser()
if(!CIFlambda(thelambdamin)$allOK){
nwhilellop <- 0
while(!CIFlambda(thelambdamin)$allOK & nwhilellop<30){
## print(paste("While loop (1), step ",nwhilellop,": thelambdamin=",thelambdamin,"start"))
nwhilellop <- nwhilellop + 1
thelambdamin <- uniroot(f=function(l){as.numeric(CIFlambda(l)$allOK) - 0.5},
lower=thelambdamin,
upper=0,
## extendInt = c("downX"),
tol=mytol)$root
## print(paste("While loop (1), step ",nwhilellop,": thelambdamin=",thelambdamin,"stop"))
}
}
## print(paste("lambda.min : done"))
## print(paste("thelambdamin=",thelambdamin))
## browser()
if(sum(data$status==2)>=1){ # only if there are cometing events
## browser()
thelambdamax <- N*1000
try(thelambdamax <- uniroot(f=function(l){as.numeric(CIFlambda(l)$allOK) - 0.5},
lower=0,
upper=N*1000, # How to choose that ????
## extendInt = c("upX"),
tol=mytol)$root,silent=TRUE)
## print(paste("lambda.max : first done"))
if(!CIFlambda(thelambdamax)$allOK){
nwhilellop2 <- 0
while(!CIFlambda(thelambdamax)$allOK & nwhilellop2<30){
## print(paste("While loop (2), step ",nwhilellop2,": thelambdamax=",thelambdamax))
nwhilellop2 <- nwhilellop2 + 1
thelambdamax <- uniroot(f=function(l){as.numeric(CIFlambda(l)$allOK) - 0.5},
lower=0,
upper=thelambdamax,
tol=mytol)$root
## print(paste("while loop :",nwhilellop2))
}
}
}else{
thelambdamax <- N*1000
}
## print(paste("thelambdamax=",thelambdamax))
## print(paste("lambda.max : done"))
# }}}
# {{{ to understand bugs
## browser()
if(plotUNBUG){
lengthxxx <- 1000
## xxx <- seq(from=thelambdamin-1,to=thelambdamax+1,length.out=lengthxxx)
xxx <- seq(from=thelambdamin,to=thelambdamax,length.out=lengthxxx)
yyy <- sapply(xxx,function(x){o <- CIFlambda(x);o$forRoot - CIF1star})
plot(xxx,yyy,ylim=c(-1,1),col=ifelse(yyy<=0,"blue","red"))
abline(h=0)
abline(v=thelambdamin)
abline(v=thelambdamax)
## abline(v=(-N/(1-CIF1star)),col="red")
## abline(v=(N/CIF1star),col="red")
#
## yyy[1]
## yyy[lengthxxx]
## CIFlambda(xxx[1])$alla1a2Positive
## CIFlambda(xxx[lengthxxx])$alla1a2Positive
## CIFlambda(xxx[1] + 5)$alla1a2Positive
## CIFlambda(xxx[1] + 100/N)$forRoot - CIF1star
## CIFlambda(xxx[lengthxxx])$alla1a2Positive
#
## CIFlambda(thelambdamin)$alla1a2Positive
## CIFlambda(thelambdamax)$alla1a2Positive
## CIFlambda(thelambdamax)$forRoot
## CIFlambda(thelambdamax)$forRoot - CIF1star
## CIFlambda(thelambdamin)$forRoot - CIF1star
## points(thelambdamin,CIFlambda(thelambdamin)$forRoot - CIF1star,col="red")
## points(thelambdamax,CIFlambda(thelambdamax)$forRoot - CIF1star,col="red")
## CIFlambda(thelambdamax)$allOK
## CIFlambda(thelambdamax)$CIF1
## CIFlambda(thelambdamax)$CIF2
## CIFlambda(thelambdamax)$a
}
# }}}
## print(paste("Int lambda.min , lambda.max : done"))
# {{{ find lambda within interval
## browser()
thelambda <- uniroot(f=function(x){CIFlambda(x)$forRoot - CIF1star},
lower=(thelambdamin + 1/N),
upper=(thelambdamax -1/N))$root
# {{{ to understand bugs
if(plotUNBUG){
abline(v=thelambda,col="red")
}
# }}}
# }}}
# }}}
# {{{ compute everything with the right value for lambda
outCIFlambda <- CIFlambda(thelambda)
timeout <- time[II] # save the time points for we observe some jumps in CIF1 or CIF2 (as modify it just after)
if(sum(data$time<=tstar & data$status==1)==0){
# in that case we need to redefine what is used by CIFlambda
data <- data[order(data$time),]
time <- data$time
status <- data$status
# {{{ useful quantities
N <- length(time)
## tab <- table(time, status)
tab <- table(time,factor(status,levels=c(0,1,2)))
d1i <- tab[, 2]
d2i <- tab[, 3]
ci <- tab[, 1]
ti <- as.numeric(dimnames(tab)[[1]])
k <- length(ti)
ni <- c(N, N - cumsum(ci)[-k] - cumsum(d1i)[-k] - cumsum(d2i)[-k])
# keep only for ti before tstar
II <- ti <= tstar
nj <- ni[II]
d1j <- d1i[II]
d2j <- d2i[II]
cj <- ci[II]
kj <- sum(II)
## cbind(ti[II],nj,d1j,d2j,cj)
# }}}
}
outCIFlambda0 <- CIFlambda(0)
# }}}
# {{{ output
out <- list(n=N,
time = timeout,
CIF1c = outCIFlambda$CIF1,
CIF2c = outCIFlambda$CIF2,
tstar=tstar,
CIF1star=CIF1star,
outCIFlambda=outCIFlambda,
outCIFlambda0=outCIFlambda0,
lambda=thelambda,
lambdaSeachInt=c(thelambdamin,thelambdamax)
)
class(out) <- "constrainedAJ"
# }}}
## print(paste("CIF1star = ",CIF1star,": DONE"))
out
}
|
/scratch/gouwar.j/cran-all/cranData/wally/R/AJ-constrained.R
|
# Main Author for this function: Paul Blanche
# Description :
#
# This function generates 'M' new data sets from NPMLE under the constraint
# that the survival function is 'pstar' at 'tstar'.
GenSurvDataKMCons <- function (tstar, pstar, M = 1000, data, myseed=140786) {
old <- .Random.seed
# {{{ set seed
set.seed(myseed)
# }}}
# number of observations to generate
n <- nrow(data)
# {{{ To generate time to event
# fit KM with and without constraint
x <- KMconstrained(tstar, pstar, data)
survTimes <- c(x$time, Inf)
dSurv <- -diff(c(1, x$Sc))
dSurv <- abs(c(dSurv, 1 - sum(dSurv))) # absolute to avoid problems without long doubles
# }}}
# {{{ to generate censoring
# fit KM for censoring
if(sum(data$status==0)>0){
fitcens <- prodlim(Hist(time,status)~1,data=data,reverse=TRUE)
# censored observation times
censTimes <- sort(unique(data$time[data$status==0]))
# compute probability with which the observed times are drawn
survCens <- predict(fitcens,times=censTimes,type="surv")
censTimes <- c(censTimes, max(data$time) + 1)
dCens <- -diff(c(1, survCens))
dCens <- abs(c(dCens, 1 - sum(dCens))) # absolute to avoid problems without long doubles
}
# }}}
# {{{ function to generate new data
ftoloop <- function(i){
## browser()
if (sum(data$status==0)>0) {
Ci <- sample(censTimes, n, prob = dCens, replace = TRUE)
}
else{
Ci <- rep(max(data$time) + 1, n)
}
Ti <- sample(survTimes, n, prob = dSurv, replace = TRUE)
Time <- pmin(Ti,Ci)
Status <- as.numeric(Ti<=Ci)
d <- data.frame(time=Time,
status=Status,
eventtime=Ti,
censtime=Ci
)
d <- d[order(d$time),]
d
}
## browser()
## ftoloop(1)
# }}}
# {{{ output
out <- lapply(1:M,ftoloop)
# }}}
.Random.seed <<- old
out
}
|
/scratch/gouwar.j/cran-all/cranData/wally/R/KM-constrained-bootstrap.R
|
# Main Author for this function: Paul Blanche from previous code from the bpcp package.
# Description :
# This function gives NPMLE of the survival function
# under the constraint that the survival function is 'pstar'
# at 'tstar'.
#
# This is a slightly modified version of the funtion KMconstrainedfrom
# the bpcp package (bpcp_1.3.4, acessed in july 2016),
# We included some stuff of the kmgw.calc function of the same packge
KMconstrained <- function (tstar, pstar, data) {
# {{{ data management steps (just fo rme)
data <- data[order(data$time),]
time <- data$time
status <- data$status
# }}}
# {{{ From kmgw.calc function packge bpcp
N <- length(time)
tab <- table(time, status)
dstat <- dimnames(tab)$status
if (length(dstat) == 2) {
di <- tab[, 2]
ci <- tab[, 1]
}
else if (length(dstat) == 1) {
if (dstat == "1") {
di <- tab[, 1]
ci <- rep(0, length(tab))
}
else if (dstat == "0") {
ci <- tab[, 1]
di <- rep(0, length(tab))
}
}
else stop("status should be 0 or 1")
y <- as.numeric(dimnames(tab)[[1]])
k <- length(y)
ni <- c(N, N - cumsum(ci)[-k] - cumsum(di)[-k])
names(ni) <- names(di)
ni <- as.numeric(ni)
di <- as.numeric(di)
ci <- as.numeric(ci)
KM <- cumprod((ni - di)/ni)
gw <- KM^2 * cumsum(di/(ni * (ni - di)))
gw[KM == 0] <- 0
I <- di > 0
x <- list(time = y[I], # times (uncensored observations only)
di = di[I], # numbers of observed event at the times
ni = ni[I], # numbers of subjects at risk at the times
KM = KM[I], # KM estimates at the times
gw = gw[I] # Greenwood estimate of the variance of KM estimates at the times
)
# }}}
# {{{ From KMconstrained of bpcp package
II <- x$time <= tstar
if (any(II)) {
nj <- x$ni[II]
dj <- x$di[II]
rootfunc <- function(lambda) {
nl <- length(lambda)
out <- rep(NA, nl)
for (i in 1:nl) {
out[i] <- prod((nj + lambda[i] - dj)/(nj + lambda[i])) -
pstar
}
out
}
lambda <- uniroot(rootfunc, c(-min(nj - dj), 10^3 * nj[1]))$root
## browser()
pbar <- (nj + lambda - dj)/(nj + lambda)
Sbar <- cumprod(pbar)
out <- list(time = x$time[II], Sc = Sbar, x=x, tstar=tstar, pstar=pstar)
}
else {
out <- list(time = tstar, Sc = pstar, x=x, tstar=tstar, pstar=pstar)
}
class(out) <- "constrainedKM"
out
# }}}
}
|
/scratch/gouwar.j/cran-all/cranData/wally/R/KM-constrained.R
|
calibrationBarplot <- function(x,...){
control <- x$control
hanging <- x$hanging
Pred <- x$Pred
Obs <- x$Obs
# {{{ legend
if(is.logical(x$legend[1]) && x$legend[1]==FALSE){
control$barplot$legend.text <- NULL
}else{
control$barplot$legend.text <- control$legend$legend
control$barplot$args.legend <- control$legend
}
# }}}
if (is.null(control$barplot$space)) control$barplot$space <- rep(c(1,0),length(Pred))
# {{{ height of the bars
PredObs <- c(rbind(Pred,Obs))
control$barplot$height <- PredObs
if (hanging){
control$barplot$offset <- c(rbind(0,Pred-Obs))
minval <- min(Pred-Obs)
if (minval<0)
negY.offset <- 0.05+seq(0,1,0.05)[prodlim::sindex(jump.times=seq(0,1,0.05),eval.times=abs(minval))]
else
negY.offset <- 0
control$barplot$ylim[1] <- min(control$barplot$ylim[1],-negY.offset)
control$barlabels$y <- control$barlabels$y-negY.offset
}
# }}}
# {{{ call barplot
coord <- do.call("barplot",control$barplot)
# }}}
# {{{ label bars (below)
if (is.character(x$labels)){
mids <- rowMeans(matrix(coord,ncol=2,byrow=TRUE))
text(x=mids,
y=rep(control$barlabels$y,length.out=length(mids)),
labels=control$barlabels$text,
xpd=NA,
cex=control$barlabels$cex)
}
# }}}
# {{{ horizontal line
if (hanging){
do.call("abline",control$abline)
}
# }}}
# {{{ labels on top of the bars
if (x$showFrequencies){
if(hanging){
text(x=coord,
cex=control$frequencies$cex,
pos=3,
y=(as.vector(rbind(Pred,Pred)) +rep(control$frequencies$offset,times=length(as.vector(coord))/2)),
paste(round(100*c(rbind(Pred,Obs)),0),ifelse(control$frequencies$percent,"%",""),sep=""),xpd=NA)
}else{
text(x=coord,
pos=3,
y=c(rbind(Pred,Obs))+control$frequencies$offset,
cex=control$frequencies$cex,
paste(round(100*c(rbind(Pred,Obs)),0),
ifelse(control$frequencies$percent,"%",""),
sep=""),xpd=NA)
}
}
# }}}
# {{{ Paulo add for ISCB
if (hanging){
offset <- control$barplot$offset
hline.args <- c(list(x=c(0,1,ceiling(coord[,1]),ceiling(coord[,1])[length(ceiling(coord[,1]))],ceiling(coord[,1])[length(ceiling(coord[,1]))]+1),
y= c(offset[1],offset,offset[length(offset)],rep(offset[1],2))),
control$hline)
do.call("lines",hline.args)
}
# }}}
# {{{ axis
if (x$axes){
control$axis2$labels <- paste(100*control$axis2$at,"%")
do.call("axis",control$axis2)
}
invisible(coord)
# }}}
}
#----------------------------------------------------------------------
### plotCalibrationPlot.R ends here
|
/scratch/gouwar.j/cran-all/cranData/wally/R/calibrationBarplot.R
|
### wally-package.R ---
#----------------------------------------------------------------------
## Author: Thomas Alexander Gerds
## Created: Apr 28 2017 (11:13)
## Version:
## Last-Updated: May 16 2017 (08:11)
## By: Thomas Alexander Gerds
## Update #: 7
#----------------------------------------------------------------------
##
### Commentary:
##
### Change Log:
#----------------------------------------------------------------------
##
### Code:
#'
#' divat data
#'
#' Extracted data from a french population based cohort (DIVAT cohort). The dataset includes
#' followup information on kidney graft failure outcome and predicted 5-year risks based on
#' based on the subject specific information which includes age, gender,
#' cardiovascular and diabetes histories, monitoring of the evolution of the kidney function
#' measured via serum creatinine and relevant characteristics of his or her kidney donor.
#' Graft failure is defined as either death with functioning kidney graft or return to dialysis.
#' The prediction model from which the predictions have been computed has been previously fitted
#' using an independent training sample from the DIVAT data. Details about data and modeling can
#' be found in Fournier et al. (2016).
#'
#' @name divat
#' @docType data
#' @format A subsample consisting of 1300 observations on the following 3 variables.
#' \describe{ \item{pi}{5-year risk prediction of kidney graft failure.}
#' \item{status}{0=censored, 1=kidney graft failure}
#' \item{time}{time to event (i.e., time to kidney graft failure or loss of follow-up)}}
#' @references
#' Fournier, M. C., Foucher, Y., Blanche, P., Buron, F., Giral, M., & Dantan, E. (2016).
#' A joint model for longitudinal and time-to-event data to better assess the specific
#' role of donor and recipient factors on long-term kidney transplantation outcomes.
#' European journal of epidemiology, 31(5), 469-479.
#'
#' @keywords datasets
#' @examples
#'
#' data(divat)
NULL
#' threecity data
#'
#' Extracted data from a french population based cohort (Three-City cohort). The dataset includes
#' followup information on dementia outcome and predicted 5-year risks based on
#' based on the subject specific information which includes age, gender,
#' education level and cognitive decline measured by a psychometric test
#' (Mini Mental State Examination). The prediction model from which the
#' predictions have been computed has been fitted on independent training
#' data from the Paquid cohort, another french population based cohort with similar design (see Reference Blanche et al. 2015 for details) .
#'
#' @name threecity
#' @docType data
#' @format A subsample consisting of 2000 observations on the following 3 variables.
#' \describe{ \item{pi}{5-year absolute risk predictions of dementia.}
#' \item{status}{0=censored, 1=dementia, 2=death dementia free}
#' \item{time}{time to event (i.e., time to
#' either dementia, death dementia free or loss of follow-up)}}
#' @references
#' Blanche, P., Proust-Lima, C., Loubere, L., Berr, C., Dartigues, J. F., Jacqmin-Gadda, H. (2015).
#' Quantifying and comparing dynamic
#' predictive accuracy of joint models for longitudinal marker and
#' time-to-event in presence of censoring and competing risks.
#' Biometrics, 71(1), 102-113.
#'
#' @source
#'
#' Web-appendix of Blanche et al. (2015).
#'
#' @keywords datasets
#' @examples
#'
#' data(threecity)
#'
#'
#' @importFrom prodlim Hist jackknife prodlim sindex
#' @importFrom stats rmultinom
#' @importFrom grDevices col2rgb gray
#' @importFrom graphics bxp abline axis box legend lines mtext par plot points segments text title polygon par boxplot
#' @importFrom utils capture.output find head select.list tail
#' @importFrom stats as.formula coef delete.response drop.terms family formula get_all_vars glm median model.frame model.matrix model.response na.fail na.omit optim pnorm predict qnorm quantile rbinom reformulate rexp runif sd setNames smooth terms terms.formula time uniroot update update.formula var wilcox.test
NULL
######################################################################
### wally-package.R ends here
|
/scratch/gouwar.j/cran-all/cranData/wally/R/wally-package.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.