Skip to content

Parallel runs with mirai, uniform key, population generator hook and zero-detection estimates - #101

Open
hambrecht wants to merge 38 commits into
DistanceDevelopment:masterfrom
hambrecht:pr/population-hook
Open

hambrecht wants to merge 38 commits into
DistanceDevelopment:masterfrom
hambrecht:pr/population-hook

Conversation

@hambrecht

@hambrecht hambrecht commented Nov 25, 2026 •

Copy link
Copy Markdown

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):

  • Parallel processing with mirai. Repetitions run on mirai daemons, parallel by default, with reproducible per-repetition random number streams. A failing repetition no longer stops the simulation.
  • Uniform key. make.ds.analysis(key = "unif") gives the strip transect estimate.
  • Population generator hook. make.simulation(population.generator = ) lets the user supply each repetition's population. The per-repetition true N/D are stored and used by summary().
  • Zero-detection estimates. make.ds.analysis(zero.n = "zero") records a repetition with no detections as an estimate of 0 instead of a failure.
  • Raster covariates (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.
  • Bug fixes, listed below.

Please merge #99 and #100 first, in that order. #100 already contains #99 (the cov.surface raster 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-hook

The 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.n left 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

  • Parallel processing uses mirai instead of a PSOCK cluster. Repetitions go to workers as they become free, and workers start faster.
  • run.parallel = TRUE is the default. The number of workers is parallelly::availableCores(omit = 1), which respects HPC and container limits. Daemons set up by the user with mirai::daemons() (including remote ones) are used if present.
  • Each repetition has its own L'Ecuyer random number stream. After set.seed(), results are identical in serial and in parallel, for any number of workers.
  • A repetition that errors is skipped and reported in the warnings/errors summary instead of stopping the simulation.
  • The progress counter works in parallel and shows the elapsed and estimated remaining time.
  • make.ds.analysis() accepts key = "unif" (or "uf"). Covariates are not allowed with it. The documentation already listed uniform, but only "hn" and "hr" were accepted.
  • bench/benchmark.R is a before/after benchmark script (excluded from the build).

1.2.0: population generator and zero detections

  • make.simulation(population.generator = NULL). A function(simulation, rep) called in each repetition instead of generate.population(simulation). It returns a Population, or list(population = , truth = list(N = , D = )).
    • The returned population is checked: class, required columns, no NAs, unique IDs, strata names, and locations inside their stratum.
    • The RNG state is saved and restored around the call. The generator can use its own seed stream, and the transects, detections and analyses don't depend on how many random numbers it uses.
    • It works in parallel. The docs describe what a generator needs to run on workers.
  • Truth. With a generator that returns truth, the per-repetition truth is stored in 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.
  • Realised N. The realised number of individuals per stratum and repetition is now stored in results$individuals$true.N (and results$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 new ZeroDetections column of results$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)

Bug fixes

  • Fractional N. With fixed.N = TRUE, a fractional N was silently rounded up per stratum while the unrounded N was used as the truth. make.population.description() now stops if N is not a whole number with fixed.N = TRUE.
  • CI coverage. summary() computed CI coverage from the first k repetitions instead of the k included ones when some repetitions were excluded.
  • Uniform detection function, nobody in the covered area. With key.function = "uf", a repetition with no individuals within truncation of any transect errored in rbinom() ("invalid arguments") and was skipped. Skipping these repetitions biased sparse scenarios upwards.
  • Empty populations. Surveying a population with no individuals no longer gives sf warnings.
  • R CMD check NOTE. launch.daemons() no longer triggers the "no visible binding for global variable" NOTE.
  • Flaky test. The "detections greater than truncation" test failed in about 1 in 5 runs: it sets no seed, and transects without detections are rows with distance NA in dist.data. It now uses na.rm = TRUE. No distance beyond truncation occurred in 30 seeds.

Breaking changes

  • Results for a given seed differ from 1.0.6, because the random number streams have changed.
  • N must be a whole number when fixed.N = TRUE.
  • results$Detection has an 8th column, ZeroDetections (0 unless zero.n = "zero").
  • Workers show up as mirai::daemon(...) processes instead of PSOCK workers.
  • Imports: mirai, parallel and parallelly are new; rstudioapi is no longer imported.

Testing

  • New test files:
    • 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;
    • additions to test-Parallel.R and test-check_Constructors.R.
  • Full test suite: all 50 tests pass (260 expectations), including the parallel tests.
  • 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).
  • Parallel tests need the version being tested installed in a library the workers can find, because mirai daemons are separate R processes. They are skipped on CRAN.

Notes for review

  • The version is set to 1.2.0 and NEWS.md has entries for 1.1.0 and 1.2.0. Please renumber as you see fit.
  • Rd files were regenerated with roxygen2. NAMESPACE was left as it was, because roxygen2 8.x rewrites every importFrom line.

🤖 Generated with Claude Code

hambrecht and others added 30 commits July 26, 2024 12:21
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>
hambrecht and others added 8 commits November 17, 2026 16:05
- 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>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 00:04

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 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 file
  • man/Detectability-class.Rd: Generated file
  • man/Simulation-class.Rd: Generated file
  • man/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 in make.ds.analysis() (with covariate restrictions)
  • Add make.simulation(population.generator=) with validation and optional per-rep truth capture used by summary()
  • 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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants