Repository navigation
Conversation
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)
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.
- 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
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.
- 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
- 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
- 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)
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>
…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
- 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
- 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
- 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)
…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
…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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
… fix into master Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
.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 <noreply@anthropic.com>
There was a problem hiding this comment.
🟢 Approval recommended
The change is supported by broad updates across core implementation plus comprehensive corresponding test and documentation updates for the new parallelism, uniform key, population generator, and zero-detection behaviors, with no outstanding issues noted.
No open issues 🎉
4 files not reviewed
man/DS.Analysis-class.Rd: Generated fileman/Detectability-class.Rd: Generated fileman/Simulation-class.Rd: Generated fileman/Simulation.Summary-class.Rd: Generated file
What changed in this PR
Adds mirai-based parallel execution, a uniform key option, a per-repetition population generator hook with stored truth, and explicit handling of zero-detection repetitions, along with associated bug fixes and documentation/tests updates.
Changes:
- Switch parallel repetitions to mirai with reproducible per-repetition RNG streams and non-blocking error handling
- Add
key = "unif"support inmake.ds.analysis()(with covariate restrictions) - Add
make.simulation(population.generator=)with validation and optional per-rep truth capture used bysummary() - Add
zero.n = "zero"to record no-detection reps as estimate 0 instead of failures - Update results structures, summary calculations, tests, docs, and package metadata
| File | Description |
|---|---|
| vignettes/dsims-examples.Rmd | Updates the user-facing examples vignette to reflect new simulation/analysis options and behaviors. |
| tests/testthat/test-ProblemCases.R | Adjusts problem-case regression tests to cover updated edge-case handling and outcomes. |
| tests/testthat/test-Parallel.R | Updates parallel execution tests to validate mirai-based parallel runs and reproducibility behavior. |
| tests/testthat/test-check_UniformNoDetections.R | Adds/updates tests ensuring uniform key simulations handle no-detection cases correctly without failing. |
| tests/testthat/test-check_UniformKey.R | Adds tests validating the new uniform key option in make.ds.analysis() and its constraints. |
| tests/testthat/test-check_RasterCovariate.R | Updates raster covariate tests to remain compatible with revised simulation and results plumbing. |
| tests/testthat/test-check_PopulationGenerator.R | Adds comprehensive tests for the population generator hook, including reference comparisons and parallel/serial consistency. |
| tests/testthat/test-check_IndividualCovariates.R | Updates individual-covariate tests to align with changes in detection/simulation pipelines and result structures. |
| tests/testthat/test-check_Constructors.R | Extends/updates constructor validation tests for new arguments and stricter input checks. |
| tests/testthat/fixtures/make-reference-d668415.R | Adds a fixture script to generate/store reference outputs used by the new population generator tests. |
| R/Survey.PT.R | Updates point-transect survey execution to integrate with revised simulation loops and result accumulation. |
| R/Survey.LT.R | Updates line-transect survey execution to integrate with revised simulation loops and result accumulation. |
| R/store.ddf.results.R | Adjusts how Distance Sampling model outputs are stored to support new result fields and zero-detection handling. |
| R/single.sim.loop.R | Refactors the per-repetition simulation loop to support mirai parallelism, error isolation, and generator hooks. |
| R/Simulation.Summary.R | Updates summary computation and reporting to incorporate stored truth, exclusions, and zero-detection repetitions. |
| R/Simulation.R | Updates the Simulation class logic to accommodate new options and downstream result fields. |
| R/simulate.detections.R | Modifies detection simulation to support the uniform key path and robust handling of sparse/no-detection scenarios. |
| R/run.simulation.R | Reworks the simulation runner to use mirai parallel execution by default while preserving reproducibility semantics. |
| R/population.generator.R | Introduces support code for user-supplied population generators, including validation and truth capture handling. |
| R/Population.Description.R | Tightens population description validation (including whole-number N requirements under fixed-N) and related checks. |
| R/DS.Analysis.R | Adds support for key = "unif" and zero.n behavior and enforces documented constraints (e.g., covariates). |
| R/Detectability.R | Adjusts detectability logic to align with the new key options and updated simulation/analysis plumbing. |
| R/create.results.arrays.R | Extends result array initialization to include new fields (e.g., truth storage and zero-detection flags). |
| R/ClassConstructors.R | Updates class constructors to accept and validate newly introduced arguments and defaults. |
| R/check.simulation.R | Enhances simulation input checks to cover new configuration options and stricter validation rules. |
| R/calculate.scale.param.R | Updates scale parameter calculations as needed for compatibility with revised key handling and downstream analyses. |
| R/calc.rad.dists.R | Adjusts radial distance calculations to support updated detection function paths and robustness fixes. |
| R/calc.perp.dists.R | Adjusts perpendicular distance calculations to support updated detection function paths and robustness fixes. |
| R/add.summary.results.R | Updates summary aggregation to correctly incorporate included repetitions and handle zero-detection estimates. |
| R/accumulate.PP.results.R | Updates post-processing accumulation to correctly merge per-rep results, truth, and detection metadata. |
| NEWS.md | Adds release notes entries describing the new parallelism, generator hook, zero-detection handling, and bug fixes. |
| NAMESPACE | Updates exported/imported symbols as needed for new functionality and package checks. |
| man/summary.Simulation-methods.Rd | Updates documentation for summary() to describe truth sourcing, exclusions, and zero-detection inclusion rules. |
| man/Simulation.Summary-class.Rd | Updates the Simulation.Summary class documentation to reflect new stored fields and behaviors. |
| man/Simulation-class.Rd | Updates the Simulation class documentation for new options and runtime behavior changes. |
| man/run.simulation-methods.Rd | Updates run.simulation method documentation to reflect mirai parallel behavior, defaults, and error handling. |
| man/make.simulation.Rd | Documents the new population.generator option and associated behavior/requirements. |
| man/make.population.description.Rd | Documents stricter validation behavior for population descriptions (including fixed-N whole-number requirements). |
| man/make.ds.analysis.Rd | Documents key = "unif" and zero.n options and their constraints/effects on results. |
| man/make.detectability.Rd | Updates detectability documentation to match the expanded set of key and simulation behaviors. |
| man/DS.Analysis-class.Rd | Updates DS.Analysis class documentation to include new configuration fields and their meaning. |
| man/Detectability-class.Rd | Updates Detectability class documentation to reflect any new/changed fields and behavior. |
| DESCRIPTION | Updates package metadata to include new imports/suggests and versioning aligned with the added functionality. |
| bench/benchmark.R | Adds a benchmarking script to compare performance before/after the parallel execution changes (excluded from builds). |
| .Rbuildignore | Updates build ignore rules to exclude benchmark and other non-build artifacts. |
| .gitignore | Updates git ignore entries to account for new generated or local development artifacts. |
Review effort: Balanced
Copilot was unable to complete this review at the selected tier due to model policy or plan restrictions.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR builds on #100 and adds the work done in my fork since then (versions 1.1.0 and 1.2.0 in NEWS.md):
make.ds.analysis(key = "unif")gives the strip transect estimate.make.simulation(population.generator = )lets the user supply each repetition's population. The per-repetition true N/D are stored and used bysummary().make.ds.analysis(zero.n = "zero")records a repetition with no detections as an estimate of 0 instead of a failure.cov.surface). Lower memory use with large rasters in parallel runs, and corrected documentation. The feature itself is in Feature: spatially explicit detectability covariates through a new cov.surface interface #99.Please merge #99 and #100 first, in that order. #100 already contains #99 (the
cov.surfaceraster covariate feature), and this PR builds on #100. Until they are merged, this PR's diff also contains their changes. The changes since #100 alone are here: hambrecht/dsims@perf/parallel-major-improvements...pr/population-hookThe commit list is not a clean history. It also contains older commits from my fork. Their changes are either already in #99/#100 or undone again in this PR (e.g. e443ce5, which disabled the Density validity check, is reverted by 8cb81d4). A squash merge is probably easiest.
All new options default to the previous behaviour. With the population generator and
zero.nleft at their defaults, results are identical to 1.1.0 for the same seed. (Results change compared with 1.0.6 because of the new random number streams; see Breaking changes.)Changes
1.1.0: parallel processing and uniform key
run.parallel = TRUEis the default. The number of workers isparallelly::availableCores(omit = 1), which respects HPC and container limits. Daemons set up by the user withmirai::daemons()(including remote ones) are used if present.set.seed(), results are identical in serial and in parallel, for any number of workers.make.ds.analysis()acceptskey = "unif"(or"uf"). Covariates are not allowed with it. The documentation already listed uniform, but only"hn"and"hr"were accepted.bench/benchmark.Ris a before/after benchmark script (excluded from the build).1.2.0: population generator and zero detections
make.simulation(population.generator = NULL). Afunction(simulation, rep)called in each repetition instead ofgenerate.population(simulation). It returns aPopulation, orlist(population = , truth = list(N = , D = )).results$truth.summary()uses it for the truth, bias, RMSE and CI coverage of the total abundance/density, and prints where the truth came from.results$individuals$true.N(andresults$clusters$true.N).make.ds.analysis(zero.n = c("fail", "zero")). With"zero", a repetition with no detections within truncation is recorded as Estimate 0 (lcl 0; se, cv and ucl NA; n = 0, with the effort and covered area as usual). It is flagged in a newZeroDetectionscolumn ofresults$Detection.summary()includes these repetitions in the mean, SD, bias and RMSE. CI coverage uses only repetitions with a defined CI.Raster covariates (
cov.surface, from #99/#100)terra::values()of the whole raster in every worker. With a 10 m canopy raster (73 million cells) and 31 workers, this ran out of memory ("cannot allocate vector of size 233 Mb"). The cache now holds only the raster handle, andterra::extract()reads the values at the animal locations, loading only the blocks it needs (c05c025). Results are unchanged, and the raster covariate tests pass as before.Detectabilityclass docs now describecov.paramas a named list of numeric vectors (continuous/discrete covariates) or data.frames (categorical covariates). Before, they said "numeric ... Not yet implemented". The docs also now cover thecov.surfaceslot. This takes over the review fix made on Feature: spatially explicit detectability covariates through a new cov.surface interface #99 (971b41a), and the Rd file is regenerated (212eb0a).Bug fixes
N. Withfixed.N = TRUE, a fractionalNwas silently rounded up per stratum while the unroundedNwas used as the truth.make.population.description()now stops ifNis not a whole number withfixed.N = TRUE.summary()computed CI coverage from the first k repetitions instead of the k included ones when some repetitions were excluded.key.function = "uf", a repetition with no individuals within truncation of any transect errored inrbinom()("invalid arguments") and was skipped. Skipping these repetitions biased sparse scenarios upwards.sfwarnings.launch.daemons()no longer triggers the "no visible binding for global variable" NOTE.dist.data. It now usesna.rm = TRUE. No distance beyond truncation occurred in 30 seeds.Breaking changes
Nmust be a whole number whenfixed.N = TRUE.results$Detectionhas an 8th column,ZeroDetections(0 unlesszero.n = "zero").mirai::daemon(...)processes instead of PSOCK workers.Testing
test-check_PopulationGenerator.R, including a comparison against reference results saved from 1.1.0, and serial vs parallel runs;test-check_UniformKey.R;test-check_UniformNoDetections.R;test-Parallel.Randtest-check_Constructors.R.R CMD check --no-manual --ignore-vignettes(with_R_CHECK_FORCE_SUGGESTS_=false, as bookdown and lwgeom aren't installed here): Status: OK, with no errors, warnings or notes (tests: PASS 234, SKIP 1 = the parallel test skipped on CRAN).Notes for review
importFromline.🤖 Generated with Claude Code