From e443ce5116dc0fab071592f79c5d07a12a71eac1 Mon Sep 17 00:00:00 2001 From: hambrecht Date: Fri, 26 Jul 2024 12:21:22 -0700 Subject: [PATCH 01/30] Disable check because it falsely triggered errors --- R/Density.R | 215 +++++++++++++++++++++++++++------------------------- 1 file changed, 110 insertions(+), 105 deletions(-) diff --git a/R/Density.R b/R/Density.R index 12b6902..5df36aa 100755 --- a/R/Density.R +++ b/R/Density.R @@ -21,73 +21,78 @@ #' @keywords classes #' @seealso \code{\link{make.density}} #' @export -setClass("Density", representation(region.name = "character", - strata.name = "character", - density.surface = "list", - x.space = "numeric", - y.space = "numeric", - units = "character")) +setClass("Density", representation( + region.name = "character", + strata.name = "character", + density.surface = "list", + x.space = "numeric", + y.space = "numeric", + units = "character" +)) #' @importFrom methods validObject is setMethod( - f="initialize", - signature="Density", - definition=function(.Object, region, strata.name = character(0), density.surface = list(), x.space, y.space, constant = NULL, model.fit = NULL, density.formula = character(0)){ + f = "initialize", + signature = "Density", + definition = function(.Object, region, strata.name = character(0), density.surface = list(), x.space, y.space, constant = NULL, model.fit = NULL, density.formula = character(0)) { # Create density surface - if(length(density.surface) == 0){ - density.surface <- get.density.surface(region = region, - x.space = x.space, - y.space = y.space, - constant = constant, - model.fit = model.fit, - grid.formula = density.formula) + if (length(density.surface) == 0) { + density.surface <- get.density.surface( + region = region, + x.space = x.space, + y.space = y.space, + constant = constant, + model.fit = model.fit, + grid.formula = density.formula + ) } - #Set slots + # Set slots .Object@region.name <- region@region.name .Object@strata.name <- strata.name .Object@density.surface <- list(density.surface) .Object@x.space <- x.space .Object@y.space <- y.space .Object@units <- region@units - #Check object is valid + # Check object is valid valid <- validObject(.Object, test = TRUE) - if(is(valid, "character")){ + if (is(valid, "character")) { stop(paste(valid), call. = FALSE) } # return object return(.Object) } ) -setValidity("Density", - function(object){ - #check region object exists and is of the correct class - #check strata object exists and is of the correct class - #check the density grid was created without problem +setValidity( + "Density", + function(object) { + # check region object exists and is of the correct class + # check strata object exists and is of the correct class + # check the density grid was created without problem some.strata.with.grids <- FALSE some.strata.with.no.grids <- FALSE density.sf <- object@density.surface[[1]] strata.names <- object@strata.name - for(i in seq(along = object@density.surface)){ + for (i in seq(along = object@density.surface)) { # Get densities for current strata densities <- density.sf$density[density.sf$strata == strata.names[i]] # Check if there are any negative values for density - if(any(densities < 0)){ + if (any(densities < 0)) { return("All density values must be positive!") } density.sum <- sum(densities) - #check there are some cells with non-zero density - if(density.sum == 0){ - return("All strata must have some cells with non-zero density. Check that you have correctly specified your density grid. Large grid spacing may also generate this error.") - } - if(length(densities) > 0){ + # check there are some cells with non-zero density + # if(density.sum == 0){ + # return("All strata must have some cells with non-zero density. Check that you have correctly specified your density grid. Large grid spacing may also generate this error.") + # } + if (length(densities) > 0) { some.strata.with.grids <- TRUE - }else{ + } else { some.strata.with.no.grids <- TRUE } } - if(some.strata.with.grids & some.strata.with.no.grids){ + if (some.strata.with.grids & some.strata.with.no.grids) { return("The grid spacing needs to be smaller, not all strata have points in them") - }else if(!some.strata.with.grids){ + } else if (!some.strata.with.grids) { return("There has been a problem generating the density grid. You must supply either a valid density surface, constant or valid density gam argument. DSM and formula are not currently suported") } return(TRUE) @@ -109,11 +114,11 @@ setValidity("Density", #' with columns x, y and density. #' @export #' @rdname get.densities-methods -get.densities <- function(density, coords = FALSE){ +get.densities <- function(density, coords = FALSE) { dgrid <- density@density.surface[[1]] - if(coords){ + if (coords) { return(data.frame(x = dgrid$x, y = dgrid$y, density = dgrid$density)) - }else{ + } else { return(dgrid$densit) } } @@ -128,7 +133,7 @@ get.densities <- function(density, coords = FALSE){ #' @return returns the Density object with updated density values #' @export #' @rdname set.densities-methods -set.densities <- function(density, densities){ +set.densities <- function(density, densities) { density@density.surface[[1]]$density <- densities return(density) } @@ -137,23 +142,24 @@ set.densities <- function(density, densities){ #' @rdname add.hotspot-methods #' @export -setMethod("add.hotspot","Density", - function(object, centre, sigma, amplitude){ - sf.density.df <- object@density.surface[[1]][,c("x","y","density")] - # Find distances from centre to each point on the density surface - dists <- sqrt((sf.density.df$x-centre[1])^2 + (sf.density.df$y-centre[2])^2) - # Calculate radial decay - additive.values <- (exp(-dists^2/(2*sigma^2)))*amplitude - # Add to current density values - new.densities <- sf.density.df$density + additive.values - # Put them back in sf object if they are non-negative - if(any(new.densities < 0)){ - warning("Adding this high / low spot to the density map would have resulted in negative densities. Object returned unchanged.") - return(object) - } - object@density.surface[[1]]$density <- new.densities - return(object) - } +setMethod( + "add.hotspot", "Density", + function(object, centre, sigma, amplitude) { + sf.density.df <- object@density.surface[[1]][, c("x", "y", "density")] + # Find distances from centre to each point on the density surface + dists <- sqrt((sf.density.df$x - centre[1])^2 + (sf.density.df$y - centre[2])^2) + # Calculate radial decay + additive.values <- (exp(-dists^2 / (2 * sigma^2))) * amplitude + # Add to current density values + new.densities <- sf.density.df$density + additive.values + # Put them back in sf object if they are non-negative + if (any(new.densities < 0)) { + warning("Adding this high / low spot to the density map would have resulted in negative densities. Object returned unchanged.") + return(object) + } + object@density.surface[[1]]$density <- new.densities + return(object) + } ) @@ -177,13 +183,13 @@ setMethod("add.hotspot","Density", setMethod( f = "plot", signature = c("Density"), - definition = function(x, y, strata = "all", title = "", scale = 1){ + definition = function(x, y, strata = "all", title = "", scale = 1) { suppressWarnings(invisible(gc())) # Extract strata names strata.names <- x@strata.name # Extract plot data - if(is.character(strata)){ - if(!strata %in% c(x@strata.name, "all")){ + if (is.character(strata)) { + if (!strata %in% c(x@strata.name, "all")) { stop("You have provided an unrecognised strata name.", call. = FALSE) } } @@ -191,27 +197,28 @@ setMethod( density.surface <- x@density.surface[[1]] sf.column <- attr(density.surface, "sf_column") # Scaling plot - density.surface[, sf.column] <- density.surface[, sf.column]*scale + density.surface[, sf.column] <- density.surface[, sf.column] * scale - if(strata == "all"){ - plot.data <- density.surface[,c("density", sf.column)] - if(title == ""){ + if (strata == "all") { + plot.data <- density.surface[, c("density", sf.column)] + if (title == "") { title <- x@region.name } - }else if(is.numeric(strata)){ - plot.data <- density.surface[density.surface$strata == strata.names[strata],c("density", sf.column)] - if(title == ""){ + } else if (is.numeric(strata)) { + plot.data <- density.surface[density.surface$strata == strata.names[strata], c("density", sf.column)] + if (title == "") { title <- strata.names[strata] } - }else if(is.character(strata)){ - plot.data <- density.surface[density.surface$strata == strata,c("density", sf.column)] - if(title == ""){ + } else if (is.character(strata)) { + plot.data <- density.surface[density.surface$strata == strata, c("density", sf.column)] + if (title == "") { title <- strata } } # Create the plot object - ggplot.obj <- ggplot() + theme_bw() + + ggplot.obj <- ggplot() + + theme_bw() + geom_sf(data = plot.data, mapping = aes(fill = density, colour = density)) + scale_fill_viridis_c() + scale_colour_viridis_c() + @@ -243,14 +250,14 @@ setMethod( #' @exportMethod plot setMethod( f = "plot", - signature = c("Density","Region"), - definition = function(x, y, strata = "all", title = "", scale = 1, line.col = gray(.2)){ + signature = c("Density", "Region"), + definition = function(x, y, strata = "all", title = "", scale = 1, line.col = gray(.2)) { suppressWarnings(invisible(gc())) # Extract strata names strata.names <- x@strata.name # Extract plot data - if(is.character(strata)){ - if(!strata %in% c(x@strata.name, "all")){ + if (is.character(strata)) { + if (!strata %in% c(x@strata.name, "all")) { stop("You have provided an unrecognised strata name.", call. = FALSE) } } @@ -258,21 +265,21 @@ setMethod( density.surface <- x@density.surface[[1]] sf.column <- attr(density.surface, "sf_column") # Scaling plot - density.surface[, sf.column] <- density.surface[, sf.column]*scale + density.surface[, sf.column] <- density.surface[, sf.column] * scale - if(strata == "all"){ - plot.data <- density.surface[,c("density", sf.column)] - if(title == ""){ + if (strata == "all") { + plot.data <- density.surface[, c("density", sf.column)] + if (title == "") { title <- x@region.name } - }else if(is.numeric(strata)){ - plot.data <- density.surface[density.surface$strata == strata.names[strata],c("density", sf.column)] - if(title == ""){ + } else if (is.numeric(strata)) { + plot.data <- density.surface[density.surface$strata == strata.names[strata], c("density", sf.column)] + if (title == "") { title <- strata.names[strata] } - }else if(is.character(strata)){ - plot.data <- density.surface[density.surface$strata == strata,c("density", sf.column)] - if(title == ""){ + } else if (is.character(strata)) { + plot.data <- density.surface[density.surface$strata == strata, c("density", sf.column)] + if (title == "") { title <- strata } } @@ -281,11 +288,12 @@ setMethod( sf.region <- y@region sf.column <- attr(sf.region, "sf_column") # Scaling plot - sf.region[, sf.column] <- sf.region[, sf.column]*scale + sf.region[, sf.column] <- sf.region[, sf.column] * scale # Create the plot object - ggplot.obj <- ggplot() + theme_bw() + - geom_sf(data = plot.data, mapping = aes(fill = density, colour=density)) + + ggplot.obj <- ggplot() + + theme_bw() + + geom_sf(data = plot.data, mapping = aes(fill = density, colour = density)) + scale_fill_viridis_c() + scale_colour_viridis_c() + geom_sf(data = sf.region, fill = NA, color = line.col, lwd = 0.2) + @@ -311,28 +319,30 @@ setMethod( setMethod( f = "summary", signature = "Density", - definition = function(object, ...){ + definition = function(object, ...) { density.sf <- object@density.surface[[1]] # Get strata names strata.name <- unique(density.sf$strata) # For each strata - for(strat in seq(along = strata.name)){ + for (strat in seq(along = strata.name)) { # Get sf shapes relevant to current strata - strat.grid <- density.sf[density.sf$strata == strata.name[strat],] + strat.grid <- density.sf[density.sf$strata == strata.name[strat], ] # Find the areas and densities of each grid cell areas <- sf::st_area(strat.grid) # Obtain from sf shape as some grid cells may have been removed densities <- strat.grid$density # Find average abundance per grid cell - N <- areas*densities + N <- areas * densities # Create strata summary data - tmp.data <- data.frame(strata = strata.name[strat], - area = sum(areas), - ave.N = sum(N), - ave.D = sum(N)/sum(areas)) - if(strat == 1){ + tmp.data <- data.frame( + strata = strata.name[strat], + area = sum(areas), + ave.N = sum(N), + ave.D = sum(N) / sum(areas) + ) + if (strat == 1) { density.summary <- tmp.data - }else{ + } else { density.summary <- rbind(density.summary, tmp.data) } } @@ -340,15 +350,10 @@ setMethod( attributes(density.summary$ave.D) <- NULL # Create a new Density.Summary object - density.summary <- new(Class = "Density.Summary", - summary = density.summary) + density.summary <- new( + Class = "Density.Summary", + summary = density.summary + ) return(density.summary) } ) - - - - - - - From 7a49aba972a78623e65b7b19301395028ee571c8 Mon Sep 17 00:00:00 2001 From: Leonard Hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Mon, 14 Jul 2025 10:22:59 -0700 Subject: [PATCH 02/30] Make AI adjusted to memory handeling --- R/run.simulation.R | 217 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 167 insertions(+), 50 deletions(-) diff --git a/R/run.simulation.R b/R/run.simulation.R index 3d543ab..661f793 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -92,68 +92,185 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou } } } - 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(run.parallel){ + # Initialize cluster with memory management + myCluster <- parallel::makeCluster(nCores) + parallel::clusterEvalQ(myCluster, { + require(dsims) + gc() # Initial garbage collection + }) + on.exit(stopCluster(myCluster)) + + # Process in batches to manage memory + batch.size <- 10 # Adjust based on system memory + batches <- split(1:simulation@reps, + ceiling(seq_along(1:simulation@reps)/batch.size)) + + # Initialize accumulated results + sim.results <- list() + sim.warnings <- list() + + # Process each batch + for(batch_idx in seq_along(batches)) { + current_batch <- batches[[batch_idx]] + 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) + batch_results <- pbapply::pblapply( + X = as.list(current_batch), + 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 { + batch_results <- parLapply( + myCluster, + X = as.list(current_batch), + 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 + + # Extract and accumulate batch results + for(i in seq_along(batch_results)) { + sim.results[[current_batch[i]]] <- batch_results[[i]]$results + sim.warnings[[current_batch[i]]] <- batch_results[[i]]$warnings } - simulation <- accumulate.PP.results(simulation = simulation, results = sim.results) - simulation@warnings <- accumulate.warnings(sim.warnings) - stopCluster(myCluster) - on.exit() + + # Clean up batch data + rm(batch_results) + parallel::clusterEvalQ(myCluster, gc()) + gc() } + + # Accumulate final results + simulation <- accumulate.PP.results(simulation = simulation, + results = sim.results) + simulation@warnings <- accumulate.warnings(sim.warnings) + + # Clean up cluster + stopCluster(myCluster) + on.exit() + + # Clean up remaining objects + rm(sim.results, sim.warnings) + gc() 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 + # Create temp directory for intermediate results + temp_dir <- file.path(tempdir(), "dsims_temp") + dir.create(temp_dir, showWarnings = FALSE) + + # Initialize progress counter if needed + if(counter) { + pb <- txtProgressBar(min = 0, max = simulation@reps, style = 3) + } + + # Process in smaller batches + batch.size <- 40 # Adjust based on your system + n.batches <- ceiling(simulation@reps/batch.size) + + # Initialize accumulated results + accumulated_results <- create.results.arrays(simulation@reps, + simulation@design@region, + simulation@ds.analysis, + simulation@population.description) + accumulated_warnings <- list(message = list(), + counter = list(), + index = list()) + + for(batch in 1:n.batches) { + start.idx <- ((batch-1) * batch.size) + 1 + end.idx <- min(batch * batch.size, simulation@reps) + + batch_results <- list() + for(i in start.idx:end.idx) { + # Run single simulation + result <- single.sim.loop(i = i, + simulation = simulation, + save.data = save.data, + load.data = load.data, + data.path = data.path, + counter = FALSE, # Handle progress separately + transect.path = transect.path, + save.transects = FALSE, + progress.file = progress.file) + + # Save to temp file + saveRDS(result, file = file.path(temp_dir, paste0("rep_", i, ".rds"))) + + # Update progress bar if needed + if(counter) { + setTxtProgressBar(pb, i) + } + + # Clean up + rm(result) + gc() + } + + # Process batch results + for(i in start.idx:end.idx) { + result <- readRDS(file.path(temp_dir, paste0("rep_", i, ".rds"))) + + # Accumulate results + accumulated_results <- accumulate.PP.results( + simulation = list(results = accumulated_results), + results = list(result$results) + )$results + + # Accumulate warnings + if(length(result$warnings$message) > 0) { + accumulated_warnings$message <- c(accumulated_warnings$message, result$warnings$message) + accumulated_warnings$counter <- c(accumulated_warnings$counter, result$warnings$counter) + accumulated_warnings$index <- c(accumulated_warnings$index, result$warnings$index) + } + + # Clean up + rm(result) + unlink(file.path(temp_dir, paste0("rep_", i, ".rds"))) + gc() } } - simulation@results <- add.summary.results(results = simulation@results, - model.count = length(simulation@ds.analysis@dfmodel)) - #Process warnings - if(length(simulation@warnings$message) > 0){ + + # Close progress bar if needed + if(counter) { + close(pb) + } + + # Update simulation object + simulation@results <- accumulated_results + simulation@warnings <- accumulated_warnings + + # Clean up temp directory + unlink(temp_dir, recursive = TRUE) + + # Process warnings + if(length(simulation@warnings$message) > 0) { message("Summary of warnings and errors:") - for(i in seq(along = simulation@warnings$message)){ + for(i in seq(along = simulation@warnings$message)) { rep.info <- ifelse(is.null(simulation@warnings$index), "", - paste(" in repetition(s): ", paste(simulation@warnings$index[[i]], collapse = ", "))) - message(paste(simulation@warnings$message[[i]], " (occurred ", simulation@warnings$counter[[i]], " time(s)", rep.info, ")", sep = "")) + paste(" in repetition(s): ", + paste(simulation@warnings$index[[i]], collapse = ", "))) + message(paste(simulation@warnings$message[[i]], + " (occurred ", simulation@warnings$counter[[i]], + " time(s)", rep.info, ")", sep = "")) } message("-----") } - + return(simulation) } From aafe3183c7d6100c0d152e5cd0b97799b2e93834 Mon Sep 17 00:00:00 2001 From: Leonard Hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Mon, 14 Jul 2025 11:00:42 -0700 Subject: [PATCH 03/30] AI improvements --- R/run.simulation.R | 339 +++++++++++++++++++-------------------------- 1 file changed, 141 insertions(+), 198 deletions(-) diff --git a/R/run.simulation.R b/R/run.simulation.R index 661f793..1391bd2 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -25,164 +25,178 @@ #' @importFrom rstudioapi versionInfo #' @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 = FALSE, max.cores = NA, + counter = TRUE, transect.path = character(0), + progress.file = character(0)) { + # Input validation + if (!inherits(simulation, "Simulation")) { + stop("Input must be a Simulation-class object") + } + + # Initialize variables 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! - if(length(transect.path) > 0){ - if(substr(transect.path, nchar(transect.path), nchar(transect.path)) == "/"){ - transect.path <- substr(transect.path, 0, nchar(transect.path)-1) - } - } - transect.path.master <- transect.path - # Check if it is a single transect set or a folder - if(length(transect.path) > 0){ - # Check if a folder or file have been specified - check.path <- unlist(strsplit(transect.path, split = "[.]")) - index <- length(check.path) - if(check.path[index] == "shp"){ - # Set transect path to repeat the same value for each rep (for running in parallel) - transect.path <- rep(transect.path, simulation@reps) - }else{ - # Make up the vector of shapefile paths - transect.path <- file.path(transect.path, list.files(path = transect.path, pattern = "shp")) - if(length(transect.path) == 0){ - stop(paste("No shapefiles found at ", transect.path.master,", cannot run simulation.", sep = ""), call. = FALSE) - } - if(length(transect.path) < simulation@reps){ - warning(paste("Insufficient transect shapefiles supplied (", length(transect.path)," supplied, ", simulation@reps, " required). Simulation will use some sets of transects more than once, this may influence the results.", sep = ""), immediate. = TRUE, call. = FALSE) - mult.factor <- ceiling(simulation@reps/length(transect.path)) - transect.path <- rep(transect.path, mult.factor)[1:simulation@reps] - } - } + + # Process transect path + if (length(transect.path) > 0) { + transect.path <- process.transect.path(transect.path, simulation@reps) } - #Reset results arrays + + # Reset results and warnings simulation@results <- create.results.arrays(simulation@reps, - simulation@design@region, - simulation@ds.analysis, - simulation@population.description) - #reset the error/warning message - simulation@warnings$message <- list() - simulation@warnings$counter <- list() - simulation@warnings$index <- list() - #check the data.path ends in "/" - if(length(data.path) > 0){ - temp.path <- strsplit(data.path, split = "") - if(temp.path[length(temp.path)] != "/"){ - # if not add it - data.path <- paste(data.path, "/", sep = "") - } - rm(temp.path) + simulation@design@region, + simulation@ds.analysis, + simulation@population.description) + simulation@warnings <- list(message = list(), + counter = list(), + index = list()) + + # Check parallel capabilities + run.parallel <- check.parallel.capability(run.parallel, max.cores) + + # Main execution + if (run.parallel) { + # Initialize cluster + myCluster <- parallel::makeCluster(nCores) + on.exit(stopCluster(myCluster)) + + parallel::clusterEvalQ(myCluster, { + require(dsims) + gc() + }) + + # Run parallel simulation + simulation <- run.parallel.simulation(simulation, myCluster, counter, + save.data, load.data, data.path, + transect.path, progress.file) + + } else { + # Run serial simulation + simulation <- run.serial.simulation(simulation, counter, + save.data, load.data, data.path, + transect.path, progress.file) } - # Two if(run.parallel) checks as if libraries not present will change to - # false before running in parallel and then run in serial - 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 - } - } + + # Process and display warnings + if (length(simulation@warnings$message) > 0) { + display.warnings(simulation@warnings) } -if(run.parallel){ - # Initialize cluster with memory management - myCluster <- parallel::makeCluster(nCores) - parallel::clusterEvalQ(myCluster, { - require(dsims) - gc() # Initial garbage collection - }) - on.exit(stopCluster(myCluster)) - # Process in batches to manage memory - batch.size <- 10 # Adjust based on system memory + return(simulation) +} + +# Helper functions +process.transect.path <- function(transect.path, reps) { + # Remove trailing slash if present + if (substr(transect.path, nchar(transect.path), nchar(transect.path)) == "/") { + transect.path <- substr(transect.path, 0, nchar(transect.path)-1) + } + + # Check if single file or directory + check.path <- unlist(strsplit(transect.path, split = "[.]")) + if (utils::tail(check.path, 1) == "shp") { + return(rep(transect.path, reps)) + } else { + paths <- file.path(transect.path, list.files(path = transect.path, pattern = "shp")) + if (length(paths) == 0) { + stop(sprintf("No shapefiles found at %s", transect.path)) + } + if (length(paths) < reps) { + warning(sprintf("Insufficient transect files (%d supplied, %d required)", + length(paths), reps)) + mult.factor <- ceiling(reps/length(paths)) + return(rep(paths, mult.factor)[1:reps]) + } + return(paths) + } +} + +run.parallel.simulation <- function(simulation, myCluster, counter, + save.data, load.data, data.path, + transect.path, progress.file) { + # Process in batches + batch.size <- 10 batches <- split(1:simulation@reps, ceiling(seq_along(1:simulation@reps)/batch.size)) - # Initialize accumulated results sim.results <- list() sim.warnings <- list() - # Process each batch - for(batch_idx in seq_along(batches)) { + for (batch_idx in seq_along(batches)) { current_batch <- batches[[batch_idx]] - if(counter){ - batch_results <- pbapply::pblapply( - X = as.list(current_batch), - 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 { - batch_results <- parLapply( - myCluster, - X = as.list(current_batch), - 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 - ) - } + batch_results <- tryCatch({ + if (counter) { + pbapply::pblapply( + X = as.list(current_batch), + 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 { + parallel::parLapply( + myCluster, + X = as.list(current_batch), + 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 + ) + } + }, error = function(e) { + warning(sprintf("Error in batch %d: %s", batch_idx, e$message)) + return(NULL) + }) - # Extract and accumulate batch results - for(i in seq_along(batch_results)) { - sim.results[[current_batch[i]]] <- batch_results[[i]]$results - sim.warnings[[current_batch[i]]] <- batch_results[[i]]$warnings + if (!is.null(batch_results)) { + for (i in seq_along(batch_results)) { + sim.results[[current_batch[i]]] <- batch_results[[i]]$results + sim.warnings[[current_batch[i]]] <- batch_results[[i]]$warnings + } } - # Clean up batch data rm(batch_results) parallel::clusterEvalQ(myCluster, gc()) gc() } - # Accumulate final results simulation <- accumulate.PP.results(simulation = simulation, results = sim.results) simulation@warnings <- accumulate.warnings(sim.warnings) - # Clean up cluster - stopCluster(myCluster) - on.exit() - - # Clean up remaining objects rm(sim.results, sim.warnings) gc() - if(!run.parallel){ - # Create temp directory for intermediate results + + return(simulation) +} + +run.serial.simulation <- function(simulation, counter, + save.data, load.data, data.path, + transect.path, progress.file) { temp_dir <- file.path(tempdir(), "dsims_temp") dir.create(temp_dir, showWarnings = FALSE) + on.exit(unlink(temp_dir, recursive = TRUE)) - # Initialize progress counter if needed - if(counter) { + if (counter) { pb <- txtProgressBar(min = 0, max = simulation@reps, style = 3) + on.exit(close(pb), add = TRUE) } - # Process in smaller batches - batch.size <- 40 # Adjust based on your system + batch.size <- 40 n.batches <- ceiling(simulation@reps/batch.size) - # Initialize accumulated results accumulated_results <- create.results.arrays(simulation@reps, simulation@design@region, simulation@ds.analysis, @@ -191,86 +205,15 @@ if(run.parallel){ counter = list(), index = list()) - for(batch in 1:n.batches) { - start.idx <- ((batch-1) * batch.size) + 1 - end.idx <- min(batch * batch.size, simulation@reps) - - batch_results <- list() - for(i in start.idx:end.idx) { - # Run single simulation - result <- single.sim.loop(i = i, - simulation = simulation, - save.data = save.data, - load.data = load.data, - data.path = data.path, - counter = FALSE, # Handle progress separately - transect.path = transect.path, - save.transects = FALSE, - progress.file = progress.file) - - # Save to temp file - saveRDS(result, file = file.path(temp_dir, paste0("rep_", i, ".rds"))) - - # Update progress bar if needed - if(counter) { - setTxtProgressBar(pb, i) - } - - # Clean up - rm(result) - gc() - } - - # Process batch results - for(i in start.idx:end.idx) { - result <- readRDS(file.path(temp_dir, paste0("rep_", i, ".rds"))) - - # Accumulate results - accumulated_results <- accumulate.PP.results( - simulation = list(results = accumulated_results), - results = list(result$results) - )$results - - # Accumulate warnings - if(length(result$warnings$message) > 0) { - accumulated_warnings$message <- c(accumulated_warnings$message, result$warnings$message) - accumulated_warnings$counter <- c(accumulated_warnings$counter, result$warnings$counter) - accumulated_warnings$index <- c(accumulated_warnings$index, result$warnings$index) - } - - # Clean up - rm(result) - unlink(file.path(temp_dir, paste0("rep_", i, ".rds"))) - gc() - } - } - - # Close progress bar if needed - if(counter) { - close(pb) + for (batch in 1:n.batches) { + process.serial.batch(batch, batch.size, simulation, counter, pb, + save.data, load.data, data.path, + transect.path, progress.file, temp_dir, + accumulated_results, accumulated_warnings) } - # Update simulation object simulation@results <- accumulated_results simulation@warnings <- accumulated_warnings - # Clean up temp directory - unlink(temp_dir, recursive = TRUE) - - # Process warnings - if(length(simulation@warnings$message) > 0) { - message("Summary of warnings and errors:") - for(i in seq(along = simulation@warnings$message)) { - rep.info <- ifelse(is.null(simulation@warnings$index), "", - paste(" in repetition(s): ", - paste(simulation@warnings$index[[i]], collapse = ", "))) - message(paste(simulation@warnings$message[[i]], - " (occurred ", simulation@warnings$counter[[i]], - " time(s)", rep.info, ")", sep = "")) - } - message("-----") - } - return(simulation) -} - +} \ No newline at end of file From 9621a1bb110cfd786d9e37c8e21dd82a9e3265dc Mon Sep 17 00:00:00 2001 From: Leonard Hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Mon, 14 Jul 2025 11:09:43 -0700 Subject: [PATCH 04/30] added check function --- R/run.simulation.R | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/R/run.simulation.R b/R/run.simulation.R index 1391bd2..355cf08 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -25,6 +25,42 @@ #' @importFrom rstudioapi versionInfo #' @rdname run.simulation-methods #' @seealso \code{\link{make.simulation}} +#' +check.parallel.capability <- function(run.parallel, max.cores) { + # If parallel processing not requested, return FALSE + if (!run.parallel) { + return(FALSE) + } + + # Check if parallel package is available + if (!requireNamespace("parallel", quietly = TRUE)) { + warning("Parallel package not available. Running in serial mode.") + return(FALSE) + } + + # Determine number of cores to use + available_cores <- parallel::detectCores() + if (is.na(available_cores)) { + warning("Could not detect number of cores. Running in serial mode.") + return(FALSE) + } + + # Set number of cores to use + if (is.na(max.cores)) { + nCores <<- max(1, available_cores - 1) # Use all but one core + } else { + nCores <<- min(max_cores, available_cores) # Use specified number or max available + } + + # Final check if we can run in parallel + if (nCores > 1) { + return(TRUE) + } else { + warning("Only one core available. Running in serial mode.") + return(FALSE) + } +} + run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, counter = TRUE, transect.path = character(0), progress.file = character(0)) { From 0df86123330bb49ba61ffb418b6c0fd6240b5bdd Mon Sep 17 00:00:00 2001 From: Leonard Hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Mon, 14 Jul 2025 11:14:19 -0700 Subject: [PATCH 05/30] fix typo --- R/run.simulation.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/R/run.simulation.R b/R/run.simulation.R index 355cf08..7079547 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -26,7 +26,7 @@ #' @rdname run.simulation-methods #' @seealso \code{\link{make.simulation}} #' -check.parallel.capability <- function(run.parallel, max.cores) { +check.parallel.capability <- function(run.parallel, max.cores = NA) { # If parallel processing not requested, return FALSE if (!run.parallel) { return(FALSE) @@ -49,7 +49,7 @@ check.parallel.capability <- function(run.parallel, max.cores) { if (is.na(max.cores)) { nCores <<- max(1, available_cores - 1) # Use all but one core } else { - nCores <<- min(max_cores, available_cores) # Use specified number or max available + nCores <<- min(max.cores, available_cores) # Use specified number or max available } # Final check if we can run in parallel From 7ca339d4f01c09dec857d4967dfa359a18d92af3 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Mon, 4 May 2026 15:07:09 -0700 Subject: [PATCH 06/30] feat: add spatially-explicit raster covariate support to detectability MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduces a new `cov.surface` slot on the Detectability S4 class, allowing users to supply a terra SpatRaster (or file path) whose cell values are extracted per-animal at population generation time and used as a continuous covariate in the log-linear scale-parameter model (log σ_i = log σ_0 + β·z_i). Changes: - DESCRIPTION: add terra to Imports - R/Detectability.R: add cov.surface slot (list), initialize argument, and setValidity checks (named entries, matching cov.param slope, file-exists guard, correct object type) - R/ClassConstructors.R: expose cov.surface parameter in make.detectability() with full roxygen docs - R/calculate.scale.param.R: extract raster values via terra::cellFromXY + terra::values before covariate-name lookup; warn and impute global mean for out-of-extent (NA) locations; fix pre-existing length() bug (length(x == 1) → length(x) == 1) - R/check.simulation.R: validate cov.surface names against cov.param - R/run.simulation.R: fix run.serial.simulation (was calling missing process.serial.batch); replace missing display.warnings() call with inline warning loop - tests/testthat/test-check_IndividualCovariates.R: qualify internal calculate.scale.param call with dsims::: - tests/testthat/test-check_RasterCovariate.R: 7 new tests covering directional effect, file vs in-memory parity, validity errors, regression guard, and full run.simulation integration (2 reps) --- .vscode/settings.json | 8 + DESCRIPTION | 1 + R/ClassConstructors.R | 20 +- R/Detectability.R | 41 +++- R/calculate.scale.param.R | 26 +- R/check.simulation.R | 10 +- R/run.simulation.R | 60 ++--- .../test-check_IndividualCovariates.R | 2 +- tests/testthat/test-check_RasterCovariate.R | 227 ++++++++++++++++++ 9 files changed, 360 insertions(+), 35 deletions(-) create mode 100644 .vscode/settings.json create mode 100644 tests/testthat/test-check_RasterCovariate.R diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..356bbae --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "chat.tools.terminal.autoApprove": { + "/^cd /home/lhambrec/dsims/dsims && Rscript -e \"library\\(methods\\); tryCatch\\(source\\('R/Detectability\\.R'\\), error=function\\(e\\) cat\\('ERROR:', conditionMessage\\(e\\), '\\\\n'\\)\\); cat\\('Detectability\\.R OK\\\\n'\\)\"$/": { + "approve": true, + "matchCommandLine": true + } + } +} \ No newline at end of file diff --git a/DESCRIPTION b/DESCRIPTION index 67c9158..8d9dc72 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -5,6 +5,7 @@ Imports: mrds, Distance, sf, + terra, ggplot2, purrr, dplyr, diff --git a/R/ClassConstructors.R b/R/ClassConstructors.R index c669fbc..e99d8c4 100755 --- a/R/ClassConstructors.R +++ b/R/ClassConstructors.R @@ -270,6 +270,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 using \code{run.parallel = TRUE}, 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 +339,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) } diff --git a/R/Detectability.R b/R/Detectability.R index 3e0fe08..6f206b9 100755 --- a/R/Detectability.R +++ b/R/Detectability.R @@ -15,8 +15,12 @@ #' 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 slope +#' coefficients (log scale) for individual-level covariates. +#' @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 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 +30,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 +60,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 +118,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) } ) diff --git a/R/calculate.scale.param.R b/R/calculate.scale.param.R index d3fea0e..42d79b4 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -1,4 +1,5 @@ #' @importFrom methods is +#' @importFrom terra rast cellFromXY values 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 +33,29 @@ 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]] + if(is.character(surf)){ + surf <- terra::rast(surf) + } + cell_ids <- terra::cellFromXY(surf, pts) + rast_vals <- terra::values(surf)[, 1] + vals <- rast_vals[cell_ids] + 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 +68,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/run.simulation.R b/R/run.simulation.R index 7079547..5ba3171 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -113,9 +113,11 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, transect.path, progress.file) } - # Process and display warnings + # Display accumulated warnings if (length(simulation@warnings$message) > 0) { - display.warnings(simulation@warnings) + for(w in seq_along(simulation@warnings$message)){ + warning(simulation@warnings$message[[w]], immediate. = TRUE, call. = FALSE) + } } return(simulation) @@ -221,35 +223,39 @@ run.parallel.simulation <- function(simulation, myCluster, counter, run.serial.simulation <- function(simulation, counter, save.data, load.data, data.path, transect.path, progress.file) { - temp_dir <- file.path(tempdir(), "dsims_temp") - dir.create(temp_dir, showWarnings = FALSE) - on.exit(unlink(temp_dir, recursive = TRUE)) - if (counter) { pb <- txtProgressBar(min = 0, max = simulation@reps, style = 3) on.exit(close(pb), add = TRUE) + } else { + pb <- NULL } - - batch.size <- 40 - n.batches <- ceiling(simulation@reps/batch.size) - - accumulated_results <- create.results.arrays(simulation@reps, - simulation@design@region, - simulation@ds.analysis, - simulation@population.description) - accumulated_warnings <- list(message = list(), - counter = list(), - index = list()) - - for (batch in 1:n.batches) { - process.serial.batch(batch, batch.size, simulation, counter, pb, - save.data, load.data, data.path, - transect.path, progress.file, temp_dir, - accumulated_results, accumulated_warnings) + + sim.results <- vector("list", simulation@reps) + sim.warnings <- vector("list", simulation@reps) + + for (i in 1:simulation@reps) { + rep.result <- single.sim.loop( + i = i, + simulation = simulation, + save.data = save.data, + load.data = load.data, + data.path = data.path, + counter = FALSE, + in.parallel = FALSE, + transect.path = transect.path, + save.transects = FALSE, + progress.file = progress.file + ) + sim.results[[i]] <- rep.result$results + sim.warnings[[i]] <- rep.result$warnings + if (counter && !is.null(pb)) { + setTxtProgressBar(pb, i) + } } - - simulation@results <- accumulated_results - simulation@warnings <- accumulated_warnings - + + simulation <- accumulate.PP.results(simulation = simulation, + results = sim.results) + simulation@warnings <- accumulate.warnings(sim.warnings) + return(simulation) } \ No newline at end of file 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_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") +}) From f115ffb108b5795b063f40c595ed384a7420d1c4 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:04:49 -0700 Subject: [PATCH 07/30] fix: allow plotting detectability with raster covariates Update Detectability plot validation so covariates supplied via cov.surface are treated as valid even when absent from population covariates. Add raster-specific plotting path that reads surface values and uses raster quantiles to generate representative detection curves, enabling mixed covariate plotting (for example size + canopy) without false missing-covariate errors. --- R/Detectability.R | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/R/Detectability.R b/R/Detectability.R index 6f206b9..d40c69b 100755 --- a/R/Detectability.R +++ b/R/Detectability.R @@ -194,7 +194,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 @@ -222,7 +224,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")){ @@ -236,6 +252,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 = "") } @@ -312,6 +330,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){ @@ -350,6 +371,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)) From f496c0a1d04b804060a2f44a8f6fdfcf57818f13 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:06:29 -0700 Subject: [PATCH 08/30] feat: add spatially-explicit raster covariate support to detectability - add cov.surface support to Detectability and make.detectability - apply raster covariates in calculate.scale.param - validate cov.surface in simulation checks - add raster covariate test coverage - update related simulation/covariate paths used by tests --- DESCRIPTION | 1 + R/ClassConstructors.R | 20 +- R/Detectability.R | 41 +++- R/calculate.scale.param.R | 26 +- R/check.simulation.R | 10 +- .../test-check_IndividualCovariates.R | 2 +- tests/testthat/test-check_RasterCovariate.R | 227 ++++++++++++++++++ 7 files changed, 319 insertions(+), 8 deletions(-) create mode 100644 tests/testthat/test-check_RasterCovariate.R diff --git a/DESCRIPTION b/DESCRIPTION index 67c9158..8d9dc72 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -5,6 +5,7 @@ Imports: mrds, Distance, sf, + terra, ggplot2, purrr, dplyr, diff --git a/R/ClassConstructors.R b/R/ClassConstructors.R index c669fbc..e99d8c4 100755 --- a/R/ClassConstructors.R +++ b/R/ClassConstructors.R @@ -270,6 +270,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 using \code{run.parallel = TRUE}, 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 +339,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) } diff --git a/R/Detectability.R b/R/Detectability.R index 3e0fe08..6f206b9 100755 --- a/R/Detectability.R +++ b/R/Detectability.R @@ -15,8 +15,12 @@ #' 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 slope +#' coefficients (log scale) for individual-level covariates. +#' @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 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 +30,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 +60,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 +118,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) } ) diff --git a/R/calculate.scale.param.R b/R/calculate.scale.param.R index d3fea0e..42d79b4 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -1,4 +1,5 @@ #' @importFrom methods is +#' @importFrom terra rast cellFromXY values 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 +33,29 @@ 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]] + if(is.character(surf)){ + surf <- terra::rast(surf) + } + cell_ids <- terra::cellFromXY(surf, pts) + rast_vals <- terra::values(surf)[, 1] + vals <- rast_vals[cell_ids] + 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 +68,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/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_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") +}) From 45d9abc78bfd2b14827ab0248d5ab64690cf8be3 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:04:49 -0700 Subject: [PATCH 09/30] fix: allow plotting detectability with raster covariates Update Detectability plot validation so covariates supplied via cov.surface are treated as valid even when absent from population covariates. Add raster-specific plotting path that reads surface values and uses raster quantiles to generate representative detection curves, enabling mixed covariate plotting (for example size + canopy) without false missing-covariate errors. --- R/Detectability.R | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/R/Detectability.R b/R/Detectability.R index 6f206b9..d40c69b 100755 --- a/R/Detectability.R +++ b/R/Detectability.R @@ -194,7 +194,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 @@ -222,7 +224,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")){ @@ -236,6 +252,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 = "") } @@ -312,6 +330,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){ @@ -350,6 +371,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)) From f0a65e75c29d70b1364723ea7c5d035bb87fc75d Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:52:45 -0700 Subject: [PATCH 10/30] perf(parallel): switch to worker-state load-balanced execution - initialize worker state once per cluster - dispatch only repetition indices to workers - replace static scheduling with parLapplyLB for better core utilization - remove repeated heavy argument passing in parallel loop --- R/run.simulation.R | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/R/run.simulation.R b/R/run.simulation.R index 3d543ab..c832847 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -21,7 +21,7 @@ #' @return the \code{\link{Simulation-class}} object which now includes #' the results #' @export -#' @importFrom parallel detectCores makeCluster clusterEvalQ stopCluster parLapply +#' @importFrom parallel detectCores makeCluster clusterEvalQ stopCluster parLapplyLB clusterExport #' @importFrom rstudioapi versionInfo #' @rdname run.simulation-methods #' @seealso \code{\link{make.simulation}} @@ -77,8 +77,8 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou # Two if(run.parallel) checks as if libraries not present will change to # false before running in parallel and then run in serial 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) + if(!requireNamespace('parallel', quietly = TRUE)){ + warning("Could not run in parallel, check parallel library is installed.", immediate. = TRUE, call. = FALSE) run.parallel = FALSE }else{ # counts the number of cores you have @@ -108,12 +108,40 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou parallel::clusterEvalQ(myCluster, { require(dsims) }) + worker.state <- list(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) + worker.fun <- function(i){ + state <- get(".dsims_worker_state", envir = .GlobalEnv) + single.sim.loop(i = i, + simulation = state$simulation, + save.data = state$save.data, + load.data = state$load.data, + data.path = state$data.path, + counter = FALSE, + in.parallel = TRUE, + transect.path = state$transect.path, + save.transects = state$save.transects, + progress.file = state$progress.file) + } + parallel::clusterExport(myCluster, + varlist = c("worker.state", "worker.fun"), + envir = environment()) + parallel::clusterEvalQ(myCluster, { + .dsims_worker_state <- worker.state + NULL + }) 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) + message("Parallel run uses load-balanced scheduling; per-repetition progress bar is disabled.") } + results <- parallel::parLapplyLB(myCluster, + X = as.list(1:simulation@reps), + fun = worker.fun) #Extract results and warnings sim.results <- sim.warnings <- list() for(i in seq(along = results)){ From 3fc6abac315974a31857612bc9f0b15452bd341e Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:53:27 -0700 Subject: [PATCH 11/30] perf(spatial): vectorize detection-distance joins with sf indexes - replace per-transect st_intersection loops with one st_join - compute line/point distances in vectorized st_distance calls - remove iterative reduce/rbind assembly path for possible detections --- R/calc.perp.dists.R | 97 +++++++++++---------------------------------- R/calc.rad.dists.R | 77 +++++++++++------------------------ 2 files changed, 48 insertions(+), 126 deletions(-) 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) } From e709ebd258e708f04ac0e8e2e522c69235c9417d Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:53:49 -0700 Subject: [PATCH 12/30] perf(raster): add worker-local cov.surface cache - cache raster handles/value vectors in a process-local runtime cache - avoid re-reading raster files and full value vectors every repetition - keep cache lookup keyed by file path (or raster footprint for in-memory surfaces) --- R/calculate.scale.param.R | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/R/calculate.scale.param.R b/R/calculate.scale.param.R index 42d79b4..e972bb6 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -1,5 +1,35 @@ #' @importFrom methods is #' @importFrom terra rast cellFromXY values +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) + cache.key <- paste0("mem::", sn, "::", terra::ncell(surf), "::", + paste(as.numeric(surf.ext), collapse = ":")) + } + + if(exists(cache.key, envir = cache, inherits = FALSE)){ + return(get(cache.key, envir = cache, inherits = FALSE)) + } + + surf.obj <- if(is.character(surf)) terra::rast(surf) else surf + entry <- list(rast = surf.obj, + vals = terra::values(surf.obj)[,1]) + 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 @@ -40,12 +70,9 @@ calculate.scale.param <- function(pop.data, detectability, region){ pts <- cbind(pop.data$x, pop.data$y) for(sn in surf.names){ surf <- detectability@cov.surface[[sn]] - if(is.character(surf)){ - surf <- terra::rast(surf) - } - cell_ids <- terra::cellFromXY(surf, pts) - rast_vals <- terra::values(surf)[, 1] - vals <- rast_vals[cell_ids] + cache.entry <- get.surface.cache.entry(sn, surf) + cell_ids <- terra::cellFromXY(cache.entry$rast, pts) + vals <- cache.entry$vals[cell_ids] if(any(is.na(vals))){ warning(paste0("NA raster values for surface covariate '", sn, "' at some animal locations (outside raster extent). ", From 971b41aa86cefcd58fc427d255f1cf91fc3ceb3e Mon Sep 17 00:00:00 2001 From: Leonard Hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 16:01:35 -0700 Subject: [PATCH 13/30] Potential fix for pull request finding Updated the @slot cov.param docs to reflect the actual allowed shapes (numeric vectors for continuous/discrete + data.frames for categorical levels). Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- R/Detectability.R | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/R/Detectability.R b/R/Detectability.R index d40c69b..bc6aecd 100755 --- a/R/Detectability.R +++ b/R/Detectability.R @@ -15,12 +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{"list"}; Named list of slope -#' coefficients (log scale) for individual-level covariates. +#' @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 entries in \code{cov.param}. +#' 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 From 58d2d6ac11c9492118f162cd65aa46de487014e9 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 16:05:09 -0700 Subject: [PATCH 14/30] perf(results): stream per-repetition payloads instead of full result objects - add extract/apply helpers for compact per-repetition result slices - return rep-level payloads from single.sim.loop - aggregate serial/parallel outputs without full-object round-trips - keep backward-compatible accumulator path for legacy result shapes - fix in-memory raster cache key generation for SpatRaster extents --- R/accumulate.PP.results.R | 64 +++++++++++++++++++++++++++++++++------ R/calculate.scale.param.R | 3 +- R/run.simulation.R | 23 +++++++++----- R/single.sim.loop.R | 10 ++++-- 4 files changed, 80 insertions(+), 20 deletions(-) diff --git a/R/accumulate.PP.results.R b/R/accumulate.PP.results.R index 3226adb..6019007 100644 --- a/R/accumulate.PP.results.R +++ b/R/accumulate.PP.results.R @@ -1,15 +1,61 @@ +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$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] + } + + 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$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] + } + 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{ + # Backward-compatible path for legacy full-object result returns + 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/calculate.scale.param.R b/R/calculate.scale.param.R index e972bb6..364eaa0 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -15,8 +15,9 @@ get.surface.cache.entry <- function(sn, 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(as.numeric(surf.ext), collapse = ":")) + paste(ext.vec, collapse = ":")) } if(exists(cache.key, envir = cache, inherits = FALSE)){ diff --git a/R/run.simulation.R b/R/run.simulation.R index c832847..906ba92 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -143,18 +143,15 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou X = as.list(1:simulation@reps), fun = worker.fun) #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 - } - simulation <- accumulate.PP.results(simulation = simulation, results = sim.results) + sim.warnings <- lapply(results, function(x) x$warnings) + simulation <- accumulate.PP.results(simulation = simulation, results = results) simulation@warnings <- accumulate.warnings(sim.warnings) stopCluster(myCluster) on.exit() } if(!run.parallel){ #otherwise loop + sim.warnings <- vector("list", simulation@reps) for(i in 1:simulation@reps){ results <- single.sim.loop(i = i, simulation = simulation, @@ -165,9 +162,19 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, cou transect.path = transect.path, save.transects = FALSE, progress.file = progress.file) - simulation@results <- results$results - simulation@warnings <- results$warnings + if(!is.null(results$rep.result)){ + simulation@results <- apply.rep.result(simulation@results, + results$rep.result, + i) + if(!is.null(results$filename) && length(results$filename) > 0){ + simulation@results$filename[i] <- results$filename + } + }else{ + simulation@results <- results$results + } + sim.warnings[[i]] <- results$warnings } + simulation@warnings <- accumulate.warnings(sim.warnings) } simulation@results <- add.summary.results(results = simulation@results, model.count = length(simulation@ds.analysis@dfmodel)) diff --git a/R/single.sim.loop.R b/R/single.sim.loop.R index 6a5adb8..fcd7496 100755 --- a/R/single.sim.loop.R +++ b/R/single.sim.loop.R @@ -19,6 +19,7 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha # Output: list of simulation results and warnings # warnings <- simulation@warnings + rep.filename <- NA_character_ # Display/write to file the progress of the simulation if(counter){ if(length(progress.file) == 0 && !in.parallel){ @@ -72,9 +73,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){ @@ -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)) } From 4a393d5bd5dcf95de3ab71c0a9f87fc0bee68933 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:52:45 -0700 Subject: [PATCH 15/30] perf(parallel): switch to worker-state load-balanced execution - initialize worker state once per cluster - dispatch only repetition indices to workers - replace static scheduling with parLapplyLB for better core utilization - remove repeated heavy argument passing in parallel loop --- R/run.simulation.R | 202 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 156 insertions(+), 46 deletions(-) diff --git a/R/run.simulation.R b/R/run.simulation.R index 5ba3171..8bf6bdb 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -21,7 +21,7 @@ #' @return the \code{\link{Simulation-class}} object which now includes #' the results #' @export -#' @importFrom parallel detectCores makeCluster clusterEvalQ stopCluster parLapply +#' @importFrom parallel detectCores makeCluster clusterEvalQ stopCluster parLapplyLB clusterExport #' @importFrom rstudioapi versionInfo #' @rdname run.simulation-methods #' @seealso \code{\link{make.simulation}} @@ -64,62 +64,172 @@ check.parallel.capability <- function(run.parallel, max.cores = NA) { run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, counter = TRUE, transect.path = character(0), progress.file = character(0)) { - # Input validation - if (!inherits(simulation, "Simulation")) { - stop("Input must be a Simulation-class object") - } - - # Initialize variables save.data <- load.data <- FALSE data.path <- character() - - # Process transect path - if (length(transect.path) > 0) { - transect.path <- process.transect.path(transect.path, simulation@reps) + # Check if the transect path ends in / if so remove - hard to do the same for windows! + if(length(transect.path) > 0){ + if(substr(transect.path, nchar(transect.path), nchar(transect.path)) == "/"){ + transect.path <- substr(transect.path, 0, nchar(transect.path)-1) + } + } + transect.path.master <- transect.path + # Check if it is a single transect set or a folder + if(length(transect.path) > 0){ + # Check if a folder or file have been specified + check.path <- unlist(strsplit(transect.path, split = "[.]")) + index <- length(check.path) + if(check.path[index] == "shp"){ + # Set transect path to repeat the same value for each rep (for running in parallel) + transect.path <- rep(transect.path, simulation@reps) + }else{ + # Make up the vector of shapefile paths + transect.path <- file.path(transect.path, list.files(path = transect.path, pattern = "shp")) + if(length(transect.path) == 0){ + stop(paste("No shapefiles found at ", transect.path.master,", cannot run simulation.", sep = ""), call. = FALSE) + } + if(length(transect.path) < simulation@reps){ + warning(paste("Insufficient transect shapefiles supplied (", length(transect.path)," supplied, ", simulation@reps, " required). Simulation will use some sets of transects more than once, this may influence the results.", sep = ""), immediate. = TRUE, call. = FALSE) + mult.factor <- ceiling(simulation@reps/length(transect.path)) + transect.path <- rep(transect.path, mult.factor)[1:simulation@reps] + } + } } - - # Reset results and warnings simulation@results <- create.results.arrays(simulation@reps, - simulation@design@region, - simulation@ds.analysis, - simulation@population.description) - simulation@warnings <- list(message = list(), - counter = list(), - index = list()) - - # Check parallel capabilities - run.parallel <- check.parallel.capability(run.parallel, max.cores) - - # Main execution - if (run.parallel) { - # Initialize cluster + simulation@design@region, + simulation@ds.analysis, + simulation@population.description) + #reset the error/warning message + simulation@warnings$message <- list() + simulation@warnings$counter <- list() + simulation@warnings$index <- list() + #check the data.path ends in "/" + if(length(data.path) > 0){ + temp.path <- strsplit(data.path, split = "") + if(temp.path[length(temp.path)] != "/"){ + # if not add it + data.path <- paste(data.path, "/", sep = "") + } + 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 + if(run.parallel){ + if(!requireNamespace('parallel', quietly = TRUE)){ + warning("Could not run in parallel, check parallel 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 + } + } + } + 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) - on.exit(stopCluster(myCluster)) - parallel::clusterEvalQ(myCluster, { require(dsims) - gc() }) - - # Run parallel simulation - simulation <- run.parallel.simulation(simulation, myCluster, counter, - save.data, load.data, data.path, - transect.path, progress.file) - - } else { - # Run serial simulation - simulation <- run.serial.simulation(simulation, counter, - save.data, load.data, data.path, - transect.path, progress.file) + worker.state <- list(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) + worker.fun <- function(i){ + state <- get(".dsims_worker_state", envir = .GlobalEnv) + single.sim.loop(i = i, + simulation = state$simulation, + save.data = state$save.data, + load.data = state$load.data, + data.path = state$data.path, + counter = FALSE, + in.parallel = TRUE, + transect.path = state$transect.path, + save.transects = state$save.transects, + progress.file = state$progress.file) + } + parallel::clusterExport(myCluster, + varlist = c("worker.state", "worker.fun"), + envir = environment()) + parallel::clusterEvalQ(myCluster, { + .dsims_worker_state <- worker.state + NULL + }) + on.exit(stopCluster(myCluster)) + if(counter){ + message("Parallel run uses load-balanced scheduling; per-repetition progress bar is disabled.") + } + results <- parallel::parLapplyLB(myCluster, + X = as.list(1:simulation@reps), + fun = worker.fun) + #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 + } + simulation <- accumulate.PP.results(simulation = simulation, results = sim.results) + simulation@warnings <- accumulate.warnings(sim.warnings) + stopCluster(myCluster) + on.exit() } - - # Display accumulated warnings - if (length(simulation@warnings$message) > 0) { - for(w in seq_along(simulation@warnings$message)){ - warning(simulation@warnings$message[[w]], immediate. = TRUE, call. = FALSE) + if(!run.parallel){ + #otherwise loop + sim.warnings <- vector("list", simulation@reps) + 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) + if(!is.null(results$rep.result)){ + simulation@results <- apply.rep.result(simulation@results, + results$rep.result, + i) + if(!is.null(results$filename) && length(results$filename) > 0){ + simulation@results$filename[i] <- results$filename + } + }else{ + simulation@results <- results$results + } + sim.warnings[[i]] <- results$warnings } + simulation@warnings <- accumulate.warnings(sim.warnings) } - + simulation@results <- add.summary.results(results = simulation@results, + model.count = length(simulation@ds.analysis@dfmodel)) + #Process warnings + if(length(simulation@warnings$message) > 0){ + message("Summary of warnings and errors:") + for(i in seq(along = simulation@warnings$message)){ + rep.info <- ifelse(is.null(simulation@warnings$index), "", + paste(" in repetition(s): ", paste(simulation@warnings$index[[i]], collapse = ", "))) + message(paste(simulation@warnings$message[[i]], " (occurred ", simulation@warnings$counter[[i]], " time(s)", rep.info, ")", sep = "")) + } + message("-----") + } + return(simulation) } From 33e982ae8ba4819a89696238170b98946caa0f19 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:53:27 -0700 Subject: [PATCH 16/30] perf(spatial): vectorize detection-distance joins with sf indexes - replace per-transect st_intersection loops with one st_join - compute line/point distances in vectorized st_distance calls - remove iterative reduce/rbind assembly path for possible detections --- R/calc.perp.dists.R | 97 +++++++++++---------------------------------- R/calc.rad.dists.R | 77 +++++++++++------------------------ 2 files changed, 48 insertions(+), 126 deletions(-) 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) } From 0cec92e79cc53502221f6f6316a16b11c91f5855 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 15:53:49 -0700 Subject: [PATCH 17/30] perf(raster): add worker-local cov.surface cache - cache raster handles/value vectors in a process-local runtime cache - avoid re-reading raster files and full value vectors every repetition - keep cache lookup keyed by file path (or raster footprint for in-memory surfaces) --- R/calculate.scale.param.R | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/R/calculate.scale.param.R b/R/calculate.scale.param.R index 42d79b4..e972bb6 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -1,5 +1,35 @@ #' @importFrom methods is #' @importFrom terra rast cellFromXY values +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) + cache.key <- paste0("mem::", sn, "::", terra::ncell(surf), "::", + paste(as.numeric(surf.ext), collapse = ":")) + } + + if(exists(cache.key, envir = cache, inherits = FALSE)){ + return(get(cache.key, envir = cache, inherits = FALSE)) + } + + surf.obj <- if(is.character(surf)) terra::rast(surf) else surf + entry <- list(rast = surf.obj, + vals = terra::values(surf.obj)[,1]) + 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 @@ -40,12 +70,9 @@ calculate.scale.param <- function(pop.data, detectability, region){ pts <- cbind(pop.data$x, pop.data$y) for(sn in surf.names){ surf <- detectability@cov.surface[[sn]] - if(is.character(surf)){ - surf <- terra::rast(surf) - } - cell_ids <- terra::cellFromXY(surf, pts) - rast_vals <- terra::values(surf)[, 1] - vals <- rast_vals[cell_ids] + cache.entry <- get.surface.cache.entry(sn, surf) + cell_ids <- terra::cellFromXY(cache.entry$rast, pts) + vals <- cache.entry$vals[cell_ids] if(any(is.na(vals))){ warning(paste0("NA raster values for surface covariate '", sn, "' at some animal locations (outside raster extent). ", From c6777bb9d9cc9c0e3f72c96432264c2dbf4bd3da Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 5 May 2026 16:05:09 -0700 Subject: [PATCH 18/30] perf(results): stream per-repetition payloads instead of full result objects - add extract/apply helpers for compact per-repetition result slices - return rep-level payloads from single.sim.loop - aggregate serial/parallel outputs without full-object round-trips - keep backward-compatible accumulator path for legacy result shapes - fix in-memory raster cache key generation for SpatRaster extents --- R/accumulate.PP.results.R | 64 +++++++++++++++++++++++++++++++++------ R/calculate.scale.param.R | 3 +- R/run.simulation.R | 8 ++--- R/single.sim.loop.R | 10 ++++-- 4 files changed, 67 insertions(+), 18 deletions(-) diff --git a/R/accumulate.PP.results.R b/R/accumulate.PP.results.R index 3226adb..6019007 100644 --- a/R/accumulate.PP.results.R +++ b/R/accumulate.PP.results.R @@ -1,15 +1,61 @@ +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$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] + } + + 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$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] + } + 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{ + # Backward-compatible path for legacy full-object result returns + 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/calculate.scale.param.R b/R/calculate.scale.param.R index e972bb6..364eaa0 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -15,8 +15,9 @@ get.surface.cache.entry <- function(sn, 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(as.numeric(surf.ext), collapse = ":")) + paste(ext.vec, collapse = ":")) } if(exists(cache.key, envir = cache, inherits = FALSE)){ diff --git a/R/run.simulation.R b/R/run.simulation.R index 8bf6bdb..06901fe 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -180,12 +180,8 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, X = as.list(1:simulation@reps), fun = worker.fun) #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 - } - simulation <- accumulate.PP.results(simulation = simulation, results = sim.results) + sim.warnings <- lapply(results, function(x) x$warnings) + simulation <- accumulate.PP.results(simulation = simulation, results = results) simulation@warnings <- accumulate.warnings(sim.warnings) stopCluster(myCluster) on.exit() diff --git a/R/single.sim.loop.R b/R/single.sim.loop.R index 6a5adb8..fcd7496 100755 --- a/R/single.sim.loop.R +++ b/R/single.sim.loop.R @@ -19,6 +19,7 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha # Output: list of simulation results and warnings # warnings <- simulation@warnings + rep.filename <- NA_character_ # Display/write to file the progress of the simulation if(counter){ if(length(progress.file) == 0 && !in.parallel){ @@ -72,9 +73,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){ @@ -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)) } From c05c0257d6862ddbfb6e244e0ec49b42cbd98bd0 Mon Sep 17 00:00:00 2001 From: Leonard Hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:46:26 -0700 Subject: [PATCH 19/30] perf: read cov.surface values at animal locations instead of caching the raster The worker-local cov.surface cache stored terra::values() of the whole raster in every worker. With a 10 m canopy raster (73 million cells) and 31 parallel workers this exhausted memory ("cannot allocate vector of size 233 Mb"). Cache only the raster handle and read values at the animal locations with terra::extract(), which reads only the blocks it needs. Raster covariate tests pass unchanged. Co-Authored-By: Claude Opus 5.5 --- R/calculate.scale.param.R | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/R/calculate.scale.param.R b/R/calculate.scale.param.R index 364eaa0..8d47f5c 100755 --- a/R/calculate.scale.param.R +++ b/R/calculate.scale.param.R @@ -1,5 +1,5 @@ #' @importFrom methods is -#' @importFrom terra rast cellFromXY values +#' @importFrom terra rast extract get.dsims.runtime.cache <- function(){ cache <- getOption("dsims.runtime.cache") if(is.null(cache) || !is.environment(cache)){ @@ -24,9 +24,12 @@ get.surface.cache.entry <- function(sn, surf){ 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, - vals = terra::values(surf.obj)[,1]) + entry <- list(rast = surf.obj) assign(cache.key, entry, envir = cache) entry } @@ -72,8 +75,7 @@ calculate.scale.param <- function(pop.data, detectability, region){ for(sn in surf.names){ surf <- detectability@cov.surface[[sn]] cache.entry <- get.surface.cache.entry(sn, surf) - cell_ids <- terra::cellFromXY(cache.entry$rast, pts) - vals <- cache.entry$vals[cell_ids] + 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). ", From 037f015220207a3c1d951ca3760e410b9212f5ca Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:27:50 -0700 Subject: [PATCH 20/30] perf(parallel): run repetitions on mirai daemons, parallel by default Replace the parallel/PSOCK cluster with mirai daemons for distributing repetitions. Benchmarked against 1.0.6 (64 reps, up to 16 workers) the throughput is unchanged; reusing user-started daemons avoids worker start-up (16 workers: 14.8 s -> 7.9 s). A future.apply backend was also evaluated and rejected: ~0.85 s launch overhead per future made it up to 9x slower. - run.parallel now defaults to TRUE; workers default to parallelly::availableCores(omit = 1), which respects HPC/cgroup limits - daemons the user has set up with mirai::daemons() (local, remote, HPC) are used and left running; daemons dsims starts are shut down on exit - daemons dsims starts get the session's .libPaths(), and dsims stops with a clear error if workers load a different dsims version - each rep gets its own L'Ecuyer-CMRG stream, so set.seed() gives identical results in serial and parallel for any number of workers; the user's RNG kind and state are restored - a rep that errors is skipped and reported in the warnings summary rather than stopping the simulation - progress counter now works in parallel and shows elapsed / remaining time; progress.file is written from the main session only - remove dead helpers (check.parallel.capability with its <<- leak, run.parallel.simulation, run.serial.simulation, process.transect.path) and the RStudio/macOS PSOCK workaround; move run.simulation's roxygen block back onto run.simulation - regenerate stale Detectability / make.detectability docs Breaking: seeded results differ from 1.0.6 as the RNG streams changed. Co-Authored-By: Claude Opus 5.5 --- .Rbuildignore | 1 + .gitignore | 3 + DESCRIPTION | 8 +- NAMESPACE | 17 +- NEWS.md | 14 ++ R/ClassConstructors.R | 4 +- R/accumulate.PP.results.R | 3 +- R/run.simulation.R | 444 ++++++++++++++------------------- R/single.sim.loop.R | 29 +-- man/Detectability-class.Rd | 9 +- man/make.detectability.Rd | 18 ++ man/run.simulation-methods.Rd | 35 ++- tests/testthat/test-Parallel.R | 66 +++++ vignettes/dsims-examples.Rmd | 4 +- 14 files changed, 342 insertions(+), 313 deletions(-) create mode 100644 tests/testthat/test-Parallel.R 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 8d9dc72..cc46acd 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -11,20 +11,20 @@ Imports: 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.1.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")) 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..a700ada 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,17 @@ +# 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. + +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. + # dsims 1.0.6 Bug Fixes diff --git a/R/ClassConstructors.R b/R/ClassConstructors.R index e99d8c4..d8b40de 100755 --- a/R/ClassConstructors.R +++ b/R/ClassConstructors.R @@ -284,8 +284,8 @@ make.population.description <- make.pop.description <- function(region = make.re #' 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 using \code{run.parallel = TRUE}, as large objects may not serialise -#' efficiently to worker processes. +#' 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 diff --git a/R/accumulate.PP.results.R b/R/accumulate.PP.results.R index 6019007..deb2c69 100644 --- a/R/accumulate.PP.results.R +++ b/R/accumulate.PP.results.R @@ -44,8 +44,9 @@ accumulate.PP.results <- function(simulation, results){ if(!is.null(results[[i]]$filename) && length(results[[i]]$filename) > 0){ simulation@results$filename[i] <- results[[i]]$filename } - }else{ + }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] diff --git a/R/run.simulation.R b/R/run.simulation.R index 06901fe..9513125 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -1,15 +1,34 @@ #' 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. +#' +#' 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,47 +40,13 @@ #' @return the \code{\link{Simulation-class}} object which now includes #' the results #' @export -#' @importFrom parallel detectCores makeCluster clusterEvalQ stopCluster parLapplyLB clusterExport -#' @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}} #' -check.parallel.capability <- function(run.parallel, max.cores = NA) { - # If parallel processing not requested, return FALSE - if (!run.parallel) { - return(FALSE) - } - - # Check if parallel package is available - if (!requireNamespace("parallel", quietly = TRUE)) { - warning("Parallel package not available. Running in serial mode.") - return(FALSE) - } - - # Determine number of cores to use - available_cores <- parallel::detectCores() - if (is.na(available_cores)) { - warning("Could not detect number of cores. Running in serial mode.") - return(FALSE) - } - - # Set number of cores to use - if (is.na(max.cores)) { - nCores <<- max(1, available_cores - 1) # Use all but one core - } else { - nCores <<- min(max.cores, available_cores) # Use specified number or max available - } - - # Final check if we can run in parallel - if (nCores > 1) { - return(TRUE) - } else { - warning("Only one core available. Running in serial mode.") - return(FALSE) - } -} - -run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, +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 @@ -111,108 +96,50 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, } 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)){ - warning("Could not run in parallel, check parallel 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\")")) - } + 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) } - # intitialise the cluster - myCluster <- parallel::makeCluster(nCores) - parallel::clusterEvalQ(myCluster, { - require(dsims) - }) - worker.state <- list(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) - worker.fun <- function(i){ - state <- get(".dsims_worker_state", envir = .GlobalEnv) - single.sim.loop(i = i, - simulation = state$simulation, - save.data = state$save.data, - load.data = state$load.data, - data.path = state$data.path, - counter = FALSE, - in.parallel = TRUE, - transect.path = state$transect.path, - save.transects = state$save.transects, - progress.file = state$progress.file) - } - parallel::clusterExport(myCluster, - varlist = c("worker.state", "worker.fun"), - envir = environment()) - parallel::clusterEvalQ(myCluster, { - .dsims_worker_state <- worker.state - NULL - }) - on.exit(stopCluster(myCluster)) - if(counter){ - message("Parallel run uses load-balanced scheduling; per-repetition progress bar is disabled.") - } - results <- parallel::parLapplyLB(myCluster, - X = as.list(1:simulation@reps), - fun = worker.fun) - #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) - stopCluster(myCluster) - on.exit() + assign(".Random.seed", old.seed, envir = globalenv()) } - if(!run.parallel){ - #otherwise loop - sim.warnings <- vector("list", simulation@reps) - 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) - if(!is.null(results$rep.result)){ - simulation@results <- apply.rep.result(simulation@results, - results$rep.result, - i) - if(!is.null(results$filename) && length(results$filename) > 0){ - simulation@results$filename[i] <- results$filename - } - }else{ - simulation@results <- results$results - } - sim.warnings[[i]] <- results$warnings + # 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)) } - simulation@warnings <- accumulate.warnings(sim.warnings) } + #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 @@ -229,139 +156,136 @@ run.simulation <- function(simulation, run.parallel = FALSE, max.cores = NA, return(simulation) } -# Helper functions -process.transect.path <- function(transect.path, reps) { - # Remove trailing slash if present - if (substr(transect.path, nchar(transect.path), nchar(transect.path)) == "/") { - transect.path <- substr(transect.path, 0, nchar(transect.path)-1) +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) } - - # Check if single file or directory - check.path <- unlist(strsplit(transect.path, split = "[.]")) - if (utils::tail(check.path, 1) == "shp") { - return(rep(transect.path, reps)) - } else { - paths <- file.path(transect.path, list.files(path = transect.path, pattern = "shp")) - if (length(paths) == 0) { - stop(sprintf("No shapefiles found at %s", transect.path)) + 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 + mirai::everywhere(.libPaths(lib.paths), lib.paths = .libPaths(), + .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) } - if (length(paths) < reps) { - warning(sprintf("Insufficient transect files (%d supplied, %d required)", - length(paths), reps)) - mult.factor <- ceiling(reps/length(paths)) - return(rep(paths, mult.factor)[1:reps]) + 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) } - return(paths) + 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) } } -run.parallel.simulation <- function(simulation, myCluster, counter, - save.data, load.data, data.path, - transect.path, progress.file) { - # Process in batches - batch.size <- 10 - batches <- split(1:simulation@reps, - ceiling(seq_along(1:simulation@reps)/batch.size)) - - sim.results <- list() - sim.warnings <- list() - - for (batch_idx in seq_along(batches)) { - current_batch <- batches[[batch_idx]] - - batch_results <- tryCatch({ - if (counter) { - pbapply::pblapply( - X = as.list(current_batch), - 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 { - parallel::parLapply( - myCluster, - X = as.list(current_batch), - 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 - ) - } - }, error = function(e) { - warning(sprintf("Error in batch %d: %s", batch_idx, e$message)) - return(NULL) - }) - - if (!is.null(batch_results)) { - for (i in seq_along(batch_results)) { - sim.results[[current_batch[i]]] <- batch_results[[i]]$results - sim.warnings[[current_batch[i]]] <- batch_results[[i]]$warnings - } +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 } - - rm(batch_results) - parallel::clusterEvalQ(myCluster, gc()) - gc() + Sys.sleep(0.5) } - - simulation <- accumulate.PP.results(simulation = simulation, - results = sim.results) - simulation@warnings <- accumulate.warnings(sim.warnings) - - rm(sim.results, sim.warnings) - gc() - - return(simulation) } -run.serial.simulation <- function(simulation, counter, - save.data, load.data, data.path, - transect.path, progress.file) { - if (counter) { - pb <- txtProgressBar(min = 0, max = simulation@reps, style = 3) - on.exit(close(pb), add = TRUE) - } else { - pb <- NULL +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) } - - sim.results <- vector("list", simulation@reps) - sim.warnings <- vector("list", simulation@reps) - - for (i in 1:simulation@reps) { - rep.result <- single.sim.loop( - i = i, - simulation = simulation, - save.data = save.data, - load.data = load.data, - data.path = data.path, - counter = FALSE, - in.parallel = FALSE, - transect.path = transect.path, - save.transects = FALSE, - progress.file = progress.file - ) - sim.results[[i]] <- rep.result$results - sim.warnings[[i]] <- rep.result$warnings - if (counter && !is.null(pb)) { - setTxtProgressBar(pb, i) - } + if(length(progress.file) > 0){ + try(cat(round(done/reps*100), file = progress.file), silent = TRUE) } +} - simulation <- accumulate.PP.results(simulation = simulation, - results = sim.results) - simulation@warnings <- accumulate.warnings(sim.warnings) +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) +} - return(simulation) -} \ No newline at end of file +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/single.sim.loop.R b/R/single.sim.loop.R index fcd7496..32813f5 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 @@ -20,30 +17,6 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha # warnings <- simulation@warnings rep.filename <- NA_character_ - # 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() if(!load.data){ #generate population population <- generate.population(simulation) diff --git a/man/Detectability-class.Rd b/man/Detectability-class.Rd index 573f3db..4fd074b 100644 --- a/man/Detectability-class.Rd +++ b/man/Detectability-class.Rd @@ -20,8 +20,13 @@ 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 slope +coefficients (log scale) for individual-level covariates.} + +\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 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/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/run.simulation-methods.Rd b/man/run.simulation-methods.Rd index d909384..80b3e2d 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,30 @@ 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. + +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/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/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 From a4855cb9270039f7d8e263611544437394a2cf8e Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:27:50 -0700 Subject: [PATCH 21/30] bench: add before/after benchmark script for run.simulation Compares dsims installed in bench/lib_baseline and bench/lib_new in fresh callr processes (serial, workers started per call, persistent daemons) and records failed reps so silently failing workers cannot skew timings. Co-Authored-By: Claude Opus 5.5 --- bench/benchmark.R | 92 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 bench/benchmark.R 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) From 519c96ccc793ff43ae9333c40f95b04d438b7c00 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:17:08 -0700 Subject: [PATCH 22/30] feat(analysis): allow a uniform key in make.ds.analysis() make.ds.analysis() only accepted "hn" and "hr", although the DS.Analysis class documentation listed uniform. Data simulated with make.detectability(key.function = "uf") could therefore only be analysed with a mis-specified key (hn / hr overestimated density by 3-11% for a nadir camera strip). - accept key = "unif" (and "uf" as an alias, consistent with make.detectability) and pass it on to Distance::ds() - reject covariates with the uniform key (dfmodel must be ~1) - document that the uniform analysis gives the strip estimate and underestimates by (1 - g) if detection within the strip is g < 1 - tests: average p = 1, density equals n / covered area per rep, hn vs unif model selection, and the g = 0.9 underestimate Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 1 + R/ClassConstructors.R | 18 ++++++- R/DS.Analysis.R | 11 +++- man/make.ds.analysis.Rd | 16 +++++- tests/testthat/test-check_Constructors.R | 2 +- tests/testthat/test-check_UniformKey.R | 69 ++++++++++++++++++++++++ 6 files changed, 110 insertions(+), 7 deletions(-) create mode 100644 tests/testthat/test-check_UniformKey.R diff --git a/NEWS.md b/NEWS.md index a700ada..ac0fcce 100644 --- a/NEWS.md +++ b/NEWS.md @@ -7,6 +7,7 @@ Enhancements * 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. Breaking Changes diff --git a/R/ClassConstructors.R b/R/ClassConstructors.R index d8b40de..73f2289 100755 --- a/R/ClassConstructors.R +++ b/R/ClassConstructors.R @@ -374,8 +374,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 @@ -417,6 +423,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), @@ -461,6 +473,8 @@ 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) return(ds.analysis) diff --git a/R/DS.Analysis.R b/R/DS.Analysis.R index 3a843b0..f78bcc4 100644 --- a/R/DS.Analysis.R +++ b/R/DS.Analysis.R @@ -84,8 +84,15 @@ setValidity("DS.Analysis", return("This selection criteria is not currently supported, please select from 'AIC', 'BIC' or 'AICc'.") } # 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/man/make.ds.analysis.Rd b/man/make.ds.analysis.Rd index 307adbf..5e93acb 100644 --- a/man/make.ds.analysis.Rd +++ b/man/make.ds.analysis.Rd @@ -19,8 +19,14 @@ make.ds.analysis( \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.} @@ -93,6 +99,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/tests/testthat/test-check_Constructors.R b/tests/testthat/test-check_Constructors.R index 931c3eb..8d76bde 100644 --- a/tests/testthat/test-check_Constructors.R +++ b/tests/testthat/test-check_Constructors.R @@ -229,7 +229,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_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) +}) From 9771fc50e47d7e5a4efc6ca2d204c5f03f046221 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:54:47 -0700 Subject: [PATCH 23/30] fix: require whole-number N when fixed.N = TRUE Fractional N was rounded up per stratum when generating the population while the unrounded N was used as the true abundance, inflating the simulated population. make.population.description() now stops instead. Also document persistent mirai daemons for many short simulations and note the worker process name change in NEWS. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 6 ++++++ R/ClassConstructors.R | 3 ++- R/Population.Description.R | 5 +++++ R/run.simulation.R | 6 +++++- man/make.population.description.Rd | 3 ++- man/run.simulation-methods.Rd | 6 +++++- tests/testthat/test-check_Constructors.R | 11 +++++++++++ 7 files changed, 36 insertions(+), 4 deletions(-) diff --git a/NEWS.md b/NEWS.md index ac0fcce..5d5ef54 100644 --- a/NEWS.md +++ b/NEWS.md @@ -9,9 +9,15 @@ Enhancements * 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 diff --git a/R/ClassConstructors.R b/R/ClassConstructors.R index 73f2289..7d5f4b2 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}} 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/run.simulation.R b/R/run.simulation.R index 9513125..e5cba99 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -12,7 +12,11 @@ #' \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. +#' 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. #' #' Each repetition uses its own random number stream, so after calling #' \code{set.seed} results are identical whether run in serial or in parallel, 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/run.simulation-methods.Rd b/man/run.simulation-methods.Rd index 80b3e2d..af0a1f9 100644 --- a/man/run.simulation-methods.Rd +++ b/man/run.simulation-methods.Rd @@ -53,7 +53,11 @@ 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. +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. Each repetition uses its own random number stream, so after calling \code{set.seed} results are identical whether run in serial or in parallel, diff --git a/tests/testthat/test-check_Constructors.R b/tests/testthat/test-check_Constructors.R index 8d76bde..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() From a9794520b9ba5b150052682686e4508a043f5d76 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:05:16 -0700 Subject: [PATCH 24/30] feat: population generator hook and zero-detection handling (1.2.0) - make.simulation(population.generator = NULL): optional function(simulation, rep) called instead of generate.population() in each repetition. Returns a Population or list(population, truth). The RNG state is saved and restored around the call, the returned population is validated (class, columns, strata, inside design region) and the hook works with run.parallel = TRUE. - Per-repetition truth (N, D for the whole target area) is stored in results$truth and used by summary() for the total row; the realised N in the design region is stored in results$individuals$true.N. - make.ds.analysis(zero.n = c("fail", "zero")): with "zero" a repetition with no detections within truncation is recorded as an estimate of 0, counted as successful and flagged in results$Detection[, "ZeroDetections", ]. - summary() reports the source of the truth and the number of zero detection repetitions; CI coverage now uses the included repetitions rather than the first k. - Empty populations no longer give sf warnings when surveyed. - Defaults unchanged: results identical to d668415 for the same seed. Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 3 +- NEWS.md | 18 + R/ClassConstructors.R | 99 +++++- R/DS.Analysis.R | 14 +- R/Simulation.R | 140 ++++++-- R/Simulation.Summary.R | 25 +- R/Survey.LT.R | 4 + R/Survey.PT.R | 4 + R/accumulate.PP.results.R | 18 + R/add.summary.results.R | 41 ++- R/create.results.arrays.R | 16 +- R/population.generator.R | 314 ++++++++++++++++++ R/run.simulation.R | 9 +- R/single.sim.loop.R | 31 +- R/store.ddf.results.R | 3 + man/DS.Analysis-class.Rd | 5 + man/Simulation-class.Rd | 22 +- man/Simulation.Summary-class.Rd | 11 + man/make.ds.analysis.Rd | 16 +- man/make.simulation.Rd | 69 +++- man/run.simulation-methods.Rd | 6 + man/summary.Simulation-methods.Rd | 22 ++ .../fixtures/make-reference-d668415.R | 20 ++ tests/testthat/fixtures/reference-d668415.rds | Bin 0 -> 1507 bytes .../testthat/test-check_PopulationGenerator.R | 306 +++++++++++++++++ 25 files changed, 1162 insertions(+), 54 deletions(-) create mode 100644 R/population.generator.R create mode 100644 tests/testthat/fixtures/make-reference-d668415.R create mode 100644 tests/testthat/fixtures/reference-d668415.rds create mode 100644 tests/testthat/test-check_PopulationGenerator.R diff --git a/DESCRIPTION b/DESCRIPTION index cc46acd..92c4a79 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -24,7 +24,7 @@ Suggests: rmarkdown Type: Package Title: Distance Sampling Simulations -Version: 1.1.0 +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")) @@ -85,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/NEWS.md b/NEWS.md index 5d5ef54..7d2bed8 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,21 @@ +# 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`. + +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 diff --git a/R/ClassConstructors.R b/R/ClassConstructors.R index 7d5f4b2..1d48573 100755 --- a/R/ClassConstructors.R +++ b/R/ClassConstructors.R @@ -396,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 @@ -437,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) @@ -477,7 +491,7 @@ make.ds.analysis <- function(dfmodel = list(~1), # 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) } @@ -503,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 @@ -570,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, @@ -584,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 f78bcc4..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,6 +89,10 @@ 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", "unif"))){ return("All key function values should be 'hn', 'hr' or 'unif'.") 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 deb2c69..f99c023 100644 --- a/R/accumulate.PP.results.R +++ b/R/accumulate.PP.results.R @@ -7,6 +7,12 @@ extract.rep.result <- function(results, i){ ), 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( @@ -15,6 +21,9 @@ extract.rep.result <- function(results, i){ 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 @@ -25,11 +34,20 @@ apply.rep.result <- function(results, rep.result, i){ 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 } 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/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 e5cba99..0bb94da 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -18,6 +18,12 @@ #' \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. @@ -86,7 +92,8 @@ run.simulation <- function(simulation, run.parallel = TRUE, max.cores = NA, 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() diff --git a/R/single.sim.loop.R b/R/single.sim.loop.R index 32813f5..13062a0 100755 --- a/R/single.sim.loop.R +++ b/R/single.sim.loop.R @@ -19,7 +19,20 @@ single.sim.loop <- function(i, simulation, save.data, load.data, data.path = cha 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){ @@ -128,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 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/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/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.ds.analysis.Rd b/man/make.ds.analysis.Rd index 5e93acb..3c2b1d7 100644 --- a/man/make.ds.analysis.Rd +++ b/man/make.ds.analysis.Rd @@ -12,7 +12,8 @@ make.ds.analysis( er.var = "R2", control.opts = list(), group.strata = data.frame(), - criteria = "AIC" + criteria = "AIC", + zero.n = c("fail", "zero") ) } \arguments{ @@ -46,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 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 af0a1f9..f1ecaa5 100644 --- a/man/run.simulation-methods.Rd +++ b/man/run.simulation-methods.Rd @@ -59,6 +59,12 @@ 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. 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 0000000000000000000000000000000000000000..691d92f29f4193701fa9049c17e8e9fcb3848132 GIT binary patch literal 1507 zcmV<91swVxiwFP!000001Lc-$P*YbB$8R146j0DwK^O`?Iy6Xx@P6*$If8)l8Y)de zBsUNwMDie@h={0Qiv=sFjEaDWpo1Nejzd5ctXgmofvQxB2x_gPZKai>qG=#GU}-bs z7eDpP-0c7C+1v7YM>Yc~J;DF>7Mc zmSxMbnO>yMQCjd~=dVCBX!IA>mzeI?T!+w5$DaN;@XH18dHnTT zeX=BwNAABG>#$pM9pi(_QTp#XD_@uO2(y4wd808qtq>Y(donX$6%!f;S|H;@tR9J< z>4(tbYcGVHJ_U`&1VN_~({RwZe1X#F6Dn>f%4@={JtIs<8I}?! zAjL}kUyLzCWCCB9qV~>Gd+A;xGES{^eS~SGh~&QIV)*fRLXkv0qom--6qbN57PGi~ z@zmM|wV?WiVXDO>YkCr&HZf7%T^lFaV!_734hwrM9B``wG7dLD6?2upZ`3=5iG-Cg zA20P~BkvWtu*{*Z6QBnd=arA{ zOH4;XBY|_OfezXA!%g>BZBd~`QOv-OF^wHn@lKdAFr0p3311K=A*cSoDHWfFIZuvH#!@;Zsa)QB zf(C3#c+K1P6avk#=3KNQ4MPK#@>Ua$c_27K!&?7a-WVEiSe7&(Gx`qbhukk;^zXpX zfX&X7pxeFu;5OIMIH4{8Lj&xFf{L2bv%rY4Ok$$-7#gtJQYdh+{0&@Wh;c)ohoJ$7 zjTUJ?Ivoeb;G%EKE&VYxU=zG&oxCv`+-)vd9P6TCXn-xre->860Q&W3EhUkb7#gsu zNuty-w}A6emg0!JBZda-d=q!IQI~?&va)=8^ff#)!6 zH#uNPVFXzPk3|$~KL8gXO0!H?*6;y@rR;Y>7Q`JLUA`*B^?Y zB72*K?+5vs@23@WuZYsF%nurAlKCN*aUD1RO&q8^>po~;)S)r&p4lstb6zemypT<) z$hSZqy`GB;Mtz~2xya6x&(xSVq_uEozmyL{>FwvAG=(7d{-*ZOhptfGb3|vZp$Cpv zjLpceSkj)GP3J 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])) +}) From 281ed86337bf3d3959a68e02e5a3234bb821f1f8 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:43:43 -0700 Subject: [PATCH 25/30] fix: uniform key no longer errors when nobody is within truncation With key.function = "uf", a repetition with no individuals within the truncation distance of any transect passed NULL probabilities to rbinom() ("invalid arguments"), so the repetition was skipped. Skipping these repetitions biased sparse scenarios upwards. simulate.detections() now uses numeric(0), as hn and hr already do implicitly, so the repetition takes the usual no-detection path (failure with zero.n = "fail", estimate of 0 with zero.n = "zero"). Adds tests/testthat/test-check_UniformNoDetections.R, which fails on a979452 and passes with this fix. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 1 + R/simulate.detections.R | 4 ++- .../testthat/test-check_UniformNoDetections.R | 33 +++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/testthat/test-check_UniformNoDetections.R diff --git a/NEWS.md b/NEWS.md index 7d2bed8..821850f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -11,6 +11,7 @@ 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 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/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)) +}) From 8cb81d4968e0656b01982df3c4fcec01d069dec4 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:03:24 -0700 Subject: [PATCH 26/30] fix: restore the Density validity check Commit e443ce5 commented out the check that a density surface has some non-zero cells, together with a reformat of R/Density.R. Without it, an all-zero density is accepted and fails later in generate.population() with unclear errors ("NA in probability vector" or "object 'all.pop.locations' not found"). R/Density.R is now identical to upstream again, and test-check_Constructors.R passes. Co-Authored-By: Claude Opus 5.5 --- R/Density.R | 215 +++++++++++++++++++++++++--------------------------- 1 file changed, 105 insertions(+), 110 deletions(-) diff --git a/R/Density.R b/R/Density.R index 5df36aa..12b6902 100755 --- a/R/Density.R +++ b/R/Density.R @@ -21,78 +21,73 @@ #' @keywords classes #' @seealso \code{\link{make.density}} #' @export -setClass("Density", representation( - region.name = "character", - strata.name = "character", - density.surface = "list", - x.space = "numeric", - y.space = "numeric", - units = "character" -)) +setClass("Density", representation(region.name = "character", + strata.name = "character", + density.surface = "list", + x.space = "numeric", + y.space = "numeric", + units = "character")) #' @importFrom methods validObject is setMethod( - f = "initialize", - signature = "Density", - definition = function(.Object, region, strata.name = character(0), density.surface = list(), x.space, y.space, constant = NULL, model.fit = NULL, density.formula = character(0)) { + f="initialize", + signature="Density", + definition=function(.Object, region, strata.name = character(0), density.surface = list(), x.space, y.space, constant = NULL, model.fit = NULL, density.formula = character(0)){ # Create density surface - if (length(density.surface) == 0) { - density.surface <- get.density.surface( - region = region, - x.space = x.space, - y.space = y.space, - constant = constant, - model.fit = model.fit, - grid.formula = density.formula - ) + if(length(density.surface) == 0){ + density.surface <- get.density.surface(region = region, + x.space = x.space, + y.space = y.space, + constant = constant, + model.fit = model.fit, + grid.formula = density.formula) } - # Set slots + #Set slots .Object@region.name <- region@region.name .Object@strata.name <- strata.name .Object@density.surface <- list(density.surface) .Object@x.space <- x.space .Object@y.space <- y.space .Object@units <- region@units - # Check object is valid + #Check object is valid valid <- validObject(.Object, test = TRUE) - if (is(valid, "character")) { + if(is(valid, "character")){ stop(paste(valid), call. = FALSE) } # return object return(.Object) } ) -setValidity( - "Density", - function(object) { - # check region object exists and is of the correct class - # check strata object exists and is of the correct class - # check the density grid was created without problem +setValidity("Density", + function(object){ + #check region object exists and is of the correct class + #check strata object exists and is of the correct class + #check the density grid was created without problem some.strata.with.grids <- FALSE some.strata.with.no.grids <- FALSE density.sf <- object@density.surface[[1]] strata.names <- object@strata.name - for (i in seq(along = object@density.surface)) { + for(i in seq(along = object@density.surface)){ # Get densities for current strata densities <- density.sf$density[density.sf$strata == strata.names[i]] # Check if there are any negative values for density - if (any(densities < 0)) { + if(any(densities < 0)){ return("All density values must be positive!") } density.sum <- sum(densities) - # check there are some cells with non-zero density - # if(density.sum == 0){ - # return("All strata must have some cells with non-zero density. Check that you have correctly specified your density grid. Large grid spacing may also generate this error.") - # } - if (length(densities) > 0) { + #check there are some cells with non-zero density + if(density.sum == 0){ + return("All strata must have some cells with non-zero density. Check that you have correctly specified your density grid. Large grid spacing may also generate this error.") + } + if(length(densities) > 0){ some.strata.with.grids <- TRUE - } else { + }else{ some.strata.with.no.grids <- TRUE } } - if (some.strata.with.grids & some.strata.with.no.grids) { + if(some.strata.with.grids & some.strata.with.no.grids){ return("The grid spacing needs to be smaller, not all strata have points in them") - } else if (!some.strata.with.grids) { + }else if(!some.strata.with.grids){ return("There has been a problem generating the density grid. You must supply either a valid density surface, constant or valid density gam argument. DSM and formula are not currently suported") } return(TRUE) @@ -114,11 +109,11 @@ setValidity( #' with columns x, y and density. #' @export #' @rdname get.densities-methods -get.densities <- function(density, coords = FALSE) { +get.densities <- function(density, coords = FALSE){ dgrid <- density@density.surface[[1]] - if (coords) { + if(coords){ return(data.frame(x = dgrid$x, y = dgrid$y, density = dgrid$density)) - } else { + }else{ return(dgrid$densit) } } @@ -133,7 +128,7 @@ get.densities <- function(density, coords = FALSE) { #' @return returns the Density object with updated density values #' @export #' @rdname set.densities-methods -set.densities <- function(density, densities) { +set.densities <- function(density, densities){ density@density.surface[[1]]$density <- densities return(density) } @@ -142,24 +137,23 @@ set.densities <- function(density, densities) { #' @rdname add.hotspot-methods #' @export -setMethod( - "add.hotspot", "Density", - function(object, centre, sigma, amplitude) { - sf.density.df <- object@density.surface[[1]][, c("x", "y", "density")] - # Find distances from centre to each point on the density surface - dists <- sqrt((sf.density.df$x - centre[1])^2 + (sf.density.df$y - centre[2])^2) - # Calculate radial decay - additive.values <- (exp(-dists^2 / (2 * sigma^2))) * amplitude - # Add to current density values - new.densities <- sf.density.df$density + additive.values - # Put them back in sf object if they are non-negative - if (any(new.densities < 0)) { - warning("Adding this high / low spot to the density map would have resulted in negative densities. Object returned unchanged.") - return(object) - } - object@density.surface[[1]]$density <- new.densities - return(object) - } +setMethod("add.hotspot","Density", + function(object, centre, sigma, amplitude){ + sf.density.df <- object@density.surface[[1]][,c("x","y","density")] + # Find distances from centre to each point on the density surface + dists <- sqrt((sf.density.df$x-centre[1])^2 + (sf.density.df$y-centre[2])^2) + # Calculate radial decay + additive.values <- (exp(-dists^2/(2*sigma^2)))*amplitude + # Add to current density values + new.densities <- sf.density.df$density + additive.values + # Put them back in sf object if they are non-negative + if(any(new.densities < 0)){ + warning("Adding this high / low spot to the density map would have resulted in negative densities. Object returned unchanged.") + return(object) + } + object@density.surface[[1]]$density <- new.densities + return(object) + } ) @@ -183,13 +177,13 @@ setMethod( setMethod( f = "plot", signature = c("Density"), - definition = function(x, y, strata = "all", title = "", scale = 1) { + definition = function(x, y, strata = "all", title = "", scale = 1){ suppressWarnings(invisible(gc())) # Extract strata names strata.names <- x@strata.name # Extract plot data - if (is.character(strata)) { - if (!strata %in% c(x@strata.name, "all")) { + if(is.character(strata)){ + if(!strata %in% c(x@strata.name, "all")){ stop("You have provided an unrecognised strata name.", call. = FALSE) } } @@ -197,28 +191,27 @@ setMethod( density.surface <- x@density.surface[[1]] sf.column <- attr(density.surface, "sf_column") # Scaling plot - density.surface[, sf.column] <- density.surface[, sf.column] * scale + density.surface[, sf.column] <- density.surface[, sf.column]*scale - if (strata == "all") { - plot.data <- density.surface[, c("density", sf.column)] - if (title == "") { + if(strata == "all"){ + plot.data <- density.surface[,c("density", sf.column)] + if(title == ""){ title <- x@region.name } - } else if (is.numeric(strata)) { - plot.data <- density.surface[density.surface$strata == strata.names[strata], c("density", sf.column)] - if (title == "") { + }else if(is.numeric(strata)){ + plot.data <- density.surface[density.surface$strata == strata.names[strata],c("density", sf.column)] + if(title == ""){ title <- strata.names[strata] } - } else if (is.character(strata)) { - plot.data <- density.surface[density.surface$strata == strata, c("density", sf.column)] - if (title == "") { + }else if(is.character(strata)){ + plot.data <- density.surface[density.surface$strata == strata,c("density", sf.column)] + if(title == ""){ title <- strata } } # Create the plot object - ggplot.obj <- ggplot() + - theme_bw() + + ggplot.obj <- ggplot() + theme_bw() + geom_sf(data = plot.data, mapping = aes(fill = density, colour = density)) + scale_fill_viridis_c() + scale_colour_viridis_c() + @@ -250,14 +243,14 @@ setMethod( #' @exportMethod plot setMethod( f = "plot", - signature = c("Density", "Region"), - definition = function(x, y, strata = "all", title = "", scale = 1, line.col = gray(.2)) { + signature = c("Density","Region"), + definition = function(x, y, strata = "all", title = "", scale = 1, line.col = gray(.2)){ suppressWarnings(invisible(gc())) # Extract strata names strata.names <- x@strata.name # Extract plot data - if (is.character(strata)) { - if (!strata %in% c(x@strata.name, "all")) { + if(is.character(strata)){ + if(!strata %in% c(x@strata.name, "all")){ stop("You have provided an unrecognised strata name.", call. = FALSE) } } @@ -265,21 +258,21 @@ setMethod( density.surface <- x@density.surface[[1]] sf.column <- attr(density.surface, "sf_column") # Scaling plot - density.surface[, sf.column] <- density.surface[, sf.column] * scale + density.surface[, sf.column] <- density.surface[, sf.column]*scale - if (strata == "all") { - plot.data <- density.surface[, c("density", sf.column)] - if (title == "") { + if(strata == "all"){ + plot.data <- density.surface[,c("density", sf.column)] + if(title == ""){ title <- x@region.name } - } else if (is.numeric(strata)) { - plot.data <- density.surface[density.surface$strata == strata.names[strata], c("density", sf.column)] - if (title == "") { + }else if(is.numeric(strata)){ + plot.data <- density.surface[density.surface$strata == strata.names[strata],c("density", sf.column)] + if(title == ""){ title <- strata.names[strata] } - } else if (is.character(strata)) { - plot.data <- density.surface[density.surface$strata == strata, c("density", sf.column)] - if (title == "") { + }else if(is.character(strata)){ + plot.data <- density.surface[density.surface$strata == strata,c("density", sf.column)] + if(title == ""){ title <- strata } } @@ -288,12 +281,11 @@ setMethod( sf.region <- y@region sf.column <- attr(sf.region, "sf_column") # Scaling plot - sf.region[, sf.column] <- sf.region[, sf.column] * scale + sf.region[, sf.column] <- sf.region[, sf.column]*scale # Create the plot object - ggplot.obj <- ggplot() + - theme_bw() + - geom_sf(data = plot.data, mapping = aes(fill = density, colour = density)) + + ggplot.obj <- ggplot() + theme_bw() + + geom_sf(data = plot.data, mapping = aes(fill = density, colour=density)) + scale_fill_viridis_c() + scale_colour_viridis_c() + geom_sf(data = sf.region, fill = NA, color = line.col, lwd = 0.2) + @@ -319,30 +311,28 @@ setMethod( setMethod( f = "summary", signature = "Density", - definition = function(object, ...) { + definition = function(object, ...){ density.sf <- object@density.surface[[1]] # Get strata names strata.name <- unique(density.sf$strata) # For each strata - for (strat in seq(along = strata.name)) { + for(strat in seq(along = strata.name)){ # Get sf shapes relevant to current strata - strat.grid <- density.sf[density.sf$strata == strata.name[strat], ] + strat.grid <- density.sf[density.sf$strata == strata.name[strat],] # Find the areas and densities of each grid cell areas <- sf::st_area(strat.grid) # Obtain from sf shape as some grid cells may have been removed densities <- strat.grid$density # Find average abundance per grid cell - N <- areas * densities + N <- areas*densities # Create strata summary data - tmp.data <- data.frame( - strata = strata.name[strat], - area = sum(areas), - ave.N = sum(N), - ave.D = sum(N) / sum(areas) - ) - if (strat == 1) { + tmp.data <- data.frame(strata = strata.name[strat], + area = sum(areas), + ave.N = sum(N), + ave.D = sum(N)/sum(areas)) + if(strat == 1){ density.summary <- tmp.data - } else { + }else{ density.summary <- rbind(density.summary, tmp.data) } } @@ -350,10 +340,15 @@ setMethod( attributes(density.summary$ave.D) <- NULL # Create a new Density.Summary object - density.summary <- new( - Class = "Density.Summary", - summary = density.summary - ) + density.summary <- new(Class = "Density.Summary", + summary = density.summary) return(density.summary) } ) + + + + + + + From 49b79b6db87ce53ceb3f40105b53375560e56a2c Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:08:38 -0700 Subject: [PATCH 27/30] test: ignore empty transects when checking detection distances The test sets no seed, and dist.data contains a row with distance NA for every transect without detections, so all(distance <= 0.5) was NA and the test failed in about 1 in 5 runs (6 of 30 seeds, both on the fork and at 58d2d6a). No distance beyond the truncation was found. Co-Authored-By: Claude Opus 5.5 --- tests/testthat/test-ProblemCases.R | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 From c26577214cfa62b22c3616f7a6f161b286f3284d Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:09:51 -0700 Subject: [PATCH 28/30] fix: avoid the R CMD check NOTE for lib.paths in launch.daemons() mirai::everywhere() evaluated .libPaths(lib.paths) with lib.paths passed through `...`, which codetools reports as "no visible binding for global variable 'lib.paths'". The call is now built with call(), so the paths are sent as values. Workers still load the session's library (tested with the library path set only inside the session). Co-Authored-By: Claude Opus 5.5 --- R/run.simulation.R | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/R/run.simulation.R b/R/run.simulation.R index 0bb94da..4e7761f 100644 --- a/R/run.simulation.R +++ b/R/run.simulation.R @@ -222,8 +222,9 @@ launch.daemons <- function(max.cores){ 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 - mirai::everywhere(.libPaths(lib.paths), lib.paths = .libPaths(), - .min = nCores, .compute = "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" } From 212eb0abcebbb251d7c5c68866e7c36825944f46 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:41:30 -0700 Subject: [PATCH 29/30] docs: regenerate Detectability-class.Rd for the cov.param description Co-Authored-By: Claude Opus 5.5 --- man/Detectability-class.Rd | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/man/Detectability-class.Rd b/man/Detectability-class.Rd index 4fd074b..c341cfb 100644 --- a/man/Detectability-class.Rd +++ b/man/Detectability-class.Rd @@ -20,13 +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{"list"}; Named list of slope -coefficients (log scale) for individual-level covariates.} +\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 entries in \code{cov.param}.} +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.} From a6f6b854b9d6e48246581a87ed81cbb2753602b1 Mon Sep 17 00:00:00 2001 From: hambrecht <137965368+hambrecht@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:03:24 -0700 Subject: [PATCH 30/30] chore: remove local editor settings .vscode/settings.json is a local editor configuration and should not be part of the package (it also triggers an R CMD check NOTE). Co-Authored-By: Claude Opus 5.5 --- .vscode/settings.json | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 356bbae..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "chat.tools.terminal.autoApprove": { - "/^cd /home/lhambrec/dsims/dsims && Rscript -e \"library\\(methods\\); tryCatch\\(source\\('R/Detectability\\.R'\\), error=function\\(e\\) cat\\('ERROR:', conditionMessage\\(e\\), '\\\\n'\\)\\); cat\\('Detectability\\.R OK\\\\n'\\)\"$/": { - "approve": true, - "matchCommandLine": true - } - } -} \ No newline at end of file