diff --git a/.Rbuildignore b/.Rbuildignore index f301229..d6640e5 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -10,3 +10,4 @@ cran-comments.md ^pkgdown$ ^vignettes +^bench$ diff --git a/.gitignore b/.gitignore index b74ce8f..7a91210 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,6 @@ doc Meta /doc/ /Meta/ +bench/lib_*/ +bench/results.csv +bench/benchmark.log diff --git a/DESCRIPTION b/DESCRIPTION index 67c9158..92c4a79 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -5,25 +5,26 @@ Imports: mrds, Distance, sf, + terra, ggplot2, purrr, dplyr, mgcv, methods, - rstudioapi, + mirai, + parallel, + parallelly, gridExtra, rlang Suggests: testthat, bookdown, - parallel, - pbapply, knitr, lwgeom, rmarkdown Type: Package Title: Distance Sampling Simulations -Version: 1.0.6 +Version: 1.2.0 Authors@R: c( person("Laura", "Marshall", email = "lhm@st-and.ac.uk", role = c("aut", "cre")), person("Thomas", "Len", email = "len.thomas@st-andrews.ac.uk", role = "ctb")) @@ -84,6 +85,7 @@ Collate: 'get.density.surface.R' 'message.handler.R' 'modify.strata.for.analysis.R' + 'population.generator.R' 'process.dist.shapes.R' 'read.line.transects.R' 'read.point.transects.R' diff --git a/NAMESPACE b/NAMESPACE index 216ae22..6185322 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -75,15 +75,19 @@ importFrom(methods,slot) importFrom(methods,slotNames) importFrom(methods,validObject) importFrom(mgcv,predict.gam) +importFrom(mirai,daemons) +importFrom(mirai,daemons_set) +importFrom(mirai,everywhere) +importFrom(mirai,is_error_value) +importFrom(mirai,is_mirai_error) +importFrom(mirai,mirai) +importFrom(mirai,mirai_map) +importFrom(mirai,unresolved) importFrom(mrds,dht) -importFrom(parallel,clusterEvalQ) -importFrom(parallel,detectCores) -importFrom(parallel,makeCluster) -importFrom(parallel,parLapply) -importFrom(parallel,stopCluster) +importFrom(parallel,nextRNGStream) +importFrom(parallelly,availableCores) importFrom(purrr,reduce) importFrom(rlang,.data) -importFrom(rstudioapi,versionInfo) importFrom(sf,as_Spatial) importFrom(sf,st_area) importFrom(sf,st_as_sf) @@ -112,6 +116,5 @@ importFrom(stats,rnorm) importFrom(stats,rpois) importFrom(stats,runif) importFrom(stats,sd) -importFrom(utils,flush.console) importFrom(utils,packageVersion) importFrom(utils,write.table) diff --git a/NEWS.md b/NEWS.md index 44bf76b..821850f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,43 @@ +# dsims 1.2.0 + +Enhancements + +* `make.simulation()` has a new argument `population.generator`, a `function(simulation, rep)` which is called in each repetition instead of `generate.population(simulation)`. It returns a `Population` object or `list(population = , truth = list(N = , D = ))`. This allows, for example, a population to be drawn over a whole study area in every repetition with only the individuals inside the survey region (the design region) being surveyed. The returned population is checked (class, required columns, strata names and that all individuals lie inside the design region) and an informative error is given if a check fails. The random number generator state is saved before the generator is called and restored afterwards, so the generator can use its own seed stream (e.g. one which depends only on `rep`): simulations which differ only in their design then see identical populations in each repetition, and the transects, detections and analyses are unaffected by the random numbers the generator uses. The generator works with `run.simulation(run.parallel = TRUE)`; see the 'Population generator' section of `?make.simulation` for the requirements. +* If the population generator returns `truth`, the per-repetition true N and/or D of the whole target area are stored in `simulation@results$truth` (array `[1, c("N", "D"), reps + 2]`) and `summary()` uses them, instead of the population description, for the truth, percent bias, RMSE and CI coverage of the total abundance / density. The printed summary shows the source of the truth (also stored in the new `truth.source` slot of `Simulation.Summary`). +* The realised number of individuals in the design region is now stored for every repetition in `simulation@results$individuals$true.N` (and `simulation@results$clusters$true.N` for clusters), with one row per stratum as in the other results arrays. +* `make.ds.analysis()` has a new argument `zero.n = c("fail", "zero")`. With `"zero"` a repetition with no detections within the truncation distance is recorded as a successful estimate of zero (N and D Estimate = 0, lcl = 0, se, cv and ucl = NA, with n = 0 and the area, covered area and effort recorded as usual) and flagged in the new `ZeroDetections` column of `simulation@results$Detection`. `summary()` includes these repetitions in the mean, SD, RMSE and bias (CI coverage only uses repetitions with a defined confidence interval) and reports their number. Repetitions with detections where no model could be fitted remain failures. The default `"fail"` keeps the previous behaviour. + +Bug Fixes + +* CI coverage in `summary()` was calculated from the first k repetitions rather than the k included repetitions when some repetitions had failed (or with `use.max.reps = FALSE` and some models not converging). It now uses the included repetitions. Results are unchanged when no repetitions are excluded. +* Surveying a population with no individuals no longer gives warnings from `sf`. +* With the uniform detection function (`key.function = "uf"` in `make.detectability()`), a repetition in which no individual was within the truncation distance of any transect stopped with "invalid arguments" from `rbinom()` and was skipped. It is now handled like the other keys (a failure with the default `zero.n = "fail"`, an estimate of zero with `zero.n = "zero"`). Previously, skipping these repetitions biased results upwards in sparse scenarios. + +Other changes + +* `simulation@results$Detection` has an additional column, `ZeroDetections` (0 for repetitions analysed as usual). With `population.generator` and `zero.n` left at their defaults, simulation results are otherwise identical to dsims 1.1.0 for the same seed. + +# dsims 1.1.0 + +Enhancements + +* Parallel processing now uses the mirai package. Repetitions are distributed to workers as they become free, and workers start faster than with the previous cluster setup. +* Simulations are now run in parallel by default (`run.parallel = TRUE`). The default number of workers is `parallelly::availableCores(omit = 1)`, which respects limits set by HPC schedulers and containers. Daemons set up by the user with `mirai::daemons()` (including remote / HPC daemons) are used if present. +* Each repetition uses its own random number stream, so after `set.seed()` results are identical whether run in serial or in parallel, regardless of the number of workers. +* A repetition that fails with an error no longer stops the simulation; it is skipped and reported in the summary of warnings and errors. +* The progress counter is now shown when running in parallel and includes the elapsed and estimated remaining time. +* `make.ds.analysis()` now accepts `key = "unif"` (or `"uf"`) to fit a uniform detection function, giving the strip transect estimate n / covered area. Covariates cannot be used with the uniform key. Previously only "hn" and "hr" were allowed although the documentation listed uniform. + +Bug Fixes + +* Fractional values of `N` with `fixed.N = TRUE` were silently rounded up when generating each stratum's population, while the unrounded `N` was used as the true abundance. With many small strata this inflated the simulated population relative to the truth. `make.population.description()` now stops if `N` is not a whole number when `fixed.N = TRUE`. + +Breaking Changes + +* Results from simulations run with a given seed will differ from those obtained with previous versions of dsims, as the random number streams have changed. +* `N` must be whole numbers when `fixed.N = TRUE` (see Bug Fixes). +* Worker processes now appear as `mirai::daemon(...)` rather than PSOCK workers (`workRSOCK`), which affects scripts that monitor the worker processes. + # dsims 1.0.6 Bug Fixes diff --git a/R/ClassConstructors.R b/R/ClassConstructors.R index c669fbc..1d48573 100755 --- a/R/ClassConstructors.R +++ b/R/ClassConstructors.R @@ -116,7 +116,8 @@ make.density <- function(region = make.region(), x.space = 20, y.space = NULL, c #' @param density the Density object describing the distribution of the individuals / clusters (see \link{make.density}). #' @param covariates Named list with one named entry per individual-level covariate. Cluster sizes can be defined here, it must be named 'size'. The distribution of covariate values can either be defined by specifying a particular distribution and its parameters or as a discrete distribution in a dataframe. Dataframes should have columns level and prob (and optionally strata) specifying the covariates levels, probabilities and strata if they are strata specific. Distributions can be defined as lists with named entries distribution and the relevant parameters as specified in details. A list of distributions can be provided with one for each strata. #' @param N the number of individuals / clusters in a population with one value per -#' strata. Total population size is 1000 by default. +#' strata. Total population size is 1000 by default. When \code{fixed.N = TRUE} +#' the values must be whole numbers. #' @param fixed.N a logical value. If TRUE the population is generated from the value(s) #' of N otherwise it is generated from the values in the density grid. #' @return \code{\link{Population.Description-class}} @@ -270,6 +271,22 @@ make.population.description <- make.pop.description <- function(region = make.re #' @param scale.param numeric vector with either a single value to be applied globally or a value for each strata. These should be supplied on the natural scale. #' @param shape.param numeric vector with either a single value to be applied globally or a value for each strata. These should be supplied on the natural scale. #' @param cov.param Named list with one named entry per individual level covariate. Covariate parameter values should be defined on the log scale (rather than the natural scale), this is the same scale as provided in the ddf output in mrds and also in the MCDS output in Distance. Cluster sizes parameter values can be defined here. Each list entry will either be a data.frame containing 2 or 3 columns: level, param and where desired strata. If the region has multiple strata but this column is omitted then the values will be assumed to apply globally. The cluster size entry in the list must be named 'size'. Alternatively the list element may a numeric vector with either a single value to be applied globally or a value for each strata. +#' @param cov.surface Optional named list of raster surfaces providing spatially-explicit +#' covariate values based on each animal's simulated location. Each element name must +#' match a numeric entry in \code{cov.param} (which gives the log-scale slope applied to +#' the extracted raster value). Each element should be either a character file path to a +#' single-layer raster readable by \code{terra::rast()}, or an in-memory +#' \code{terra} SpatRaster object. At every simulation replicate the raster is sampled at +#' each animal's (x, y) location; the value is used as the covariate in the standard +#' log-linear scaling formula: +#' \eqn{\log(\sigma_i) = \log(\sigma_0) + \beta \cdot z_i}. +#' Use a negative \code{cov.param} slope to model lower detectability where raster values +#' are higher (e.g. denser canopy cover reduces detection range). +#' Animal locations outside the raster extent or with NA cell values are replaced with the +#' raster mean and a warning is issued. +#' \strong{Parallel note:} file paths are strongly preferred over in-memory SpatRaster +#' objects when running in parallel (see \code{\link{run.simulation}}), as large +#' objects may not serialise efficiently to worker processes. #' @param truncation the maximum perpendicular (or radial) distance at which #' objects may be detected from a line (or point) transect. #' @return \code{\link{Detectability-class}} object @@ -323,9 +340,9 @@ make.population.description <- make.pop.description <- function(region = make.re #' #' plot(detect, popdesc) #' -make.detectability <- function(key.function = "hn", scale.param = 25, shape.param = numeric(0), cov.param = list(), truncation = 50){ +make.detectability <- function(key.function = "hn", scale.param = 25, shape.param = numeric(0), cov.param = list(), cov.surface = list(), truncation = 50){ # Passes all arguments to function to make a new instance of the class - detectability <- new(Class = "Detectability", key.function = key.function, scale.param = scale.param, shape.param = shape.param, cov.param = cov.param, truncation = truncation) + detectability <- new(Class = "Detectability", key.function = key.function, scale.param = scale.param, shape.param = shape.param, cov.param = cov.param, cov.surface = cov.surface, truncation = truncation) return(detectability) } @@ -358,8 +375,14 @@ make.detectability <- function(key.function = "hn", scale.param = 25, shape.para #' #' @param dfmodel list of distance sampling model formula specifying the detection function #' (see \code{?Distance::ds} for further details) -#' @param key key function to use; "hn" gives half-normal (default) and "hr" gives -#' hazard-rate. +#' @param key key function to use; "hn" gives half-normal (default), "hr" gives +#' hazard-rate and "unif" (or "uf") gives uniform. The uniform key has no +#' parameters, so it assumes all animals within the truncation distance are +#' detected (a strip transect estimate) and covariates cannot be included +#' (the corresponding dfmodel must be ~1). If the simulated detectability is +#' less than 1 within the strip (e.g. \code{make.detectability(key.function = "uf", +#' scale.param = 0.9)}) the uniform analysis will underestimate abundance by +#' the same proportion, as g(0) < 1 cannot be estimated from the distances. #' @param truncation absolute truncation distance in simulation units matching the #' region units. #' @param cutpoints supply a vector of cutpoints if you wish the simulation to perform @@ -373,6 +396,18 @@ make.detectability <- function(key.function = "hn", scale.param = 25, shape.para #' second specifies how they should be grouped (into less strata) for the analyses. See #' details for more information. #' @param criteria character model selection criteria (AIC, AICc, BIC) +#' @param zero.n how to treat a repetition with no detections within the +#' truncation distance. "fail" (default) skips the repetition, it is reported +#' as a warning and counted as excluded in the summary. "zero" records the +#' repetition as a successful estimate of zero: abundance and density +#' Estimate = 0, lcl = 0 and se, cv and ucl = NA. The number of detections +#' (n = 0), area, covered area and effort are recorded as usual and the +#' repetition is flagged in the ZeroDetections column of +#' \code{simulation@@results$Detection}. Zero detection repetitions are then +#' included in the mean, SD, RMSE and bias reported by +#' \code{summary()}, while CI coverage only uses repetitions with a defined +#' confidence interval. Repetitions with one or more detections where no model +#' could be fitted remain failures under both options. #' @return \code{\link{DS.Analysis-class}} object #' @export #' @importFrom methods new is @@ -401,6 +436,12 @@ make.detectability <- function(key.function = "hn", scale.param = 25, shape.para #' truncation = 500, #' criteria = "AIC") #' +#' # Uniform (strip transect) analysis, e.g. for a camera where every animal +#' # within the strip is detected (see make.detectability with key.function = "uf") +#' ds.analyses <- make.ds.analysis(dfmodel = ~1, +#' key = "unif", +#' truncation = 50) +#' make.ds.analysis <- function(dfmodel = list(~1), key = "hn", truncation = numeric(0), @@ -408,8 +449,10 @@ make.ds.analysis <- function(dfmodel = list(~1), er.var = "R2", control.opts = list(), group.strata = data.frame(), - criteria = "AIC"){ + criteria = "AIC", + zero.n = c("fail", "zero")){ # Do some pre-creation input checking / formatting + zero.n <- match.arg(zero.n) if(length(truncation) == 0){ truncation <- 50} if(!is.double(truncation) || length(truncation) > 1){ stop("Truncation must be supplied as a single numeric value giving the absolute truncation distance.", call. = FALSE) @@ -445,8 +488,10 @@ make.ds.analysis <- function(dfmodel = list(~1), }else if(length(dfmodel) > 1 && length(key) == 1){ key <- rep(key, length(dfmodel)) } + # Allow "uf" for consistency with make.detectability, Distance uses "unif" + key[key == "uf"] <- "unif" # Create class instance - ds.analysis <- new(Class = "DS.Analysis", dfmodel = dfmodel, key = key, truncation = truncation, cutpoints = cutpoints, er.var = er.var, control.opts = control.opts, group.strata = group.strata, criteria = criteria) + ds.analysis <- new(Class = "DS.Analysis", dfmodel = dfmodel, key = key, truncation = truncation, cutpoints = cutpoints, er.var = er.var, control.opts = control.opts, group.strata = group.strata, criteria = criteria, zero.n = zero.n) return(ds.analysis) } @@ -472,6 +517,68 @@ make.ds.analysis <- function(dfmodel = list(~1), #' \link{make.detectability} #' @param ds.analysis an objects of class DS.Analysis created by #' a call to \link{make.ds.analysis} +#' @param population.generator optional function used to generate the +#' population in each repetition instead of +#' \code{generate.population(simulation)}. Default NULL uses the +#' population description. See the 'Population generator' section. +#' @section Population generator: +#' A population generator is a \code{function(simulation, rep)} which is +#' called once per repetition with the simulation object and the repetition +#' number. It must return either a \code{\link{Population-class}} object or a +#' list with elements \code{population} (a Population object) and +#' \code{truth}, a named numeric vector or list with entries \code{N} and/or +#' \code{D} giving the true abundance / density of the whole target area for +#' this repetition. This allows, for example, a population to be generated +#' over a larger study area and only the individuals inside the survey +#' region (the design region) to be returned, while bias is assessed +#' against the density of the whole study area. +#' +#' \strong{Requirements for the returned population.} It is checked in every +#' repetition: it must be a Population object whose \code{population} slot is a +#' data.frame with columns \code{individual}, \code{x}, \code{y}, +#' \code{Region.Label} and \code{scale.param} (plus \code{shape.param} for a +#' hazard-rate detection function and any covariates used in the +#' detectability description). Region.Label values must be strata names of +#' \code{simulation@@design@@region}, all individuals must lie inside the +#' design region and the detectability slot must be a Detectability object. +#' The simplest way to get all of these right is to start from a population +#' made by \code{generate.population()} (with a region covering the study +#' area) and subset its rows. A population with no individuals is allowed. +#' The detection function used for the survey is taken from the +#' population's detectability slot. +#' +#' \strong{Random numbers.} The state of the random number generator is saved +#' before the generator is called and restored afterwards. The generator may +#' therefore set its own seed (e.g. \code{set.seed(1000 + rep)}) without +#' changing the transects, detections and analyses of the simulation, which +#' come from the per-repetition random number streams of dsims. Simulations +#' that differ only in their design then see identical populations in each +#' repetition. As the generator does not advance the dsims stream, a +#' generator which simply returns \code{generate.population(simulation)} +#' gives the same populations as the default but different transects and +#' detections. +#' +#' \strong{Parallel processing.} \code{run.simulation(run.parallel = TRUE)} sends +#' the simulation, including the generator, to separate R worker processes +#' (mirai daemons, these are new R sessions not forks). The generator's +#' enclosing environment is sent with it unless it is the global environment +#' or a package namespace. So: (i) any data the generator needs should be +#' created inside the function or captured in its enclosing environment, for +#' example by returning the generator from a factory function +#' (\code{make.gen <- function(study.pop) function(simulation, rep) ...}); +#' objects referenced from the global environment are not available on the +#' workers; (ii) call functions from other packages with \code{pkg::fun()} (or +#' load the packages inside the generator), the packages must be installed +#' for the workers; (iii) keep captured objects small as they are copied to +#' each worker with every repetition. If the generator fails on a worker the +#' repetition is skipped and the error is reported in the summary of +#' warnings and errors. +#' +#' \strong{Results.} If the generator returns \code{truth}, it is stored in +#' \code{simulation@@results$truth} (an array [1, c("N", "D"), reps + 2]) and +#' \code{summary()} uses it, instead of the population description, as the +#' truth for the total row of the individual abundance / density tables (see +#' \code{\link{summary,Simulation-method}}). #' @return \code{\link{Simulation-class}} object #' @export #' @importFrom methods new is @@ -539,13 +646,23 @@ make.simulation <- function(reps = 10, design = make.design(), population.description = make.population.description(), detectability = make.detectability(), - ds.analysis = make.ds.analysis()){ - + ds.analysis = make.ds.analysis(), + population.generator = NULL){ + if(!is.null(population.generator) && !is.function(population.generator)){ + stop("population.generator must be NULL or a function(simulation, rep).", call. = FALSE) + } + if(is.function(population.generator)){ + gen.args <- names(formals(population.generator)) + if(length(gen.args) < 2 && !("..." %in% gen.args)){ + stop("population.generator must be a function which accepts two arguments: function(simulation, rep).", call. = FALSE) + } + } # Make the results arrays and store in a list results <- create.results.arrays(reps, design@region, ds.analysis, - population.description) + population.description, + population.generator = population.generator) # Create a simulation object simulation <- new(Class = "Simulation", reps = reps, @@ -553,7 +670,8 @@ make.simulation <- function(reps = 10, population.description = population.description, detectability = detectability, ds.analysis = ds.analysis, - results = results) + results = results, + population.generator = population.generator) # Check the simulation object simulation <- check.simulation(simulation) # If it has returned a character this is an error diff --git a/R/DS.Analysis.R b/R/DS.Analysis.R index 3a843b0..a3144f7 100644 --- a/R/DS.Analysis.R +++ b/R/DS.Analysis.R @@ -30,6 +30,10 @@ #' be grouped (into less strata) for the analyses #' @slot criteria Object of class \code{"character"}; describes #' which model selection criteria to use ("AIC","AICc","BIC"). +#' @slot zero.n Object of class \code{"character"}; how repetitions with no +#' detections within the truncation distance are treated, either "fail" +#' (the repetition is skipped) or "zero" (abundance and density are recorded +#' as 0). See \code{\link{make.ds.analysis}}. #' @section Methods: #' \describe{ #' \item{\code{run.analysis}}{\code{signature=c(object = "DS.Analysis", @@ -46,13 +50,14 @@ setClass(Class = "DS.Analysis", representation(dfmodel = "list", er.var = "character", control.opts = "list", group.strata = "data.frame", - criteria = "character")) + criteria = "character", + zero.n = "character")) #' @importFrom methods validObject is setMethod( f="initialize", signature="DS.Analysis", - definition=function(.Object, dfmodel, key, adjustment = list(), truncation, cutpoints, er.var, control.opts, group.strata, criteria){ + definition=function(.Object, dfmodel, key, adjustment = list(), truncation, cutpoints, er.var, control.opts, group.strata, criteria, zero.n = "fail"){ # Pre-processing #make sure these are characters not factors group.strata$design.id <- as.character(group.strata$design.id) @@ -67,6 +72,7 @@ setMethod( .Object@control.opts <- control.opts .Object@group.strata <- group.strata .Object@criteria <- criteria + .Object@zero.n <- zero.n #Check object is valid valid <- validObject(.Object, test = TRUE) if(is(valid, "character")){ @@ -83,9 +89,20 @@ setValidity("DS.Analysis", if(!(object@criteria %in% c("AIC", "BIC", "AICc"))){ return("This selection criteria is not currently supported, please select from 'AIC', 'BIC' or 'AICc'.") } + # Check zero detection option + if(length(object@zero.n) != 1 || !(object@zero.n %in% c("fail", "zero"))){ + return("zero.n must be either 'fail' or 'zero'.") + } # Check key functions - if(!all(object@key %in% c("hr", "hn"))){ - return("All key function values should be either 'hn' or 'hr'.") + if(!all(object@key %in% c("hr", "hn", "unif"))){ + return("All key function values should be 'hn', 'hr' or 'unif'.") + } + # The uniform key has no parameters so cannot include covariates + unif.index <- which(object@key == "unif") + for(i in unif.index){ + if(length(attr(stats::terms(object@dfmodel[[i]]), "term.labels")) > 0){ + return("Covariates cannot be included in the model when the uniform key function is used, please use dfmodel = ~1.") + } } # Check no models are repeated if(length(object@adjustment) == 0){ diff --git a/R/Detectability.R b/R/Detectability.R index 3e0fe08..bc6aecd 100755 --- a/R/Detectability.R +++ b/R/Detectability.R @@ -15,8 +15,15 @@ #' parameter for the detection function. #' @slot shape.param Object of class \code{"numeric"}; The shape #' parameter for the detection function. -#' @slot cov.param Object of class \code{"numeric"}; The parameter -#' values associated with the covariates. Not yet implemented +#' @slot cov.param Object of class \code{"list"}; Named list of covariate +#' effect parameters (log scale) for individual-level covariates. Entries may +#' be numeric vectors for continuous/discrete covariates, or data.frames for +#' categorical covariates with columns such as \code{strata}, \code{level}, +#' and \code{param}. +#' @slot cov.surface Object of class \code{"list"}; Optional named list of +#' raster surfaces (character file paths or terra SpatRaster objects) providing +#' spatially-explicit covariate values sampled at each animal's location. Names +#' must match numeric-vector entries in \code{cov.param}. #' @slot truncation Object of class \code{"numeric"}; The maximum #' distance at which objects may be detected. #' @keywords classes @@ -26,12 +33,13 @@ setClass("Detectability", representation(key.function = "character", scale.param = "numeric", shape.param = "numeric", cov.param = "list", + cov.surface = "list", truncation = "numeric")) #' @importFrom methods validObject is setMethod( f="initialize", signature="Detectability", - definition=function(.Object, key.function = "hn", scale.param = 25, shape.param = numeric(0), covariates = character(0), cov.param = list(), truncation = 50){ + definition=function(.Object, key.function = "hn", scale.param = 25, shape.param = numeric(0), covariates = character(0), cov.param = list(), cov.surface = list(), truncation = 50){ #Input pre-processing # - this needs to be done here as cannot alter object inside validation method cov.names <- names(cov.param) @@ -55,6 +63,7 @@ setMethod( .Object@scale.param <- scale.param .Object@shape.param <- shape.param .Object@cov.param <- cov.param + .Object@cov.surface <- cov.surface .Object@truncation <- truncation #Check object is valid valid <- validObject(.Object, test = TRUE) @@ -112,6 +121,35 @@ setValidity("Detectability", } } } + # Validate cov.surface + if(length(object@cov.surface) > 0){ + surf.names <- names(object@cov.surface) + if(is.null(surf.names) || any(surf.names == "")){ + return("Not all elements of cov.surface are named. Please provide names matching entries in cov.param.") + } + cov.param.names <- names(object@cov.param) + for(sn in surf.names){ + if(!sn %in% cov.param.names){ + return(paste0("cov.surface entry '", sn, "' has no matching numeric entry in cov.param. ", + "Each raster surface needs a corresponding slope in cov.param.")) + } + if(is.data.frame(object@cov.param[[sn]])){ + return(paste0("cov.param entry '", sn, "' paired with cov.surface must be a numeric slope, not a factor data.frame.")) + } + surf <- object@cov.surface[[sn]] + if(!is.character(surf) && !inherits(surf, "SpatRaster")){ + return(paste0("cov.surface entry '", sn, "' must be a file path (character) or a terra SpatRaster object.")) + } + if(is.character(surf)){ + if(length(surf) != 1){ + return(paste0("cov.surface entry '", sn, "' must be a single file path.")) + } + if(!file.exists(surf)){ + return(paste0("cov.surface raster file does not exist: '", surf, "'.")) + } + } + } + } return(TRUE) } ) @@ -159,7 +197,9 @@ setMethod( cov.names <- names(object@cov.param) # Check if there are covariates in detectability that are not in pop.desc pop.covs <- names(pop.desc@covariates) - if(any(!cov.names %in% pop.covs)){ + surface.covs <- names(object@cov.surface) + missing.covs <- setdiff(cov.names, c(pop.covs, surface.covs)) + if(length(missing.covs) > 0){ stop("You have defined detectability for covariates that are not included in the population description.", call. = FALSE) } # set mfrow storing old settings @@ -187,7 +227,21 @@ setMethod( for(cov in seq(along = object@cov.param)){ cov.params <- object@cov.param[[cov]] cov.dist <- pop.desc@covariates[[cov.names[cov]]] - if(is(object@cov.param[[cov]], "data.frame")){ + if(is.null(cov.dist) && cov.names[cov] %in% surface.covs){ + param.type <- "surface" + no.cov.strata <- max(1, length(cov.params)) + cov.surface <- object@cov.surface[[cov.names[cov]]] + if(is.character(cov.surface)){ + cov.surface <- terra::rast(cov.surface) + } + surf.values <- terra::values(cov.surface)[,1] + surf.values <- surf.values[!is.na(surf.values)] + if(length(surf.values) == 0){ + quantiles <- c(0, 0, 0) + }else{ + quantiles <- as.numeric(quantile(surf.values, c(0.025, 0.5, 0.975))) + } + }else if(is(object@cov.param[[cov]], "data.frame")){ param.type = "categorical" no.cov.strata <- ifelse(is.null(cov.params$strata), 1, length(unique(cov.params$strata))) }else if(is(cov.dist[[1]], "data.frame")){ @@ -201,6 +255,8 @@ setMethod( plot.title <- paste("Covariate: ", cov.names[cov], " (factor)", sep = "") }else if(param.type == "discrete"){ plot.title <- paste("Covariate: ", cov.names[cov], " (discrete)", sep = "") + }else if(param.type == "surface"){ + plot.title <- paste("Covariate: ", cov.names[cov], " (raster)", sep = "") }else{ plot.title <- paste("Covariate: ", cov.names[cov], " (continuous)", sep = "") } @@ -277,6 +333,9 @@ setMethod( "poisson" = qpois(int, dist.param$lambda), "lognormal" = qlnorm(int, dist.param$meanlog, dist.param$sdlog)) } + }else if(param.type == "surface"){ + # quantiles were already computed from the raster values + quantiles <- quantiles } # get adjustment paramters if(length(cov.params) == no.strata){ @@ -315,6 +374,8 @@ setMethod( desc.ints <- "min,max" }else if(param.type == "continuous"){ desc.ints <- "95%ints" + }else if(param.type == "surface"){ + desc.ints <- "raster 95%ints" } if(param.type == "categorical"){ no.levels <- length(unique(cov.params$level)) diff --git a/R/Population.Description.R b/R/Population.Description.R index d1bb165..4139f79 100755 --- a/R/Population.Description.R +++ b/R/Population.Description.R @@ -92,6 +92,11 @@ setValidity("Population.Description", if(length(object@N) > 0 & sum(object@N) <= 0){ return("You must provide a positive, non-zero abundance") } + # Fractional values would be rounded up when generating the population + # while the true abundance would remain fractional + if(object@gen.by.N && any(abs(object@N - round(object@N)) > 1e-8)){ + return("Population size N must be a whole number in each strata when fixed.N = TRUE, please round the values of N.") + } return(TRUE) } ) diff --git a/R/Simulation.R b/R/Simulation.R index 4046a84..2c87066 100755 --- a/R/Simulation.R +++ b/R/Simulation.R @@ -24,6 +24,9 @@ #' description of the detectability of the population. #' @slot ds.analysis Object of class \code{"DS.Analysis"} #' @slot add.options a list to expand simulation options in the future. +#' @slot population.generator Object of class \code{"function"} or +#' \code{NULL}; an optional function(simulation, rep) used to generate the +#' population in each repetition, see \code{\link{make.simulation}}. #' @slot ddf.param.ests Object of class \code{"array"}; stores the #' parameters associated with the detection function. #' @slot results A \code{"list"} with elements 'individuals' (and @@ -88,10 +91,20 @@ #' information criteria between the best and second best fitting #' models where two or more models were fitted and converged), #' 'SuccessfulModels' (the number of models which successfully -#' converged). Currently detection functions are pooled across -#' all strata so there is only one global value for each -#' simulated dataset as well as a mean value and standard -#' deviation where appropriate. +#' converged) and 'ZeroDetections' (1 if the repetition had no +#' detections within the truncation distance and was recorded as +#' an estimate of zero, see the zero.n argument of +#' \code{\link{make.ds.analysis}}, 0 otherwise). Currently detection +#' functions are pooled across all strata so there is only one +#' global value for each simulated dataset as well as a mean value +#' and standard deviation where appropriate. +#' +#' The 'individuals' (and 'clusters') elements also contain +#' 'true.N', an array [strata, "N", reps + 2] giving the realised +#' number of individuals (clusters) in the design region in each +#' repetition. If a population generator returned the truth for +#' the whole target area (see \code{\link{make.simulation}}) the +#' results also contain 'truth', an array [1, c("N", "D"), reps + 2]. #' #' @slot warnings A \code{"list"} to store warnings and error messages encountered #' during runtime. @@ -114,6 +127,8 @@ #' @rdname Simulation-class #' @importClassesFrom dssd Region #' @seealso \code{\link{make.simulation}} +setClassUnion("functionOrNULL", c("function", "NULL")) + setClass("Simulation", representation(reps = "numeric", design = "Survey.Design", population.description = "Population.Description", @@ -122,14 +137,15 @@ setClass("Simulation", representation(reps = "numeric", add.options = "list", ddf.param.ests = "array", results = "list", - warnings = "list")) + warnings = "list", + population.generator = "functionOrNULL")) #' @importFrom methods validObject is #' @importFrom dssd make.design setMethod( f="initialize", signature="Simulation", - definition=function(.Object, reps = 10, single.transect.set = FALSE, design = make.design(), population.description = make.population.description(), detectability = make.detectability(), ds.analysis = make.ds.analysis(), results = list()){ + definition=function(.Object, reps = 10, single.transect.set = FALSE, design = make.design(), population.description = make.population.description(), detectability = make.detectability(), ds.analysis = make.ds.analysis(), results = list(), population.generator = NULL){ #Set slots .Object@reps <- reps .Object@design <- design @@ -138,6 +154,7 @@ setMethod( .Object@ds.analysis <- ds.analysis .Object@results <- results .Object@warnings <- list() + .Object@population.generator <- population.generator #Consistency check .Object <- simulation.consistency.check(.Object) #Check object is valid @@ -335,15 +352,15 @@ histogram.N.ests <- function(x, use.max.reps = FALSE, N.ests = "individuals", .. # Find the number of rows total.row <- dim(x@results$individuals$N)[1] # UExtract the estimates + # Includes zero detection repetitions (zero.n = "zero") + rep.index <- get.rep.index(x@results$Detection, x@reps, + length(x@ds.analysis@dfmodel), use.max.reps) if(use.max.reps){ - rep.index <- which(x@results$Detection[1,"SuccessfulModels",1:x@reps] > 0) N.ind.ests <- x@results$individuals$N[total.row, "Estimate", rep.index] if(clusters){ N.cls.ests <- x@results$clusters$N[total.row, "Estimate", rep.index] } }else{ - model.count <- length(x@ds.analysis@dfmodel) - rep.index <- which(x@results$Detection[1,"SuccessfulModels",1:x@reps] == model.count) N.ind.ests <- x@results$individuals$N[total.row, "Estimate", rep.index] if(clusters){ N.cls.ests <- x@results$clusters$N[total.row, "Estimate", rep.index] @@ -387,6 +404,27 @@ histogram.N.ests <- function(x, use.max.reps = FALSE, N.ests = "individuals", .. #' explanation of the summary should be displayed #' @param use.max.reps by default this is FALSE meaning that only simulation repetitions where all models converged for that data set are included. By setting this to TRUE any repetition where one or more models converged will be included in the summary results. #' @param ... no additional arguments currently implemented +#' @details +#' \strong{Source of the true values.} By default the true abundance and +#' density (the Truth column used for percent.bias, RMSE and CI coverage) come +#' from the population description. If the simulation has a population +#' generator (see \code{\link{make.simulation}}) which returned a +#' per-repetition truth (N and/or D for the whole target area), this is used +#' instead for the total row of the individual abundance / density tables +#' (the only row of an unstratified region): Truth is then the mean truth over +#' the included repetitions, percent.bias is +#' (mean estimate - mean truth) / mean truth * 100, RMSE is +#' sqrt(mean((estimate_i - truth_i)^2)) and the CI coverage counts +#' repetitions where lcl_i < truth_i < ucl_i. Strata rows then have no truth +#' (NA). The source of the truth is shown in the printed summary and stored +#' in the truth.source slot. +#' +#' \strong{Zero detection repetitions.} If the analysis was created with +#' \code{zero.n = "zero"} the repetitions with no detections within the +#' truncation distance are included (as estimates of 0) in the mean +#' estimates, SD, RMSE and bias. CI coverage only uses repetitions with a +#' defined confidence interval, so excludes them. Their number is shown in +#' the printed summary and stored in the zero.detection.reps slot. #' @rdname summary.Simulation-methods #' @importFrom stats na.omit qlnorm qnorm #' @importFrom methods slotNames slot show is @@ -407,10 +445,9 @@ setMethod( #These will use max iters by default results <- object@results # Update summary stats depending on use.max.reps option - if(use.max.reps){ - rep.index <- which(object@results$Detection[1,"SuccessfulModels",1:reps] > 0) - }else{ - rep.index <- which(object@results$Detection[1,"SuccessfulModels",1:reps] == model.count) + # Includes zero detection repetitions when zero.n = "zero" + rep.index <- get.rep.index(object@results$Detection, reps, model.count, use.max.reps) + if(!use.max.reps){ results <- add.summary.results(results = results, model.count = model.count, use.max.reps = use.max.reps) @@ -631,9 +668,9 @@ setMethod( zero.n <- array(NA, dim = c(included.reps, length(true.N.individuals))) for(strat in seq(along = true.N.individuals)){ for(i in seq(along = rep.index)){ - capture[i, strat] <- ifelse(results$individuals$N[strat, "lcl", i] < true.N.individuals[strat] & results$individuals$N[strat, "ucl", i] > true.N.individuals[strat], TRUE, FALSE) - capture.D[i, strat] <- ifelse(results$individuals$D[strat, "lcl", i] < true.D.individuals[strat] & results$individuals$D[strat, "ucl", i] > true.D.individuals[strat], TRUE, FALSE) - zero.n[i, strat] <- ifelse(results$individuals$summary[strat, "n", i] == 0, TRUE, FALSE) + capture[i, strat] <- ifelse(results$individuals$N[strat, "lcl", rep.index[i]] < true.N.individuals[strat] & results$individuals$N[strat, "ucl", rep.index[i]] > true.N.individuals[strat], TRUE, FALSE) + capture.D[i, strat] <- ifelse(results$individuals$D[strat, "lcl", rep.index[i]] < true.D.individuals[strat] & results$individuals$D[strat, "ucl", rep.index[i]] > true.D.individuals[strat], TRUE, FALSE) + zero.n[i, strat] <- ifelse(results$individuals$summary[strat, "n", rep.index[i]] == 0, TRUE, FALSE) } } #Calculates the percentage of times the true value is within the confidence intervals @@ -693,6 +730,29 @@ setMethod( CI.coverage.prob = percent.capture.D/100, mean.se = results$individuals$D[,"se","mean"], sd.of.means = results$individuals$D[,"Estimate","sd"]) + # Use the per-repetition truth supplied by a population generator for the + # total row if available + truth.source <- c(N = "population description", D = "population description") + for(quantity in c("N", "D")){ + rep.truth <- get.rep.truth(results, quantity, reps, rep.index) + if(is.null(rep.truth)){ + next + } + tab <- if(quantity == "N") individual.N else individual.D + tab <- apply.rep.truth(tab, results$individuals[[quantity]], rep.truth, rep.index) + if(quantity == "N") individual.N <- tab else individual.D <- tab + truth.source[quantity] <- if(nrow(tab) > 1){ + "per-repetition truth from population.generator (total row only, mean over included repetitions)" + }else{ + "per-repetition truth from population.generator (mean over included repetitions)" + } + } + # Count the zero detection repetitions included + zero.detection.reps <- numeric(0) + if(get.zero.n(object@ds.analysis) == "zero" && + "ZeroDetections" %in% dimnames(results$Detection)[[2]]){ + zero.detection.reps <- sum(results$Detection[1, "ZeroDetections", rep.index] == 1, na.rm = TRUE) + } if(!is.null(results$clusters)){ capture <- array(NA, dim = c(included.reps, length(true.N.clusters))) @@ -700,9 +760,9 @@ setMethod( zero.n <- array(NA, dim = c(included.reps, length(true.N.clusters))) for(strat in seq(along = true.N.clusters)){ for(i in seq(along = rep.index)){ - capture[i, strat] <- ifelse(results$clusters$N[strat, "lcl", i] < true.N.clusters[strat] & results$clusters$N[strat, "ucl", i] > true.N.clusters[strat], TRUE, FALSE) - capture.D[i, strat] <- ifelse(results$clusters$D[strat, "lcl", i] < true.D.clusters[strat] & results$clusters$D[strat, "ucl", i] > true.D.clusters[strat], TRUE, FALSE) - zero.n[i, strat] <- ifelse(results$clusters$summary[strat, "n", i] == 0, TRUE, FALSE) + capture[i, strat] <- ifelse(results$clusters$N[strat, "lcl", rep.index[i]] < true.N.clusters[strat] & results$clusters$N[strat, "ucl", rep.index[i]] > true.N.clusters[strat], TRUE, FALSE) + capture.D[i, strat] <- ifelse(results$clusters$D[strat, "lcl", rep.index[i]] < true.D.clusters[strat] & results$clusters$D[strat, "ucl", rep.index[i]] > true.D.clusters[strat], TRUE, FALSE) + zero.n[i, strat] <- ifelse(results$clusters$summary[strat, "n", rep.index[i]] == 0, TRUE, FALSE) } } percent.capture <- (apply(capture, 2, sum, na.rm = TRUE)/nrow(na.omit(capture)))*100 @@ -791,11 +851,51 @@ setMethod( model.selection = tab.model.selection, design.summary = design.parameters, detectability.summary = detectability.summary, - analysis.summary = analysis.summary) + analysis.summary = analysis.summary, + truth.source = truth.source, + zero.detection.reps = zero.detection.reps) return(summary.x) } ) +get.rep.truth <- function(results, quantity, reps, rep.index){ + # Returns the per-repetition truth (vector over all reps) for N or D stored + # from a population generator, or NULL if there is none for the included + # repetitions + if(is.null(results$truth) || !(quantity %in% dimnames(results$truth)[[2]])){ + return(NULL) + } + rep.truth <- results$truth[1, quantity, seq_len(reps)] + if(all(is.na(rep.truth[rep.index]))){ + return(NULL) + } + rep.truth +} + +apply.rep.truth <- function(tab, estimates, rep.truth, rep.index){ + # Replaces the truth based columns of the total (last) row of an abundance + # or density summary table using a truth which varies by repetition. Bias, + # RMSE and coverage are calculated over the included repetitions where both + # the estimate and the truth are available. The other rows have no truth. + total <- nrow(tab) + truth <- rep.truth[rep.index] + est <- estimates[total, "Estimate", rep.index] + lcl <- estimates[total, "lcl", rep.index] + ucl <- estimates[total, "ucl", rep.index] + ok <- !is.na(truth) & !is.na(est) + mean.truth <- mean(truth[ok]) + tab$Truth[total] <- mean.truth + tab$percent.bias[total] <- (mean(est[ok]) - mean.truth) / mean.truth * 100 + tab$RMSE[total] <- sqrt(mean((est[ok] - truth[ok])^2)) + # Coverage only over repetitions with a defined confidence interval + ci.ok <- ok & !is.na(lcl) & !is.na(ucl) + tab$CI.coverage.prob[total] <- if(any(ci.ok)) mean(lcl[ci.ok] < truth[ci.ok] & ucl[ci.ok] > truth[ci.ok]) else NA + if(total > 1){ + tab[-total, c("Truth", "percent.bias", "RMSE", "CI.coverage.prob")] <- NA + } + tab +} + diff --git a/R/Simulation.Summary.R b/R/Simulation.Summary.R index d708836..42b0ceb 100644 --- a/R/Simulation.Summary.R +++ b/R/Simulation.Summary.R @@ -8,6 +8,11 @@ #' @name Simulation.Summary-class #' @title S4 Class "Simulation.Summary" #' @docType class +#' @slot truth.source named character vector (N, D) giving the source of the +#' true values used in the summary tables (the population description or a +#' per-repetition truth from a population generator). +#' @slot zero.detection.reps the number of included repetitions recorded as +#' zero detections (only when the analysis uses \code{zero.n = "zero"}). #' @keywords classes #' @section Methods: #' \describe{ @@ -28,14 +33,16 @@ setClass("Simulation.Summary", representation(region.name = "character", design.summary = "list", detectability.summary = "list", analysis.summary = "list", - include.glossary = "logical")) + include.glossary = "logical", + truth.source = "character", + zero.detection.reps = "numeric")) #' @importFrom methods validObject setMethod( f="initialize", signature="Simulation.Summary", - definition=function(.Object, region.name, strata.name, total.reps, failures, use.max.reps, individuals, clusters = list(), expected.size = data.frame(NULL), population.covars, detection, model.selection, design.summary = list(), detectability.summary = list(), analysis.summary = list(), include.glossary = FALSE){ + definition=function(.Object, region.name, strata.name, total.reps, failures, use.max.reps, individuals, clusters = list(), expected.size = data.frame(NULL), population.covars, detection, model.selection, design.summary = list(), detectability.summary = list(), analysis.summary = list(), include.glossary = FALSE, truth.source = character(0), zero.detection.reps = numeric(0)){ #Set slots .Object@region.name <- region.name .Object@strata.name <- strata.name @@ -52,6 +59,8 @@ setMethod( .Object@detectability.summary <- detectability.summary .Object@analysis.summary <- analysis.summary .Object@include.glossary <- include.glossary + .Object@truth.source <- truth.source + .Object@zero.detection.reps <- zero.detection.reps #Check object is valid validObject(.Object) # return object @@ -97,6 +106,11 @@ setMethod( }else{ cat("\nNo. Excluded Repetitions: ", object@failures, fill = TRUE) } + # Objects created with earlier versions of dsims do not have these slots + zero.reps <- if(methods::.hasSlot(object, "zero.detection.reps")) object@zero.detection.reps else numeric(0) + if(length(zero.reps) > 0 && !not.run){ + cat("No. Zero Detection Repetitions (included as estimates of 0): ", zero.reps, fill = TRUE) + } use.max.reps <- object@use.max.reps if(use.max.reps){ cat("Using all repetitions where at least one model converged.", fill = TRUE) @@ -197,6 +211,13 @@ setMethod( # Check to see if simulation has been run if(!not.run && !run.no.results){ cat("\nSummary for Individuals\n") + truth.source <- if(methods::.hasSlot(object, "truth.source")) object@truth.source else character(0) + if(length(truth.source) > 0){ + cat("\nSource of the true values (Truth):", fill = TRUE) + for(quantity in names(truth.source)){ + cat(" ", quantity, ": ", truth.source[[quantity]], fill = TRUE, sep = "") + } + } if(length(object@clusters) == 0){ cat("\nSummary Statistics\n\n") print(object@individuals$summary) diff --git a/R/Survey.LT.R b/R/Survey.LT.R index c5b50d4..156865d 100755 --- a/R/Survey.LT.R +++ b/R/Survey.LT.R @@ -62,6 +62,10 @@ setMethod( run.survey.body.LT <- function(object, region){ population <- object@population + # No individuals (e.g. from a population generator): no detections + if(nrow(population@population) == 0){ + return(object) + } line.transect <- object@transect # Find possible detection distances poss.distances <- calc.perp.dists(population, line.transect) diff --git a/R/Survey.PT.R b/R/Survey.PT.R index 2065753..cff3829 100755 --- a/R/Survey.PT.R +++ b/R/Survey.PT.R @@ -61,6 +61,10 @@ setMethod( run.survey.body.PT <- function(object, region){ population <- object@population + # No individuals (e.g. from a population generator): no detections + if(nrow(population@population) == 0){ + return(object) + } point.transect <- object@transect # Find possible detection distances poss.distances <- calc.rad.dists(population, point.transect) diff --git a/R/accumulate.PP.results.R b/R/accumulate.PP.results.R index 3226adb..f99c023 100644 --- a/R/accumulate.PP.results.R +++ b/R/accumulate.PP.results.R @@ -1,15 +1,80 @@ +extract.rep.result <- function(results, i){ + rep.result <- list( + individuals = list( + summary = results$individuals$summary[,,i, drop = FALSE], + N = results$individuals$N[,,i, drop = FALSE], + D = results$individuals$D[,,i, drop = FALSE] + ), + Detection = results$Detection[,,i, drop = FALSE] + ) + if(!is.null(results$individuals$true.N)){ + rep.result$individuals$true.N <- results$individuals$true.N[,,i, drop = FALSE] + } + if(!is.null(results$truth)){ + rep.result$truth <- results$truth[,,i, drop = FALSE] + } + + if(!is.null(results$clusters)){ + rep.result$clusters <- list( + summary = results$clusters$summary[,,i, drop = FALSE], + N = results$clusters$N[,,i, drop = FALSE], + D = results$clusters$D[,,i, drop = FALSE] + ) + rep.result$expected.size <- results$expected.size[,,i, drop = FALSE] + if(!is.null(results$clusters$true.N)){ + rep.result$clusters$true.N <- results$clusters$true.N[,,i, drop = FALSE] + } + } + + rep.result +} + +apply.rep.result <- function(results, rep.result, i){ + results$individuals$summary[,,i] <- rep.result$individuals$summary[,,1] + results$individuals$N[,,i] <- rep.result$individuals$N[,,1] + results$individuals$D[,,i] <- rep.result$individuals$D[,,1] + results$Detection[,,i] <- rep.result$Detection[,,1] + if(!is.null(results$individuals$true.N) && !is.null(rep.result$individuals$true.N)){ + results$individuals$true.N[,,i] <- rep.result$individuals$true.N[,,1] + } + if(!is.null(results$truth) && !is.null(rep.result$truth)){ + results$truth[,,i] <- rep.result$truth[,,1] + } + if(!is.null(results$clusters) && !is.null(rep.result$clusters)){ + results$clusters$summary[,,i] <- rep.result$clusters$summary[,,1] + results$clusters$N[,,i] <- rep.result$clusters$N[,,1] + results$clusters$D[,,i] <- rep.result$clusters$D[,,1] + results$expected.size[,,i] <- rep.result$expected.size[,,1] + if(!is.null(results$clusters$true.N) && !is.null(rep.result$clusters$true.N)){ + results$clusters$true.N[,,i] <- rep.result$clusters$true.N[,,1] + } + } + results +} + accumulate.PP.results <- function(simulation, results){ simulation@results$filename <- rep(NA, length(results)) for(i in seq(along = results)){ - simulation@results$individuals$summary[,,i] <- results[[i]]$individuals$summary[,,i] - simulation@results$individuals$N[,,i] <- results[[i]]$individuals$N[,,i] - simulation@results$individuals$D[,,i] <- results[[i]]$individuals$D[,,i] - simulation@results$Detection[,,i] <- results[[i]]$Detection[,,i] - if(!is.null(simulation@results$clusters)){ - simulation@results$clusters$summary[,,i] <- results[[i]]$clusters$summary[,,i] - simulation@results$clusters$N[,,i] <- results[[i]]$clusters$N[,,i] - simulation@results$clusters$D[,,i] <- results[[i]]$clusters$D[,,i] - simulation@results$expected.size[,,i] <- results[[i]]$expected.size[,,i] + if(!is.null(results[[i]]$rep.result)){ + simulation@results <- apply.rep.result(simulation@results, + results[[i]]$rep.result, + i) + if(!is.null(results[[i]]$filename) && length(results[[i]]$filename) > 0){ + simulation@results$filename[i] <- results[[i]]$filename + } + }else if(!is.null(results[[i]]$individuals)){ + # Backward-compatible path for legacy full-object result returns + # (reps which failed with an error return only warnings and are skipped) + simulation@results$individuals$summary[,,i] <- results[[i]]$individuals$summary[,,i] + simulation@results$individuals$N[,,i] <- results[[i]]$individuals$N[,,i] + simulation@results$individuals$D[,,i] <- results[[i]]$individuals$D[,,i] + simulation@results$Detection[,,i] <- results[[i]]$Detection[,,i] + if(!is.null(simulation@results$clusters)){ + simulation@results$clusters$summary[,,i] <- results[[i]]$clusters$summary[,,i] + simulation@results$clusters$N[,,i] <- results[[i]]$clusters$N[,,i] + simulation@results$clusters$D[,,i] <- results[[i]]$clusters$D[,,i] + simulation@results$expected.size[,,i] <- results[[i]]$expected.size[,,i] + } } } return(simulation) diff --git a/R/add.summary.results.R b/R/add.summary.results.R index c1ddeee..e5e36d7 100644 --- a/R/add.summary.results.R +++ b/R/add.summary.results.R @@ -2,16 +2,11 @@ add.summary.results <- function(results, model.count, use.max.reps = TRUE){ strata.names <- dimnames(results$individuals$summary)[[1]] reps <- length(dimnames(results$individuals$summary)[[3]])-2 - #Make backwards compatible - if("SuccessfulModels" %in% dimnames(results$Detection)[[2]]){ - if(use.max.reps){ - rep.index <- which(results$Detection[1,"SuccessfulModels",1:reps] > 0) - }else{ - rep.index <- which(results$Detection[1,"SuccessfulModels",1:reps] == model.count) - } - }else{ - rep.index <- 1:reps - } + # Repetitions to include (backwards compatible if SuccessfulModels is not + # recorded), includes zero detection repetitions (zero.n = "zero") + rep.index <- get.rep.index(results$Detection, reps, model.count, use.max.reps) + # Truth and realised abundance are summarised over the same repetitions + results <- add.summary.truth(results, rep.index) reps <- length(rep.index) #Summarise results for individuals if(reps > 1){ @@ -69,3 +64,29 @@ add.summary.results <- function(results, model.count, use.max.reps = TRUE){ } return(results) } + +add.summary.truth <- function(results, rep.index){ + # Adds the mean and sd over the included repetitions to the arrays of the + # realised abundance in the design region and the truth supplied by a + # population generator + summarise <- function(x){ + if(is.null(x)){ + return(x) + } + for(row in seq_len(dim(x)[1])){ + for(col in seq_len(dim(x)[2])){ + values <- x[row, col, rep.index] + values <- values[!is.na(values)] + x[row, col, "mean"] <- if(length(values) > 0) mean(values) else NA + x[row, col, "sd"] <- if(length(values) > 1) stats::sd(values) else NA + } + } + x + } + results$individuals$true.N <- summarise(results$individuals$true.N) + if(!is.null(results$clusters)){ + results$clusters$true.N <- summarise(results$clusters$true.N) + } + results$truth <- summarise(results$truth) + results +} diff --git a/R/calc.perp.dists.R b/R/calc.perp.dists.R index 572c9e5..357dc20 100644 --- a/R/calc.perp.dists.R +++ b/R/calc.perp.dists.R @@ -1,7 +1,6 @@ #' @importFrom graphics points -#' @importFrom sf st_intersection st_drop_geometry st_crs +#' @importFrom sf st_drop_geometry st_crs st_join st_intersects st_distance st_geometry st_coordinates #' @importFrom methods is -#' @importFrom purrr reduce calc.perp.dists <- function(population, transects, plot = FALSE){ # Calculates the possible detection distances to the transects # Arguments: @@ -10,82 +9,34 @@ calc.perp.dists <- function(population, transects, plot = FALSE){ # Returns: # A data frame of possible detection distances - subset.buff.func <- function(i, sf.pop, samplers, cov.areas){ - #returns the locations of the population within the truncation distance of transect i. - # Extract relevant sampler - sf.column.t <- attr(samplers, "sf_column") - samp <- samplers[[sf.column.t]][[i]] - #Extract associated covered area - cov.area <- cov.areas[cov.areas$transect == i,] - # Find the population in the covered area of transect i - pop.in.cov <- suppressWarnings( - st_intersection(sf.pop, cov.area)) - #Turn into a data.frame - sub.pop.coords <- as.data.frame(sf::st_coordinates(pop.in.cov)) - names(sub.pop.coords) <- c("x","y") - # Add other info back in - sub.pop.coords <- cbind(sub.pop.coords, st_drop_geometry(pop.in.cov)) - #Find start and end point [note may be a multilinestring] - if(is(samp, "LINESTRING")){ - start.X <- samp[1] - start.Y <- samp[3] - end.X <- samp[2] - end.Y <- samp[4] - }else if(is(samp, "MULTILINESTRING")){ - index.final <- length(samp) - start.X <- samp[[1]][1,1] - start.Y <- samp[[1]][1,2] - end.X <- samp[[index.final]][2,1] - end.Y <- samp[[index.final]][2,2] - }else{ - stop("sampler is not of type linestring or multilinestring", call. = TRUE) - } - #now calculate distances to transect - #find the angle between the transect and the vector from the animal to the start of the transect - transect.angle <- atan2(end.Y-start.Y, end.X-start.X) - animal.angle <- atan2(sub.pop.coords$y-start.Y, sub.pop.coords$x-start.X) - delta.angle <- abs(animal.angle-transect.angle) - delta.angle <- (ifelse(delta.angle > pi, 2*pi - delta.angle, delta.angle)) - #calculate the distance from the transect start to the animal (the hypotenuse) - hyp <- sqrt((sub.pop.coords$y-start.Y)^2+(sub.pop.coords$x-start.X)^2) - #calculate the perpendicular distance (the opposite side of the RA triangle) - perp.dists <- hyp*sin(delta.angle) - #Add perp distances - if(nrow(sub.pop.coords) > 0){ - #Make new dataset - new.data <- cbind(sub.pop.coords, - Sample.Label = rep(samplers$transect[i], nrow(sub.pop.coords)), - distance = perp.dists) - }else{ - new.data <- NULL - } - return(new.data) - } - #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - #Main function begins samplers <- transects@samplers covered.areas <- transects@cov.area.polys pop <- population@population - sf.pop <- st_as_sf(pop, coords = c("x", "y")) + sf.pop <- sf::st_as_sf(pop, coords = c("x", "y")) sf::st_crs(sf.pop) <- sf::st_crs(covered.areas) - #get all possible detection distances - all.poss.detects <- lapply(1:nrow(samplers), - FUN = subset.buff.func, - sf.pop = sf.pop, - samplers = samplers, - cov.areas = covered.areas) - - #Build up into a single data.frame - new.dataframe <- reduce(all.poss.detects, rbind) - if(!is.null(new.dataframe)){ - # Order the data by individual - index <- order(new.dataframe$individual) - new.dataframe <- new.dataframe[index,] - }else{ + # One indexed spatial join is significantly faster than N per-transect intersections + covered.lookup <- covered.areas[, c("transect")] + joined <- suppressWarnings( + sf::st_join(sf.pop, covered.lookup, join = sf::st_intersects, left = FALSE) + ) + + if(nrow(joined) == 0){ new.dataframe <- data.frame() + return(new.dataframe) } - # remove duplicate / redundant cols - #index <- which(names(tmp4) %in% c("transect", "strata")) - #ordered.data <- ordered.data[,-index] + + transect.ids <- as.character(joined$transect) + sampler.ids <- as.character(samplers$transect) + sampler.index <- match(transect.ids, sampler.ids) + sampler.geom <- sf::st_geometry(samplers)[sampler.index] + distances <- as.numeric(sf::st_distance(sf::st_geometry(joined), sampler.geom, by_element = TRUE)) + + coords <- as.data.frame(sf::st_coordinates(joined)) + names(coords) <- c("x", "y") + new.dataframe <- cbind(coords, sf::st_drop_geometry(joined)) + new.dataframe$Sample.Label <- joined$transect + new.dataframe$distance <- distances + index <- order(new.dataframe$individual) + new.dataframe <- new.dataframe[index,] return(new.dataframe) } diff --git a/R/calc.rad.dists.R b/R/calc.rad.dists.R index 43e8a52..caecf72 100644 --- a/R/calc.rad.dists.R +++ b/R/calc.rad.dists.R @@ -1,6 +1,5 @@ #' @importFrom graphics points -#' @importFrom sf st_intersection st_drop_geometry st_crs -#' @importFrom purrr reduce +#' @importFrom sf st_drop_geometry st_crs st_join st_intersects st_distance st_geometry st_coordinates calc.rad.dists <- function(population, transects, plot = FALSE){ # Calculates the possible detection distances to the transects # Arguments: @@ -9,63 +8,35 @@ calc.rad.dists <- function(population, transects, plot = FALSE){ # Returns: # A data frame of possible detection distances - subset.calc.dist <- function(i, sf.pop, samplers, cov.areas){ - # Find individuals within covered area of transect i - #returns the locations of the population within the truncation distance of transect i. - # Extract relevant sampler - sf.column.t <- attr(samplers, "sf_column") - samp <- samplers[[sf.column.t]][[i]] - #Extract associated covered area - cov.area <- cov.areas[cov.areas$transect == i,] - # Find the population in the covered area of transect i - pop.in.cov <- suppressWarnings( - st_intersection(sf.pop, cov.area)) - #Turn into a data.frame - sub.pop.coords <- as.data.frame(sf::st_coordinates(pop.in.cov)) - names(sub.pop.coords) <- c("x","y") - # Add other info back in - sub.pop <- cbind(sub.pop.coords, st_drop_geometry(pop.in.cov)) - # Get sampler coords - x.coord <- samp[1] - y.coord <- samp[2] - rad.dists <- sqrt((x.coord - sub.pop$x)^2 + (y.coord - sub.pop$y)^2) - # Add rad distances - if(nrow(sub.pop) > 0){ - #Make new dataset - new.data <- cbind(sub.pop, - Sample.Label = rep(samplers$transect[i], nrow(sub.pop)), - distance = rad.dists) - }else{ - new.data <- NULL - } - return(new.data) - } - #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - #Main function begins samplers <- transects@samplers covered.areas <- transects@cov.area.polys pop <- population@population - sf.pop <- st_as_sf(pop, coords = c("x", "y")) + sf.pop <- sf::st_as_sf(pop, coords = c("x", "y")) sf::st_crs(sf.pop) <- sf::st_crs(covered.areas) - #get all possible detection distances - all.poss.detects <- lapply(1:nrow(samplers), - FUN = subset.calc.dist, - sf.pop = sf.pop, - samplers = samplers, - cov.areas = covered.areas) - - #Build up into a single data.frame - new.dataframe <- reduce(all.poss.detects, rbind) - if(!is.null(new.dataframe)){ - # Order the data by individual - index <- order(new.dataframe$individual) - new.dataframe <- new.dataframe[index,] - }else{ + # One indexed spatial join is significantly faster than N per-transect intersections + covered.lookup <- covered.areas[, c("transect")] + joined <- suppressWarnings( + sf::st_join(sf.pop, covered.lookup, join = sf::st_intersects, left = FALSE) + ) + + if(nrow(joined) == 0){ new.dataframe <- data.frame() + return(new.dataframe) } - # remove duplicate / redundant cols - #index <- which(names(tmp4) %in% c("transect", "strata")) - #ordered.data <- ordered.data[,-index] + + transect.ids <- as.character(joined$transect) + sampler.ids <- as.character(samplers$transect) + sampler.index <- match(transect.ids, sampler.ids) + sampler.geom <- sf::st_geometry(samplers)[sampler.index] + distances <- as.numeric(sf::st_distance(sf::st_geometry(joined), sampler.geom, by_element = TRUE)) + + coords <- as.data.frame(sf::st_coordinates(joined)) + names(coords) <- c("x", "y") + new.dataframe <- cbind(coords, sf::st_drop_geometry(joined)) + new.dataframe$Sample.Label <- joined$transect + new.dataframe$distance <- distances + index <- order(new.dataframe$individual) + new.dataframe <- new.dataframe[index,] return(new.dataframe) } diff --git a/R/calculate.scale.param.R b/R/calculate.scale.param.R index d3fea0e..8d47f5c 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -1,4 +1,39 @@ #' @importFrom methods is +#' @importFrom terra rast extract +get.dsims.runtime.cache <- function(){ + cache <- getOption("dsims.runtime.cache") + if(is.null(cache) || !is.environment(cache)){ + cache <- new.env(parent = emptyenv()) + options(dsims.runtime.cache = cache) + } + cache +} + +get.surface.cache.entry <- function(sn, surf){ + cache <- get.dsims.runtime.cache() + if(is.character(surf)){ + cache.key <- paste0("file::", normalizePath(surf, mustWork = FALSE)) + }else{ + surf.ext <- terra::ext(surf) + ext.vec <- c(surf.ext$xmin, surf.ext$xmax, surf.ext$ymin, surf.ext$ymax) + cache.key <- paste0("mem::", sn, "::", terra::ncell(surf), "::", + paste(ext.vec, collapse = ":")) + } + + if(exists(cache.key, envir = cache, inherits = FALSE)){ + return(get(cache.key, envir = cache, inherits = FALSE)) + } + + # Cache only the raster handle: for a file-backed raster, values are read at + # the animal locations on demand (terra::extract), so memory stays small even + # for large rasters with many parallel workers. Caching terra::values() held + # the whole raster in memory in every worker. + surf.obj <- if(is.character(surf)) terra::rast(surf) else surf + entry <- list(rast = surf.obj) + assign(cache.key, entry, envir = cache) + entry +} + calculate.scale.param <- function(pop.data, detectability, region){ # This function calculates the scale parameters including any covariate effects # and adds these values to the population dataframe which is then returned. Also @@ -32,6 +67,25 @@ calculate.scale.param <- function(pop.data, detectability, region){ detectability@shape.param <- rep(shape[1], strata.no) } } + # Extract raster surface values at each animal's location and append as columns. + # This must happen before the covariate-name check so the columns are present. + if(length(detectability@cov.surface) > 0){ + surf.names <- names(detectability@cov.surface) + pts <- cbind(pop.data$x, pop.data$y) + for(sn in surf.names){ + surf <- detectability@cov.surface[[sn]] + cache.entry <- get.surface.cache.entry(sn, surf) + vals <- terra::extract(cache.entry$rast, pts)[, 1] + if(any(is.na(vals))){ + warning(paste0("NA raster values for surface covariate '", sn, + "' at some animal locations (outside raster extent). ", + "Replacing with global raster mean."), + call. = FALSE, immediate. = TRUE) + vals[is.na(vals)] <- mean(vals, na.rm = TRUE) + } + pop.data[[sn]] <- vals + } + } # Check the covariate names in detectability are present in the population pop.cov.names <- names(pop.data) detect.cov.names <- names(detectability@cov.param) @@ -44,7 +98,7 @@ calculate.scale.param <- function(pop.data, detectability, region){ for(cov in seq(along = detectability@cov.param)){ current.cov <- detectability@cov.param[[cov]] if(!is(current.cov, "data.frame")){ - if(length(current.cov == 1)){ + if(length(current.cov) == 1){ # repeat it for the number of strata detectability@cov.param[[cov]] <- rep(current.cov, strata.no) }else if(length(current.cov) != strata.no){ diff --git a/R/check.simulation.R b/R/check.simulation.R index 855b9ac..d8a8f07 100644 --- a/R/check.simulation.R +++ b/R/check.simulation.R @@ -28,7 +28,15 @@ check.simulation <- function(object){ } } } - + # Check that cov.surface names all have corresponding cov.param entries + surf.names <- names(detect@cov.surface) + if(length(surf.names) > 0){ + for(sn in surf.names){ + if(!sn %in% cov.names){ + return(paste0("cov.surface entry '", sn, "' does not have a matching numeric entry in cov.param.")) + } + } + } # DESIGN CHECKS design <- object@design if(any(design@edge.protocol == "plus")){ diff --git a/R/create.results.arrays.R b/R/create.results.arrays.R index e130573..feb3bec 100644 --- a/R/create.results.arrays.R +++ b/R/create.results.arrays.R @@ -1,4 +1,4 @@ -create.results.arrays <- function(reps, region, ds.analysis, population.description){ +create.results.arrays <- function(reps, region, ds.analysis, population.description, population.generator = NULL){ # Make the results arrays and store in a list no.strata <- ifelse(length(region@strata.name) > 1, length(region@strata.name)+1, 1) # Check to see if the strata are grouped in the analyses @@ -25,17 +25,25 @@ create.results.arrays <- function(reps, region, ds.analysis, population.descript } individuals <- list(summary = array(NA, dim = c(no.strata, 9, reps+2), dimnames = list(strata.name, c("Area", "CoveredArea", "Effort", "n", "n.miss.dist", "k", "ER", "se.ER", "cv.ER"), c(1:reps,"mean","sd"))), N = array(NA, dim = c(no.strata, 6, reps+2), dimnames = list(strata.name, c("Estimate", "se", "cv", "lcl", "ucl", "df"), c(1:reps,"mean","sd"))), - D = array(NA, dim = c(no.strata, 6, reps+2), dimnames = list(strata.name, c("Estimate", "se", "cv", "lcl", "ucl", "df"), c(1:reps,"mean", "sd")))) - detection = array(NA, dim = c(1, 7, reps+2), dimnames = list("Pooled", c("True.Pa", "Pa", "ESW", "f(0)", "SelectedModel", "DeltaCriteria", "SuccessfulModels"), c(1:reps,"mean","sd"))) + D = array(NA, dim = c(no.strata, 6, reps+2), dimnames = list(strata.name, c("Estimate", "se", "cv", "lcl", "ucl", "df"), c(1:reps,"mean", "sd"))), + # Realised number of individuals in the design region + true.N = array(NA, dim = c(no.strata, 1, reps+2), dimnames = list(strata.name, "N", c(1:reps,"mean","sd")))) + # ZeroDetections flags repetitions recorded as zero (zero.n = "zero") + detection = array(NA, dim = c(1, 8, reps+2), dimnames = list("Pooled", c("True.Pa", "Pa", "ESW", "f(0)", "SelectedModel", "DeltaCriteria", "SuccessfulModels", "ZeroDetections"), c(1:reps,"mean","sd"))) #create additional arrays if animals are in clusters if(population.description@size){ clusters <- list(summary = array(NA, dim = c(no.strata, 9, reps+2), dimnames = list(strata.name, c("Area", "CoveredArea", "Effort", "n", "n.miss.dist", "k", "ER", "se.ER", "cv.ER"), c(1:reps,"mean","sd"))), N = array(NA, dim = c(no.strata, 6, reps+2), dimnames = list(strata.name, c("Estimate", "se", "cv", "lcl", "ucl", "df"), c(1:reps,"mean","sd"))), - D = array(NA, dim = c(no.strata, 6, reps+2), dimnames = list(strata.name, c("Estimate", "se", "cv", "lcl", "ucl", "df"), c(1:reps,"mean", "sd")))) + D = array(NA, dim = c(no.strata, 6, reps+2), dimnames = list(strata.name, c("Estimate", "se", "cv", "lcl", "ucl", "df"), c(1:reps,"mean", "sd"))), + true.N = array(NA, dim = c(no.strata, 1, reps+2), dimnames = list(strata.name, "N", c(1:reps,"mean","sd")))) expected.size <- array(NA, dim = c(no.strata, 3, reps+2), dimnames = list(strata.name, c("Expected.S", "se.Expected.S", "cv.Expected.S"), c(1:reps,"mean","sd"))) results <- list(individuals = individuals, clusters = clusters, expected.size = expected.size, Detection = detection) }else{ results <- list(individuals = individuals, Detection = detection) } + # Truth for the whole target area supplied by a population generator + if(!is.null(population.generator)){ + results$truth <- array(NA, dim = c(1, 2, reps+2), dimnames = list("Total", c("N", "D"), c(1:reps,"mean","sd"))) + } return(results) } diff --git a/R/population.generator.R b/R/population.generator.R new file mode 100644 index 0000000..8ab0559 --- /dev/null +++ b/R/population.generator.R @@ -0,0 +1,314 @@ +# Helper functions for user supplied population generators (see the +# population.generator argument of make.simulation) and for recording +# repetitions with zero detections (see the zero.n argument of +# make.ds.analysis). + +get.population.generator <- function(simulation){ + # Returns the population generator or NULL (also for Simulation objects + # created with an earlier version of dsims which do not have the slot) + if(!methods::.hasSlot(simulation, "population.generator")){ + return(NULL) + } + simulation@population.generator +} + +get.zero.n <- function(ds.analysis){ + # Returns the zero detection option ("fail" for DS.Analysis objects created + # with an earlier version of dsims) + if(!methods::.hasSlot(ds.analysis, "zero.n") || length(ds.analysis@zero.n) == 0){ + return("fail") + } + ds.analysis@zero.n +} + +run.population.generator <- function(simulation, i){ + # Calls the user supplied population generator for repetition i, saving and + # restoring the random number generator state so the generator can use its + # own random number stream without changing the stream used for the + # transects, detections and analyses. Returns a list with the validated + # population and the truth (NULL if not supplied). + generator <- get.population.generator(simulation) + global.env <- globalenv() + had.seed <- exists(".Random.seed", envir = global.env, inherits = FALSE) + if(had.seed){ + old.seed <- get(".Random.seed", envir = global.env, inherits = FALSE) + } + gen.output <- tryCatch({ + generator(simulation, i) + }, error = function(e){ + e + }, finally = { + # .Random.seed also encodes the RNG kind so this restores any change of + # kind made by the generator + if(had.seed){ + assign(".Random.seed", old.seed, envir = global.env) + }else if(exists(".Random.seed", envir = global.env, inherits = FALSE)){ + rm(".Random.seed", envir = global.env) + } + }) + if(inherits(gen.output, "error")){ + stop("population.generator failed in repetition ", i, ": ", + conditionMessage(gen.output), call. = FALSE) + } + # Separate the population from the truth + truth <- NULL + if(is(gen.output, "Population")){ + population <- gen.output + }else if(is.list(gen.output) && !is.null(gen.output$population)){ + population <- gen.output$population + truth <- gen.output$truth + unknown <- setdiff(names(gen.output), c("population", "truth")) + if(length(unknown) > 0){ + stop("population.generator returned a list with unknown element(s) '", + paste(unknown, collapse = "', '"), "' in repetition ", i, + ", only 'population' and 'truth' are allowed.", call. = FALSE) + } + }else{ + stop("population.generator must return a Population object or a list(population = , truth = ), it returned an object of class '", + paste(class(gen.output), collapse = "/"), "' in repetition ", i, ".", call. = FALSE) + } + check.generated.population(population, simulation, i) + truth <- check.generated.truth(truth, i) + list(population = population, truth = truth) +} + +check.generated.population <- function(population, simulation, i){ + # Checks that a population returned by a population generator can be used + # by the rest of the simulation, stops with an informative error otherwise. + fail <- function(...){ + stop("Invalid population returned by population.generator in repetition ", + i, ": ", ..., call. = FALSE) + } + if(!is(population, "Population")){ + fail("expected an object of class 'Population' but got class '", + paste(class(population), collapse = "/"), "'.") + } + if(!is(population@detectability, "Detectability")){ + fail("the detectability slot must contain a 'Detectability' object.") + } + pop.data <- population@population + if(!is.data.frame(pop.data)){ + fail("the population slot must be a data.frame.") + } + region <- simulation@design@region + # Required columns + required <- c("individual", "x", "y", "Region.Label") + if(nrow(pop.data) > 0){ + required <- c(required, "scale.param") + if(population@detectability@key.function == "hr"){ + required <- c(required, "shape.param") + } + # Covariates used in the analyses + analysis.vars <- unique(unlist(lapply(simulation@ds.analysis@dfmodel, all.vars))) + required <- c(required, analysis.vars) + # Cluster size if the population description has clusters + if(simulation@population.description@size){ + required <- c(required, "size") + } + } + missing.cols <- setdiff(unique(required), names(pop.data)) + if(length(missing.cols) > 0){ + fail("the population data.frame is missing the column(s) '", + paste(missing.cols, collapse = "', '"), + "'. Populations made by generate.population() contain all required columns.") + } + if(nrow(pop.data) == 0){ + return(invisible(TRUE)) + } + for(col in intersect(c("x", "y", "scale.param", "shape.param"), names(pop.data))){ + if(!is.numeric(pop.data[[col]]) || any(is.na(pop.data[[col]]))){ + fail("column '", col, "' must be numeric with no missing values.") + } + } + if(any(duplicated(pop.data$individual))){ + fail("the values in column 'individual' must be unique.") + } + # Strata names + strata.names <- region@strata.name + if(length(strata.names) == 0){ + strata.names <- region@region.name + } + bad.strata <- setdiff(unique(as.character(pop.data$Region.Label)), strata.names) + if(length(bad.strata) > 0){ + fail("Region.Label value(s) '", paste(bad.strata, collapse = "', '"), + "' do not match the strata names of the design region ('", + paste(strata.names, collapse = "', '"), "').") + } + # Locations must be inside the design region (in the stratum given by + # Region.Label) + region.sf <- region@region + for(strat in unique(as.character(pop.data$Region.Label))){ + index <- which(as.character(pop.data$Region.Label) == strat) + poly.index <- ifelse(length(strata.names) > 1, match(strat, strata.names), 1) + pts <- sf::st_as_sf(pop.data[index, c("x", "y")], coords = c("x", "y"), + crs = sf::st_crs(region.sf)) + inside <- lengths(sf::st_intersects(pts, sf::st_geometry(region.sf)[poly.index])) > 0 + if(!all(inside)){ + fail(sum(!inside), " individual(s) with Region.Label '", strat, + "' lie outside this stratum of the design region (e.g. individual ", + pop.data$individual[index[which(!inside)[1]]], + "). Only individuals inside the design region should be returned.") + } + } + invisible(TRUE) +} + +check.generated.truth <- function(truth, i){ + # Checks the truth returned by a population generator and returns it as a + # named numeric vector with entries N and D (NA if not supplied) or NULL. + if(is.null(truth)){ + return(NULL) + } + if(is.list(truth)){ + if(!all(vapply(truth, function(x) is.numeric(x) && length(x) == 1, logical(1)))){ + stop("The truth returned by population.generator in repetition ", i, + " must contain single numeric values.", call. = FALSE) + } + truth <- unlist(truth) + } + if(!is.numeric(truth) || is.null(names(truth)) || any(names(truth) == "") || + !all(names(truth) %in% c("N", "D")) || any(duplicated(names(truth)))){ + stop("The truth returned by population.generator in repetition ", i, + " must be a named list or vector with numeric entries 'N' and/or 'D'.", call. = FALSE) + } + if(any(!is.finite(truth)) || any(truth < 0)){ + stop("The truth returned by population.generator in repetition ", i, + " must contain finite, non-negative values.", call. = FALSE) + } + out <- c(N = NA_real_, D = NA_real_) + out[names(truth)] <- truth + out +} + +results.strata.map <- function(results.strata, region, group.strata){ + # Returns a list with one element per row of the results arrays giving the + # design strata names which make up that row + design.strata <- region@strata.name + if(length(design.strata) <= 1){ + out <- list(design.strata) + names(out) <- results.strata + return(out) + } + out <- list() + for(row.name in results.strata){ + if(row.name == "Total"){ + out[[row.name]] <- design.strata + }else if(nrow(group.strata) > 0){ + out[[row.name]] <- as.character(group.strata$design.id[group.strata$analysis.id == row.name]) + }else{ + out[[row.name]] <- row.name + } + } + out +} + +store.true.N <- function(results, population, region, group.strata, i){ + # Stores the realised number of individuals (and clusters) in the design + # region in repetition i + if(is.null(results$individuals$true.N)){ + return(results) + } + pop.data <- population@population + strata.map <- results.strata.map(dimnames(results$individuals$true.N)[[1]], + region, group.strata) + labels <- as.character(pop.data$Region.Label) + has.size <- "size" %in% names(pop.data) + for(row.name in names(strata.map)){ + index <- if(length(region@strata.name) <= 1) seq_along(labels) else which(labels %in% strata.map[[row.name]]) + n.ind <- if(has.size) sum(pop.data$size[index]) else length(index) + results$individuals$true.N[row.name, "N", i] <- n.ind + if(!is.null(results$clusters$true.N)){ + results$clusters$true.N[row.name, "N", i] <- length(index) + } + } + results +} + +store.truth <- function(results, truth, i){ + # Stores the truth returned by a population generator for repetition i + if(is.null(truth) || is.null(results$truth)){ + return(results) + } + results$truth[1, c("N", "D"), i] <- truth[c("N", "D")] + results +} + +count.in.truncation <- function(dist.data, left, right){ + # Number of detections with distances within the truncation distances + distances <- dist.data$distance + distances <- distances[!is.na(distances)] + if(length(distances) == 0 || is.na(right)){ + return(0) + } + sum(distances >= left & distances <= right) +} + +store.zero.detection.results <- function(results, transects, region, group.strata, left, right, i){ + # Records a repetition with no detections within the truncation distance as + # an estimate of zero (zero.n = "zero") + samplers <- transects@samplers + is.line <- inherits(transects, "Line.Transect") + if(is.line){ + effort <- as.numeric(sf::st_length(samplers)) + }else{ + effort <- rep(1, nrow(samplers)) + } + sampler.strata <- as.character(samplers$strata) + strata.map <- results.strata.map(dimnames(results$individuals$summary)[[1]], + region, group.strata) + region.strata <- region@strata.name + if(length(region.strata) == 0){ + region.strata <- region@region.name + } + width <- right - left + for(row.name in names(strata.map)){ + if(length(region@strata.name) <= 1){ + design.strata <- region.strata + samp.index <- seq_along(sampler.strata) + }else{ + design.strata <- strata.map[[row.name]] + samp.index <- which(sampler.strata %in% design.strata) + } + area <- sum(region@area[region.strata %in% design.strata]) + row.effort <- sum(effort[samp.index]) + covered <- if(is.line) 2 * width * row.effort else pi * (right^2 - left^2) * row.effort + summary.values <- c(Area = area, CoveredArea = covered, Effort = row.effort, + n = 0, n.miss.dist = 0, k = length(samp.index), + ER = 0, se.ER = NA, cv.ER = NA) + estimate.values <- c(Estimate = 0, se = NA, cv = NA, lcl = 0, ucl = NA, df = NA) + results$individuals$summary[row.name, names(summary.values), i] <- summary.values + results$individuals$N[row.name, names(estimate.values), i] <- estimate.values + results$individuals$D[row.name, names(estimate.values), i] <- estimate.values + if(!is.null(results$clusters)){ + results$clusters$summary[row.name, names(summary.values), i] <- summary.values + results$clusters$N[row.name, names(estimate.values), i] <- estimate.values + results$clusters$D[row.name, names(estimate.values), i] <- estimate.values + } + } + results$Detection[1, , i] <- NA + results$Detection[1, "SuccessfulModels", i] <- 0 + if("ZeroDetections" %in% dimnames(results$Detection)[[2]]){ + results$Detection[1, "ZeroDetections", i] <- 1 + } + results +} + +get.rep.index <- function(detection, reps, model.count, use.max.reps){ + # Returns the index of the repetitions to include in the summaries: those + # where all (or with use.max.reps at least one) models were fitted, plus + # those recorded as zero detections (zero.n = "zero") + if(!("SuccessfulModels" %in% dimnames(detection)[[2]])){ + return(seq_len(reps)) + } + successful <- detection[1, "SuccessfulModels", seq_len(reps)] + if(use.max.reps){ + include <- successful > 0 + }else{ + include <- successful == model.count + } + if("ZeroDetections" %in% dimnames(detection)[[2]]){ + zero <- detection[1, "ZeroDetections", seq_len(reps)] + include <- include | (!is.na(zero) & zero == 1) + } + which(include) +} diff --git a/R/run.simulation.R b/R/run.simulation.R index 3d543ab..4e7761f 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -1,15 +1,44 @@ #' Method to run a simulation #' -#' Runs the simulation and returns the simulation object with results. If -#' running in parallel and max.cores is not specified it will default to using -#' one less than the number of cores / threads on your machine. For example -#' code see \code{\link{make.simulation}} +#' Runs the simulation and returns the simulation object with results. By +#' default the repetitions are run in parallel using one less than the number +#' of cores available on your machine. For example code see +#' \code{\link{make.simulation}} +#' +#' @section Parallel processing: +#' Repetitions are distributed to worker processes using the mirai package, +#' with each worker picking up a new repetition as soon as it finishes one. +#' The number of workers defaults to +#' \code{parallelly::availableCores(omit = 1)}, which respects limits set by +#' HPC schedulers and containers. If you have already started mirai daemons +#' (e.g. \code{mirai::daemons(8)}, or remote / HPC daemons) these are used +#' instead and are left running afterwards. Otherwise workers are started and +#' stopped on every call, which takes a few seconds; when running many short +#' simulations (e.g. in a loop) start the daemons once with +#' \code{mirai::daemons(n)} beforehand and stop them with +#' \code{mirai::daemons(0)} when finished. +#' +#' The workers are separate R processes (not forks). A population generator +#' (see \code{\link{make.simulation}}) is sent to them with its enclosing +#' environment, but objects in the global environment and packages it uses +#' are not: see the 'Population generator' section of +#' \code{\link{make.simulation}}. +#' +#' Each repetition uses its own random number stream, so after calling +#' \code{set.seed} results are identical whether run in serial or in parallel, +#' regardless of the number of workers. +#' +#' If a repetition fails with an error the simulation carries on; the +#' repetition is skipped and the error is reported in the summary of warnings +#' and errors. #' #' @param simulation \code{\link{Simulation-class}} object -#' @param run.parallel logical option to use multiple processors +#' @param run.parallel logical option to use multiple processors (default +#' TRUE). Ignored if only one core is available. #' @param max.cores integer maximum number of cores to use, if not specified then #' one less than the number available will be used. -#' @param counter logical indicates if you would like to see the progress counter. +#' @param counter logical indicates if you would like to see the progress +#' counter, which also shows the elapsed and estimated remaining time. #' @param transect.path character gives the pathway to a folder of shapefiles or #' the path to a single shapefile (.shp file) which give the transects which should #' be used for the simulations. If a folder of transects a new shapefile will be @@ -21,11 +50,15 @@ #' @return the \code{\link{Simulation-class}} object which now includes #' the results #' @export -#' @importFrom parallel detectCores makeCluster clusterEvalQ stopCluster parLapply -#' @importFrom rstudioapi versionInfo +#' @importFrom mirai daemons daemons_set everywhere mirai mirai_map unresolved is_error_value is_mirai_error +#' @importFrom parallelly availableCores +#' @importFrom parallel nextRNGStream #' @rdname run.simulation-methods #' @seealso \code{\link{make.simulation}} -run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, counter = TRUE, transect.path = character(0), progress.file = character(0)){ +#' +run.simulation <- function(simulation, run.parallel = TRUE, max.cores = NA, + counter = TRUE, transect.path = character(0), + progress.file = character(0)) { save.data <- load.data <- FALSE data.path <- character() # Check if the transect path ends in / if so remove - hard to do the same for windows! @@ -56,11 +89,11 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou } } } - #Reset results arrays simulation@results <- create.results.arrays(simulation@reps, simulation@design@region, simulation@ds.analysis, - simulation@population.description) + simulation@population.description, + population.generator = get.population.generator(simulation)) #reset the error/warning message simulation@warnings$message <- list() simulation@warnings$counter <- list() @@ -74,73 +107,50 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou } rm(temp.path) } - # Two if(run.parallel) checks as if libraries not present will change to - # false before running in parallel and then run in serial + # Give each rep its own random number stream so results are reproducible + # whether run in serial or in parallel + rep.seeds <- make.rep.seeds(simulation@reps) + rep.args <- list(simulation = simulation, + save.data = save.data, + load.data = load.data, + data.path = data.path, + transect.path = transect.path, + rep.seeds = rep.seeds) if(run.parallel){ - if(!requireNamespace('parallel', quietly = TRUE) | !requireNamespace('pbapply', quietly = TRUE)){ - warning("Could not run in parallel, check pbapply library is installed.", immediate. = TRUE, call. = FALSE) - run.parallel = FALSE - }else{ - # counts the number of cores you have - nCores <- getOption("cl.cores", detectCores()) - 1 - if(!is.na(max.cores)){ - nCores <- min(nCores, max.cores) - } - if(nCores <= 1){ - warning("Could not run in parallel only one core available/requested (dsims limits running in parallel to 1 less than the number of cores on the machine).", immediate. = TRUE, call. = FALSE) - run.parallel = FALSE - } + compute <- launch.daemons(max.cores) + if(is.null(compute)){ + run.parallel <- FALSE + }else if(compute == "dsims"){ + # Only shut down the daemons dsims started + on.exit(mirai::daemons(0, .compute = "dsims"), add = TRUE) } } if(run.parallel){ - # there is an issue with parallel on some machines for some versions of R and R studio - ## WORKAROUND: https://github.com/rstudio/rstudio/issues/6692 - ## Revert to 'sequential' setup of PSOCK cluster in RStudio v1.3.959 or lower on macOS with R v4.0.0 or higher - if (Sys.getenv("RSTUDIO") == "1" && !nzchar(Sys.getenv("RSTUDIO_TERM")) && - Sys.info()["sysname"] == "Darwin" && getRversion() >= "4.0.0") { - if(rstudioapi::versionInfo()$version < "1.3.1056"){ - #warning(paste("The combination of versions of R-studio and R you are using on your mac may lead to an error when running in parallel. Please run the following command to try to correct this before running the simulation again (alternatively try updating R-studio): parallel:::setDefaultClusterOptions(setup_strategy = \"sequential\")", sep = ""), immediate. = TRUE, call. = FALSE) - eval(parse(text = "parallel:::setDefaultClusterOptions(setup_strategy = \"sequential\")")) - } - } - # intitialise the cluster - myCluster <- parallel::makeCluster(nCores) - parallel::clusterEvalQ(myCluster, { - require(dsims) - }) - on.exit(stopCluster(myCluster)) - if(counter){ - results <- pbapply::pblapply(X = as.list(1:simulation@reps), FUN = single.sim.loop, simulation = simulation, save.data = save.data, load.data = load.data, data.path = data.path, transect.path = transect.path, save.transects = FALSE, progress.file = progress.file, cl = myCluster, counter = FALSE) - }else{ - results <- parLapply(myCluster, X = as.list(1:simulation@reps), fun = single.sim.loop, simulation = simulation, save.data = save.data, load.data = load.data, data.path = data.path, counter = FALSE, transect.path = transect.path, save.transects = FALSE, progress.file = progress.file) - } - #Extract results and warnings - sim.results <- sim.warnings <- list() - for(i in seq(along = results)){ - sim.results[[i]] <- results[[i]]$results - sim.warnings[[i]] <- results[[i]]$warnings + tasks <- mirai::mirai_map(seq_len(simulation@reps), run.single.rep, + .args = rep.args, .compute = compute) + wait.for.reps(tasks, simulation@reps, counter, progress.file) + results <- tasks[] + }else{ + old.seed <- get(".Random.seed", envir = globalenv()) + results <- vector("list", simulation@reps) + start.time <- Sys.time() + for(i in seq_len(simulation@reps)){ + results[[i]] <- tryCatch(do.call(run.single.rep, c(list(i), rep.args)), + error = function(e) e) + report.progress(i, simulation@reps, start.time, counter, progress.file) } - simulation <- accumulate.PP.results(simulation = simulation, results = sim.results) - simulation@warnings <- accumulate.warnings(sim.warnings) - stopCluster(myCluster) - on.exit() - } - if(!run.parallel){ - #otherwise loop - for(i in 1:simulation@reps){ - results <- single.sim.loop(i = i, - simulation = simulation, - save.data = save.data, - load.data = load.data, - data.path = data.path, - counter = counter, - transect.path = transect.path, - save.transects = FALSE, - progress.file = progress.file) - simulation@results <- results$results - simulation@warnings <- results$warnings + assign(".Random.seed", old.seed, envir = globalenv()) + } + # Reps which failed with an error are skipped and the error recorded + for(i in seq_along(results)){ + if(inherits(results[[i]], "error") || mirai::is_error_value(results[[i]])){ + results[[i]] <- list(warnings = message.handler(list(), paste("Error in repetition, repetition skipped:", failed.rep.message(results[[i]])), i)) } } + #Extract results and warnings + sim.warnings <- lapply(results, function(x) x$warnings) + simulation <- accumulate.PP.results(simulation = simulation, results = results) + simulation@warnings <- accumulate.warnings(sim.warnings) simulation@results <- add.summary.results(results = simulation@results, model.count = length(simulation@ds.analysis@dfmodel)) #Process warnings @@ -157,3 +167,137 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou return(simulation) } +run.single.rep <- function(i, simulation, save.data, load.data, data.path, + transect.path, rep.seeds){ + # Runs repetition i using its own random number stream. Defined at the top + # level so that it is sent to the daemons by reference to the dsims namespace. + assign(".Random.seed", rep.seeds[[i]], envir = globalenv()) + single.sim.loop(i = i, + simulation = simulation, + save.data = save.data, + load.data = load.data, + data.path = data.path, + transect.path = transect.path, + save.transects = FALSE) +} + +make.rep.seeds <- function(reps){ + # Returns a list of L'Ecuyer-CMRG seeds, one independent stream per rep. + # The base seed is drawn from the current RNG so set.seed() controls the + # streams, the user's RNG kind and state are then restored. + base.seed <- sample.int(.Machine$integer.max, 1L) + old.seed <- get(".Random.seed", envir = globalenv()) + old.kind <- RNGkind() + on.exit({ + RNGkind(old.kind[1], old.kind[2], old.kind[3]) + assign(".Random.seed", old.seed, envir = globalenv()) + }) + RNGkind("L'Ecuyer-CMRG") + set.seed(base.seed) + seed <- get(".Random.seed", envir = globalenv()) + seeds <- vector("list", reps) + for(i in seq_len(reps)){ + seeds[[i]] <- seed + seed <- parallel::nextRNGStream(seed) + } + seeds +} + +launch.daemons <- function(max.cores){ + # Returns the mirai compute profile to use, or NULL to run in serial. + # Daemons the user has already set up (e.g. remote or HPC) are used as they + # are, otherwise local daemons are started under the "dsims" profile. + if(mirai::daemons_set()){ + check.daemon.version("default") + return("default") + } + nCores <- parallelly::availableCores(omit = 1) + if(!is.na(max.cores)){ + nCores <- min(nCores, max.cores) + } + if(nCores <= 1){ + warning("Could not run in parallel only one core available/requested (dsims limits running in parallel to 1 less than the number of cores on the machine).", immediate. = TRUE, call. = FALSE) + return(NULL) + } + mirai::daemons(nCores, .compute = "dsims") + # Daemons start with the default library paths, use this session's instead + # so they load the same version of dsims + # (a pre-built call, so the paths are sent as values) + lib.call <- call(".libPaths", .libPaths()) + mirai::everywhere(lib.call, .min = nCores, .compute = "dsims") + check.daemon.version("dsims") + "dsims" +} + +check.daemon.version <- function(compute){ + # Stops if the daemons load a different version of dsims to this session, + # as every rep would then fail + daemon.version <- mirai::mirai(as.character(utils::packageVersion("dsims")), + .compute = compute)[] + if(mirai::is_error_value(daemon.version)){ + if(compute == "dsims"){ + mirai::daemons(0, .compute = compute) + } + stop("Could not load dsims on the parallel workers: ", failed.rep.message(daemon.version), call. = FALSE) + } + if(daemon.version != as.character(utils::packageVersion("dsims"))){ + if(compute == "dsims"){ + mirai::daemons(0, .compute = compute) + } + stop("The parallel workers use dsims version ", daemon.version, " but this session uses version ", utils::packageVersion("dsims"), ". Please make sure the same version is installed for the workers.", call. = FALSE) + } +} + +wait.for.reps <- function(tasks, reps, counter, progress.file){ + # Polls the parallel tasks, reporting progress as reps complete + start.time <- Sys.time() + done <- 0 + repeat{ + now.done <- sum(!vapply(tasks, mirai::unresolved, logical(1))) + if(now.done != done){ + done <- now.done + report.progress(done, reps, start.time, counter, progress.file) + } + if(done == reps){ + break + } + Sys.sleep(0.5) + } +} + +report.progress <- function(done, reps, start.time, counter, progress.file){ + # Displays the progress counter with elapsed / estimated remaining time and + # writes the progress (integer %) to file for Distance for Windows + if(counter){ + elapsed <- as.numeric(difftime(Sys.time(), start.time, units = "secs")) + remaining <- elapsed / done * (reps - done) + message("\r", done, " out of ", reps, " reps (elapsed ", duration.string(elapsed), + ", remaining ~", duration.string(remaining), ") ", + appendLF = done == reps) + } + if(length(progress.file) > 0){ + try(cat(round(done/reps*100), file = progress.file), silent = TRUE) + } +} + +duration.string <- function(secs){ + # Formats a number of seconds as e.g. "1d 02h 05m", "2h 05m" or "4m 09s" + secs <- round(secs) + d <- secs %/% 86400 + h <- (secs %% 86400) %/% 3600 + m <- (secs %% 3600) %/% 60 + if(d > 0) return(sprintf("%dd %02dh %02dm", d, h, m)) + if(h > 0) return(sprintf("%dh %02dm", h, m)) + sprintf("%dm %02ds", m, secs %% 60) +} + +failed.rep.message <- function(err){ + # Extracts the message from an R error or a mirai error value + if(inherits(err, "error")){ + return(conditionMessage(err)) + } + if(mirai::is_mirai_error(err)){ + return(attr(err, "message")) + } + paste("the worker process failed (mirai error value ", as.integer(err), ")", sep = "") +} diff --git a/R/simulate.detections.R b/R/simulate.detections.R index e026beb..1102a53 100644 --- a/R/simulate.detections.R +++ b/R/simulate.detections.R @@ -7,7 +7,9 @@ simulate.detections <- function(poss.distances, detectability){ # Hazard rate "hr" = 1-exp(-(poss.distances$distance/poss.distances$scale.param)^-poss.distances$shape.param), # Uniform - "uf" = poss.distances$scale.param + # (numeric(0) when no individuals are within the truncation + # distance of any transect, poss.distances then has no columns) + "uf" = if(is.null(poss.distances$scale.param)) numeric(0) else poss.distances$scale.param ) detected <- rbinom(length(probs), 1, probs) dist.data <- poss.distances[detected == 1,] diff --git a/R/single.sim.loop.R b/R/single.sim.loop.R index 6a5adb8..13062a0 100755 --- a/R/single.sim.loop.R +++ b/R/single.sim.loop.R @@ -1,15 +1,12 @@ -#' @importFrom utils flush.console #' @importFrom methods new is #' @importFrom mrds dht #single.simulation.loop <- function(i, object){ -single.sim.loop <- function(i, simulation, save.data, load.data, data.path = character(0), counter, in.parallel = FALSE, transect.path = character(0), save.transects = FALSE, progress.file = character(0), debug = FALSE){ +single.sim.loop <- function(i, simulation, save.data, load.data, data.path = character(0), transect.path = character(0), save.transects = FALSE, debug = FALSE){ # Input: i - integer representing the loop number # simulation - an simulation of class Simulation # save.data - logical whether to save the data # load.data - logical whether to load the data # data.path - where to load/save the data - # counter - whether to display a progress counter - # in.parallel - whether it is being run in parallel # transect.path - vector of shapefile paths for each iteration or # locations to save them to (latter not yet implemented) # save.transects - logical whether to save the transects @@ -19,33 +16,23 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha # Output: list of simulation results and warnings # warnings <- simulation@warnings - # Display/write to file the progress of the simulation - if(counter){ - if(length(progress.file) == 0 && !in.parallel){ - # Write to terminal - message("\r", i, " out of ", simulation@reps, " reps \r", appendLF = FALSE) - }else if(length(progress.file) > 0){ - # Calculate progress as an integer % - progress <- round(i/simulation@reps*100) - # Check if being run in parallel - if(in.parallel){ - #If so load file to check if progress should be updated - old.progress <- try(scan(progress.file, what=integer()), silent = TRUE) - if(inherits(old.progress,"integer")){ - #Only update if this is the latest progress (when running in parallel things may not be processed in exactly the right order) - if(progress > old.progress){ - try(cat(progress, file = progress.file), silent = TRUE) - } - } - }else{ - cat(progress, file = progress.file) - } - } - } - flush.console() + rep.filename <- NA_character_ if(!load.data){ #generate population - population <- generate.population(simulation) + if(is.null(get.population.generator(simulation))){ + population <- generate.population(simulation) + }else{ + # User supplied population generator, the RNG state is restored + # afterwards so the rest of the rep uses the dsims random number stream + generated <- run.population.generator(simulation, i) + population <- generated$population + simulation@results <- store.truth(simulation@results, generated$truth, i) + rm(generated) + } + # Record the realised number of individuals in the design region + simulation@results <- store.true.N(simulation@results, population, + simulation@design@region, + simulation@ds.analysis@group.strata, i) #generate transects load.transects <- FALSE if(length(transect.path) > 0 && !save.transects){ @@ -72,9 +59,11 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha warnings <- transects$warnings transects <- transects$transects if(is.null(transects)){ - return(list(results = simulation@results, warnings = warnings)) + rep.result <- extract.rep.result(simulation@results, i) + return(list(rep.result = rep.result, warnings = warnings, filename = rep.filename)) } simulation@results$filename[i] <- filename + rep.filename <- filename }else{ transects <- generate.transects(simulation) if(save.transects){ @@ -152,8 +141,22 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha }else{ n.in.covered <- length(dists.in.covered) } + # Check for no detections within the truncation distance when these are to + # be recorded as zero estimates + zero.detections <- FALSE + if(get.zero.n(simulation@ds.analysis) == "zero" && exists("transects", inherits = FALSE)){ + zero.detections <- count.in.truncation(dist.data, left, right) == 0 + } #analyse survey if there are data to analyse - if(nrow(dist.data[!is.na(dist.data$distance),]) > 0){ + if(zero.detections){ + warnings <- message.handler(warnings, "There were no detections within the truncation distance, abundance and density recorded as zero (zero.n = 'zero').", i) + simulation@results <- store.zero.detection.results(simulation@results, + transects, + simulation@design@region, + simulation@ds.analysis@group.strata, + left, right, i) + model.results <- NULL + }else if(nrow(dist.data[!is.na(dist.data$distance),]) > 0){ model.results <- analyse.data(simulation@ds.analysis, data.obj = survey, simulation@warnings, i = i) warnings <- model.results$warnings num.successful.models <- model.results$num.successful.models @@ -228,6 +231,9 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha survey = survey, warnings = warnings)) } - return(list(results = simulation@results, warnings = warnings)) + rep.result <- extract.rep.result(simulation@results, i) + return(list(rep.result = rep.result, + warnings = warnings, + filename = rep.filename)) } diff --git a/R/store.ddf.results.R b/R/store.ddf.results.R index b916440..aefb2ab 100644 --- a/R/store.ddf.results.R +++ b/R/store.ddf.results.R @@ -15,6 +15,9 @@ store.ddf.results <- function(detection.results, ddf.results, i, N.in.covered, n detection.results[1, "DeltaCriteria", i] <- ddf.results$delta.criteria } detection.results[1, "SuccessfulModels", i] <- num.successful.models + if("ZeroDetections" %in% dimnames(detection.results)[[2]]){ + detection.results[1, "ZeroDetections", i] <- 0 + } return(detection.results) } diff --git a/bench/benchmark.R b/bench/benchmark.R new file mode 100644 index 0000000..7194d16 --- /dev/null +++ b/bench/benchmark.R @@ -0,0 +1,92 @@ +# Benchmark run.simulation(): dsims 1.0.6 (parallel package) vs mirai backend +# +# Setup (from the dsims package root): +# bench/lib_baseline - dsims installed from commit eb2bef4 (before the switch) +# bench/lib_new - dsims installed from the working tree +# R CMD INSTALL --library=bench/lib_new . +# +# Usage: Rscript bench/benchmark.R [serial.reps] [parallel.reps] [times] +# Each configuration runs in a fresh R process (callr) so the two dsims +# versions never share a session. Results are written to bench/results.csv. + +args <- commandArgs(trailingOnly = TRUE) +serial.reps <- if (length(args) >= 1) as.integer(args[1]) else 20L +parallel.reps <- if (length(args) >= 2) as.integer(args[2]) else 64L +times <- if (length(args) >= 3) as.integer(args[3]) else 3L +workers <- c(2L, 4L, 8L, 16L) + +libs <- c(baseline = normalizePath("bench/lib_baseline"), + new = normalizePath("bench/lib_new")) + +# Runs one timed simulation in a fresh process +# mode: "serial", "parallel" (workers started per call) or +# "persistent" (mirai daemons set once by the user, warm-up call not timed) +run.one <- function(version, mode, reps, workers = 1L) { + callr::r(function(version, mode, reps, workers) { + suppressMessages(library(dsims)) + sim <- make.simulation(reps = reps) + run <- function() { + if (mode == "serial") { + run.simulation(sim, run.parallel = FALSE, counter = FALSE) + } else { + run.simulation(sim, run.parallel = TRUE, max.cores = workers, counter = FALSE) + } + } + if (mode == "persistent") { + mirai::daemons(workers) + # User daemons start with the default library paths, so point them at + # the same library as this process (otherwise dsims stops on a version mismatch) + mirai::everywhere(.libPaths(lib.paths), lib.paths = .libPaths(), .min = workers) + warm <- sim + warm@reps <- workers + invisible(run.simulation(warm, counter = FALSE)) + } + invisible(gc(reset = TRUE)) + elapsed <- suppressMessages(suppressWarnings(system.time(res <- run())))[["elapsed"]] + # Reps without an abundance estimate (e.g. failed with an error) + failed <- sum(is.na(res@results$individuals$N[1, "Estimate", seq_len(reps)])) + max.mb <- sum(gc()[, ncol(gc())]) + data.frame(version = version, + dsims = as.character(packageVersion("dsims")), + mode = mode, reps = reps, workers = workers, + elapsed = elapsed, max.mem.mb = max.mb, failed = failed) + }, args = list(version = version, mode = mode, reps = reps, workers = workers), + libpath = c(libs[[version]], .libPaths())) +} + +scenarios <- rbind( + data.frame(version = c("baseline", "new"), mode = "serial", + reps = serial.reps, workers = 1L), + expand.grid(version = "baseline", mode = "parallel", reps = parallel.reps, + workers = workers, stringsAsFactors = FALSE), + expand.grid(version = "new", mode = c("parallel", "persistent"), + reps = parallel.reps, workers = workers, stringsAsFactors = FALSE) +) + +results <- list() +for (k in seq_len(times)) { + # Shuffle order each round to spread out any drift in machine load + for (s in sample(seq_len(nrow(scenarios)))) { + sc <- scenarios[s, ] + message(sprintf("[round %d] %s %s reps=%d workers=%d", k, sc$version, + sc$mode, sc$reps, sc$workers)) + res <- run.one(sc$version, sc$mode, sc$reps, sc$workers) + res$round <- k + results[[length(results) + 1]] <- res + } +} +results <- do.call(rbind, results) +write.csv(results, "bench/results.csv", row.names = FALSE) + +# Median per configuration, with speed-up relative to the baseline +if (any(results$failed > 0)) { + warning("Some reps failed, see the failed column of bench/results.csv", call. = FALSE) +} +summ <- aggregate(cbind(elapsed, max.mem.mb, failed) ~ version + mode + reps + workers, + data = results, FUN = median) +base <- summ[summ$version == "baseline", c("mode", "workers", "elapsed")] +summ$baseline.elapsed <- base$elapsed[match(summ$workers, base$workers)] +summ$ratio.vs.baseline <- round(summ$elapsed / summ$baseline.elapsed, 3) +summ$sec.per.rep <- round(summ$elapsed / summ$reps, 3) +summ <- summ[order(summ$workers, summ$version, summ$mode), ] +print(summ, row.names = FALSE) diff --git a/man/DS.Analysis-class.Rd b/man/DS.Analysis-class.Rd index a8ef45b..6ffaa3f 100644 --- a/man/DS.Analysis-class.Rd +++ b/man/DS.Analysis-class.Rd @@ -41,6 +41,11 @@ be grouped (into less strata) for the analyses} \item{\code{criteria}}{Object of class \code{"character"}; describes which model selection criteria to use ("AIC","AICc","BIC").} + +\item{\code{zero.n}}{Object of class \code{"character"}; how repetitions with no +detections within the truncation distance are treated, either "fail" +(the repetition is skipped) or "zero" (abundance and density are recorded +as 0). See \code{\link{make.ds.analysis}}.} }} \section{Methods}{ diff --git a/man/Detectability-class.Rd b/man/Detectability-class.Rd index 573f3db..c341cfb 100644 --- a/man/Detectability-class.Rd +++ b/man/Detectability-class.Rd @@ -20,8 +20,16 @@ parameter for the detection function.} \item{\code{shape.param}}{Object of class \code{"numeric"}; The shape parameter for the detection function.} -\item{\code{cov.param}}{Object of class \code{"numeric"}; The parameter -values associated with the covariates. Not yet implemented} +\item{\code{cov.param}}{Object of class \code{"list"}; Named list of covariate +effect parameters (log scale) for individual-level covariates. Entries may +be numeric vectors for continuous/discrete covariates, or data.frames for +categorical covariates with columns such as \code{strata}, \code{level}, +and \code{param}.} + +\item{\code{cov.surface}}{Object of class \code{"list"}; Optional named list of +raster surfaces (character file paths or terra SpatRaster objects) providing +spatially-explicit covariate values sampled at each animal's location. Names +must match numeric-vector entries in \code{cov.param}.} \item{\code{truncation}}{Object of class \code{"numeric"}; The maximum distance at which objects may be detected.} diff --git a/man/Simulation-class.Rd b/man/Simulation-class.Rd index 6231378..da820f9 100644 --- a/man/Simulation-class.Rd +++ b/man/Simulation-class.Rd @@ -33,6 +33,10 @@ description of the detectability of the population.} \item{\code{add.options}}{a list to expand simulation options in the future.} +\item{\code{population.generator}}{Object of class \code{"function"} or +\code{NULL}; an optional function(simulation, rep) used to generate the +population in each repetition, see \code{\link{make.simulation}}.} + \item{\code{ddf.param.ests}}{Object of class \code{"array"}; stores the parameters associated with the detection function.} @@ -98,10 +102,20 @@ for the repetition), 'DeltaCriteria' (the difference in information criteria between the best and second best fitting models where two or more models were fitted and converged), 'SuccessfulModels' (the number of models which successfully -converged). Currently detection functions are pooled across -all strata so there is only one global value for each -simulated dataset as well as a mean value and standard -deviation where appropriate.} +converged) and 'ZeroDetections' (1 if the repetition had no +detections within the truncation distance and was recorded as +an estimate of zero, see the zero.n argument of +\code{\link{make.ds.analysis}}, 0 otherwise). Currently detection +functions are pooled across all strata so there is only one +global value for each simulated dataset as well as a mean value +and standard deviation where appropriate. + +The 'individuals' (and 'clusters') elements also contain +'true.N', an array [strata, "N", reps + 2] giving the realised +number of individuals (clusters) in the design region in each +repetition. If a population generator returned the truth for +the whole target area (see \code{\link{make.simulation}}) the +results also contain 'truth', an array [1, c("N", "D"), reps + 2].} \item{\code{warnings}}{A \code{"list"} to store warnings and error messages encountered during runtime.} diff --git a/man/Simulation.Summary-class.Rd b/man/Simulation.Summary-class.Rd index ad73aec..7212baa 100644 --- a/man/Simulation.Summary-class.Rd +++ b/man/Simulation.Summary-class.Rd @@ -10,6 +10,17 @@ the simulation results. This is returned when \code{summary(Simulation)} is called. If it is not assigned to a variable the object will be displayed via the \code{show} method. } +\section{Slots}{ + +\describe{ +\item{\code{truth.source}}{named character vector (N, D) giving the source of the +true values used in the summary tables (the population description or a +per-repetition truth from a population generator).} + +\item{\code{zero.detection.reps}}{the number of included repetitions recorded as +zero detections (only when the analysis uses \code{zero.n = "zero"}).} +}} + \section{Methods}{ \describe{ diff --git a/man/make.detectability.Rd b/man/make.detectability.Rd index 817ee8a..f6d4bc9 100644 --- a/man/make.detectability.Rd +++ b/man/make.detectability.Rd @@ -9,6 +9,7 @@ make.detectability( scale.param = 25, shape.param = numeric(0), cov.param = list(), + cov.surface = list(), truncation = 50 ) } @@ -22,6 +23,23 @@ half-normal "hn", hazard rate "hr" or uniform "uf")} \item{cov.param}{Named list with one named entry per individual level covariate. Covariate parameter values should be defined on the log scale (rather than the natural scale), this is the same scale as provided in the ddf output in mrds and also in the MCDS output in Distance. Cluster sizes parameter values can be defined here. Each list entry will either be a data.frame containing 2 or 3 columns: level, param and where desired strata. If the region has multiple strata but this column is omitted then the values will be assumed to apply globally. The cluster size entry in the list must be named 'size'. Alternatively the list element may a numeric vector with either a single value to be applied globally or a value for each strata.} +\item{cov.surface}{Optional named list of raster surfaces providing spatially-explicit +covariate values based on each animal's simulated location. Each element name must +match a numeric entry in \code{cov.param} (which gives the log-scale slope applied to +the extracted raster value). Each element should be either a character file path to a +single-layer raster readable by \code{terra::rast()}, or an in-memory +\code{terra} SpatRaster object. At every simulation replicate the raster is sampled at +each animal's (x, y) location; the value is used as the covariate in the standard +log-linear scaling formula: +\eqn{\log(\sigma_i) = \log(\sigma_0) + \beta \cdot z_i}. +Use a negative \code{cov.param} slope to model lower detectability where raster values +are higher (e.g. denser canopy cover reduces detection range). +Animal locations outside the raster extent or with NA cell values are replaced with the +raster mean and a warning is issued. +\strong{Parallel note:} file paths are strongly preferred over in-memory SpatRaster +objects when running in parallel (see \code{\link{run.simulation}}), as large +objects may not serialise efficiently to worker processes.} + \item{truncation}{the maximum perpendicular (or radial) distance at which objects may be detected from a line (or point) transect.} } diff --git a/man/make.ds.analysis.Rd b/man/make.ds.analysis.Rd index 307adbf..3c2b1d7 100644 --- a/man/make.ds.analysis.Rd +++ b/man/make.ds.analysis.Rd @@ -12,15 +12,22 @@ make.ds.analysis( er.var = "R2", control.opts = list(), group.strata = data.frame(), - criteria = "AIC" + criteria = "AIC", + zero.n = c("fail", "zero") ) } \arguments{ \item{dfmodel}{list of distance sampling model formula specifying the detection function (see \code{?Distance::ds} for further details)} -\item{key}{key function to use; "hn" gives half-normal (default) and "hr" gives -hazard-rate.} +\item{key}{key function to use; "hn" gives half-normal (default), "hr" gives +hazard-rate and "unif" (or "uf") gives uniform. The uniform key has no +parameters, so it assumes all animals within the truncation distance are +detected (a strip transect estimate) and covariates cannot be included +(the corresponding dfmodel must be ~1). If the simulated detectability is +less than 1 within the strip (e.g. \code{make.detectability(key.function = "uf", +scale.param = 0.9)}) the uniform analysis will underestimate abundance by +the same proportion, as g(0) < 1 cannot be estimated from the distances.} \item{truncation}{absolute truncation distance in simulation units matching the region units.} @@ -40,6 +47,19 @@ second specifies how they should be grouped (into less strata) for the analyses. details for more information.} \item{criteria}{character model selection criteria (AIC, AICc, BIC)} + +\item{zero.n}{how to treat a repetition with no detections within the +truncation distance. "fail" (default) skips the repetition, it is reported +as a warning and counted as excluded in the summary. "zero" records the +repetition as a successful estimate of zero: abundance and density +Estimate = 0, lcl = 0 and se, cv and ucl = NA. The number of detections +(n = 0), area, covered area and effort are recorded as usual and the +repetition is flagged in the ZeroDetections column of +\code{simulation@results$Detection}. Zero detection repetitions are then +included in the mean, SD, RMSE and bias reported by +\code{summary()}, while CI coverage only uses repetitions with a defined +confidence interval. Repetitions with one or more detections where no model +could be fitted remain failures under both options.} } \value{ \code{\link{DS.Analysis-class}} object @@ -93,6 +113,12 @@ ds.analyses <- make.ds.analysis(dfmodel = list(~1, ~size, ~1), truncation = 500, criteria = "AIC") +# Uniform (strip transect) analysis, e.g. for a camera where every animal +# within the strip is detected (see make.detectability with key.function = "uf") +ds.analyses <- make.ds.analysis(dfmodel = ~1, + key = "unif", + truncation = 50) + } \seealso{ \code{\link[Distance]{ds}} \code{\link{make.simulation}} diff --git a/man/make.population.description.Rd b/man/make.population.description.Rd index ddbeaa4..6d33151 100644 --- a/man/make.population.description.Rd +++ b/man/make.population.description.Rd @@ -20,7 +20,8 @@ make.population.description( \item{covariates}{Named list with one named entry per individual-level covariate. Cluster sizes can be defined here, it must be named 'size'. The distribution of covariate values can either be defined by specifying a particular distribution and its parameters or as a discrete distribution in a dataframe. Dataframes should have columns level and prob (and optionally strata) specifying the covariates levels, probabilities and strata if they are strata specific. Distributions can be defined as lists with named entries distribution and the relevant parameters as specified in details. A list of distributions can be provided with one for each strata.} \item{N}{the number of individuals / clusters in a population with one value per -strata. Total population size is 1000 by default.} +strata. Total population size is 1000 by default. When \code{fixed.N = TRUE} +the values must be whole numbers.} \item{fixed.N}{a logical value. If TRUE the population is generated from the value(s) of N otherwise it is generated from the values in the density grid.} diff --git a/man/make.simulation.Rd b/man/make.simulation.Rd index fb6837d..31ce712 100644 --- a/man/make.simulation.Rd +++ b/man/make.simulation.Rd @@ -9,7 +9,8 @@ make.simulation( design = make.design(), population.description = make.population.description(), detectability = make.detectability(), - ds.analysis = make.ds.analysis() + ds.analysis = make.ds.analysis(), + population.generator = NULL ) } \arguments{ @@ -26,6 +27,11 @@ created by a call to \link{make.population.description}} \item{ds.analysis}{an objects of class DS.Analysis created by a call to \link{make.ds.analysis}} + +\item{population.generator}{optional function used to generate the +population in each repetition instead of +\code{generate.population(simulation)}. Default NULL uses the +population description. See the 'Population generator' section.} } \value{ \code{\link{Simulation-class}} object @@ -46,6 +52,67 @@ The \code{make.simulation} function is now set up so that by default (with the exception of specifying point transects rather than line) it can run a simple simulation example. See examples. } +\section{Population generator}{ + +A population generator is a \code{function(simulation, rep)} which is +called once per repetition with the simulation object and the repetition +number. It must return either a \code{\link{Population-class}} object or a +list with elements \code{population} (a Population object) and +\code{truth}, a named numeric vector or list with entries \code{N} and/or +\code{D} giving the true abundance / density of the whole target area for +this repetition. This allows, for example, a population to be generated +over a larger study area and only the individuals inside the survey +region (the design region) to be returned, while bias is assessed +against the density of the whole study area. + +\strong{Requirements for the returned population.} It is checked in every +repetition: it must be a Population object whose \code{population} slot is a +data.frame with columns \code{individual}, \code{x}, \code{y}, +\code{Region.Label} and \code{scale.param} (plus \code{shape.param} for a +hazard-rate detection function and any covariates used in the +detectability description). Region.Label values must be strata names of +\code{simulation@design@region}, all individuals must lie inside the +design region and the detectability slot must be a Detectability object. +The simplest way to get all of these right is to start from a population +made by \code{generate.population()} (with a region covering the study +area) and subset its rows. A population with no individuals is allowed. +The detection function used for the survey is taken from the +population's detectability slot. + +\strong{Random numbers.} The state of the random number generator is saved +before the generator is called and restored afterwards. The generator may +therefore set its own seed (e.g. \code{set.seed(1000 + rep)}) without +changing the transects, detections and analyses of the simulation, which +come from the per-repetition random number streams of dsims. Simulations +that differ only in their design then see identical populations in each +repetition. As the generator does not advance the dsims stream, a +generator which simply returns \code{generate.population(simulation)} +gives the same populations as the default but different transects and +detections. + +\strong{Parallel processing.} \code{run.simulation(run.parallel = TRUE)} sends +the simulation, including the generator, to separate R worker processes +(mirai daemons, these are new R sessions not forks). The generator's +enclosing environment is sent with it unless it is the global environment +or a package namespace. So: (i) any data the generator needs should be +created inside the function or captured in its enclosing environment, for +example by returning the generator from a factory function +(\code{make.gen <- function(study.pop) function(simulation, rep) ...}); +objects referenced from the global environment are not available on the +workers; (ii) call functions from other packages with \code{pkg::fun()} (or +load the packages inside the generator), the packages must be installed +for the workers; (iii) keep captured objects small as they are copied to +each worker with every repetition. If the generator fails on a worker the +repetition is skipped and the error is reported in the summary of +warnings and errors. + +\strong{Results.} If the generator returns \code{truth}, it is stored in +\code{simulation@results$truth} (an array [1, c("N", "D"), reps + 2]) and +\code{summary()} uses it, instead of the population description, as the +truth for the total row of the individual abundance / density tables (see +\code{\link{summary,Simulation-method}}). +} + \examples{ # Create a basic rectangular study area region <- make.region() diff --git a/man/run.simulation-methods.Rd b/man/run.simulation-methods.Rd index d909384..f1ecaa5 100644 --- a/man/run.simulation-methods.Rd +++ b/man/run.simulation-methods.Rd @@ -6,7 +6,7 @@ \usage{ run.simulation( simulation, - run.parallel = FALSE, + run.parallel = TRUE, max.cores = NA, counter = TRUE, transect.path = character(0), @@ -16,12 +16,14 @@ run.simulation( \arguments{ \item{simulation}{\code{\link{Simulation-class}} object} -\item{run.parallel}{logical option to use multiple processors} +\item{run.parallel}{logical option to use multiple processors (default +TRUE). Ignored if only one core is available.} \item{max.cores}{integer maximum number of cores to use, if not specified then one less than the number available will be used.} -\item{counter}{logical indicates if you would like to see the progress counter.} +\item{counter}{logical indicates if you would like to see the progress +counter, which also shows the elapsed and estimated remaining time.} \item{transect.path}{character gives the pathway to a folder of shapefiles or the path to a single shapefile (.shp file) which give the transects which should @@ -38,11 +40,40 @@ the \code{\link{Simulation-class}} object which now includes the results } \description{ -Runs the simulation and returns the simulation object with results. If -running in parallel and max.cores is not specified it will default to using -one less than the number of cores / threads on your machine. For example -code see \code{\link{make.simulation}} +Runs the simulation and returns the simulation object with results. By +default the repetitions are run in parallel using one less than the number +of cores available on your machine. For example code see +\code{\link{make.simulation}} } +\section{Parallel processing}{ + +Repetitions are distributed to worker processes using the mirai package, +with each worker picking up a new repetition as soon as it finishes one. +The number of workers defaults to +\code{parallelly::availableCores(omit = 1)}, which respects limits set by +HPC schedulers and containers. If you have already started mirai daemons +(e.g. \code{mirai::daemons(8)}, or remote / HPC daemons) these are used +instead and are left running afterwards. Otherwise workers are started and +stopped on every call, which takes a few seconds; when running many short +simulations (e.g. in a loop) start the daemons once with +\code{mirai::daemons(n)} beforehand and stop them with +\code{mirai::daemons(0)} when finished. + +The workers are separate R processes (not forks). A population generator +(see \code{\link{make.simulation}}) is sent to them with its enclosing +environment, but objects in the global environment and packages it uses +are not: see the 'Population generator' section of +\code{\link{make.simulation}}. + +Each repetition uses its own random number stream, so after calling +\code{set.seed} results are identical whether run in serial or in parallel, +regardless of the number of workers. + +If a repetition fails with an error the simulation carries on; the +repetition is skipped and the error is reported in the summary of warnings +and errors. +} + \seealso{ \code{\link{make.simulation}} } diff --git a/man/summary.Simulation-methods.Rd b/man/summary.Simulation-methods.Rd index 3ed35e9..57e25b7 100644 --- a/man/summary.Simulation-methods.Rd +++ b/man/summary.Simulation-methods.Rd @@ -22,3 +22,25 @@ Object of class Simulation.Summary \description{ Provides a summary of the simulation results. } +\details{ +\strong{Source of the true values.} By default the true abundance and +density (the Truth column used for percent.bias, RMSE and CI coverage) come +from the population description. If the simulation has a population +generator (see \code{\link{make.simulation}}) which returned a +per-repetition truth (N and/or D for the whole target area), this is used +instead for the total row of the individual abundance / density tables +(the only row of an unstratified region): Truth is then the mean truth over +the included repetitions, percent.bias is +(mean estimate - mean truth) / mean truth * 100, RMSE is +sqrt(mean((estimate_i - truth_i)^2)) and the CI coverage counts +repetitions where lcl_i < truth_i < ucl_i. Strata rows then have no truth +(NA). The source of the truth is shown in the printed summary and stored +in the truth.source slot. + +\strong{Zero detection repetitions.} If the analysis was created with +\code{zero.n = "zero"} the repetitions with no detections within the +truncation distance are included (as estimates of 0) in the mean +estimates, SD, RMSE and bias. CI coverage only uses repetitions with a +defined confidence interval, so excludes them. Their number is shown in +the printed summary and stored in the zero.detection.reps slot. +} diff --git a/tests/testthat/fixtures/make-reference-d668415.R b/tests/testthat/fixtures/make-reference-d668415.R new file mode 100644 index 0000000..56d759f --- /dev/null +++ b/tests/testthat/fixtures/make-reference-d668415.R @@ -0,0 +1,20 @@ +# Creates reference-d668415.rds: results of a small line transect simulation +# run with dsims at commit d668415 (before the population generator and +# zero.n options were added). Run with that version of dsims installed: +# Rscript make-reference-d668415.R +library(dsims) +region <- make.region() +dens <- make.density(region = region, x.space = 50, constant = 1) +pd <- make.population.description(region = region, density = dens, N = 300, fixed.N = TRUE) +det <- make.detectability(scale.param = 25, truncation = 50) +des <- make.design(region = region, transect.type = "line", design = "systematic", + samplers = 10, truncation = 50) +ana <- make.ds.analysis(truncation = 50) +sim <- make.simulation(reps = 5, design = des, population.description = pd, + detectability = det, ds.analysis = ana) +set.seed(123) +sim <- run.simulation(sim, run.parallel = FALSE, counter = FALSE) +ref <- list(version = as.character(packageVersion("dsims")), + individuals = sim@results$individuals[c("summary", "N", "D")], + Detection = sim@results$Detection) +saveRDS(ref, "reference-d668415.rds") diff --git a/tests/testthat/fixtures/reference-d668415.rds b/tests/testthat/fixtures/reference-d668415.rds new file mode 100644 index 0000000..691d92f Binary files /dev/null and b/tests/testthat/fixtures/reference-d668415.rds differ diff --git a/tests/testthat/test-Parallel.R b/tests/testthat/test-Parallel.R new file mode 100644 index 0000000..691cafd --- /dev/null +++ b/tests/testthat/test-Parallel.R @@ -0,0 +1,66 @@ +library(dsims) +library(testthat) + +context("Parallel processing") + +test_that("Results are reproducible in serial and in parallel", { + skip_on_cran() + sim <- make.simulation(reps = 4) + RNGkind("Mersenne-Twister") + + set.seed(101) + sim.serial <- run.simulation(sim, run.parallel = FALSE, counter = FALSE) + # User's RNG kind is not changed + expect_equal(RNGkind()[1], "Mersenne-Twister") + + set.seed(101) + sim.para <- run.simulation(sim, run.parallel = TRUE, max.cores = 2, counter = FALSE) + + expect_equal(sim.serial@results$individuals$N, sim.para@results$individuals$N) + expect_equal(sim.serial@results$Detection, sim.para@results$Detection) + # dsims shuts down the daemons it started + expect_false(mirai::daemons_set(.compute = "dsims")) +}) + +test_that("Daemons set up by the user are used and left running", { + skip_on_cran() + sim <- make.simulation(reps = 2) + mirai::daemons(2) + on.exit(mirai::daemons(0)) + sim.para <- run.simulation(sim, counter = FALSE) + expect_s4_class(sim.para, "Simulation") + expect_true(mirai::daemons_set()) + expect_false(mirai::daemons_set(.compute = "dsims")) +}) + +test_that("A failing repetition is skipped without stopping the simulation", { + sim <- make.simulation(reps = 3) + sim.loop <- dsims:::single.sim.loop + local_mocked_bindings(single.sim.loop = function(i, ...){ + if(i == 2) stop("test failure") + sim.loop(i, ...) + }) + expect_message(sim.res <- run.simulation(sim, run.parallel = FALSE, counter = FALSE), + "Error in repetition, repetition skipped: test failure") + expect_true(all(is.na(sim.res@results$individuals$N[, "Estimate", 2]))) + expect_false(any(is.na(sim.res@results$individuals$N[, "Estimate", c(1, 3)]))) + expect_equal(sim.res@warnings$index[[1]], 2) +}) + +test_that("Errors returned by mirai are reported", { + skip_on_cran() + mirai::daemons(1, .compute = "test") + on.exit(mirai::daemons(0, .compute = "test")) + err <- mirai::mirai(stop("worker failure"), .compute = "test")[] + expect_equal(dsims:::failed.rep.message(err), "worker failure") +}) + +test_that("Progress counter shows elapsed and remaining time", { + expect_equal(dsims:::duration.string(65), "1m 05s") + expect_equal(dsims:::duration.string(2*3600 + 5*60), "2h 05m") + expect_equal(dsims:::duration.string(86400 + 2*3600 + 5*60), "1d 02h 05m") + progress.file <- tempfile() + expect_message(dsims:::report.progress(5, 10, Sys.time() - 10, TRUE, progress.file), + "5 out of 10 reps") + expect_equal(scan(progress.file, quiet = TRUE), 50) +}) diff --git a/tests/testthat/test-ProblemCases.R b/tests/testthat/test-ProblemCases.R index d1047db..a431028 100644 --- a/tests/testthat/test-ProblemCases.R +++ b/tests/testthat/test-ProblemCases.R @@ -138,5 +138,6 @@ test_that("Check cannot get detections greater than truncation", { survey <- run.survey(sim) # Check all distances are less than truncation distance (Issue #76) - expect_true(all(survey@dist.data$distance <= 0.5)) + # (transects without detections are rows with distance NA) + expect_true(all(survey@dist.data$distance <= 0.5, na.rm = TRUE)) }) \ No newline at end of file diff --git a/tests/testthat/test-check_Constructors.R b/tests/testthat/test-check_Constructors.R index 931c3eb..44601d0 100644 --- a/tests/testthat/test-check_Constructors.R +++ b/tests/testthat/test-check_Constructors.R @@ -95,6 +95,17 @@ test_that("Can create objects or return correct error / warning messages", { N = -100), "You must provide a positive, non-zero abundance", fixed = TRUE) + # Fractional N would be rounded up when generating the population + expect_error(make.population.description(region = region, + density = density, + N = 100.4), + "Population size N must be a whole number", fixed = TRUE) + expect_s4_class(make.population.description(region = region, + density = density, + N = 100.4, + fixed.N = FALSE), + "Population.Description") + # This should work below covariate.list <- list() @@ -229,7 +240,7 @@ test_that("Can create objects or return correct error / warning messages", { expect_error(make.ds.analysis(dfmodel = list(~1, ~size, ~size+sex), key = c("hn","zz","uf"), truncation = 25), - "All key function values should be either 'hn' or 'hr'.") + "All key function values should be 'hn', 'hr' or 'unif'.") expect_error(make.ds.analysis(dfmodel = list(~1, ~size, ~size+sex), key = c("hn","hr","hr"), diff --git a/tests/testthat/test-check_IndividualCovariates.R b/tests/testthat/test-check_IndividualCovariates.R index 45c329e..f670024 100644 --- a/tests/testthat/test-check_IndividualCovariates.R +++ b/tests/testthat/test-check_IndividualCovariates.R @@ -269,7 +269,7 @@ test_that("Factor level covariates", { pop.data <- data.frame(individual, x, y, Region.Label, size, sex) - check.scale.params <- calculate.scale.param(pop.data, detect, region) + check.scale.params <- dsims:::calculate.scale.param(pop.data, detect, region) ind1.scale <- exp(log(0.08) + log(1.02)*size[1] + log(1.5)) ind2.scale <- exp(log(0.08) + log(1.02)*size[2] + log(1.5)) diff --git a/tests/testthat/test-check_PopulationGenerator.R b/tests/testthat/test-check_PopulationGenerator.R new file mode 100644 index 0000000..73f874b --- /dev/null +++ b/tests/testthat/test-check_PopulationGenerator.R @@ -0,0 +1,306 @@ +library(dsims) +library(testthat) + +context("Population generator and zero detections") + +# Small line transect simulation, identical to the one in +# fixtures/make-reference-d668415.R +make.test.sim <- function(reps = 5, population.generator = NULL, + design = NULL, zero.n = "fail", detect.scale = 25){ + region <- make.region() + dens <- make.density(region = region, x.space = 50, constant = 1) + pd <- make.population.description(region = region, density = dens, N = 300, + fixed.N = TRUE) + det <- make.detectability(scale.param = detect.scale, truncation = 50) + if(is.null(design)){ + design <- make.design(region = region, transect.type = "line", + design = "systematic", samplers = 10, + truncation = 50) + } + ana <- make.ds.analysis(truncation = 50, zero.n = zero.n) + make.simulation(reps = reps, design = design, population.description = pd, + detectability = det, ds.analysis = ana, + population.generator = population.generator) +} + +run.serial <- function(sim, seed = 123){ + set.seed(seed) + suppressMessages(run.simulation(sim, run.parallel = FALSE, counter = FALSE)) +} + +# Returns a generator which records the populations it returns +make.recorder <- function(gen.fun){ + env <- new.env() + env$pops <- list() + list(env = env, + generator = function(simulation, rep){ + pop <- gen.fun(simulation, rep) + env$pops[[rep]] <- pop + pop + }) +} + +pop.data <- function(pop){ + # population data.frame of a Population (or of a generator list return) + if(is.list(pop)) pop <- pop$population + pop@population +} + +test_that("(a) Without a population generator results match dsims d668415", { + ref <- readRDS(test_path("fixtures", "reference-d668415.rds")) + sim <- run.serial(make.test.sim()) + for(n in c("summary", "N", "D")){ + expect_equal(sim@results$individuals[[n]], ref$individuals[[n]]) + } + # The existing Detection columns are unchanged, ZeroDetections is new + old.cols <- dimnames(ref$Detection)[[2]] + expect_equal(sim@results$Detection[, old.cols, , drop = FALSE], ref$Detection) + expect_equal(unname(sim@results$Detection[1, "ZeroDetections", 1:5]), rep(0, 5)) + # Realised number of individuals in the design region is recorded + expect_equal(unname(sim@results$individuals$true.N[1, "N", 1:5]), rep(300, 5)) + expect_null(sim@results$truth) + expect_null(sim@population.generator) +}) + +test_that("(b) The RNG state is saved and restored around the generator", { + # Populations from a generator returning generate.population(simulation) + # are the populations the default would generate in each repetition + rec <- make.recorder(function(simulation, rep) generate.population(simulation)) + sim.a <- run.serial(make.test.sim(population.generator = rec$generator)) + sim.default <- make.test.sim() + set.seed(123) + seeds <- dsims:::make.rep.seeds(5) + old.seed <- .Random.seed + for(i in 1:5){ + assign(".Random.seed", seeds[[i]], envir = globalenv()) + expect_identical(pop.data(rec$env$pops[[i]]), + generate.population(sim.default)@population) + } + assign(".Random.seed", old.seed, envir = globalenv()) + # The same populations from a generator which uses many more random + # numbers (and a different RNG kind), or none at all, give identical + # results: the generator does not change the dsims stream + gen.b <- function(simulation, rep){ + pop <- generate.population(simulation) + RNGkind("Mersenne-Twister") + set.seed(rep) + runif(1000) + pop + } + sim.b <- run.serial(make.test.sim(population.generator = gen.b)) + fixed.pops <- rec$env$pops + gen.c <- function(simulation, rep) fixed.pops[[rep]] + sim.c <- run.serial(make.test.sim(population.generator = gen.c)) + expect_identical(sim.a@results, sim.b@results) + expect_identical(sim.a@results, sim.c@results) + # The user's RNG state is not changed by the generator + sim.b.def <- make.test.sim(population.generator = gen.b) + set.seed(5) + expected <- runif(1) + set.seed(5) + pop <- dsims:::run.population.generator(sim.b.def, 1) + expect_identical(runif(1), expected) +}) + +test_that("(c) Simulations with different designs see identical populations", { + gen.fun <- function(simulation, rep){ + set.seed(1000 + rep) + generate.population(simulation) + } + rec1 <- make.recorder(gen.fun) + rec2 <- make.recorder(gen.fun) + des2 <- make.design(region = make.region(), transect.type = "line", + design = "random", samplers = 6, truncation = 50) + sim1 <- run.serial(make.test.sim(population.generator = rec1$generator)) + sim2 <- run.serial(make.test.sim(population.generator = rec2$generator, + design = des2), seed = 999) + for(i in 1:5){ + expect_identical(pop.data(rec1$env$pops[[i]]), pop.data(rec2$env$pops[[i]])) + } + # but the populations differ between repetitions + expect_false(identical(pop.data(rec1$env$pops[[1]]), pop.data(rec1$env$pops[[2]]))) + # and the surveys differ between designs + expect_false(identical(sim1@results$individuals$N, sim2@results$individuals$N)) +}) + +test_that("(d) The population generator works in parallel", { + skip_on_cran() + skip_if(parallelly::availableCores() < 3, "Not enough cores") + # Generator made by a factory so the data it needs (here the number of + # individuals to keep) travels with it to the workers + make.gen <- function(keep){ + function(simulation, rep){ + set.seed(rep) + pop <- generate.population(simulation) + pop@population <- pop@population[seq_len(keep), ] + pop@N <- keep + list(population = pop, truth = list(N = 2 * keep, D = 2 * keep / 1e6)) + } + } + sim <- make.test.sim(reps = 4, population.generator = make.gen(250)) + sim.serial <- run.serial(sim, seed = 42) + set.seed(42) + sim.para <- suppressMessages(run.simulation(sim, run.parallel = TRUE, + max.cores = 2, counter = FALSE)) + expect_identical(sim.serial@results, sim.para@results) + expect_equal(unname(sim.para@results$individuals$true.N[1, "N", 1:4]), rep(250, 4)) + expect_equal(unname(sim.para@results$truth[1, "N", 1:4]), rep(500, 4)) + expect_false(mirai::daemons_set(.compute = "dsims")) +}) + +test_that("(e) zero.n = 'zero' records zero detection repetitions as 0", { + # Empty populations in even repetitions + gen <- function(simulation, rep){ + pop <- generate.population(simulation) + if(rep %% 2 == 0){ + pop@population <- pop@population[0, ] + pop@N <- 0 + } + pop + } + sim.zero <- run.serial(make.test.sim(population.generator = gen, zero.n = "zero")) + res <- sim.zero@results + for(i in c(2, 4)){ + expect_equal(unname(res$individuals$N[1, c("Estimate", "lcl"), i]), c(0, 0)) + expect_true(all(is.na(res$individuals$N[1, c("se", "cv", "ucl"), i]))) + expect_equal(unname(res$individuals$D[1, "Estimate", i]), 0) + expect_equal(unname(res$individuals$summary[1, "n", i]), 0) + expect_equal(unname(res$Detection[1, "ZeroDetections", i]), 1) + expect_equal(unname(res$individuals$true.N[1, "N", i]), 0) + } + expect_equal(unname(res$Detection[1, "ZeroDetections", c(1, 3, 5)]), c(0, 0, 0)) + # Effort and covered area are recorded as for the other repetitions + summ <- res$individuals$summary + expect_equal(unname(summ[1, "Effort", 2]), unname(summ[1, "Effort", 1])) + expect_equal(unname(summ[1, "CoveredArea", 1:5]), + unname(2 * 50 * summ[1, "Effort", 1:5])) + expect_equal(unname(summ[1, "Area", 2]), 1e6) + # Counted as successful and included in the mean + sum.zero <- summary(sim.zero, description.summary = FALSE) + expect_equal(sum.zero@failures, 0) + expect_equal(sum.zero@zero.detection.reps, 2) + expect_equal(sum.zero@individuals$N$mean.Estimate, + mean(res$individuals$N[1, "Estimate", 1:5])) + expect_equal(sum.zero@individuals$N$sd.of.means, + sd(res$individuals$N[1, "Estimate", 1:5])) + expect_output(show(sum.zero), "Zero Detection Repetitions") + # With the default, the same repetitions are failures + sim.fail <- run.serial(make.test.sim(population.generator = gen)) + sum.fail <- summary(sim.fail, description.summary = FALSE) + expect_equal(sum.fail@failures, 2) + expect_true(all(is.na(sim.fail@results$individuals$N[1, "Estimate", c(2, 4)]))) + # Zero detections with animals present (detection probability ~ 0) + sim.nodet <- run.serial(make.test.sim(reps = 2, zero.n = "zero", detect.scale = 0.001)) + expect_equal(unname(sim.nodet@results$individuals$N[1, "Estimate", 1:2]), c(0, 0)) + expect_equal(unname(sim.nodet@results$individuals$true.N[1, "N", 1:2]), c(300, 300)) + # Invalid values are rejected + expect_error(make.ds.analysis(zero.n = "skip")) +}) + +test_that("(f) Per-repetition truth is used by summary()", { + gen <- function(simulation, rep){ + pop <- generate.population(simulation) + list(population = pop, truth = c(N = 1000 + 100 * rep, D = (1000 + 100 * rep) / 4e6)) + } + sim <- run.serial(make.test.sim(population.generator = gen)) + truth.N <- 1000 + 100 * (1:5) + expect_equal(unname(sim@results$truth[1, "N", 1:5]), truth.N) + expect_equal(unname(sim@results$truth[1, "N", "mean"]), mean(truth.N)) + summ <- summary(sim, description.summary = FALSE) + est <- sim@results$individuals$N[1, "Estimate", 1:5] + lcl <- sim@results$individuals$N[1, "lcl", 1:5] + ucl <- sim@results$individuals$N[1, "ucl", 1:5] + expect_equal(summ@individuals$N$Truth, mean(truth.N)) + expect_equal(summ@individuals$N$percent.bias, + (mean(est) - mean(truth.N)) / mean(truth.N) * 100) + expect_equal(summ@individuals$N$RMSE, sqrt(mean((est - truth.N)^2))) + expect_equal(summ@individuals$N$CI.coverage.prob, mean(lcl < truth.N & ucl > truth.N)) + expect_equal(summ@individuals$D$Truth, mean(truth.N / 4e6)) + expect_match(summ@truth.source[["N"]], "population.generator") + expect_output(show(summ), "per-repetition truth from population.generator") + # Without truth the population description is used + summ.default <- summary(run.serial(make.test.sim()), description.summary = FALSE) + expect_equal(summ.default@individuals$N$Truth, 300) + expect_equal(summ.default@truth.source[["N"]], "population description") + # Only D supplied: N truth from the population description + gen.D <- function(simulation, rep){ + list(population = generate.population(simulation), truth = list(D = 1e-4)) + } + summ.D <- summary(run.serial(make.test.sim(population.generator = gen.D)), + description.summary = FALSE) + expect_equal(summ.D@individuals$N$Truth, 300) + expect_equal(summ.D@individuals$D$Truth, 1e-4) + expect_equal(summ.D@truth.source[["N"]], "population description") +}) + +test_that("Invalid generator output gives clear errors", { + sim <- make.test.sim(population.generator = function(simulation, rep) generate.population(simulation)) + check <- function(gen, pattern){ + sim@population.generator <- gen + expect_error(dsims:::run.population.generator(sim, 1), pattern) + } + set.seed(1) + good <- generate.population(sim) + check(function(simulation, rep) data.frame(x = 1), "Population object") + check(function(simulation, rep) list(pop = good), "Population object") + check(function(simulation, rep) list(population = good, truth = list(M = 3)), "'N' and/or 'D'") + check(function(simulation, rep) list(population = good, truth = c(N = -1)), "non-negative") + check(function(simulation, rep) stop("boom"), "failed in repetition 1: boom") + bad <- good + bad@population$scale.param <- NULL + check(function(simulation, rep) bad, "missing the column\\(s\\) 'scale.param'") + bad <- good + bad@population$Region.Label <- "elsewhere" + check(function(simulation, rep) bad, "do not match the strata names") + bad <- good + bad@population$x[3] <- 5000 + check(function(simulation, rep) bad, "outside this stratum of the design region") + # Generator errors in a simulation skip the repetition + sim@population.generator <- function(simulation, rep) stop("boom") + set.seed(1) + expect_message(sim.run <- run.simulation(sim, run.parallel = FALSE, counter = FALSE), + "population.generator failed") + expect_true(all(is.na(sim.run@results$individuals$N[1, "Estimate", 1:5]))) + # make.simulation checks the argument + expect_error(make.test.sim(population.generator = "gen"), "NULL or a function") + expect_error(make.test.sim(population.generator = function(x) x), "two arguments") +}) + +test_that("Zero detections and realised N with points and strata", { + # Two strata, point transects, empty population in repetition 2 + shape <- sf::st_sfc(sf::st_polygon(list(rbind(c(0,0),c(1000,0),c(1000,500),c(0,500),c(0,0)))), + sf::st_polygon(list(rbind(c(1000,0),c(2000,0),c(2000,500),c(1000,500),c(1000,0))))) + region <- make.region(region.name = "study", strata.name = c("B", "A"), shape = shape) + dens <- make.density(region = region, x.space = 50, constant = 1) + pd <- make.population.description(region = region, density = dens, N = c(200, 400)) + det <- make.detectability(scale.param = 25, truncation = 50) + des <- make.design(region = region, transect.type = "point", design = "systematic", + samplers = 40, truncation = 50) + ana <- make.ds.analysis(truncation = 50, er.var = "P3", zero.n = "zero") + gen <- function(simulation, rep){ + pop <- generate.population(simulation) + if(rep == 2){ + pop@population <- pop@population[0, ] + pop@N <- 0 + } + pop + } + sim <- make.simulation(reps = 3, design = des, population.description = pd, + detectability = det, ds.analysis = ana, + population.generator = gen) + sim <- run.serial(sim) + res <- sim@results + expect_equal(dimnames(res$individuals$true.N)[[1]], c("A", "B", "Total")) + expect_equal(unname(res$individuals$true.N[, "N", 1]), c(400, 200, 600)) + expect_equal(unname(res$individuals$true.N[, "N", 2]), c(0, 0, 0)) + expect_equal(unname(res$Detection[1, "ZeroDetections", 1:3]), c(0, 1, 0)) + expect_equal(unname(res$individuals$N[, "Estimate", 2]), c(0, 0, 0)) + summ <- res$individuals$summary + # Point transect effort and covered area as calculated by dht + for(i in 1:3){ + expect_equal(unname(summ[, "CoveredArea", i]), unname(pi * 50^2 * summ[, "Effort", i])) + expect_equal(unname(summ["Total", "Effort", i]), sum(summ[c("A", "B"), "Effort", i])) + expect_equal(unname(summ[, "Area", i]), c(5e5, 5e5, 1e6)) + } + expect_equal(unname(summ[, "k", 2]), unname(summ[, "Effort", 2])) +}) diff --git a/tests/testthat/test-check_RasterCovariate.R b/tests/testthat/test-check_RasterCovariate.R new file mode 100644 index 0000000..3559d8a --- /dev/null +++ b/tests/testthat/test-check_RasterCovariate.R @@ -0,0 +1,227 @@ +context("Raster-based spatial covariate detectability (cov.surface)") + +# --------------------------------------------------------------------------- +# Helper: build a minimal single-stratum region covering [0,1] x [0,1] +# --------------------------------------------------------------------------- +make_test_region <- function(){ + pol <- sf::st_polygon(list(matrix(c(0,0, 0,1, 1,1, 1,0, 0,0), ncol = 2, byrow = TRUE))) + sfc <- sf::st_sfc(pol) + sf.pol <- sf::st_sf(strata = "main", geom = sfc) + make.region(region.name = "test", strata.name = "main", shape = sf.pol) +} + +# --------------------------------------------------------------------------- +# 1. Canopy raster reduces scale.param at higher cover values +# --------------------------------------------------------------------------- +test_that("Canopy raster covariate: higher cover yields smaller scale.param", { + skip_if_not_installed("terra") + + region <- make_test_region() + + # Two-zone raster: left half (x < 0.5) canopy = 0.2, right half = 0.8 + r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 1, ymin = 0, ymax = 1) + m <- matrix(c(rep(0.2, 50), rep(0.8, 50)), nrow = 10, ncol = 10, byrow = FALSE) + terra::values(r) <- as.vector(t(m)) + + rast_path <- tempfile(fileext = ".tif") + on.exit(unlink(rast_path), add = TRUE) + terra::writeRaster(r, rast_path, overwrite = TRUE) + + # Slope = -1 on log scale: higher canopy -> smaller sigma -> lower detectability + detect <- make.detectability( + key.function = "hn", + scale.param = 25, + cov.param = list(canopy = -1), + cov.surface = list(canopy = rast_path), + truncation = 50 + ) + + pop.data <- data.frame( + individual = 1:4, + x = c(0.1, 0.3, 0.6, 0.8), + y = c(0.5, 0.5, 0.5, 0.5), + Region.Label = "main" + ) + + result <- dsims:::calculate.scale.param(pop.data, detect, region) + + # Expected: sigma = exp(log(25) + (-1) * canopy_value) + low_scale <- exp(log(25) + (-1) * 0.2) # left-zone animals + high_scale <- exp(log(25) + (-1) * 0.8) # right-zone animals + + # Animals 1 & 2 are in low-canopy zone; 3 & 4 are in high-canopy zone + expect_lt(result$scale.param[3], result$scale.param[1], + label = "high-canopy scale.param < low-canopy scale.param") + expect_equal(result$scale.param[1], low_scale, tolerance = 0.05) + expect_equal(result$scale.param[2], low_scale, tolerance = 0.05) + expect_equal(result$scale.param[3], high_scale, tolerance = 0.05) + expect_equal(result$scale.param[4], high_scale, tolerance = 0.05) +}) + +# --------------------------------------------------------------------------- +# 2. File path and in-memory SpatRaster give identical results +# --------------------------------------------------------------------------- +test_that("File path and in-memory SpatRaster produce the same scale.param", { + skip_if_not_installed("terra") + + region <- make_test_region() + + r <- terra::rast(nrows = 5, ncols = 5, xmin = 0, xmax = 1, ymin = 0, ymax = 1) + terra::values(r) <- seq(0, 1, length.out = 25) + + rast_path <- tempfile(fileext = ".tif") + on.exit(unlink(rast_path), add = TRUE) + terra::writeRaster(r, rast_path, overwrite = TRUE) + + pop.data <- data.frame( + individual = 1:3, + x = c(0.1, 0.5, 0.9), + y = c(0.5, 0.5, 0.5), + Region.Label = "main" + ) + + detect_path <- make.detectability(cov.param = list(canopy = -0.5), + cov.surface = list(canopy = rast_path)) + detect_mem <- make.detectability(cov.param = list(canopy = -0.5), + cov.surface = list(canopy = r)) + + res_path <- dsims:::calculate.scale.param(pop.data, detect_path, region) + res_mem <- dsims:::calculate.scale.param(pop.data, detect_mem, region) + + expect_equal(res_path$scale.param, res_mem$scale.param, tolerance = 1e-6) +}) + +# --------------------------------------------------------------------------- +# 3. Validation: cov.surface name not in cov.param triggers an error +# --------------------------------------------------------------------------- +test_that("make.detectability errors when cov.surface name absent from cov.param", { + skip_if_not_installed("terra") + + rast_path <- tempfile(fileext = ".tif") + r <- terra::rast(nrows = 2, ncols = 2, xmin = 0, xmax = 1, ymin = 0, ymax = 1) + terra::values(r) <- 1:4 + on.exit(unlink(rast_path), add = TRUE) + terra::writeRaster(r, rast_path, overwrite = TRUE) + + expect_error( + make.detectability( + cov.param = list(size = log(1.1)), # 'size', not 'canopy' + cov.surface = list(canopy = rast_path) # 'canopy' has no cov.param slope + ), + regexp = "cov.surface entry 'canopy' has no matching" + ) +}) + +# --------------------------------------------------------------------------- +# 4. Validation: non-character / non-SpatRaster entry triggers an error +# --------------------------------------------------------------------------- +test_that("make.detectability errors when cov.surface element is wrong type", { + expect_error( + make.detectability( + cov.param = list(canopy = -0.5), + cov.surface = list(canopy = 42) # numeric scalar is invalid + ), + regexp = "must be a file path" + ) +}) + +# --------------------------------------------------------------------------- +# 5. Validation: non-existent file path triggers an error +# --------------------------------------------------------------------------- +test_that("make.detectability errors when cov.surface file path does not exist", { + expect_error( + make.detectability( + cov.param = list(canopy = -0.5), + cov.surface = list(canopy = "/does/not/exist/canopy.tif") + ), + regexp = "does not exist" + ) +}) + +# --------------------------------------------------------------------------- +# 6. Existing behaviour unchanged when cov.surface is empty (regression guard) +# --------------------------------------------------------------------------- +test_that("calculate.scale.param unchanged when no cov.surface is supplied", { + region <- make_test_region() + + detect <- make.detectability( + key.function = "hn", + scale.param = 25, + cov.param = list(size = log(1.02)), + truncation = 50 + ) + + pop.data <- data.frame( + individual = 1:3, + x = c(0.2, 0.5, 0.8), + y = c(0.5, 0.5, 0.5), + Region.Label = "main", + size = c(10L, 20L, 30L) + ) + + result <- dsims:::calculate.scale.param(pop.data, detect, region) + + expected <- exp(log(25) + log(1.02) * c(10, 20, 30)) + expect_equal(result$scale.param, expected, tolerance = 1e-8) +}) + +# --------------------------------------------------------------------------- +# 7. Integration: run.simulation uses raster covariate each replicate +# --------------------------------------------------------------------------- +test_that("run.simulation completes with cov.surface raster (2 reps)", { + skip_if_not_installed("terra") + skip_if_not_installed("Distance") + + region <- make_test_region() + + # Flat-gradient raster (constant value = 0.5, so slope effect is fixed) + r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 1, ymin = 0, ymax = 1) + terra::values(r) <- 0.5 + rast_path <- tempfile(fileext = ".tif") + on.exit(unlink(rast_path), add = TRUE) + terra::writeRaster(r, rast_path, overwrite = TRUE) + + density <- make.density(region = region, x.space = 0.1, constant = 200) + + popdesc <- make.population.description( + region = region, + density = density, + fixed.N = TRUE, + N = 200 + ) + + detect <- make.detectability( + key.function = "hn", + scale.param = 0.05, + cov.param = list(canopy = -0.5), + cov.surface = list(canopy = rast_path), + truncation = 0.1 + ) + + design <- make.design( + region = region, + transect.type = "line", + design = "systematic", + samplers = 5, + truncation = 0.1 + ) + + analysis <- make.ds.analysis( + dfmodel = list(~1), + key = "hn", + truncation = 0.1, + criteria = "AIC" + ) + + sim <- make.simulation( + reps = 2, + design = design, + population.description = popdesc, + detectability = detect, + ds.analysis = analysis + ) + + # Should run without error and return a Simulation object with results + result <- run.simulation(sim, run.parallel = FALSE, counter = FALSE) + expect_s4_class(result, "Simulation") +}) diff --git a/tests/testthat/test-check_UniformKey.R b/tests/testthat/test-check_UniformKey.R new file mode 100644 index 0000000..b0b17e8 --- /dev/null +++ b/tests/testthat/test-check_UniformKey.R @@ -0,0 +1,69 @@ +library(dsims) +library(testthat) + +context("Uniform key function analyses") + +test_that("Uniform analyses can be created and covariates are rejected", { + analysis <- make.ds.analysis(dfmodel = ~1, key = "unif", truncation = 50) + expect_s4_class(analysis, "DS.Analysis") + expect_equal(analysis@key, "unif") + + # "uf" is accepted for consistency with make.detectability + analysis <- make.ds.analysis(dfmodel = ~1, key = "uf", truncation = 50) + expect_equal(analysis@key, "unif") + + expect_error(make.ds.analysis(dfmodel = ~size, key = "unif", truncation = 50), + "Covariates cannot be included in the model when the uniform key function is used") + expect_error(make.ds.analysis(dfmodel = list(~1, ~size), key = c("hn", "unif"), truncation = 50), + "Covariates cannot be included") + + analysis <- make.ds.analysis(dfmodel = ~1, key = c("hn", "unif"), truncation = 50, criteria = "AIC") + expect_equal(analysis@key, c("hn", "unif")) + + expect_error(make.ds.analysis(dfmodel = ~1, key = "gamma", truncation = 50), + "All key function values should be 'hn', 'hr' or 'unif'.") +}) + +test_that("Uniform analysis of uniform detections gives the strip estimate", { + detect <- make.detectability(key.function = "uf", scale.param = 1, truncation = 50) + set.seed(42) + sim <- make.simulation(reps = 10, + detectability = detect, + ds.analysis = make.ds.analysis(dfmodel = ~1, key = "unif", truncation = 50)) + sim <- run.simulation(sim, run.parallel = FALSE, counter = FALSE) + reps <- 1:10 + results <- sim@results + ok <- !is.na(results$individuals$D[1, "Estimate", reps]) + expect_true(all(ok)) + # All animals in the strip are detected so the estimated average p is 1 + expect_equal(unname(results$Detection[1, "Pa", reps]), rep(1, 10)) + # Density estimate equals n / covered area + n <- results$individuals$summary[1, "n", reps] + covered.area <- results$individuals$summary[1, "CoveredArea", reps] + expect_equal(unname(results$individuals$D[1, "Estimate", reps]), unname(n / covered.area)) + # Unbiased within Monte Carlo error + sim.sum <- summary(sim, description.summary = FALSE) + expect_lt(abs(sim.sum@individuals$N$percent.bias), 5) + + # Model selection between half-normal and uniform runs + sim <- make.simulation(reps = 3, + detectability = detect, + ds.analysis = make.ds.analysis(dfmodel = ~1, key = c("hn", "unif"), + truncation = 50, criteria = "AIC")) + sim <- run.simulation(sim, run.parallel = FALSE, counter = FALSE) + expect_true(all(sim@results$Detection[1, "SuccessfulModels", 1:3] >= 1)) + expect_true(all(sim@results$Detection[1, "SelectedModel", 1:3] %in% c(1, 2))) +}) + +test_that("Uniform analysis underestimates when detection in the strip is below 1", { + # g(0) < 1 cannot be estimated from the distances, so the uniform analysis + # underestimates abundance by about (1 - scale.param) + detect <- make.detectability(key.function = "uf", scale.param = 0.9, truncation = 50) + set.seed(42) + sim <- make.simulation(reps = 10, + detectability = detect, + ds.analysis = make.ds.analysis(dfmodel = ~1, key = "unif", truncation = 50)) + sim <- run.simulation(sim, run.parallel = FALSE, counter = FALSE) + sim.sum <- summary(sim, description.summary = FALSE) + expect_equal(sim.sum@individuals$N$percent.bias, -10, tolerance = 5, scale = 1) +}) diff --git a/tests/testthat/test-check_UniformNoDetections.R b/tests/testthat/test-check_UniformNoDetections.R new file mode 100644 index 0000000..60e2e55 --- /dev/null +++ b/tests/testthat/test-check_UniformNoDetections.R @@ -0,0 +1,33 @@ +library(dsims) +library(testthat) + +context("Uniform detection function with no individuals near the transects") + +test_that("simulate.detections handles empty possible distances for all keys", { + empty <- data.frame() + for(key in c("uf", "hn")){ + detect <- make.detectability(key.function = key, scale.param = ifelse(key == "uf", 1, 10), truncation = 10) + out <- dsims:::simulate.detections(empty, detect) + expect_equal(nrow(out), 0) + } +}) + +test_that("A uniform-key repetition with no individuals near the transects is a zero estimate, not an error", { + region <- make.region(region.name = "study area", + shape = sf::st_polygon(list(matrix(c(0,0,1000,0,1000,1000,0,1000,0,0), ncol = 2, byrow = TRUE)))) + design <- make.design(region = region, transect.type = "line", design = "systematic", + spacing = 500, truncation = 5, edge.protocol = "minus") + density <- make.density(region = region, x.space = 100, constant = 1) + popdesc <- make.population.description(region = region, density = density, N = 1, fixed.N = TRUE) + detect <- make.detectability(key.function = "uf", scale.param = 1, truncation = 5) + analysis <- make.ds.analysis(dfmodel = ~1, key = "unif", truncation = 5, zero.n = "zero") + sim <- make.simulation(reps = 20, design = design, population.description = popdesc, + detectability = detect, ds.analysis = analysis) + set.seed(42) + sim <- run.simulation(sim, run.parallel = FALSE, counter = FALSE) + errors <- grepl("Error in repetition", unlist(sim@warnings$message)) + expect_false(any(errors)) + zero <- sim@results$Detection[1, "ZeroDetections", 1:20] + expect_true(sum(zero == 1, na.rm = TRUE) > 0) + expect_true(all(sim@results$individuals$N[1, "Estimate", which(zero == 1)] == 0)) +}) diff --git a/vignettes/dsims-examples.Rmd b/vignettes/dsims-examples.Rmd index 6abf357..b6dc320 100644 --- a/vignettes/dsims-examples.Rmd +++ b/vignettes/dsims-examples.Rmd @@ -490,7 +490,7 @@ head(survey.cov@dist.data) ## Running Simulations -To run simulations the syntax has changed slightly from *run* in DSsim to *run.simulations* in dsims and the *object* argument is now *simulation*. The simulations can still be run in parallel using *run.parallel* with the maximum cores set using *max.cores* and the *counter* argument is retained. The *transect.path* argument of the *run.simulation* function in dsims is where you can optionally supply a folder or filename if you wish to load pre-generated shapefiles (in DSsim this was specified in the design). This option is not expected to be widely used and was incorporated to allow simulations in Distance for Windows to be run using dsims. +To run simulations the syntax has changed slightly from *run* in DSsim to *run.simulations* in dsims and the *object* argument is now *simulation*. Simulations are run in parallel by default (*run.parallel = TRUE*) with the maximum number of cores set using *max.cores*, and the *counter* argument is retained. The counter shows the number of repetitions completed with the elapsed and estimated remaining time. Each repetition uses its own random number stream, so after `set.seed()` the results are the same whether run in serial or in parallel. If a repetition fails with an error it is skipped and reported in the summary of warnings and errors, rather than stopping the simulation. The *transect.path* argument of the *run.simulation* function in dsims is where you can optionally supply a folder or filename if you wish to load pre-generated shapefiles (in DSsim this was specified in the design). This option is not expected to be widely used and was incorporated to allow simulations in Distance for Windows to be run using dsims. Here we demonstrate how to run the basic simulation as an example. You will see the code to do this incorporated into the multiple simulations run within for loops in the following sections. Note that it is advisable to first run your simulation with a few iterations (<10) to give an indication that it should run without issues before setting it off on hundreds / thousands repetitions. Once you have run a simulation you can view the results using the summary function which provides a glossary to explain the output. A histogram of the estimates of abundance can also be viewed, Figure \@ref(fig:simhist). @@ -719,7 +719,7 @@ for(tdist in 2:5){#seq(along = truncation)){ ## Results -As these simulations take a substantial amount of time to run we have saved the results and summaries; these can be downloaded as [dsims_truncation_results.zip](dsims_truncation_results.zip). Running one of these simulations with 999 repetitions for one truncation distance takes about 11 minutes on an i7-2600K 3.40GHz processor when running in parallel across 7 threads. When running in parallel the maximum number of cores (or threads) permitted is one less than the number on the machine, this is the default number used unless max.cores specifies a lower number. +As these simulations take a substantial amount of time to run we have saved the results and summaries; these can be downloaded as [dsims_truncation_results.zip](dsims_truncation_results.zip). Running one of these simulations with 999 repetitions for one truncation distance takes about 11 minutes on an i7-2600K 3.40GHz processor when running in parallel across 7 threads. When running in parallel the maximum number of cores (or threads) permitted is one less than the number available on the machine (as reported by `parallelly::availableCores()`, which respects limits set by HPC schedulers), this is the default number used unless max.cores specifies a lower number. Alternatively, if you have started your own [mirai](https://mirai.r-lib.org/) daemons, e.g. `mirai::daemons(8)` or daemons on remote machines or an HPC cluster, dsims will use those. ```{r runparallel, eval = FALSE, echo = TRUE} # Running simulations in parallel