From edd15f5158dbefaa07c6763c15dcca99e293399e Mon Sep 17 00:00:00 2001 From: "Barry W. Brook" Date: Fri, 4 Dec 2026 19:46:54 +1100 Subject: [PATCH 1/3] Release OpenPVA 2.4.0: ergonomic authoring layer, static formula compiler, and cookbook --- AGENTS.md | 14 +- DESCRIPTION | 6 +- NAMESPACE | 26 + NEWS.md | 73 ++ R/ensemble.R | 93 +- R/formula.R | 498 +++++++++ R/lifecycle.R | 48 +- R/mating.R | 6 +- R/mating_process.R | 3 +- R/model.R | 1197 +++++++++++++++++++++ R/model_audit.R | 178 +++ R/pedigree.R | 3 +- R/process.R | 35 +- R/processes_demography.R | 106 +- R/processes_environment.R | 28 +- R/processes_management.R | 18 +- R/rates.R | 287 ++++- R/scenario.R | 28 +- R/spatial.R | 3 +- R/state.R | 5 +- R/survey.R | 9 +- README.md | 102 +- docs/design/lifecycle_process_contract.md | 31 +- docs/for-agents.md | 74 +- docs/reference/public_api.md | 45 +- docs/vision_and_scope.md | 36 +- man/age_sex_rate.Rd | 15 +- man/demography_processes.Rd | 6 +- man/lifecycle.Rd | 11 +- man/lifecycle_steps.Rd | 318 ++++++ man/management_processes.Rd | 4 +- man/model_audit.Rd | 51 + man/print.pva_state.Rd | 14 +- man/pva_model.Rd | 102 ++ man/pva_process.Rd | 4 +- man/run_pva_ensemble.Rd | 10 +- scripts/build_rd.R | 14 +- scripts/build_site.R | 2 + scripts/check_r_floor.R | 52 +- scripts/rd_topics.R | 244 ++++- site/_litedown.yml | 5 +- site/articles.Rmd | 2 +- site/index.Rmd | 2 +- site/manual.Rmd | 2 +- tests/testthat/helper-models.R | 340 ++++++ tests/testthat/test-b4-compilation.R | 245 +++++ tests/testthat/test-b4-ensemble-audit.R | 124 +++ tests/testthat/test-b4-rates-formulas.R | 156 +++ tests/testthat/test-model-authoring.R | 408 +++++++ tests/testthat/test-model-diagnostics.R | 265 +++++ tests/testthat/test-model-oracles.R | 124 +++ tests/testthat/test-model-parity.R | 138 +++ vignettes/cookbook.Rmd | 485 +++++++++ vignettes/rosetta.Rmd | 11 +- vignettes/workflow.Rmd | 15 +- 55 files changed, 5897 insertions(+), 224 deletions(-) create mode 100644 R/formula.R create mode 100644 R/model.R create mode 100644 R/model_audit.R create mode 100644 man/lifecycle_steps.Rd create mode 100644 man/model_audit.Rd create mode 100644 man/pva_model.Rd create mode 100644 tests/testthat/helper-models.R create mode 100644 tests/testthat/test-b4-compilation.R create mode 100644 tests/testthat/test-b4-ensemble-audit.R create mode 100644 tests/testthat/test-b4-rates-formulas.R create mode 100644 tests/testthat/test-model-authoring.R create mode 100644 tests/testthat/test-model-diagnostics.R create mode 100644 tests/testthat/test-model-oracles.R create mode 100644 tests/testthat/test-model-parity.R create mode 100644 vignettes/cookbook.Rmd diff --git a/AGENTS.md b/AGENTS.md index f16c54c..7a5b147 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,15 +12,23 @@ OpenPVA is a modern, open-R descendant of the GAPPS construction philosophy—bu so conservation biologists (and their AI agents) can compose transparent, inspectable, individual-based Population Viability Analyses in ordinary R. -## Core architecture (OpenPVA 2.3.0) +## Core architecture (OpenPVA 2.4.0) - **One unified, pure-base-R engine:** `NeedsCompilation: no`, `Depends: R (>= 4.1.0)`, and runtime `Imports` restricted to base/recommended packages (`codetools`, `graphics`, `grDevices`, `parallel`, `stats`, `tools`, `utils`), with only `litedown` and `testthat` in `Suggests` (`VignetteBuilder: litedown`). Do not - add `dplyr`, `tibble`, `ggplot2`, `renv` boilerplate, a lifecycle DSL, a global - registry, an S4/R6 hierarchy, or a second compiled sidecar engine unless a + add `dplyr`, `tibble`, `ggplot2`, `renv` boilerplate, a YAML/external lifecycle DSL, + a global registry, an S4/R6 hierarchy, or a second compiled sidecar engine unless a measured, unavoidable bottleneck proves pure R inadequate. +- **Ergonomic blueprint layer compiling to native processes:** `pva_model()` separates + parameter-evidence, vital-rate, and initial cohort tables (`cohort_population()`) from + an ordered, copy-on-modify `step_*()` pipeline using statically compiled one-sided `~` + formulas (`R/formula.R`, `R/model.R`, `R/model_audit.R`). `compile_scenario()` lowers + every authored model into standard `pva_process()` and `scenario_spec()` objects with + zero hidden global state, zero runtime `eval()`, and seamless custom `step_process()` + interoperability; `run_pva_ensemble()` accepts blueprints or named structural model lists + directly (`seed_by = TRUE`). - **Direct ordered process list:** A lifecycle is an ordinary ordered list of `pva_process()` objects declaring `requires`, `writes`, and `creates`. Community processes compose through the exact same public contract without controller edits. diff --git a/DESCRIPTION b/DESCRIPTION index a1a94b7..d68296e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: OpenPVA Title: Composable Individual-Based Population Viability Analysis -Version: 2.3.0 +Version: 2.4.0 Authors@R: person("Barry W.", "Brook", email = "barry.brook@utas.edu.au", role = c("aut", "cre", "cph")) @@ -17,6 +17,10 @@ Description: An execution engine for individual-based population viability variation, catastrophes, density feedback and inbreeding depression. Optional neutral loci are dropped through the simulated pedigree to report heterozygosity, allelic retention and founder representation. + A model-authoring layer keeps parameter, vital-rate and cohort tables + apart from an ordered pipeline of lifecycle steps written as one-sided + formulas, which are checked and compiled once into the same process + objects, with audits of where every parameter is used. Ensemble helpers separate structural and parametric designs from Monte Carlo replicates and report viability summaries with Monte Carlo standard errors, and base-graphics plot methods display lifecycle flow diff --git a/NAMESPACE b/NAMESPACE index 29b3e44..3938586 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -2,10 +2,16 @@ S3method("[",pva_ensemble) S3method("[",pva_lifecycle) S3method(plot,pva_ensemble) S3method(plot,pva_lifecycle) +S3method(plot,pva_model) S3method(plot,pva_run) S3method(plot,pva_scenario) +S3method(print,pva_deferred) S3method(print,pva_ensemble) +S3method(print,pva_formula) S3method(print,pva_lifecycle) +S3method(print,pva_model) +S3method(print,pva_model_audit) +S3method(print,pva_parameters) S3method(print,pva_process) S3method(print,pva_run) S3method(print,pva_scenario) @@ -20,7 +26,11 @@ export(catastrophe_process) export(ceiling_density_multiplier) export(ceiling_process) export(census_process) +export(cohort_population) +export(compile_scenario) export(describe_lifecycle) +export(describe_model) +export(describe_parameters) export(dispersal_process) export(env_ar1) export(env_trend) @@ -47,6 +57,7 @@ export(offspring_sex_bernoulli) export(pairing_process) export(patch_counts) export(pva_events) +export(pva_model) export(pva_population) export(pva_process) export(pva_result) @@ -62,6 +73,21 @@ export(sex_ratio_effective_size) export(shift_logit) export(spatial_correlation) export(staged_survival_process) +export(step_age) +export(step_assign) +export(step_catastrophe) +export(step_ceiling) +export(step_census) +export(step_dispersal) +export(step_environment) +export(step_introduce) +export(step_mating) +export(step_pairing) +export(step_process) +export(step_remove) +export(step_reproduction) +export(step_survey) +export(step_survival) export(summarise_accounting) export(summarise_markers) export(summarise_pedigree) diff --git a/NEWS.md b/NEWS.md index 0234a40..89ba861 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,78 @@ # OpenPVA news +## OpenPVA 2.4.0 + +- Model authoring from separated inputs: `pva_model()` holds a parameter list + or parameter-evidence table (extra columns such as `unit` and `source` are + kept), one or more vital-rate tables, the initial population (a cohort-count + table, a founder table, a population or a function) and typed defaults for + custom individual fields. Fifteen pipeable builders add the ordered + lifecycle: `step_environment()`, `step_catastrophe()`, `step_survival()` + (ordinary or staged), `step_age()`, `step_pairing()`, `step_mating()`, + `step_reproduction()`, `step_dispersal()`, `step_survey()`, `step_remove()`, + `step_ceiling()`, `step_introduce()`, `step_assign()`, `step_census()` and + `step_process()`, which inserts any native or custom `pva_process()` (or a + `function(params)` returning one) at an exact position. Every step takes + `enabled` (a compile-time switch) and `when` (an interval schedule). + Declare parameters read indirectly by a callback or factory with `uses`. + Factories run once per enabled step and must be deterministic. Skipped + surveys emit `survey_skip`. Skipped catastrophes reset their flag. +- One-sided formulas replace routine callbacks: `~ rate("p_surv")`, + `~ age >= maturity`, `~ if (observed < trigger) release_size else 0`. + `compile_scenario()` resolves each formula once against the model's + parameters, population fields, globals, `time`, `dt`, `n_steps`, `N`, + `rate("")` lookups and a fixed list of pure functions, and rewrites + it into an ordinary closure bound to the package namespace, with the + process's `requires` derived from what it reads. Nothing is evaluated per + interval beyond that closure, and nothing is captured from the workspace. + The result is a standard `pva_scenario`. Compilation always checks the + process plan and records the default execution mode (`"strict"` or `"fast"`). + `env_ar1()`, `env_trend()`, `spatial_correlation()`, the litter, + offspring-sex and mate helpers and `survey_quota()` accept formulas for + their own arguments inside a step. +- Fail-fast diagnostics at compile time, before any random number is drawn: + unknown or misspelled symbols (with a suggestion), names shared between + parameters, fields, globals and reserved words, impure code in a formula, + rate tables with overlapping or missing age classes, a missing sex or a + probability outside [0, 1], invalid cohort counts, untyped field defaults, + a step that reads a global written only by a disabled step, a + `survey_quota()` before its survey, unknown overrides and overrides that + cannot affect the scenario. Unused base parameters are reported by the + audit, not rejected. +- `run_pva_ensemble()` accepts a `pva_model` as `build` (design columns + override parameters by name; `NA` leaves the base value) or a named list of + models selected by a `model` column for structural comparisons, validates + every design row before drawing a seed, and takes `seed_by = TRUE` to pair + all rows on one seed. A declared parameter can also be a seed-block column, + `label` or `scenario`. Each cache entry tracks its own selected model. +- Audit: `describe_model()` and `describe_parameters()` report cohorts, + fields, each step's formulas with the values bound into them, and for every + parameter its base and effective value, consuming steps, status and evidence + columns. Base and effective values retain matrix cells and dimnames. + The optional `life_table_metrics()` check projects the authored rates. `describe_lifecycle()`, `format_lifecycle()` and `plot()` accept a + `pva_model`; the text summary lists authored formulas. +- Native API additions, all backwards compatible: `pva_process(role = )`, with + every built-in constructor declaring its role on the process object, so + `describe_lifecycle()` reads a stored role instead of re-deriving one. Each + constructor declares the role 2.3.0 displayed for that process, so lifecycle + tables and diagrams of existing native models are unchanged; `age_sex_rate()` and `validate_age_sex_table()` accept + an `age` column written as `"0"`, `"1-2"` or `"3+"`, `sex = "All"` and + stratifying columns through `by`; `introduction_process(fields = )` and + `reproduction_process(newborn_fields = )` accept plain named lists; + `census_process(metrics = )` accepts a named list of conditions and values; + `cohort_population()` expands cohort counts into a population. +- Documentation: new `vignette("cookbook", package = "OpenPVA")`, a + model-building guide that uses tables and ordered steps only; README + quickstart rewritten around `pva_model()`; the grizzly blurb corrected + (mating, harvest and birth share one interval); four missing `requires` + declarations added to the seasonal-herd example in `vignette("rosetta")`; + the workflow vignette runs 20 replicates per scenario instead of 40 to keep + the three vignettes inside CRAN's build time. +- *Development provenance:* this release was implemented and verified by + Anthropic Claude (Claude Fable 5.2, running in Claude Code) working + autonomously to a charter set by Barry W. Brook, on top of the unchanged + `2.3.0` simulation core. + ## OpenPVA 2.3.0 - Visual lifecycle translation and inspection: `describe_lifecycle()` audits any diff --git a/R/ensemble.R b/R/ensemble.R index 875d559..f2f63d6 100644 --- a/R/ensemble.R +++ b/R/ensemble.R @@ -275,8 +275,14 @@ run_pva_ensemble <- function( if (!is.data.frame(design) || !nrow(design)) { .stop("design must be a data frame with one row per ensemble member") } - if (!is.function(build)) { - .stop("build must be a function of one design row returning scenario components") + if (!is.null(seed_by) && !.is_flag(seed_by) && + (!is.character(seed_by) || !all(seed_by %in% names(design)))) { + .stop("seed_by must be TRUE or name design columns") + } + models <- .ensemble_models(build) + if (is.null(models) && !is.function(build)) { + .stop("build must be a pva_model, a named list of models, or a function of one design row ", + "returning scenario components") } if (is.null(summarise)) { summarise <- .default_ensemble_summary @@ -288,9 +294,10 @@ run_pva_ensemble <- function( validation <- match.arg(validation) n_runs <- .as_count(n_runs, "n_runs", minimum = 1) workers <- .as_count(workers, "workers", minimum = 1) - if (!is.null(seed_by) && - (!is.character(seed_by) || !all(seed_by %in% names(design)))) { - .stop("seed_by must name design columns") + members <- NULL + if (!is.null(models)) { + members <- .model_members(models, design, seed_by, n_runs, validation) + build <- NULL } if (!is.null(cache_dir)) { if (!.is_name(cache_dir)) { @@ -303,8 +310,10 @@ run_pva_ensemble <- function( } n_members <- nrow(design) - block <- if (is.null(seed_by)) { + block <- if (is.null(seed_by) || isFALSE(seed_by)) { seq_len(n_members) + } else if (isTRUE(seed_by)) { + rep.int(1L, n_members) } else { keys <- do.call(paste, c(unname(as.list(design[seed_by])), sep = "\r")) match(keys, unique(keys)) @@ -318,22 +327,31 @@ run_pva_ensemble <- function( rng_header <- .GlobalEnv$.Random.seed[1L] block_seeds <- sample.int(.Machine$integer.max, max(block)) member_seeds <- block_seeds[block] + model_fingerprints <- NULL revision <- if (!is.null(cache_dir)) { + if (!is.null(models)) { + fingerprints <- vapply(models, .callback_bindings, character(1), fingerprint = TRUE) + selected <- if (is.null(names(models))) rep.int(1L, n_members) else as.character(design[["model"]]) + model_fingerprints <- unname(fingerprints[selected]) + } list(validation = validation, package_version = version, r_version = R.version.string, rng_kind = rng_kind, callbacks = .callback_bindings(list(build, summarise), fingerprint = TRUE), cache_key = cache_key) } + items <- lapply(seq_len(n_members), function(i) { + list(index = i, row = as.list(design[i, , drop = FALSE]), seed = member_seeds[[i]], + scenario = members[[i]], model_fingerprint = model_fingerprints[[i]]) + }) payload <- list( - design = design, build = build, summarise = summarise, n_runs = n_runs, - seeds = member_seeds, rng_header = rng_header, validation = validation, cache_dir = cache_dir, - revision = revision + build = build, summarise = summarise, n_runs = n_runs, rng_header = rng_header, + validation = validation, cache_dir = cache_dir, revision = revision ) summaries <- .dispatch( - seq_len(n_members), .member_worker, payload, + items, .member_worker, payload, parallel = workers > 1L || !is.null(cluster), workers = min(workers, n_members), backend = backend, cluster = cluster, - preschedule = FALSE + preschedule = FALSE, models = models ) }) sizes <- vapply(summaries, nrow, integer(1)) @@ -359,10 +377,12 @@ run_pva_ensemble <- function( out } -.member_worker <- function(member, payload) { - row <- payload$design[member, , drop = FALSE] - seed <- payload$seeds[[member]] - key <- list(row = as.list(row), seed = seed, n_runs = payload$n_runs, revision = payload$revision) +.member_worker <- function(item, payload) { + member <- item$index + row <- item$row + seed <- item$seed + key <- list(row = row, seed = seed, n_runs = payload$n_runs, revision = payload$revision) + if (!is.null(item$model_fingerprint)) key$model <- item$model_fingerprint path <- if (is.null(payload$cache_dir)) { NULL } else { @@ -377,27 +397,30 @@ run_pva_ensemble <- function( summary <- .with_rng_restored({ .set_pva_seed(seed, payload$rng_header) assign(".Random.seed", parallel::nextRNGSubStream(.GlobalEnv$.Random.seed), envir = .GlobalEnv) - components <- payload$build(as.list(row)) - if (!is.list(components) || - !all(c("init_fun", "processes", "n_steps") %in% names(components))) { - .stop("build must return a list with init_fun, processes and n_steps") + if (is.function(payload$build)) { + components <- payload$build(row) + if (!is.list(components) || + !all(c("init_fun", "processes", "n_steps") %in% names(components))) { + .stop("build must return a list with init_fun, processes and n_steps") + } + scenario <- scenario_spec( + name = paste0("member-", member), + n_runs = payload$n_runs, + n_steps = components$n_steps, + init_fun = components$init_fun, + processes = components$processes, + seed = seed, + dt = if (is.null(components$dt)) 1 else components$dt, + initial_census = components$initial_census + ) + keep <- if (is.null(components$keep)) "census" else components$keep + } else { + scenario <- item$scenario + scenario$seed <- seed + keep <- "census" } - scenario <- scenario_spec( - name = paste0("member-", member), - n_runs = payload$n_runs, - n_steps = components$n_steps, - init_fun = components$init_fun, - processes = components$processes, - seed = seed, - dt = if (is.null(components$dt)) 1 else components$dt, - initial_census = components$initial_census - ) - result <- run_scenario( - scenario, - validation = payload$validation, - keep = if (is.null(components$keep)) "census" else components$keep - ) - payload$summarise(result, as.list(row)) + result <- run_scenario(scenario, validation = payload$validation, keep = keep) + payload$summarise(result, row) }) if (!is.data.frame(summary) || !nrow(summary)) { .stop("summarise must return a data frame with at least one row") diff --git a/R/formula.R b/R/formula.R new file mode 100644 index 0000000..038e0e0 --- /dev/null +++ b/R/formula.R @@ -0,0 +1,498 @@ +# Static compilation of one-sided formulas used by the pva_model() authoring +# layer. A formula is stored without its environment, resolved once against a +# closed vocabulary (parameters, population fields, globals, context scalars, +# rate-table lookups and an allowlist of pure functions) and rewritten into an +# ordinary closure. Nothing is evaluated per interval beyond the closure body. + +.formula_context <- c("time", "dt", "n_steps", "N") +.formula_reserved <- c(.formula_context, "observed", "rate") + +# name in a formula -> the call head written into the compiled closure +.formula_functions <- c( + "+" = "+", "-" = "-", "*" = "*", "/" = "/", "^" = "^", "%%" = "%%", "%/%" = "%/%", + "(" = "(", "==" = "==", "!=" = "!=", "<" = "<", ">" = ">", "<=" = "<=", ">=" = ">=", + "&" = "&", "|" = "|", "!" = "!", "&&" = "&&", "||" = "||", "%in%" = "%in%", + "[" = "[", "[[" = "[[", "if" = "if", "ifelse" = "ifelse", "xor" = "xor", + "isTRUE" = "isTRUE", "pmin" = "pmin", "pmax" = "pmax", "min" = "min", "max" = "max", + "sum" = "sum", "mean" = "mean", "prod" = "prod", "range" = "range", + "abs" = "abs", "sqrt" = "sqrt", "exp" = "exp", "expm1" = "expm1", "log" = "log", + "log1p" = "log1p", "log2" = "log2", "log10" = "log10", "floor" = "floor", + "ceiling" = "ceiling", "round" = "round", "trunc" = "trunc", "sign" = "sign", + "is.na" = "is.na", "is.finite" = "is.finite", "any" = "any", "all" = "all", + "which" = "which", "length" = "length", "rep" = "rep", "rep_len" = "rep_len", + "c" = "c", "cbind" = "cbind", "rbind" = "rbind", "rev" = "rev", "cumsum" = "cumsum", + "match" = "match", "unique" = "unique", "duplicated" = "duplicated", + "tabulate" = "tabulate", + "as.numeric" = "as.numeric", "as.integer" = "as.integer", + "as.logical" = "as.logical", "as.character" = "as.character", "unname" = "unname", + "plogis" = "stats::plogis", "qlogis" = "stats::qlogis", "pnorm" = "stats::pnorm", + "qnorm" = "stats::qnorm", "pbeta" = "stats::pbeta", "qbeta" = "stats::qbeta", + "median" = "stats::median", + "shift_logit" = "shift_logit", "qbeta_norm" = "qbeta_norm", + "ceiling_density_multiplier" = "ceiling_density_multiplier", + "beverton_holt_multiplier" = "beverton_holt_multiplier", + "ricker_multiplier" = "ricker_multiplier", + "inbreeding_multiplier" = "inbreeding_multiplier", + "sex_ratio_effective_size" = "sex_ratio_effective_size", + "patch_counts" = "patch_counts" +) + +.formula_probability_args <- c(shift_logit = "probability", qbeta_norm = "mean", + inbreeding_multiplier = "inbreeding", + qlogis = "p", qnorm = "p", qbeta = "p") + +.formula_impure <- c( + "<-" = "assignment", "<<-" = "assignment", "=" = "assignment", "->" = "assignment", + "->>" = "assignment", "assign" = "assignment", "function" = "a function definition", + "{" = "a code block", "for" = "a loop", "while" = "a loop", "repeat" = "a loop", + "set.seed" = "seeding the random-number generator", "eval" = "evaluation of code", + "parse" = "evaluation of code", "library" = "attaching a package", + "require" = "attaching a package", "source" = "running a script", + "Sys.time" = "reading the clock", "Sys.Date" = "reading the clock", + "print" = "output", "cat" = "output", "message" = "output", + "runif" = "a random draw", "rnorm" = "a random draw", "rbinom" = "a random draw", + "rpois" = "a random draw", "rbeta" = "a random draw", "rgamma" = "a random draw", + "rexp" = "a random draw", "rlnorm" = "a random draw", "sample" = "a random draw", + "sample.int" = "a random draw", "::" = "a namespace-qualified call", + ":::" = "a namespace-qualified call", "$" = "list extraction with $", + "@" = "slot extraction", "~" = "a nested formula" +) + +.namespace <- function() environment(.namespace) + +.is_formula <- function(x) inherits(x, "formula") + +.is_authored <- function(x) { + .is_formula(x) || inherits(x, "pva_formula") || inherits(x, "pva_deferred") +} + +.any_authored <- function(...) { + for (value in list(...)) { + if (.is_authored(value)) return(TRUE) + if (is.list(value) && !is.data.frame(value) && !inherits(value, "pva_process")) { + for (element in value) if (.is_authored(element)) return(TRUE) + } + } + FALSE +} + +# Keep the expression, drop the environment: a stored formula can never reach +# the workspace it was written in. +.capture <- function(x) { + if (.is_formula(x)) { + if (length(x) != 2L) { + .stop("model formulas must be one-sided, for example ~ age >= 2") + } + return(structure(list(expr = x[[2L]]), class = "pva_formula")) + } + if (inherits(x, "pva_formula") || inherits(x, "pva_deferred") || + inherits(x, "pva_process") || is.function(x) || is.data.frame(x)) { + return(x) + } + if (is.list(x)) { + keep <- attributes(x) + x <- lapply(x, .capture) + attributes(x) <- keep + } + x +} + +# A helper such as env_ar1(sd = ~env_sd) cannot run until its formulas are +# bound to parameters, so it returns its own call as data. +.deferred <- function(helper, args) { + structure(list(helper = helper, args = lapply(args, .capture)), class = "pva_deferred") +} + +print.pva_formula <- function(x, ...) { + cat("~", paste(deparse(x$expr, width.cutoff = 500L), collapse = " "), "\n") + invisible(x) +} + +print.pva_deferred <- function(x, ...) { + cat("\n", sep = "") + invisible(x) +} + +.deparse_authored <- function(x) { + if (inherits(x, "pva_formula")) { + return(paste0("~", paste(deparse(x$expr, width.cutoff = 500L), collapse = " "))) + } + if (inherits(x, "pva_deferred")) { + args <- x$args + shown <- vapply(names(args), function(name) { + paste0(name, " = ", .deparse_authored(args[[name]])) + }, character(1)) + return(paste0(x$helper, "(", paste(shown, collapse = ", "), ")")) + } + if (is.function(x)) return("") + if (inherits(x, "pva_process")) return(paste0("")) + if (is.list(x) && !is.data.frame(x)) { + labels <- names(x) + if (is.null(labels)) labels <- rep("", length(x)) + shown <- vapply(seq_along(x), function(i) { + paste0(if (nzchar(labels[[i]])) paste0(labels[[i]], " = "), .deparse_authored(x[[i]])) + }, character(1)) + return(paste0("list(", paste(shown, collapse = ", "), ")")) + } + text <- paste(deparse(x, width.cutoff = 500L), collapse = " ") + if (nchar(text) > 60L) text <- paste0(substr(text, 1L, 57L), "...") + text +} + +.did_you_mean <- function(name, candidates) { + candidates <- unique(candidates[nzchar(candidates)]) + if (!length(candidates)) return("") + distance <- utils::adist(name, candidates, ignore.case = TRUE)[1L, ] + tied <- which(distance == min(distance)) + letters <- strsplit(tolower(name), "", fixed = TRUE)[[1L]] + overlap <- vapply(strsplit(tolower(candidates[tied]), "", fixed = TRUE), function(chars) { + length(intersect(letters, chars)) + }, integer(1)) + best <- tied[[which.max(overlap)]] + if (distance[[best]] <= max(2L, nchar(name) %/% 3L)) { + return(paste0(" (did you mean '", candidates[[best]], "'?)")) + } + "" +} + +# The vocabulary a model's formulas may use. `params`, `fields` and `globals` +# must be disjoint from each other and from the reserved names. +.vocabulary <- function(params, fields, globals, rates, where = "model") { + sets <- list(parameter = names(params), `population field` = fields, + global = globals, `reserved name` = .formula_reserved) + labels <- rep(names(sets), lengths(sets)) + symbols <- unlist(sets, use.names = FALSE) + clash <- unique(symbols[duplicated(symbols)]) + if (length(clash)) { + first <- clash[[1L]] + .stop(where, ": the name '", first, "' is used as both a ", + paste(unique(labels[symbols == first]), collapse = " and a "), + "; names in formulas must be unambiguous, so rename one of them") + } + list(params = params, fields = fields, globals = globals, rates = rates) +} + +.frame_formals <- list( + individual = c("pop", "state", "context", "params"), + scalar = c("state", "context", "params"), + rule = c("obs", "state", "context", "params"), + trend = c("time", "dt", "params"), + rows = c("rows", "pop", "state", "context", "params") +) + +.rate_lookup <- function(args, vocabulary, label) { + if (!length(args) || !is.character(args[[1L]]) || length(args[[1L]]) != 1L) { + .stop(label, ": rate() needs a quoted column name, for example rate(\"p_surv\")") + } + spec <- list(column = args[[1L]], table = NULL, missing_sex = "error", by = NULL) + extra <- args[-1L] + if (length(extra)) { + if (is.null(names(extra)) || !all(names(extra) %in% c("table", "missing_sex", "by"))) { + .stop(label, ": rate() accepts only the named options table, missing_sex and by") + } + for (name in names(extra)) { + value <- extra[[name]] + if (is.call(value) && identical(value[[1L]], as.name("c"))) { + value <- unlist(as.list(value)[-1L]) + } + if (!is.character(value)) { + .stop(label, ": rate() option ", name, " must be a quoted name") + } + spec[[name]] <- value + } + } + rates <- vocabulary$rates + if (!length(rates)) { + .stop(label, ": rate(\"", spec$column, "\") needs a vital-rate table; supply pva_model(rates = ...)") + } + if (is.null(spec$table)) { + holders <- names(rates)[vapply(rates, function(table) spec$column %in% names(table), logical(1))] + if (!length(holders)) { + columns <- unlist(lapply(rates, names), use.names = FALSE) + .stop(label, ": no vital-rate table has a column '", spec$column, "'", + .did_you_mean(spec$column, columns)) + } + if (length(holders) > 1L) { + .stop(label, ": column '", spec$column, "' is in several rate tables (", + paste(holders, collapse = ", "), "); name one with rate(\"", spec$column, + "\", table = \"", holders[[1L]], "\")") + } + spec$table <- holders + } else if (!spec$table %in% names(rates)) { + .stop(label, ": unknown rate table '", spec$table, "'", .did_you_mean(spec$table, names(rates))) + } else if (!spec$column %in% names(rates[[spec$table]])) { + .stop(label, ": rate table '", spec$table, "' has no column '", spec$column, "'", + .did_you_mean(spec$column, names(rates[[spec$table]]))) + } + if (!spec$missing_sex %in% c("error", "zero")) { + .stop(label, ": rate() missing_sex must be \"error\" or \"zero\"") + } + spec +} + +# Rewrite one expression. `sink` is a local environment that collects what the +# expression reads; it lives only for the duration of one compile call. +.rewrite <- function(expr, vocabulary, frame, sink, label, probability) { + pop <- if (frame %in% c("individual", "rows")) quote(pop) else quote(state$population) + walk <- function(node, probability = FALSE) { + if (is.name(node)) { + symbol <- as.character(node) + if (identical(symbol, "")) return(node) + if (frame == "rule" && symbol == "observed") { + sink$dynamic <- TRUE + return(quote(obs$count)) + } + if (symbol %in% names(vocabulary$params)) { + sink$uses <- c(sink$uses, symbol) + return(vocabulary$params[[symbol]]) + } + if (frame == "trend" && symbol != "pi") { + if (!symbol %in% c("time", "dt")) { + .stop(label, ": env_trend() level can read only declared parameters, time and dt; found '", + symbol, "'") + } + sink$dynamic <- TRUE + return(node) + } + if (symbol %in% vocabulary$fields) { + sink$requires <- c(sink$requires, paste0("population.", symbol)) + return(call("$", pop, node)) + } + if (symbol %in% vocabulary$globals) { + sink$requires <- c(sink$requires, paste0("globals.", symbol)) + return(call("$", quote(state$globals), node)) + } + if (symbol %in% .formula_context) { + sink$dynamic <- TRUE + return(switch(symbol, + time = quote(context$time), dt = quote(context$dt), + n_steps = quote(context$n_steps), N = call("length", call("$", pop, quote(id))) + )) + } + if (symbol == "pi") return(pi) + if (symbol == "observed") { + .stop(label, ": 'observed' is the survey count and is available only inside survey_quota()") + } + known <- c(names(vocabulary$params), vocabulary$fields, vocabulary$globals, .formula_context) + .stop(label, ": unknown symbol '", symbol, "' in a formula", .did_you_mean(symbol, known), + ". Formulas may use declared parameters, population fields, globals written by a step, ", + "time, dt, n_steps, N and rate(\"\")") + } + if (!is.call(node)) return(node) + head <- node[[1L]] + qualified <- is.call(head) && identical(head[[1L]], as.name("::")) && length(head) == 3L + if (qualified) { + pkg <- as.character(head[[2L]]) + fn <- as.character(head[[3L]]) + target <- unname(.formula_functions[fn]) + expected <- if (length(target) == 1L && !is.na(target)) { + if (startsWith(target, "stats::")) "stats" + else if (exists(fn, envir = baseenv(), inherits = FALSE)) "base" + else "OpenPVA" + } + if (!identical(pkg, expected)) { + .stop(label, ": namespace-qualified call '", paste(deparse(head), collapse = " "), + "' is not available in formulas") + } + } else if (!is.name(head)) { + walk(head) + .stop(label, ": a formula may call only named functions, not ", + paste(deparse(head), collapse = " ")) + } else { + fn <- as.character(head) + } + if (fn == "$" && length(node) == 3L && identical(node[[2L]], as.name("obs"))) { + if (frame != "rule" || !as.character(node[[3L]]) %in% c("count", "visited", "ids", "time")) { + .stop(label, ": obs$count, obs$visited, obs$ids and obs$time are available only inside survey_quota()") + } + sink$dynamic <- TRUE + return(node) + } + if (fn %in% names(.formula_impure)) { + .stop(label, ": formulas must be pure expressions, but this one contains ", + .formula_impure[[fn]], " ('", fn, "'). Use a native R callback or step_process() ", + "for anything that assigns, draws random numbers or has side effects") + } + args <- as.list(node)[-1L] + if (fn == "rate") { + if (frame == "trend") .stop(label, ": env_trend() level cannot read a population rate()") + spec <- .rate_lookup(args, vocabulary, label) + if (probability) { + column <- vocabulary$rates[[spec$table]][[spec$column]] + bad <- if (is.numeric(column)) which(column < 0 | column > 1) + if (length(bad)) { + .stop(label, ": rate(\"", spec$column, "\") is used as a probability, but the table holds ", + format(column[[bad[[1L]]]]), "; probabilities must lie in [0, 1]") + } + } + key <- paste(spec$table, spec$column, spec$missing_sex, paste(spec$by, collapse = "+"), sep = "|") + slot <- match(key, names(sink$rates)) + if (is.na(slot)) { + sink$rates[[key]] <- spec + slot <- length(sink$rates) + } + sink$requires <- c(sink$requires, paste0("population.", c("age", "sex", spec$by))) + return(call(paste0(".rate", slot), pop, quote(state), quote(context), quote(params))) + } + if (!fn %in% names(.formula_functions)) { + .stop(label, ": function '", fn, "' is not available in formulas", + .did_you_mean(fn, names(.formula_functions)), + ". Use a native R callback for anything outside the pure-function list") + } + target <- .formula_functions[[fn]] + domains <- rep(FALSE, length(args)) + if (fn %in% names(.formula_probability_args)) { + fun <- if (startsWith(target, "stats::")) getExportedValue("stats", fn) else + get(fn, envir = .namespace(), inherits = FALSE) + args <- as.list(match.call(fun, node))[-1L] + if (is.null(args$log.p) || identical(args$log.p, FALSE)) { + domains <- names(args) == .formula_probability_args[[fn]] + } + } else if (probability && fn == "(") { + domains[] <- TRUE + } + for (i in seq_along(args)) { + if (!identical(args[[i]], quote(expr = ))) args[[i]] <- walk(args[[i]], domains[[i]]) + } + if (fn == "patch_counts") { + if (frame == "trend") .stop(label, ": env_trend() level cannot read patch_counts()") + native <- as.call(c(list(as.name("patch_counts"), pop), args)) + args <- as.list(match.call(patch_counts, native))[-1L] + field <- if (is.null(args$field)) "patch_id" else args$field + if (!.is_name(field) || !field %in% vocabulary$fields) { + .stop(label, ": patch_counts() needs the population field '", + paste(format(field), collapse = ""), "'") + } + sink$requires <- c(sink$requires, paste0("population.", field)) + } + head <- if (grepl("::", target, fixed = TRUE)) { + parts <- strsplit(target, "::", fixed = TRUE)[[1L]] + call("::", as.name(parts[[1L]]), as.name(parts[[2L]])) + } else { + as.name(target) + } + as.call(c(list(head), args)) + } + walk(expr, probability) +} + +.as_prob_numeric <- function(value) { + if (is.logical(value)) as.numeric(value) else value +} + +# Compile a stored formula. +# frame - which callback signature the closure must have +# numeric - convert logical probabilities and rates to their numeric values +# fold - "allow" returns a constant when the formula reads parameters only, +# "require" insists on that, "never" always returns a closure +.compile_formula <- function(formula, vocabulary, frame = "individual", numeric = FALSE, + fold = "allow", label = "formula", probability = FALSE) { + sink <- new.env(parent = emptyenv()) + sink$uses <- character() + sink$requires <- character() + sink$rates <- list() + sink$dynamic <- FALSE + body <- .rewrite(formula$expr, vocabulary, frame, sink, label, probability) + if (numeric) body <- call(".as_prob_numeric", body) + constant <- !length(sink$requires) && !sink$dynamic && !length(sink$rates) + out <- list(uses = unique(sink$uses), requires = unique(sink$requires), + rates = unname(sink$rates), + equation = .deparse_authored(formula)) + if (fold == "require" && !constant) { + .stop(label, ": ", out$equation, " must depend on parameters only, because it is ", + "needed when the model is built") + } + if (constant && fold != "never") { + value <- tryCatch( + eval(body, new.env(parent = .namespace())), + error = function(e) .stop(label, ": ", out$equation, " could not be evaluated: ", + conditionMessage(e)) + ) + out$value <- value + out$constant <- TRUE + return(out) + } + if (frame == "rows") { + body <- call("{", call("<-", quote(value), body), + quote(if (length(value) == 1L) rep_len(value, length(rows)) else value[rows])) + } + scope <- .namespace() + if (length(sink$rates)) { + scope <- new.env(parent = .namespace()) + for (slot in seq_along(sink$rates)) { + spec <- sink$rates[[slot]] + lookup <- tryCatch( + age_sex_rate(vocabulary$rates[[spec$table]], spec$column, + missing_sex = spec$missing_sex, by = spec$by), + error = function(e) .stop(label, ": rate(\"", spec$column, "\") cannot use rate table '", + spec$table, "': ", conditionMessage(e)) + ) + assign(paste0(".rate", slot), lookup, envir = scope) + } + lockEnvironment(scope, bindings = TRUE) + } + arguments <- .frame_formals[[frame]] + closure <- as.function(c( + stats::setNames(rep(list(quote(expr = )), length(arguments)), arguments), list(body) + ), envir = scope) + out$value <- closure + out$constant <- FALSE + out +} + +# Parameters a hand-written callback reads through its `params` argument. +# Keep direct names even when another read or forwarding operation is opaque. +.params_used <- function(fn, argument = "params") { + if (!is.function(fn) || is.primitive(fn)) return(list(names = character(), opaque = FALSE)) + bindings <- attr(fn, "pva_helper", exact = TRUE) + if (!is.null(bindings)) { + parts <- lapply(mget(bindings, envir = environment(fn), inherits = FALSE), .params_used) + return(list(names = unique(unlist(lapply(parts, `[[`, "names"), use.names = FALSE)), + opaque = any(vapply(parts, `[[`, logical(1), "opaque")))) + } + if (!argument %in% names(formals(fn))) return(list(names = character(), opaque = FALSE)) + found <- character() + opaque <- FALSE + target <- as.name(argument) + walk <- function(node) { + if (is.name(node)) { + if (identical(node, target)) opaque <<- TRUE + return(invisible()) + } + if (!is.call(node)) return(invisible()) + head <- node[[1L]] + if (identical(head, as.name("function"))) { + if (!argument %in% names(node[[2L]])) { + walk_parts(node[[2L]]) + walk(node[[3L]]) + } + return(invisible()) + } + if (is.name(head) && as.character(head) %in% c("$", "[[") && length(node) == 3L && + identical(node[[2L]], target)) { + key <- node[[3L]] + if (is.name(key) && identical(as.character(head), "$")) { + found <<- c(found, as.character(key)) + return(invisible()) + } + if (is.character(key) && length(key) == 1L) { + found <<- c(found, key) + return(invisible()) + } + } + if (identical(head, as.name("$")) || identical(head, as.name("@"))) { + walk(node[[2L]]) + return(invisible()) + } + walk_parts(as.list(node)) + } + walk_parts <- function(parts) { + for (i in seq_along(parts)) { + if (!identical(parts[[i]], quote(expr = ))) walk(parts[[i]]) + } + invisible() + } + walk_parts(formals(fn)) + walk(body(fn)) + list(names = unique(found), opaque = opaque) +} diff --git a/R/lifecycle.R b/R/lifecycle.R index ffd86b8..62309c0 100644 --- a/R/lifecycle.R +++ b/R/lifecycle.R @@ -14,6 +14,16 @@ identical(utils::removeSource(process$run), utils::removeSource(.run_survey)))) { return("survey") } + if (!is.null(process$role)) { + return(process$role) + } + .infer_role(process) +} + +.default_role <- function(role) structure(role, class = "pva_default_role") + +# The role suggested by a process's name, description and declared effects. +.infer_role <- function(process) { nm <- tolower(process$name) desc <- tolower(if (is.null(process$description)) "" else process$description) writes <- process$writes @@ -66,6 +76,15 @@ return(list(already = x)) } state_source <- "supplied" + authoring <- NULL + if (inherits(x, "pva_model")) { + compiled <- .compile_model(x) + x <- .model_scenario(compiled, 1L, NULL, NULL, "strict") + x$n_runs <- NA_integer_ + if (is.null(state)) state <- compiled$state + if (!inherits(state, "pva_state")) state <- pva_state(state) + state_source <- "initial" + } if (inherits(x, "pva_run")) { if (is.null(state) && length(x$states)) { state <- x$states[[1L]] @@ -82,11 +101,12 @@ meta$has_initial_census <- !is.null(x$initial_census) processes <- x$processes initial <- x$initial_census + authoring <- x$authoring$steps } else if (is.list(x)) { processes <- validate_processes(x) initial <- NULL } else { - .stop("x must be a pva_scenario, pva_run, pva_lifecycle, or list of pva_process objects") + .stop("x must be a pva_model, pva_scenario, pva_run, pva_lifecycle, or list of pva_process objects") } if (!is.null(state)) { @@ -101,7 +121,7 @@ ) } - list(processes = processes, initial = initial, meta = meta) + list(processes = processes, initial = initial, meta = meta, authoring = authoring) } .lifecycle_edges <- function(processes) { @@ -220,6 +240,12 @@ describe_lifecycle <- function(x, state = NULL) { class(out) <- c("pva_lifecycle", "data.frame") attr(out, "edges") <- .lifecycle_edges(processes) attr(out, "metadata") <- meta + if (is.data.frame(extracted$authoring) && nrow(extracted$authoring) == length(processes)) { + authored <- extracted$authoring + authored$step <- seq_len(nrow(authored)) + rownames(authored) <- NULL + attr(out, "authoring") <- authored[c("step", "name", "type", "when", "equations", "parameters")] + } out } @@ -228,6 +254,7 @@ describe_lifecycle <- function(x, state = NULL) { if (is.data.frame(out)) { attr(out, "edges") <- NULL attr(out, "metadata") <- NULL + attr(out, "authoring") <- NULL class(out) <- setdiff(class(out), "pva_lifecycle") } out @@ -277,6 +304,18 @@ print.pva_lifecycle <- function(x, ...) { }, character(1)) cat(sprintf("Data flows (%d): %s\n", nrow(edges), paste(flow_txt, collapse = "; "))) } + authoring <- attr(x, "authoring") + if (is.data.frame(authoring)) { + shown <- authoring[nzchar(authoring$equations) | authoring$when != "every interval", , drop = FALSE] + if (nrow(shown)) { + cat("Authored steps:\n") + for (i in seq_len(nrow(shown))) { + cat(sprintf(" %d. %s: %s%s\n", shown$step[[i]], shown$name[[i]], shown$equations[[i]], + if (shown$when[[i]] != "every interval") paste0(" {when = ", shown$when[[i]], "}") else "")) + if (nzchar(shown$parameters[[i]])) cat(sprintf(" with %s\n", shown$parameters[[i]])) + } + } + } invisible(x) } @@ -779,3 +818,8 @@ plot.pva_scenario <- function(x, state = NULL, show_flows = TRUE, main = NULL, . lc <- describe_lifecycle(x, state = state) plot.pva_lifecycle(lc, show_flows = show_flows, main = main, ...) } + +plot.pva_model <- function(x, state = NULL, show_flows = TRUE, main = NULL, ...) { + lc <- describe_lifecycle(x, state = state) + plot.pva_lifecycle(lc, show_flows = show_flows, main = main, ...) +} diff --git a/R/mating.R b/R/mating.R index 18d93ac..d2cb082 100644 --- a/R/mating.R +++ b/R/mating.R @@ -3,6 +3,10 @@ mate_min_kinship <- function(eligible = NULL, max_kinship = Inf, ties = c("random", "id"), by = NULL) { + if (.any_authored(eligible, max_kinship, by)) { + return(.deferred("mate_min_kinship", + list(eligible = eligible, max_kinship = max_kinship, ties = ties, by = by))) + } .check_optional_function(eligible, "eligible") limit <- .kinship_limit(max_kinship) ties <- match.arg(ties) @@ -37,7 +41,7 @@ mate_min_kinship <- function(eligible = NULL, max_kinship = Inf, ties = c("rando out } attr(chooser, "mate_requires") <- requirement - chooser + .helper_fn(chooser, "eligible") } .mating_group_requirement <- function(by) { diff --git a/R/mating_process.R b/R/mating_process.R index 78116db..512246a 100644 --- a/R/mating_process.R +++ b/R/mating_process.R @@ -113,6 +113,7 @@ mating_process <- function( params = list(eligible = eligible, capacity = capacity, weights = weights, by = by, field = field, when = visit, clear = clear, user = params), requires = unique(c("population.sex", path, group_path, requires)), writes = path, - description = "Record seasonal sires subject to relative male weights, capacity and mating groups." + description = "Record seasonal sires subject to relative male weights, capacity and mating groups.", + role = .default_role("demography") ) } diff --git a/R/model.R b/R/model.R new file mode 100644 index 0000000..2b8dc07 --- /dev/null +++ b/R/model.R @@ -0,0 +1,1197 @@ +# The pva_model() authoring layer: separated inputs, an ordered list of step +# specifications and a compiler that turns both into the standard process list +# and scenario_spec(). A model is a plain value; nothing here keeps state. + +.syntactic <- function(names) { + !is.na(names) & nzchar(names) & make.names(names) == names +} + +# Parameters arrive as a named list or as an evidence table with one row per +# parameter. Returns the values and, for a table, its other columns. +.model_params <- function(params) { + if (is.data.frame(params)) { + key <- intersect(c("parameter", "name", "param"), names(params)) + if (!length(key) || !"value" %in% names(params)) { + .stop("a parameter table needs a 'parameter' (or 'name') column and a 'value' column") + } + key <- key[[1L]] + labels <- as.character(params[[key]]) + raw <- params$value + values <- as.list(if (is.factor(raw)) as.character(raw) else raw) + for (i in seq_along(values)) { + cell <- values[[i]] + type <- if ("type" %in% names(params)) as.character(params$type[[i]]) else NA_character_ + if (is.na(type) || !nzchar(type)) { + if (is.character(cell)) values[[i]] <- utils::type.convert(cell, as.is = TRUE) + } else { + value <- switch(type, character = as.character(cell), logical = as.logical(cell), + numeric = suppressWarnings(as.numeric(cell)), + double = suppressWarnings(as.double(cell)), + integer = suppressWarnings(as.integer(cell))) + if (is.null(value) || anyNA(value) || + (type == "integer" && value != suppressWarnings(as.double(cell)))) { + .stop("parameter '", labels[[i]], "' has invalid ", type, " value '", cell, "'") + } + values[[i]] <- value + } + } + names(values) <- labels + evidence <- params[-match(c(key, "value"), names(params))] + rownames(evidence) <- NULL + } else if (is.list(params)) { + values <- params + evidence <- NULL + } else { + .stop("params must be a named list or a parameter table (data frame)") + } + labels <- names(values) + if (length(values) && (is.null(labels) || !all(.syntactic(labels)) || anyDuplicated(labels))) { + bad <- if (is.null(labels)) "(unnamed)" else labels[!.syntactic(labels) | duplicated(labels)] + .stop("parameter names must be unique, syntactic R names; check: ", + paste(utils::head(unique(bad), 3L), collapse = ", ")) + } + for (label in labels) { + value <- values[[label]] + if (is.null(value) || !is.atomic(value) || !length(value) || is.object(value) || + (length(value) == 1L && is.na(value))) { + .stop("parameter '", label, "' must be a non-missing number, flag, text value, vector or matrix") + } + } + list(values = values, evidence = evidence) +} + +cohort_population <- function(counts, ...) { + if (!is.data.frame(counts) || !"age" %in% names(counts)) { + .stop("counts must be a data frame with an age column and either (sex, n) or (females, males)") + } + long <- all(c("sex", "n") %in% names(counts)) + wide <- all(c("females", "males") %in% names(counts)) + if (long == wide) { + .stop("counts must hold either the columns (age, sex, n) or (age, females, males)") + } + whole <- function(x, label) { + if (!is.numeric(x) || anyNA(x) || any(!is.finite(x)) || any(x < 0) || any(x != floor(x))) { + .stop("cohort ", label, " must be non-negative whole numbers without gaps or NA") + } + as.integer(x) + } + age <- whole(counts$age, "ages") + count_columns <- if (long) c("sex", "n") else c("females", "males") + extra <- counts[setdiff(names(counts), c("age", count_columns))] + if (long) { + sex <- .normalize_sex(counts$sex) + if (!all(sex %in% c("F", "M"))) .stop("cohort sex must be 'F' or 'M'") + n <- whole(counts$n, "counts") + rows <- rep(seq_len(nrow(counts)), n) + sexes <- sex[rows] + } else { + females <- whole(counts$females, "counts") + males <- whole(counts$males, "counts") + rows <- c(rep(seq_len(nrow(counts)), females), rep(seq_len(nrow(counts)), males)) + sexes <- rep(c("F", "M"), c(sum(females), sum(males))) + } + if (!length(rows)) .stop("the cohort table describes no individuals") + fields <- lapply(extra, function(column) { + if (is.factor(column)) column <- as.character(column) + column[rows] + }) + do.call(pva_population, c(list(sex = sexes, age = age[rows]), fields, list(...))) +} + +# Turn any accepted `init` into a population (or keep a function for later). +.model_population <- function(init, fields) { + if (is.function(init)) { + if (length(formals(init))) .stop("an init function must take no arguments") + return(init) + } + population <- if (is.data.frame(init) && + (("n" %in% names(init) && "sex" %in% names(init)) || + all(c("females", "males") %in% names(init)))) { + cohort_population(init) + } else if (is.data.frame(init) || is.list(init)) { + if (inherits(init, "pva_state")) { + .stop("init must be a population, cohort table or function, not a pva_state; ", + "set pedigree, n_loci and mate_field on pva_model()") + } + .as_population(init) + } else { + .stop("init must be a cohort-count table, a founder table, a pva_population() or a function") + } + n <- length(population$id) + for (field in setdiff(names(fields), names(population))) { + population[[field]] <- rep(fields[[field]], n) + } + for (field in intersect(names(fields), names(population))) { + if (!identical(typeof(population[[field]]), typeof(fields[[field]]))) { + .stop("field '", field, "' has default type ", typeof(fields[[field]]), + " but the initial population stores ", typeof(population[[field]]), + "; declare the default with the same type (for example NA_integer_ or 0L)") + } + } + .validate_population(population) +} + +pva_model <- function( + params = list(), + rates = NULL, + init, + n_steps, + fields = list(), + globals = list(), + name = "model", + dt = 1, + pedigree = FALSE, + n_loci = 0L, + mate_field = NULL, + initial_census = TRUE) { + parsed <- .model_params(params) + if (is.data.frame(rates)) rates <- list(rates = rates) + if (!is.null(rates) && + (!is.list(rates) || !length(rates) || is.null(names(rates)) || any(!nzchar(names(rates))) || + anyDuplicated(names(rates)) || !all(vapply(rates, is.data.frame, logical(1))))) { + .stop("rates must be a vital-rate data frame or a uniquely named list of data frames") + } + if (!is.list(fields) || (length(fields) && (is.null(names(fields)) || + !all(.syntactic(names(fields))) || anyDuplicated(names(fields))))) { + .stop("fields must be a uniquely named list of default values, such as list(mate_id = NA_integer_)") + } + for (field in names(fields)) { + value <- fields[[field]] + if (field %in% .reserved_fields) { + .stop("fields cannot redefine the core field '", field, "'") + } + if (!is.atomic(value) || is.null(value) || length(value) != 1L || !is.null(attributes(value)) || + (is.logical(value) && is.na(value))) { + .stop("field '", field, "' needs one typed default value; an untyped NA is ambiguous, ", + "so write NA_integer_, NA_real_ or NA_character_") + } + } + if (!is.list(globals) || (length(globals) && (is.null(names(globals)) || + !all(.syntactic(names(globals))) || anyDuplicated(names(globals))))) { + .stop("globals must be a uniquely named list of initial shared values") + } + if (!.is_name(name)) .stop("name must be one non-empty character value") + if (!is.numeric(dt) || length(dt) != 1L || !is.finite(dt) || dt <= 0) { + .stop("dt must be one positive number") + } + if (!.is_flag(pedigree)) .stop("pedigree must be TRUE or FALSE") + if (!is.null(mate_field) && !.is_name(mate_field)) .stop("mate_field must be NULL or one field name") + if (!.is_flag(initial_census) && !.is_name(initial_census)) { + .stop("initial_census must be TRUE, FALSE or the name of a census step") + } + model <- structure( + list( + name = name, + params = parsed$values, + evidence = parsed$evidence, + rates = rates, + init = .model_population(init, fields), + fields = fields, + globals = globals, + settings = list( + n_steps = .as_count(n_steps, "n_steps", minimum = 1), + dt = as.numeric(dt), + pedigree = pedigree, + n_loci = .as_count(n_loci, "n_loci"), + mate_field = mate_field, + initial_census = initial_census + ), + steps = list() + ), + class = "pva_model" + ) + .preview_state(model) + model +} + +# The initial state, built exactly as a hand-written init_fun would build it. +.model_state <- function(model) { + settings <- model$settings + initial <- if (is.function(model$init)) model$init() else model$init + if (inherits(initial, "pva_state")) { + if (settings$pedigree || settings$n_loci > 0L || !is.null(settings$mate_field) || + length(model$globals)) { + .stop("an init function that returns a pva_state() already fixes pedigree, loci, ", + "mate_field and globals; do not also set them on pva_model()") + } + if (length(model$fields)) { + initial$population <- .model_population(initial$population, model$fields) + if (!is.null(initial$sires$records)) { + initial$sires$records <- .model_population(initial$sires$records, model$fields) + } + } + return(.validate_state(initial, at_entry = TRUE)) + } + if (is.function(model$init)) initial <- .model_population(initial, model$fields) + pva_state(initial, globals = model$globals, pedigree = settings$pedigree, + n_loci = settings$n_loci, mate_field = settings$mate_field) +} + +.preview_state <- function(model) { + inputs <- model[c("init", "globals", "settings", "fields")] + .preview_call(.model_state, list(model = inputs), user_code = is.function(model$init)) +} + +.model_init_fun <- function(model) { + scope <- new.env(parent = .namespace()) + scope$model <- model[c("init", "globals", "settings", "fields")] + init_fun <- function() .model_state(model) + environment(init_fun) <- scope + init_fun +} + +.check_model <- function(model) { + if (!inherits(model, "pva_model")) { + .stop("model must be created by pva_model(); start a pipeline with pva_model(...) |> step_*()") + } + invisible(model) +} + +print.pva_model <- function(x, ...) { + settings <- x$settings + n <- if (is.function(x$init)) NA_integer_ else length(x$init$id) + cat(sprintf( + "\n", + x$name, length(x$steps), settings$n_steps, if (settings$n_steps == 1L) "" else "s", + settings$dt, if (is.na(n)) "init function" else format(n), + length(x$params), if (length(x$params) == 1L) "" else "s", + if (settings$pedigree) " | pedigree" else "", + if (settings$n_loci > 0L) sprintf(" | %d loci", settings$n_loci) else "" + )) + for (i in seq_along(x$steps)) { + step <- x$steps[[i]] + shown <- step$args[!vapply(step$args, is.null, logical(1))] + if (!is.null(names(step$written))) shown <- shown[names(shown) %in% c(names(step$written), "variables")] + if (step$type == "environment") shown <- shown$variables + text <- vapply(names(shown), function(name) { + paste0(name, " = ", .step_text(step, name, shown[[name]])) + }, character(1)) + modifiers <- c( + if (!isTRUE(step$when)) paste0("when = ", .deparse_authored(step$when)), + if (!isTRUE(step$enabled)) paste0("enabled = ", .deparse_authored(step$enabled)) + ) + cat(sprintf(" %2d. %s [%s]%s%s\n", i, step$name, step$type, + if (length(text)) paste0(" ", paste(text, collapse = ", ")) else "", + if (length(modifiers)) paste0(" {", paste(modifiers, collapse = ", "), "}") else "")) + } + invisible(x) +} + +# ---- step builders -------------------------------------------------------- + +.add_step <- function(model, type, name, args, when = TRUE, enabled = TRUE, + requires = character(), uses = NULL) { + .check_model(model) + if (!.is_name(name)) .stop("step name must be one non-empty character value") + when <- .capture(when) + enabled <- .capture(enabled) + if (!inherits(enabled, "pva_formula") && !.is_flag(enabled)) { + .stop("step '", name, "': enabled must be TRUE, FALSE or a formula naming a flag parameter, ", + "such as ~releases") + } + if (!inherits(when, "pva_formula") && !is.function(when) && !.is_flag(when) && + !(is.numeric(when) && !anyNA(when))) { + .stop("step '", name, "': when must be TRUE, zero-based interval numbers, a formula or a function") + } + requires <- .field_names(requires, paste0("step '", name, "' requires")) + if (!is.null(uses)) uses <- .field_names(uses, paste0("step '", name, "' uses")) + unknown <- setdiff(uses, names(model$params)) + if (length(unknown)) { + .stop("step '", name, "' declares unknown parameter '", unknown[[1L]], "'", + .did_you_mean(unknown[[1L]], names(model$params))) + } + # The text of the calling step_*() arguments, kept only to label R callbacks. + written <- tryCatch({ + call <- match.call(sys.function(-1L), sys.call(-1L), expand.dots = TRUE) + vapply(as.list(call)[-1L], function(part) { + text <- paste(deparse(part, width.cutoff = 500L), collapse = " ") + if (nchar(text) > 80L) paste0(substr(text, 1L, 77L), "...") else text + }, character(1)) + }, error = function(e) character()) + written <- written[names(written) != "model"] + model$steps[[length(model$steps) + 1L]] <- list( + type = type, name = name, args = lapply(args, .capture), + when = when, enabled = enabled, requires = requires, uses = uses, written = written + ) + model +} + +step_environment <- function(model, ..., name = "environment", when = TRUE, enabled = TRUE, + requires = character(), uses = NULL) { + variables <- list(...) + if (!length(variables) || is.null(names(variables)) || !all(.syntactic(names(variables))) || + anyDuplicated(names(variables))) { + .stop("step_environment() needs named variables, for example step_environment(weather = env_ar1(sd = 0.3))") + } + .add_step(model, "environment", name, list(variables = variables), when, enabled, requires, uses) +} + +step_catastrophe <- function(model, probability, mortality = NULL, eligible = NULL, + name = "catastrophe", global = name, when = TRUE, enabled = TRUE, + requires = character(), uses = NULL) { + .add_step(model, "catastrophe", name, + list(probability = probability, mortality = mortality, eligible = eligible, + global = global), when, enabled, requires, uses) +} + +step_survival <- function(model, probability, eligible = NULL, cause = "natural", stage = NULL, + post_share = NULL, field = "survival_draw", + name = if (is.null(stage)) "survival" else paste0("survival_", stage), + when = TRUE, enabled = TRUE, requires = character(), uses = NULL) { + if (is.null(stage)) { + if (!is.null(post_share)) .stop("post_share applies only to a staged survival step; set stage") + return(.add_step(model, "survival", name, + list(probability = probability, eligible = eligible, cause = cause), + when, enabled, requires, uses)) + } + if (!is.null(eligible)) .stop("a staged survival step applies to every individual; omit eligible") + if (is.null(post_share)) .stop("a staged survival step needs post_share") + .add_step(model, "staged_survival", name, + list(probability = probability, post_share = post_share, stage = stage, + field = field, cause = cause), when, enabled, requires, uses) +} + +step_age <- function(model, increment = 1L, name = "age", when = TRUE, enabled = TRUE, + uses = NULL) { + .add_step(model, "age", name, list(increment = increment), when, enabled, uses = uses) +} + +step_pairing <- function(model, eligible, capacity = Inf, priority = "id", max_kinship = Inf, + by = NULL, field = "mate_id", name = "pairing", when = TRUE, + enabled = TRUE, requires = character(), uses = NULL) { + .add_step(model, "pairing", name, + list(eligible = eligible, capacity = capacity, priority = priority, + max_kinship = max_kinship, by = by, field = field), when, enabled, requires, uses) +} + +step_mating <- function(model, eligible = NULL, male_capacity = Inf, weights = NULL, by = NULL, + field = "mate_id", clear = TRUE, name = "mating", when = TRUE, + enabled = TRUE, requires = character(), uses = NULL) { + .add_step(model, "mating", name, + list(eligible = eligible, male_capacity = male_capacity, weights = weights, + by = by, field = field, clear = clear), when, enabled, requires, uses) +} + +step_reproduction <- function(model, breeding_probability, litter_size, offspring_sex, + mate = NULL, require_mate = !is.null(mate), newborn_fields = NULL, + inherit = character(), name = "reproduction", when = TRUE, + enabled = TRUE, requires = character(), uses = NULL) { + .add_step(model, "reproduction", name, + list(breeding_probability = breeding_probability, litter_size = litter_size, + offspring_sex = offspring_sex, mate = mate, require_mate = require_mate, + newborn_fields = newborn_fields, inherit = inherit), when, enabled, requires, uses) +} + +step_dispersal <- function(model, transition = NULL, destination = NULL, patches = NULL, + eligible = NULL, count = NULL, weights = NULL, field = "patch_id", + name = "dispersal", when = TRUE, enabled = TRUE, + requires = character(), uses = NULL) { + if (is.null(transition) == is.null(destination)) { + .stop("step_dispersal() needs either a transition matrix or a destination rule") + } + if (!is.null(transition)) { + if (!is.null(patches) || !is.null(count) || !is.null(weights)) { + .stop("a transition matrix names its own patches and moves every eligible individual; ", + "use destination for count- or weight-targeted moves") + } + return(.add_step(model, "markov_dispersal", name, + list(transition = transition, eligible = eligible, field = field), + when, enabled, requires, uses)) + } + .add_step(model, "dispersal", name, + list(destination = destination, patches = patches, eligible = eligible, + field = field, count = count, weights = weights), when, enabled, requires, uses) +} + +step_survey <- function(model, detection, eligible = NULL, field = "survey", name = "survey", + when = TRUE, enabled = TRUE, requires = character(), uses = NULL) { + .add_step(model, "survey", name, + list(detection = detection, eligible = eligible, field = field), + when, enabled, requires, uses) +} + +step_remove <- function(model, count = NULL, probability = NULL, select = NULL, eligible = NULL, + weights = NULL, order = "random", cause = "removal", name = "removal", + when = TRUE, enabled = TRUE, requires = character(), uses = NULL) { + .add_step(model, "removal", name, + list(count = count, probability = probability, select = select, eligible = eligible, + order = order, cause = cause, weights = weights), when, enabled, requires, uses) +} + +step_ceiling <- function(model, capacity, eligible = NULL, weights = NULL, cause = "ceiling", + name = "ceiling", when = TRUE, enabled = TRUE, requires = character(), uses = NULL) { + .add_step(model, "ceiling", name, + list(capacity = capacity, eligible = eligible, cause = cause, weights = weights), + when, enabled, requires, uses) +} + +step_introduce <- function(model, count, fields, source = "introduction", + name = "introduction", when = TRUE, enabled = TRUE, + requires = character(), uses = NULL) { + .add_step(model, "introduction", name, + list(count = count, fields = fields, source = source), when, enabled, requires, uses) +} + +step_assign <- function(model, field, value, count = NULL, probability = NULL, select = NULL, + eligible = NULL, weights = NULL, order = "random", event = "assigned", + name = "assign", when = TRUE, enabled = TRUE, requires = character(), uses = NULL) { + .add_step(model, "assign", name, + list(field = field, value = value, count = count, probability = probability, + select = select, eligible = eligible, order = order, weights = weights, + event = event), when, enabled, requires, uses) +} + +step_census <- function(model, metrics = NULL, name = "census", when = TRUE, enabled = TRUE, + requires = character(), uses = NULL) { + .add_step(model, "census", name, list(metrics = metrics), when, enabled, requires, uses) +} + +step_process <- function(model, process, enabled = TRUE, when = TRUE, uses = NULL) { + .check_model(model) + if (inherits(process, "pva_process")) { + name <- process$name + } else if (is.function(process) && length(formals(process)) == 1L) { + name <- "process" + } else { + .stop("process must be a pva_process (from any OpenPVA constructor or pva_process()) ", + "or a function of one argument, params, that returns one") + } + .add_step(model, "process", name, list(process = process), when, enabled, uses = uses) +} + +# ---- compilation ---------------------------------------------------------- + +# How each argument of a native constructor is resolved: +# prob / rate / weight / flag / metric per-individual callbacks +# chance / count / variable callbacks of (state, context, params) +# const a value needed when the model is built +# value / rows callbacks of (rows, pop, ...) +# helper litter, sex and mate helpers +.step_specs <- list( + survival = list(constructor = "survival_process", + kinds = c(probability = "prob", eligible = "flag")), + staged_survival = list(constructor = "staged_survival_process", + kinds = c(probability = "prob", post_share = "const")), + age = list(constructor = "age_process", kinds = c(increment = "const")), + catastrophe = list(constructor = "catastrophe_process", + kinds = c(probability = "chance", mortality = "prob", eligible = "flag")), + environment = list(constructor = "environment_process", kinds = character()), + pairing = list(constructor = "pairing_process", + kinds = c(eligible = "flag", capacity = "count", max_kinship = "const")), + mating = list(constructor = "mating_process", native_when = TRUE, + kinds = c(eligible = "flag", male_capacity = "count", weights = "weight")), + reproduction = list(constructor = "reproduction_process", + kinds = c(breeding_probability = "prob", litter_size = "helper", + offspring_sex = "helper", mate = "helper")), + dispersal = list(constructor = "dispersal_process", + kinds = c(destination = "rows", patches = "const", eligible = "flag", + count = "count", weights = "weight")), + markov_dispersal = list(constructor = "markov_dispersal_process", + kinds = c(transition = "const", eligible = "flag")), + survey = list(constructor = "survey_process", native_when = TRUE, + kinds = c(detection = "prob", eligible = "flag")), + removal = list(constructor = "removal_process", + kinds = c(count = "count", probability = "prob", select = "flag", + eligible = "flag", weights = "weight")), + ceiling = list(constructor = "ceiling_process", + kinds = c(capacity = "count", eligible = "flag", weights = "weight")), + introduction = list(constructor = "introduction_process", kinds = c(count = "count")), + assign = list(constructor = "assign_process", + kinds = c(value = "value", count = "count", probability = "prob", + select = "flag", eligible = "flag", weights = "weight")), + census = list(constructor = "census_process", kinds = character()) +) + +.helper_kinds <- list( + env_ar1 = c(sd = "const", phi = "const", cor = "const", names = "const"), + env_trend = c(level = "trend", anomaly = "const"), + spatial_correlation = c(patches = "const", rho = "const", distances = "const", scale = "const"), + litter_poisson = c(mean = "rate"), + litter_binomial = c(size = "const", mean = "rate", min_size = "const"), + litter_categorical = c(sizes = "const", probabilities = "rate"), + offspring_sex_bernoulli = c(female_probability = "prob"), + mate_random = c(eligible = "flag"), + mate_min_kinship = c(eligible = "flag", max_kinship = "const", ties = "const", by = "const"), + survey_quota = c(rule = "rule", field = "const", on_skip = "skip") +) + +.kind_options <- list( + prob = list(frame = "individual", numeric = TRUE, fold = "allow"), + rate = list(frame = "individual", numeric = TRUE, fold = "allow"), + weight = list(frame = "individual", numeric = TRUE, fold = "never"), + flag = list(frame = "individual", numeric = FALSE, fold = "never"), + metric = list(frame = "individual", numeric = FALSE, fold = "never"), + chance = list(frame = "scalar", numeric = TRUE, fold = "allow"), + count = list(frame = "scalar", numeric = TRUE, fold = "allow"), + variable = list(frame = "scalar", numeric = FALSE, fold = "never"), + when = list(frame = "scalar", numeric = FALSE, fold = "allow"), + const = list(frame = "scalar", numeric = FALSE, fold = "require"), + value = list(frame = "rows", numeric = FALSE, fold = "allow"), + rows = list(frame = "rows", numeric = FALSE, fold = "never"), + trend = list(frame = "trend", numeric = FALSE, fold = "allow"), + rule = list(frame = "rule", numeric = FALSE, fold = "never"), + skip = list(frame = "rule", numeric = FALSE, fold = "allow") +) + +.helper_fn <- function(fn, inputs = character()) { + attr(fn, "pva_helper") <- inputs + fn +} + +.empty_resolution <- function(value = NULL) { + list(value = value, uses = character(), requires = character(), equation = NULL, + native = FALSE, opaque = FALSE, rates = list(), quotas = character()) +} + +.merge_resolution <- function(into, from) { + into$uses <- unique(c(into$uses, from$uses)) + into$requires <- unique(c(into$requires, from$requires)) + into$native <- into$native || isTRUE(from$native) + into$opaque <- into$opaque || isTRUE(from$opaque) + into$quotas <- unique(c(into$quotas, from$quotas)) + into$rates <- c(into$rates, from$rates) + into +} + +.check_probability <- function(value, label) { + if (is.numeric(value) && (anyNA(value) || any(value < 0 | value > 1))) { + bad <- value[is.na(value) | value < 0 | value > 1][[1L]] + .stop(label, ": a probability must lie in [0, 1], but the value is ", format(bad)) + } + invisible(value) +} + +# Resolve one authored value into what the native constructor expects. +.resolve <- function(value, kind, vocabulary, label) { + if (is.null(value)) return(.empty_resolution()) + options <- .kind_options[[kind]] + if (inherits(value, "pva_formula")) { + if (kind == "helper") { + .stop(label, ": needs a helper such as litter_poisson(~rate(\"litter_mean\")), ", + "offspring_sex_bernoulli(0.5) or mate_random(~age >= 2), not a bare formula") + } + compiled <- .compile_formula(value, vocabulary, frame = options$frame, + numeric = options$numeric, fold = options$fold, label = label, + probability = kind %in% c("prob", "chance")) + out <- .empty_resolution(compiled$value) + out$uses <- compiled$uses + out$requires <- compiled$requires + out$equation <- compiled$equation + out$rates <- compiled$rates + if (compiled$constant && kind %in% c("prob", "chance")) .check_probability(compiled$value, label) + return(out) + } + if (inherits(value, "pva_deferred")) { + kinds <- .helper_kinds[[value$helper]] + out <- .empty_resolution() + args <- value$args + for (name in names(args)) { + inner <- kinds[[name]] + part <- .resolve(args[[name]], if (is.null(inner)) "const" else inner, vocabulary, + paste0(label, " ", value$helper, "(", name, ")")) + args[name] <- list(part$value) + out <- .merge_resolution(out, part) + } + helper <- get(value$helper, envir = .namespace(), inherits = FALSE) + out$value <- tryCatch(do.call(helper, args), error = function(e) { + .stop(label, ": ", .deparse_authored(value), " failed: ", conditionMessage(e)) + }) + out$requires <- unique(c(out$requires, attr(out$value, "requires", exact = TRUE))) + out$quotas <- unique(c(out$quotas, attr(out$value, "survey_field", exact = TRUE))) + out$equation <- .deparse_authored(value) + return(out) + } + out <- .empty_resolution(value) + if (is.function(value)) { + used <- .params_used(value) + out$uses <- intersect(used$names, names(vocabulary$params)) + out$native <- length(used$names) > 0L || used$opaque + out$opaque <- used$opaque + out$requires <- attr(value, "requires", exact = TRUE) + out$quotas <- attr(value, "survey_field", exact = TRUE) + out$equation <- "" + return(out) + } + if (kind %in% c("prob", "chance", "rate") && is.logical(value)) out$value <- .as_prob_numeric(value) + if (kind %in% c("prob", "chance")) .check_probability(out$value, label) + out$equation <- .deparse_authored(value) + out +} + +.step_text <- function(step, argument, value) { + written <- step$written + if (is.function(value) && !is.null(names(written)) && argument %in% names(written)) { + return(written[[argument]]) + } + .deparse_authored(value) +} + +.step_label <- function(index, step, argument = NULL) { + paste0("step ", index, " '", step$name, "'", if (!is.null(argument)) paste0(" (", argument, ")")) +} + +.resolve_flag <- function(enabled, vocabulary, label) { + if (.is_flag(enabled)) return(list(value = enabled, uses = character())) + resolved <- .compile_formula(enabled, vocabulary, frame = "scalar", fold = "require", + label = paste0(label, " (enabled)")) + value <- resolved$value + if (is.numeric(value) && length(value) == 1L && value %in% c(0, 1)) value <- value == 1 + if (!.is_flag(value)) { + .stop(label, ": enabled = ", resolved$equation, " must give one TRUE or FALSE, not ", + paste(format(resolved$value), collapse = " ")) + } + list(value = value, uses = resolved$uses) +} + +.scheduled_run <- function(run, when, user, reset) { + force(run) + force(when) + force(user) + force(reset) + function(state, context, params) { + if (when(state, context, user)) return(run(state, context, params)) + if (!is.null(reset)) state$globals[[reset]] <- FALSE + pva_result(state) + } +} + +.survey_schedule <- function(when, user, visit) { + force(when) + force(user) + force(visit) + function(state, context, params) when(state, context, user) && visit(state, context, params) +} + +.schedule_process <- function(process, schedule, user, reset = NULL) { + if (isTRUE(schedule)) return(process) + when <- .when_function(schedule) + if (.is_survey_process(process)) { + process$params$when <- .survey_schedule(when, user, process$params$when) + } else { + run <- .scheduled_run(process$run, when, user, reset) + if (!is.null(reset)) attr(run, "catastrophe_flag") <- reset + if (identical(process$run, .update_inbreeding_proxy)) attr(run, "inbreeding_proxy") <- TRUE + process$run <- run + } + process +} + +.with_field_defaults <- function(callback, defaults) { + if (!length(defaults)) return(callback) + force(callback) + force(defaults) + function(...) { + supplied <- callback(...) + if (!is.list(supplied) || (length(supplied) && is.null(names(supplied)))) { + .stop("field callback must return a named list") + } + c(supplied, defaults[setdiff(names(defaults), names(supplied))]) + } +} + +.build_factory <- function(factory, params, label) { + kind <- RNGkind() + before <- .GlobalEnv$.Random.seed + process <- tryCatch(factory(params), error = function(e) { + .stop(label, ": the process factory failed: ", conditionMessage(e)) + }) + if (!identical(before, .GlobalEnv$.Random.seed) || !identical(kind, RNGkind())) { + .stop(label, ": stochastic process factory changed the RNG; draw random values inside the process run") + } + if (!inherits(process, "pva_process")) .stop(label, ": the process factory must return a pva_process") + process +} + +# Globals a step writes, known from its specification alone. +.step_globals <- function(step) { + args <- step$args + switch(step$type, + environment = names(args$variables), + catastrophe = args$global, + survey = args$field, + staged_survival = args$field, + process = { + process <- if (is.function(args$process)) step$built_process else args$process + sub("^globals\\.", "", grep("^globals\\.", process$writes, value = TRUE)) + }, + character() + ) +} + +.clock_schedule <- function(when, schedule) { + !is.function(schedule) || (inherits(when, "pva_formula") && !"state" %in% all.vars(body(schedule))) +} + +.starts_at_zero <- function(when, schedule, settings) { + if (!is.function(schedule)) return(isTRUE(schedule) || (is.numeric(schedule) && 0L %in% schedule)) + if (!.clock_schedule(when, schedule)) return(FALSE) + context <- list(time = 0L, dt = settings$dt, n_steps = settings$n_steps) + isTRUE(schedule(NULL, context, list())) +} + +.bound_step_params <- function(params, step, reads, opaque, label) { + if (opaque) { + if (is.null(step$uses)) { + .stop(label, ": callback reads or forwards params indirectly. Declare uses = c(...) ", + "with the parameter names it reads, or uses = character() if it forwards params unread.") + } + return(params) + } + params[union(step$uses, reads)] +} + +.compile_step <- function(index, step, vocabulary, model, user_params, build) { + label <- .step_label(index, step) + spec <- .step_specs[[step$type]] + args <- step$args + meta <- .empty_resolution() + if (!is.null(step$uses)) meta$uses <- step$uses + equations <- character() + resolve <- function(value, kind, argument) { + part <- .resolve(value, kind, vocabulary, .step_label(index, step, argument)) + meta <<- .merge_resolution(meta, part) + if (!is.null(part$equation) && + (!is.atomic(value) || argument %in% names(step$written) || !argument %in% names(args))) { + equations[[argument]] <<- if (is.function(value)) .step_text(step, argument, value) else part$equation + } + part$value + } + schedule <- if (isTRUE(step$when)) TRUE else resolve(step$when, "when", "when") + if (step$type == "process") { + process <- args$process + if (is.function(process)) { + used <- step$factory_reads + meta$uses <- union(meta$uses, used$names) + meta$opaque <- meta$opaque || used$opaque + process <- step$built_process + equations[["process"]] <- if (build) paste0("") else "" + } else { + equations[["process"]] <- "" + } + if (build) { + meta$quotas <- unique(unlist(lapply(process$params, attr, which = "survey_field", exact = TRUE))) + process$requires <- unique(c(process$requires, meta$requires)) + user <- .bound_step_params(user_params, step, meta$uses, meta$opaque, label) + process <- .schedule_process(process, schedule, user, + reset = attr(process$run, "catastrophe_flag", exact = TRUE)) + } + return(list(process = process, meta = meta, equations = equations, schedule = schedule, + name = if (is.null(process)) step$name else process$name)) + } + custom <- setdiff(vocabulary$fields, .reserved_fields) + native <- list() + for (argument in names(args)) { + value <- args[[argument]] + kind <- spec$kinds[argument] + if (step$type == "environment" && argument == "variables") { + native$variables <- list() + for (variable in names(value)) { + entry <- value[[variable]] + if (!inherits(entry, "pva_formula") && !inherits(entry, "pva_deferred") && + !is.function(entry)) { + .stop(label, ": variable '", variable, "' must be a formula, env_ar1(), env_trend() or a function") + } + part <- .resolve(entry, "variable", vocabulary, .step_label(index, step, variable)) + # A variable may read those drawn before it in the same step. + part$requires <- setdiff(part$requires, paste0("globals.", names(native$variables))) + meta <- .merge_resolution(meta, part) + equations[[variable]] <- if (is.function(entry)) .step_text(step, variable, entry) else part$equation + native$variables[[variable]] <- part$value + } + } else if (step$type == "census" && argument == "metrics") { + native$metrics <- if (is.list(value) && !inherits(value, "pva_formula")) { + if (is.null(names(value)) || any(!nzchar(names(value)))) { + .stop(label, ": census metrics given as a list must be named") + } + lapply(stats::setNames(names(value), names(value)), function(metric) { + resolve(value[[metric]], "metric", metric) + }) + } else { + resolve(value, "metric", "metrics") + } + } else if (step$type == "introduction" && argument == "fields") { + if (is.function(value)) { + native$fields <- .with_field_defaults(resolve(value, "const", "fields"), model$fields) + native$creates <- unique(c("sex", "age", custom)) + } else { + if (!is.list(value) || is.null(names(value))) { + .stop(label, ": fields must be a named list such as list(sex = c(\"F\", \"M\"), age = 2L)") + } + resolved <- lapply(stats::setNames(names(value), names(value)), function(field) { + resolve(value[[field]], "const", paste0("fields$", field)) + }) + defaults <- model$fields[setdiff(names(model$fields), names(resolved))] + native$fields <- c(resolved, defaults) + unknown <- setdiff(names(native$fields), c("sex", "age", "mother_id", "father_id", custom)) + if (length(unknown)) { + .stop(label, ": introduced individuals set '", unknown[[1L]], + "', which is not a population field", .did_you_mean(unknown[[1L]], custom)) + } + } + } else if (step$type == "reproduction" && argument == "newborn_fields") { + inherit <- args$inherit + defaults <- model$fields[setdiff(names(model$fields), inherit)] + if (is.function(value)) { + native$newborn_fields <- .with_field_defaults(resolve(value, "const", "newborn_fields"), defaults) + native$newborn_field_names <- setdiff(custom, inherit) + } else { + if (!is.null(value) && (!is.list(value) || is.null(names(value)))) { + .stop(label, ": newborn_fields must be a named list or a function") + } + resolved <- lapply(stats::setNames(names(value), names(value)), function(field) { + resolve(value[[field]], "const", paste0("newborn_fields$", field)) + }) + fields <- c(resolved, defaults[setdiff(names(defaults), names(resolved))]) + if (length(fields)) { + native$newborn_fields <- fields + native$newborn_field_names <- names(fields) + } + } + } else if (is.na(kind)) { + native[argument] <- list(resolve(value, "const", argument)) + } else { + native[argument] <- list(resolve(value, kind, argument)) + } + } + if (isTRUE(spec$native_when)) native$when <- schedule + if (!build) return(list(process = NULL, meta = meta, equations = equations, name = step$name)) + constructor <- get(spec$constructor, envir = .namespace(), inherits = FALSE) + accepted <- names(formals(constructor)) + native$name <- step$name + user <- if (meta$native || length(step$uses)) { + .bound_step_params(user_params, step, meta$uses, meta$opaque, label) + } else list() + if ("params" %in% accepted && length(user)) native$params <- user + native <- native[!vapply(native, is.null, logical(1))] + process <- tryCatch(do.call(constructor, native), error = function(e) { + .stop(label, ": ", conditionMessage(e)) + }) + process$requires <- unique(c(process$requires, meta$requires, step$requires)) + if (!isTRUE(spec$native_when)) { + process <- .schedule_process(process, schedule, user, reset = if (step$type == "catastrophe") native$global) + } + list(process = process, meta = meta, equations = equations, name = step$name, schedule = schedule, + release = if (step$type == "introduction" && is.list(native$fields)) { + list(fields = native$fields, count = native$count) + }) +} + +.check_overrides <- function(model, overrides, where) { + if (is.null(overrides)) overrides <- list() + if (!is.list(overrides) || (length(overrides) && (is.null(names(overrides)) || + any(!nzchar(names(overrides))) || anyDuplicated(names(overrides))))) { + .stop(where, "overrides must be a uniquely named list of parameter values") + } + for (name in names(overrides)) { + if (!name %in% names(model$params)) { + .stop(where, "override '", name, "' is not a parameter of model '", model$name, "'", + .did_you_mean(name, names(model$params))) + } + base <- model$params[[name]] + value <- overrides[[name]] + kind <- function(x) if (is.numeric(x)) "number" else if (is.logical(x)) "flag" else typeof(x) + compatible <- identical(kind(base), kind(value)) || + (is.logical(base) && is.numeric(value) && all(value %in% c(0, 1))) + if (is.null(value) || !is.atomic(value) || anyNA(value) || !compatible) { + .stop(where, "override '", name, "' must be a non-missing ", kind(base), + " like the base value ", .deparse_authored(base)) + } + if (is.logical(base) && is.numeric(value)) overrides[[name]] <- value == 1 + } + overrides +} + +.compile_model <- function(model, overrides = list(), where = "") { + .check_model(model) + overrides <- .check_overrides(model, overrides, where) + params <- model$params + params[names(overrides)] <- overrides + state <- .preview_state(model) + steps <- model$steps + if (!length(steps)) { + .stop(where, "model '", model$name, "' has no steps; add them with step_*()") + } + fields <- names(state$population) + flag_vocabulary <- .vocabulary(params, character(), character(), model$rates, + paste0(where, "model '", model$name, "'")) + flags <- lapply(seq_along(steps), function(index) { + .resolve_flag(steps[[index]]$enabled, flag_vocabulary, paste0(where, .step_label(index, steps[[index]]))) + }) + enabled <- vapply(flags, `[[`, logical(1), "value") + for (index in seq_along(steps)) { + step <- steps[[index]] + factory <- step$args$process + if (step$type != "process" || !is.function(factory)) next + used <- .params_used(factory, names(formals(factory))[[1L]]) + used$names <- intersect(used$names, names(params)) + steps[[index]]$factory_reads <- used + if (enabled[[index]]) { + label <- paste0(where, .step_label(index, step)) + bound <- .bound_step_params(params, step, used$names, used$opaque, label) + args <- list(factory = factory, params = bound, label = label) + steps[[index]]$built_process <- .preview_call(.build_factory, args, user_code = TRUE) + } + } + globals <- unique(c(names(state$globals), unlist(lapply(steps, .step_globals)))) + vocabulary <- .vocabulary(params, fields, globals, model$rates, + paste0(where, "model '", model$name, "'")) + compiled <- vector("list", length(steps)) + for (index in seq_along(steps)) { + compiled[[index]] <- withCallingHandlers( + .compile_step(index, steps[[index]], vocabulary, model, params, build = enabled[[index]]), + error = function(e) { + if (nzchar(where)) .stop(where, conditionMessage(e)) + } + ) + compiled[[index]]$meta$uses <- unique(c(compiled[[index]]$meta$uses, flags[[index]]$uses)) + compiled[[index]]$toggle <- flags[[index]]$uses + } + labels <- vapply(seq_along(steps), function(index) .step_label(index, steps[[index]]), character(1)) + processes <- lapply(compiled[enabled], `[[`, "process") + + # Globals must exist before the step that reads them. + available <- if (length(state$globals)) paste0("globals.", names(state$globals)) + survey_fields <- character() + conditional <- integer() + writers <- lapply(seq_along(steps), function(index) { + if (enabled[[index]]) { + grep("^globals\\.", compiled[[index]]$process$writes, value = TRUE) + } else { + paste0("globals.", .step_globals(steps[[index]])) + } + }) + for (index in which(enabled)) { + step <- compiled[[index]] + needed <- grep("^globals\\.", step$process$requires, value = TRUE) + for (path in setdiff(needed, available)) { + prior <- conditional[vapply(writers[conditional], function(w) path %in% w, logical(1))] + if (length(prior) && .clock_schedule(steps[[index]]$when, step$schedule) && + any(vapply(steps[prior], function(s) identical(s$when, steps[[index]]$when), logical(1)))) next + global <- sub("^globals\\.", "", path) + off <- which(!enabled & vapply(writers, function(w) path %in% w, logical(1))) + later <- which(enabled & seq_along(steps) > index & + vapply(writers, function(w) path %in% w, logical(1))) + if (length(later) && steps[[later[[1L]]]]$type == "survey") { + .stop(where, labels[[index]], " reads the survey record '", global, "' before ", + labels[[later[[1L]]]], " writes it; a survey_quota() must come after its step_survey()") + } + if (length(later)) { + .stop(where, labels[[index]], " reads global '", global, "' before ", labels[[later[[1L]]]], + " writes it; reorder the steps or give a starting value with pva_model(globals = list(", + global, " = ...))") + } + if (length(off)) { + .stop(where, labels[[index]], " needs global '", global, "', which is written only by the disabled ", + labels[[off[[1L]]]], "; enable that step or disable this one too") + } + if (length(prior)) { + .stop(where, labels[[index]], " reads global '", global, "' from a scheduled writer; ", + "supply its initial value in pva_model(globals = ...) or make the writer unconditional") + } + .stop(where, labels[[index]], " needs global '", global, "', which no step writes") + } + missing_survey <- setdiff(step$meta$quotas, survey_fields) + if (length(missing_survey)) { + .stop(where, labels[[index]], ": survey_quota() requires an upstream survey writer for '", + missing_survey[[1L]], "'; use step_survey(field = ...) before this step") + } + survey <- .is_survey_process(step$process) + survey_fields <- setdiff(survey_fields, sub("^globals\\.", "", writers[[index]])) + if (survey) survey_fields <- c(survey_fields, step$process$params$field) + if (!length(writers[[index]])) next + if (.starts_at_zero(steps[[index]]$when, step$schedule, model$settings) || + survey || steps[[index]]$type == "catastrophe" || + !is.null(attr(step$process$run, "catastrophe_flag", exact = TRUE))) { + available <- c(available, writers[[index]]) + } else { + conditional <- c(conditional, index) + } + } + + active <- Filter(function(step) !isFALSE(step$schedule), compiled[enabled]) + active_processes <- lapply(active, "[[", "process") + breeding <- Filter(function(p) !is.null(p$params$breeding_probability), active_processes) + newborn_fields <- lapply(breeding, function(p) attr(p$params$newborn_fields, "pva_newborn_fields", exact = TRUE)) + writes <- unique(unlist(lapply(active_processes, "[[", "writes"), use.names = FALSE)) + releases <- Filter(Negate(is.null), lapply(active, "[[", "release")) + for (index in which(enabled)) { + .check_rate_coverage(model, state, compiled[[index]]$meta$rates, newborn_fields, writes, + paste0(where, labels[[index]]), releases) + } + + # Who consumes each parameter, and whether an override can have any effect. + consumers <- lapply(stats::setNames(names(params), names(params)), function(name) { + which(vapply(compiled, function(step) name %in% step$meta$uses, logical(1))) + }) + live <- vapply(names(params), function(name) { + users <- consumers[[name]] + any(enabled[users]) || + any(vapply(compiled[users], function(step) name %in% step$toggle, logical(1))) + }, logical(1)) + for (name in names(overrides)) { + if (live[[name]]) next + users <- consumers[[name]] + if (length(users)) { + .stop(where, "override '", name, "' has no effect: it is used only by the disabled ", + paste(labels[users], collapse = ", "), "; drop the override or enable the step") + } + .stop(where, "override '", name, "' has no effect: no step of model '", model$name, + "' uses that parameter") + } + + census <- which(enabled & vapply(steps, function(step) step$type == "census", logical(1))) + choice <- model$settings$initial_census + initial_census <- NULL + if (is.character(choice)) { + named <- census[vapply(steps[census], function(step) step$name == choice, logical(1))] + if (!length(named)) { + .stop(where, "initial_census = '", choice, "' does not name an enabled census step") + } + census <- named + choice <- TRUE + } + if (isTRUE(choice) && length(census)) { + last <- census[[length(census)]] + initial_census <- compiled[[last]]$process + if (!isTRUE(steps[[last]]$when)) { + observer <- steps[[last]] + observer$when <- TRUE + initial_census <- .compile_step(last, observer, vocabulary, model, params, build = TRUE)$process + } + tryCatch(.validate_field_plan(list(initial_census), state), error = function(e) { + .stop(where, "initial_census at ", labels[[last]], ": ", conditionMessage(e)) + }) + } + + step_table <- data.frame( + step = seq_along(steps), + name = vapply(compiled, `[[`, character(1), "name"), + type = vapply(steps, `[[`, character(1), "type"), + enabled = enabled, + when = vapply(steps, function(step) { + if (isTRUE(step$when)) "every interval" else .deparse_authored(step$when) + }, character(1)), + equations = vapply(compiled, function(step) { + shown <- step$equations[setdiff(names(step$equations), "when")] + paste(sprintf("%s = %s", names(shown), shown), collapse = "; ") + }, character(1)), + parameters = vapply(compiled, function(step) { + used <- step$meta$uses + if (!length(used)) return("") + paste(sprintf("%s = %s", used, vapply(params[used], .deparse_authored, character(1))), + collapse = "; ") + }, character(1)), + stringsAsFactors = FALSE + ) + list( + model = model, params = params, overrides = overrides, state = state, + processes = processes, initial_census = initial_census, enabled = enabled, + steps = step_table, consumers = consumers, live = live, labels = labels + ) +} + +compile_scenario <- function(model, overrides = list(), n_runs = 100L, seed = NULL, name = NULL, + validation = c("strict", "fast")) { + .compile_scenario(model, overrides, n_runs, seed, name, validation) +} + +.compile_scenario <- function(model, overrides, n_runs, seed, name, validation, where = "") { + validation <- match.arg(validation, c("strict", "fast")) + .model_scenario(.compile_model(model, overrides, where), n_runs, seed, name, validation, where) +} + +.model_scenario <- function(compiled, n_runs, seed, name, validation, where = "") { + model <- compiled$model + scenario <- scenario_spec( + name = if (is.null(name)) model$name else name, + n_runs = n_runs, + n_steps = model$settings$n_steps, + init_fun = .model_init_fun(model), + processes = compiled$processes, + seed = seed, + dt = model$settings$dt, + initial_census = compiled$initial_census + ) + tryCatch(validate_processes(scenario$processes, compiled$state), error = function(e) { + .stop(where, "model '", model$name, "': ", conditionMessage(e)) + }) + scenario$validation <- validation + scenario$authoring <- list( + model = model$name, overrides = compiled$overrides, + steps = compiled$steps[compiled$enabled, , drop = FALSE] + ) + scenario +} + +# ---- ensembles built from models ------------------------------------------ + +.ensemble_models <- function(build) { + if (inherits(build, "pva_model")) return(list(build)) + if (is.list(build) && length(build) && !is.function(build) && + all(vapply(build, inherits, logical(1), "pva_model"))) { + if (is.null(names(build)) || anyNA(names(build)) || any(!nzchar(names(build))) || + anyDuplicated(names(build))) { + .stop("a list of models needs unique names, matched against the design column 'model'") + } + conflicts <- vapply(build, function(model) "model" %in% names(model$params), logical(1)) + if (any(conflicts)) { + .stop("structural model '", names(build)[which(conflicts)[1L]], + "' declares parameter 'model', reserved for model selection") + } + return(build) + } + NULL +} + +# One design row -> the model it selects and the overrides it carries. +.design_row <- function(models, row, metadata, where) { + row <- lapply(row, function(value) { + if (is.list(value)) value <- value[[1L]] + if (is.factor(value)) as.character(value) else value + }) + if (is.null(names(models))) { + model <- models[[1L]] + } else { + choice <- row[["model"]] + if (is.null(choice) || length(choice) != 1L || is.na(choice) || !choice %in% names(models)) { + .stop(where, "the design column 'model' must name one of: ", + paste(names(models), collapse = ", ")) + } + model <- models[[as.character(choice)]] + } + overrides <- list() + for (column in names(row)) { + value <- row[[column]] + if (length(value) == 1L && is.na(value)) next + if (!column %in% names(model$params)) { + if (column %in% metadata) next + .stop(where, "design column '", column, "' is not a parameter of model '", model$name, "'", + .did_you_mean(column, names(model$params)), + "; leave the cell NA where it does not apply, or name descriptive columns 'label' or 'scenario'") + } + overrides[[column]] <- value + } + list(model = model, overrides = overrides) +} + +# Compile the members before assigning any seeds or looking up cached summaries. +.model_members <- function(models, design, seed_by, n_runs, validation) { + known <- unique(unlist(lapply(models, function(model) names(model$params)))) + structural <- !is.null(names(models)) + metadata <- c("label", "scenario", if (structural) "model", if (is.character(seed_by)) seed_by) + if (structural && !"model" %in% names(design)) { + .stop("a list of models needs a design column 'model' naming the model for each row") + } + stray <- setdiff(names(design), c(metadata, known)) + if (length(stray)) { + .stop("design column '", stray[[1L]], "' is not a parameter of any supplied model", + .did_you_mean(stray[[1L]], known), + "; name descriptive columns 'label' or 'scenario'") + } + lapply(seq_len(nrow(design)), function(member) { + where <- paste0("design row ", member, ": ") + chosen <- .design_row(models, as.list(design[member, , drop = FALSE]), metadata, where) + .compile_scenario(chosen$model, chosen$overrides, n_runs, NULL, paste0("member-", member), + validation, where) + }) +} diff --git a/R/model_audit.R b/R/model_audit.R new file mode 100644 index 0000000..ad7ee07 --- /dev/null +++ b/R/model_audit.R @@ -0,0 +1,178 @@ +# Audit views of a pva_model: where every parameter goes, and what the model +# will build, without running a replicate or moving the caller's RNG. + +.format_value <- function(value) { + if (is.matrix(value)) return(sprintf("<%d x %d matrix>", nrow(value), ncol(value))) + if (is.numeric(value)) return(paste(format(value, digits = 15L, trim = TRUE), collapse = "; ")) + paste(as.character(value), collapse = "; ") +} + +.parameter_table <- function(compiled) { + model <- compiled$model + labels <- as.character(names(model$params)) + used_by <- vapply(labels, function(name) { + users <- compiled$consumers[[name]] + if (!length(users)) return("") + paste(sprintf("%s%s", compiled$steps$name[users], + ifelse(compiled$enabled[users], "", " (disabled)")), collapse = ", ") + }, character(1)) + status <- ifelse(compiled$live, "active", + ifelse(nzchar(used_by), "inactive: only disabled steps use it", "unused")) + out <- data.frame( + parameter = labels, + base = I(unname(model$params)), + value = I(unname(compiled$params)), + overridden = labels %in% names(compiled$overrides), + status = as.character(status), + used_by = used_by, + stringsAsFactors = FALSE + ) + if (!is.null(model$evidence) && ncol(model$evidence)) { + evidence <- model$evidence + for (i in which(names(evidence) %in% names(out))) { + name <- paste0("evidence.", names(evidence)[i]) + while (name %in% names(evidence)) name <- paste0("evidence.", name) + names(evidence)[i] <- name + } + out <- cbind(out, evidence) + } + rownames(out) <- NULL + class(out) <- c("pva_parameters", "data.frame") + out +} + +print.pva_parameters <- function(x, ...) { + shown <- x + for (column in intersect(c("base", "value"), names(x))) { + shown[[column]] <- vapply(x[[column]], .format_value, character(1)) + } + print.data.frame(shown, ...) + invisible(x) +} + +describe_parameters <- function(model, overrides = list()) { + .parameter_table(.with_rng_restored(.compile_model(model, overrides))) +} + +# Female rates by age for a deterministic life-table check of the authored +# rates. Formulas may use parameters, age and rate() only. +.model_life_table <- function(compiled, spec) { + if (!is.list(spec) || !all(c("survival", "fecundity") %in% names(spec)) || + !all(names(spec) %in% c("survival", "fecundity", "timing", "plus_group", "max_age"))) { + .stop("life_table must be a list with survival and fecundity (formulas or numeric vectors), ", + "and optionally timing, plus_group and max_age") + } + model <- compiled$model + max_age <- spec$max_age + if (is.null(max_age)) { + bounds <- unlist(lapply(names(model$rates), function(name) { + table <- model$rates[[name]] + if (all(c("age_min", "age_max") %in% names(table))) table$age_min + else if ("age" %in% names(table)) .rate_age_bounds(table$age)$age_min + })) + if (!length(bounds)) .stop("life_table needs max_age when the model has no rate table") + max_age <- max(bounds) + } + max_age <- .as_count(max_age, "max_age") + females <- pva_population(sex = rep("F", max_age + 1L), age = seq.int(0L, max_age)) + vocabulary <- .vocabulary(compiled$params, c("id", "sex", "age"), character(), model$rates, + paste0("model '", model$name, "' life table")) + evaluate <- function(value, label) { + value <- .capture(value) + if (!inherits(value, "pva_formula")) return(value) + compiled <- .compile_formula(value, vocabulary, frame = "individual", numeric = TRUE, + fold = "never", label = paste0("life_table ", label)) + out <- compiled$value(females, NULL, list(time = 0L, dt = model$settings$dt), NULL) + rep_len(as.numeric(out), max_age + 1L) + } + survival <- evaluate(spec$survival, "survival") + fecundity <- evaluate(spec$fecundity, "fecundity") + metrics <- life_table_metrics( + survival, fecundity, + timing = if (is.null(spec$timing)) "post_breeding" else spec$timing, + plus_group = if (is.null(spec$plus_group)) TRUE else spec$plus_group + ) + c(list(age = seq.int(0L, max_age), survival = survival, fecundity = fecundity), metrics) +} + +describe_model <- function(model, overrides = list(), life_table = NULL) { + compiled <- .with_rng_restored(.compile_model(model, overrides)) + population <- compiled$state$population + settings <- model$settings + custom <- setdiff(names(population), .reserved_fields) + cohorts <- if (length(population$id)) { + counts <- as.data.frame(table(sex = population$sex, age = population$age), + responseName = "n", stringsAsFactors = FALSE) + counts$age <- as.integer(counts$age) + counts <- counts[counts$n > 0L, , drop = FALSE] + counts <- counts[order(counts$sex, counts$age), , drop = FALSE] + rownames(counts) <- NULL + counts + } else data.frame(sex = character(), age = integer(), n = integer()) + parameters <- .parameter_table(compiled) + audit <- list( + name = model$name, + settings = c(settings[c("n_steps", "dt", "pedigree", "n_loci")], + list(mate_field = if (is.null(settings$mate_field)) NA_character_ else settings$mate_field)), + n_initial = length(population$id), + initial = cohorts, + fields = data.frame( + field = custom, + type = vapply(population[custom], typeof, character(1)), + default = vapply(custom, function(field) { + if (field %in% names(model$fields)) .format_value(model$fields[[field]]) else "(from init)" + }, character(1)), + stringsAsFactors = FALSE, row.names = NULL + ), + globals = names(compiled$state$globals), + steps = compiled$steps, + parameters = parameters, + unused = parameters$parameter[parameters$status == "unused"], + life_table = if (!is.null(life_table)) .model_life_table(compiled, life_table) + ) + class(audit) <- "pva_model_audit" + audit +} + +print.pva_model_audit <- function(x, ...) { + settings <- x$settings + cat(sprintf( + "\n", + x$name, settings$n_steps, settings$dt, x$n_initial, if (settings$pedigree) "on" else "off", + if (settings$n_loci > 0L) sprintf(" | loci: %d", settings$n_loci) else "", + if (!is.na(settings$mate_field)) sprintf(" | mate_field: %s", settings$mate_field) else "" + )) + if (x$n_initial) { + by_sex <- tapply(x$initial$n, x$initial$sex, sum) + cat(sprintf("Initial population: %s; ages %d-%d\n", + paste(sprintf("%d %s", by_sex, names(by_sex)), collapse = ", "), + min(x$initial$age), max(x$initial$age))) + } + if (nrow(x$fields)) { + cat(sprintf("Custom fields: %s\n", + paste(sprintf("%s (%s, default %s)", x$fields$field, x$fields$type, x$fields$default), + collapse = "; "))) + } + cat("\nSteps:\n") + steps <- x$steps + for (i in seq_len(nrow(steps))) { + cat(sprintf(" %2d. %s [%s]%s%s\n", steps$step[[i]], steps$name[[i]], steps$type[[i]], + if (steps$enabled[[i]]) "" else " (disabled)", + if (steps$when[[i]] != "every interval") paste0(" when ", steps$when[[i]]) else "")) + if (nzchar(steps$equations[[i]])) cat(sprintf(" %s\n", steps$equations[[i]])) + if (nzchar(steps$parameters[[i]])) cat(sprintf(" with %s\n", steps$parameters[[i]])) + } + cat("\nParameters:\n") + print(x$parameters, row.names = FALSE, right = FALSE) + if (length(x$unused)) { + cat(sprintf("\nDeclared but unused: %s\n", paste(x$unused, collapse = ", "))) + } + if (!is.null(x$life_table)) { + table <- x$life_table + cat(sprintf( + "\nFemale life table from the authored rates: lambda = %.4f, R0 = %.3f, generation time = %.2f\n", + table$lambda, table$R0, table$generation_time + )) + } + invisible(x) +} diff --git a/R/pedigree.R b/R/pedigree.R index f29ab21..153106f 100644 --- a/R/pedigree.R +++ b/R/pedigree.R @@ -354,7 +354,8 @@ inbreeding_proxy_process <- function( ), requires = unique(c(paste0("globals.", global), requires)), writes = paste0("globals.", global), - description = "Update an aggregate expected inbreeding coefficient from effective size." + description = "Update an aggregate expected inbreeding coefficient from effective size.", + role = .default_role("demography") ) } diff --git a/R/process.R b/R/process.R index 7ea0319..8f0aa60 100644 --- a/R/process.R +++ b/R/process.R @@ -13,7 +13,8 @@ pva_process <- function( requires = character(), writes = character(), creates = NULL, - description = NULL) { + description = NULL, + role = NULL) { process <- list( name = name, run = run, @@ -23,7 +24,16 @@ pva_process <- function( creates = creates, description = description ) - .validate_process(process) + default <- inherits(role, "pva_default_role") + if (!is.null(role) && !default) process$role <- role + process <- .validate_process(process) + if (default) { + # A built-in constructor: keep the role its name and effects have always + # been shown under, and fall back to the constructor's own role. + inferred <- if (identical(unclass(role), "survey")) "survey" else .infer_role(process) + process$role <- if (identical(inferred, "custom")) unclass(role) else inferred + } + process } .validate_process <- function(process) { @@ -65,6 +75,10 @@ pva_process <- function( if (!is.null(process$description) && !.is_name(process$description)) { .stop(label, " description must be NULL or one character value") } + if (!is.null(process$role) && + !(.is_name(process$role) && process$role %in% names(.lifecycle_roles))) { + .stop(label, " role must be NULL or one of: ", paste(names(.lifecycle_roles), collapse = ", ")) + } class(process) <- "pva_process" process } @@ -134,16 +148,18 @@ validate_processes <- function(processes, state = NULL) { invisible(processes) } +.is_survey_process <- function(p) { + # Serialisation can replace nested source-reference environments on workers. + identical(environment(p$run), environment(.run_survey)) && + (identical(p$run, .run_survey) || + identical(utils::removeSource(p$run), utils::removeSource(.run_survey))) +} + .prepare_execution <- function(processes) { processes <- lapply(processes, .validate_process) names_in_order <- vapply(processes, `[[`, character(1), "name") occurrence <- stats::ave(seq_along(names_in_order), names_in_order, FUN = seq_along) - survey <- vapply(processes, function(p) { - # Serialisation can replace nested source-reference environments on workers. - identical(environment(p$run), environment(.run_survey)) && - (identical(p$run, .run_survey) || - identical(utils::removeSource(p$run), utils::removeSource(.run_survey))) - }, logical(1)) + survey <- vapply(processes, .is_survey_process, logical(1)) sire_lookup <- vapply(processes, function(p) { !is.null(p$params$mate_field) && is.function(p$params$newborn_fields) }, logical(1)) @@ -176,7 +192,8 @@ validate_processes <- function(processes, state = NULL) { sire_lookup = sire_lookup, snapshot_sires = snapshot_sires, closed_proxy = any(vapply(processes, function(p) { - identical(p$run, .update_inbreeding_proxy) && is.null(p$params$migration) + (identical(p$run, .update_inbreeding_proxy) || isTRUE(attr(p$run, "inbreeding_proxy"))) && + is.null(p$params$migration) }, logical(1))), population_writes = lapply(processes, function(process) { strip(process$writes, "population.") diff --git a/R/processes_demography.R b/R/processes_demography.R index 514c2ab..5803569 100644 --- a/R/processes_demography.R +++ b/R/processes_demography.R @@ -48,6 +48,51 @@ invisible(value) } +.constant_fields <- function(values, label, newborn = FALSE) { + plain <- vapply(values, function(value) { + is.atomic(value) && !is.null(value) && is.null(attributes(value)) && length(value) >= 1L + }, logical(1)) + if (!length(values) && newborn) { + return(function(mothers, fathers, pop, state, context, params) list()) + } + if (is.null(names(values)) || any(!nzchar(names(values))) || anyDuplicated(names(values)) || + !all(plain)) { + .stop(label, " must be a function or a uniquely named list of plain values") + } + if (newborn) { + if (any(lengths(values) != 1L)) { + .stop(label, " given as a list must hold one value per field") + } + return(structure(function(mothers, fathers, pop, state, context, params) values, + pva_newborn_fields = values)) + } + if (!all(c("sex", "age") %in% names(values))) { + .stop(label, " given as a list must include sex and age") + } + function(n, state, context, params) lapply(values, rep_len, n) +} + +.census_metrics <- function(metrics) { + labels <- names(metrics) + if (!length(metrics) || is.null(labels) || any(!nzchar(labels)) || anyDuplicated(labels) || + !all(vapply(metrics, is.function, logical(1)))) { + .stop("metrics given as a list must be uniquely named functions of (pop, state, context, params)") + } + function(pop, state, context, params) { + out <- numeric(length(metrics)) + for (i in seq_along(metrics)) { + value <- metrics[[i]](pop, state, context, params) + if (is.logical(value) && !anyNA(value)) value <- sum(value) + if (!is.numeric(value) || length(value) != 1L) { + .stop("census metric ", labels[[i]], " must be one number, or a logical vector to count") + } + out[[i]] <- value + } + names(out) <- labels + out + } +} + age_process <- function(name = "age", increment = 1L) { increment <- .as_count(increment, "increment", minimum = 1) pva_process( @@ -59,7 +104,8 @@ age_process <- function(name = "age", increment = 1L) { params = list(increment = increment), requires = "population.age", writes = "population.age", - description = "Advance the age of every living individual." + description = "Advance the age of every living individual.", + role = .default_role("demography") ) } @@ -98,21 +144,26 @@ survival_process <- function( ), requires = unique(c("population.alive", requires)), writes = "population.alive", - description = "Independent Bernoulli survival of eligible individuals." + description = "Independent Bernoulli survival of eligible individuals.", + role = .default_role("demography") ) } litter_poisson <- function(mean) { + if (.any_authored(mean)) return(.deferred("litter_poisson", list(mean = mean))) mean <- .rate_function(mean, "mean") - function(mothers, pop, state, context, params) { + .helper_fn(function(mothers, pop, state, context, params) { expected <- .per_individual( mean(pop, state, context, params), length(pop$id), "litter mean", 0 ) stats::rpois(length(mothers), expected[mothers]) - } + }, "mean") } litter_binomial <- function(size, mean, min_size = 0L) { + if (.any_authored(size, mean, min_size)) { + return(.deferred("litter_binomial", list(size = size, mean = mean, min_size = min_size))) + } size <- .as_count(size, "size", minimum = 1) min_size <- .as_count(min_size, "min_size") if (min_size > size) { @@ -122,7 +173,7 @@ litter_binomial <- function(size, mean, min_size = 0L) { .per_individual(mean, 1L, "litter mean", min_size, size) } mean <- .rate_function(mean, "mean") - function(mothers, pop, state, context, params) { + .helper_fn(function(mothers, pop, state, context, params) { expected <- .per_individual( mean(pop, state, context, params), length(pop$id), "litter mean", 0 )[mothers] @@ -134,10 +185,13 @@ litter_binomial <- function(size, mean, min_size = 0L) { } min_size + stats::rbinom(length(mothers), size - min_size, (expected - min_size) / (size - min_size)) - } + }, "mean") } litter_categorical <- function(sizes, probabilities) { + if (.any_authored(sizes, probabilities)) { + return(.deferred("litter_categorical", list(sizes = sizes, probabilities = probabilities))) + } if (!is.numeric(sizes) || !length(sizes) || any(!is.finite(sizes)) || any(sizes < 0 | sizes > .Machine$integer.max) || any(sizes != floor(sizes)) || anyDuplicated(sizes)) { @@ -160,11 +214,11 @@ litter_categorical <- function(sizes, probabilities) { } if (!is.function(probabilities)) { check(probabilities) - return(function(mothers, pop, state, context, params) { + return(.helper_fn(function(mothers, pop, state, context, params) { sizes[sample.int(length(sizes), length(mothers), replace = TRUE, prob = probabilities)] - }) + })) } - function(mothers, pop, state, context, params) { + .helper_fn(function(mothers, pop, state, context, params) { p <- probabilities(pop, state, context, params) totals <- check(p, length(pop$id)) if (!is.matrix(p)) { @@ -178,32 +232,36 @@ litter_categorical <- function(sizes, probabilities) { category <- category + (draw >= cumulative) } sizes[category] - } + }, "probabilities") } offspring_sex_bernoulli <- function(female_probability = 0.5) { + if (.any_authored(female_probability)) { + return(.deferred("offspring_sex_bernoulli", list(female_probability = female_probability))) + } if (is.function(female_probability)) { - return(function(mothers, pop, state, context, params) { + return(.helper_fn(function(mothers, pop, state, context, params) { p <- female_probability(pop, state, context, params) if (!is.null(dim(p))) .stop("female_probability must return a scalar or vector") p <- .per_individual(p, length(pop$id), "female_probability", 0, 1) ifelse(stats::runif(length(mothers)) < p[mothers], "F", "M") - }) + }, "female_probability")) } if (!is.numeric(female_probability) || length(female_probability) != 1L || is.na(female_probability) || female_probability < 0 || female_probability > 1) { .stop("female_probability must be one number in [0, 1]") } - function(mothers, pop, state, context, params) { + .helper_fn(function(mothers, pop, state, context, params) { ifelse(stats::runif(length(mothers)) < female_probability, "F", "M") - } + }) } mate_random <- function(eligible) { + if (.any_authored(eligible)) return(.deferred("mate_random", list(eligible = eligible))) if (!is.function(eligible)) { .stop("eligible must be a function of (pop, state, context, params)") } - function(pop, state, context, params) { + .helper_fn(function(pop, state, context, params) { n <- length(pop$id) males <- .eligible_rows(eligible, pop, state, context, params) males <- males[pop$sex[males] == "M"] @@ -211,7 +269,7 @@ mate_random <- function(eligible) { return(rep(NA_integer_, n)) } males[sample.int(length(males), n, replace = TRUE)] - } + }, "eligible") } mate_from_field <- function(field = "mate_id", stale = c("error", "unpaired")) { @@ -237,7 +295,7 @@ mate_from_field <- function(field = "mate_id", stale = c("error", "unpaired")) { rows } attr(lookup, "mate_field") <- field - lookup + .helper_fn(lookup) } reproduction_process <- function( @@ -253,6 +311,10 @@ reproduction_process <- function( requires = character(), params = list()) { breeding_probability <- .rate_function(breeding_probability, "breeding_probability") + if (is.list(newborn_fields)) { + if (!length(newborn_field_names)) newborn_field_names <- names(newborn_fields) + newborn_fields <- .constant_fields(newborn_fields, "newborn_fields", newborn = TRUE) + } if (!is.function(litter_size)) { .stop("litter_size must be a function, for example litter_poisson()") } @@ -383,7 +445,8 @@ reproduction_process <- function( attr(mate, "mate_requires", exact = TRUE), requires)), writes = character(), creates = c("sex", "age", "mother_id", "father_id", newborn_field_names, inherit), - description = "Bernoulli breeding, a modeller-chosen litter distribution and explicit offspring sex." + description = "Bernoulli breeding, a modeller-chosen litter distribution and explicit offspring sex.", + role = .default_role("demography") ) } @@ -392,6 +455,7 @@ census_process <- function( name = "census", requires = character(), params = list()) { + if (is.list(metrics)) metrics <- .census_metrics(metrics) .check_optional_function(metrics, "metrics") if (is.null(metrics)) { metrics <- function(pop, state, context, params) { @@ -412,7 +476,8 @@ census_process <- function( }, params = list(metrics = metrics, user = params), requires = unique(c("population.sex", "population.alive", requires)), - description = "Non-mutating census; its position in the lifecycle defines what it observes." + description = "Non-mutating census; its position in the lifecycle defines what it observes.", + role = .default_role("census") ) } @@ -488,6 +553,7 @@ staged_survival_process <- function( ), requires = unique(c("population.alive", if (stage == "post") path, requires)), writes = c("population.alive", path), - description = "One stage of an interval's survival split around a mid-interval event." + description = "One stage of an interval's survival split around a mid-interval event.", + role = .default_role("demography") ) } diff --git a/R/processes_environment.R b/R/processes_environment.R index 3157724..8152667 100644 --- a/R/processes_environment.R +++ b/R/processes_environment.R @@ -21,7 +21,8 @@ environment_process <- function( params = list(variables = variables, user = params), requires = requires, writes = paste0("globals.", names(variables)), - description = "Draw shared environmental conditions for the interval." + description = "Draw shared environmental conditions for the interval.", + role = .default_role("environment") ) } @@ -29,6 +30,9 @@ environment_process <- function( # or both. The lagged value lives in state$globals under the variable's own # name, never in this closure, so replicates cannot share it. env_ar1 <- function(sd = 1, phi = 0, cor = NULL, names = NULL) { + if (.any_authored(sd, phi, cor, names)) { + return(.deferred("env_ar1", list(sd = sd, phi = phi, cor = cor, names = names))) + } if (!is.numeric(phi) || !is.null(dim(phi)) || length(phi) != 1L || !is.finite(phi) || abs(phi) >= 1) { .stop("phi must be one number with |phi| < 1") @@ -83,7 +87,7 @@ env_ar1 <- function(sd = 1, phi = 0, cor = NULL, names = NULL) { } n_draws <- if (is.null(loading)) size else ncol(loading) innovation <- sqrt(1 - phi^2) - function(state, context, params) { + .helper_fn(function(state, context, params) { if (!.is_name(context$variable)) { .stop("env_ar1() must be used as a variable of environment_process()") } @@ -109,7 +113,7 @@ env_ar1 <- function(sd = 1, phi = 0, cor = NULL, names = NULL) { } names(value) <- names value - } + }) } .environment_dimnames <- function(x, label) { @@ -130,6 +134,10 @@ env_ar1 <- function(sd = 1, phi = 0, cor = NULL, names = NULL) { } spatial_correlation <- function(patches = NULL, rho = NULL, distances = NULL, scale = NULL) { + if (.any_authored(patches, rho, distances, scale)) { + return(.deferred("spatial_correlation", + list(patches = patches, rho = rho, distances = distances, scale = scale))) + } has_rho <- !is.null(rho) has_distance <- !is.null(distances) || !is.null(scale) if (has_rho == has_distance) { @@ -175,6 +183,9 @@ spatial_correlation <- function(patches = NULL, rho = NULL, distances = NULL, sc # in the same environment_process(). The trend is never fed back through the # autoregression, so it acts in the interval it is specified for. env_trend <- function(level, anomaly = NULL) { + if (.any_authored(level, anomaly)) { + return(.deferred("env_trend", list(level = level, anomaly = anomaly))) + } if (is.function(level)) { arguments <- names(formals(level)) pass_dt <- any(c("dt", "...") %in% arguments) @@ -195,7 +206,7 @@ env_trend <- function(level, anomaly = NULL) { if (!is.null(anomaly) && !.is_name(anomaly)) { .stop("anomaly must be NULL or the name of an environment variable") } - function(state, context, params) { + trend <- function(state, context, params) { step <- context$time + 1L value <- if (is.function(level)) { args <- list(context$time) @@ -225,6 +236,8 @@ env_trend <- function(level, anomaly = NULL) { if (length(value) > 1L) value <- .align_environment(value, names(deviation), "level") value + deviation } + if (!is.null(anomaly)) attr(trend, "requires") <- paste0("globals.", anomaly) + .helper_fn(trend, "level") } catastrophe_process <- function( @@ -245,7 +258,7 @@ catastrophe_process <- function( } pva_process( name = name, - run = function(state, context, params) { + run = structure(function(state, context, params) { user <- params$user chance <- params$probability(state, context, user) if (!is.numeric(chance) || length(chance) != 1L || is.na(chance) || @@ -272,7 +285,7 @@ catastrophe_process <- function( state, pva_events(c("catastrophe", "death"), c(as.numeric(occurs), n_died), params$global) ) - }, + }, catastrophe_flag = global), params = list( probability = probability, mortality = mortality, @@ -282,7 +295,8 @@ catastrophe_process <- function( ), requires = unique(c("population.alive", requires)), writes = c(paste0("globals.", global), "population.alive"), - description = "Bernoulli catastrophe flag with optional direct mortality." + description = "Bernoulli catastrophe flag with optional direct mortality.", + role = .default_role("environment") ) } diff --git a/R/processes_management.R b/R/processes_management.R index 8e1d88c..38ed320 100644 --- a/R/processes_management.R +++ b/R/processes_management.R @@ -130,7 +130,8 @@ params = c(list(loss = loss, cause = cause), selection), requires = unique(c("population.alive", attr(selection$count, "requires", exact = TRUE), requires)), writes = "population.alive", - description = description + description = description, + role = .default_role("management") ) } @@ -228,7 +229,8 @@ assign_process <- function( }, params = c(list(field = field, value = value, event = event), selection), requires = unique(c(path, attr(count, "requires", exact = TRUE), requires)), writes = path, - description = "Assign a treatment or state value to selected living individuals." + description = "Assign a treatment or state value to selected living individuals.", + role = .default_role("management") ) } @@ -241,8 +243,12 @@ introduction_process <- function( requires = character(), params = list()) { count <- .count_function(count, "count") + if (is.list(fields)) { + creates <- unique(c(creates, names(fields))) + fields <- .constant_fields(fields, "fields") + } if (!is.function(fields)) { - .stop("fields must be a function of (n, state, context, params)") + .stop("fields must be a function of (n, state, context, params) or a named list") } if (!.is_name(source)) { .stop("source must be one non-empty character value") @@ -268,7 +274,8 @@ introduction_process <- function( params = list(count = count, fields = fields, source = source, user = params), requires = unique(c(attr(count, "requires", exact = TRUE), requires)), creates = unique(c("sex", "age", creates)), - description = "Scheduled supplementation, release or immigration with engine-allocated ids." + description = "Scheduled supplementation, release or immigration with engine-allocated ids.", + role = .default_role("management") ) } @@ -368,6 +375,7 @@ pairing_process <- function( "population.sex", "population.alive", paste0("population.", field), requirement, requires )), writes = paste0("population.", field), - description = "Form monogamous pairs up to a capacity; unpaired eligible individuals remain as floaters." + description = "Form monogamous pairs up to a capacity; unpaired eligible individuals remain as floaters.", + role = .default_role("demography") ) } diff --git a/R/rates.R b/R/rates.R index 7d67190..21da8fe 100644 --- a/R/rates.R +++ b/R/rates.R @@ -1,11 +1,68 @@ -validate_age_sex_table <- function(table, value) { - if (!is.data.frame(table) || !.is_name(value) || - !all(c("age_min", "age_max", "sex", value) %in% names(table))) { - .stop("table must be a data frame with age_min, age_max, sex and the value column") +.normalize_sex <- function(sex) { + if (is.logical(sex)) { + if (anyNA(sex) || any(sex)) .stop("a logical sex column must contain only FALSE (CSV 'F')") + return(rep("F", length(sex))) + } + as.character(sex) +} + +# Age classes may be given as age_min/age_max or as one `age` column holding +# whole ages, "a-b" ranges or an open-ended "a+". +.rate_age_bounds <- function(age) { + if (is.factor(age)) age <- as.character(age) + if (is.numeric(age)) { + return(list(age_min = as.numeric(age), age_max = as.numeric(age))) + } + text <- gsub("[[:space:]]", "", as.character(age)) + single <- grepl("^[0-9]+$", text) + open <- grepl("^[0-9]+\\+$", text) + range <- grepl("^[0-9]+-[0-9]+$", text) + if (anyNA(age) || !all(single | open | range)) { + bad <- text[!(single | open | range)] + .stop("age must be whole ages, ranges such as \"2-4\" or an open class such as \"5+\"; found \"", + if (length(bad)) bad[[1L]] else "NA", "\"") + } + lower <- as.numeric(sub("[+-].*$", "", text)) + upper <- lower + upper[open] <- Inf + upper[range] <- as.numeric(sub("^[0-9]+-", "", text[range])) + list(age_min = lower, age_max = upper) +} + +.rate_key <- function(sex, strata) { + if (!length(strata)) return(as.character(sex)) + do.call(paste, c(list(as.character(sex)), lapply(unname(strata), as.character), sep = "\r")) +} + +.rate_stratum_label <- function(table, row, by) { + if (!length(by)) return(paste("sex", table$sex[[row]])) + paste0("sex ", table$sex[[row]], ", ", + paste0(by, " ", vapply(by, function(field) as.character(table[[field]][[row]]), character(1)), + collapse = ", ")) +} + +# Validate a rate table and return it with explicit age_min/age_max and with +# sex "All" expanded to both sexes. +.rate_table <- function(table, value, by = NULL) { + by <- .field_names(by, "by") + if (any(by %in% c("sex", "age", "age_min", "age_max", value))) { + .stop("by must name stratifying columns other than sex, age and the value column") + } + has_bounds <- is.data.frame(table) && all(c("age_min", "age_max") %in% names(table)) + has_age <- is.data.frame(table) && "age" %in% names(table) + if (!is.data.frame(table) || !.is_name(value) || !(has_bounds || has_age) || + !all(c("sex", value, by) %in% names(table))) { + .stop("table must be a data frame with age_min, age_max (or age), sex and the value column", + if (length(by)) paste0(", plus the by column(s) ", paste(by, collapse = ", "))) } if (!nrow(table)) { .stop("table must have at least one row") } + if (!has_bounds) { + bounds <- .rate_age_bounds(table$age) + table$age_min <- bounds$age_min + table$age_max <- bounds$age_max + } if (!is.numeric(table$age_min) || !is.numeric(table$age_max) || anyNA(table$age_min) || anyNA(table$age_max) || any(table$age_min < 0) || any(table$age_min != floor(table$age_min)) || @@ -13,53 +70,217 @@ validate_age_sex_table <- function(table, value) { any(table$age_max < table$age_min)) { .stop("age_min and age_max must be whole, non-negative and ordered (age_max may be Inf)") } - if (!all(table$sex %in% c("F", "M"))) { - .stop("sex must be 'F' or 'M'") + sex <- .normalize_sex(table$sex) + both <- !is.na(sex) & tolower(sex) == "all" + if (!all(sex[!both] %in% c("F", "M"))) { + .stop("sex must be 'F' or 'M', or 'All' for a class shared by both sexes") + } + table$sex <- sex + if (any(both)) { + shared <- table[both, , drop = FALSE] + female <- male <- shared + female$sex <- "F" + male$sex <- "M" + table <- rbind(table[!both, , drop = FALSE], female, male) + rownames(table) <- NULL } if (!is.numeric(table[[value]]) || anyNA(table[[value]])) { .stop(value, " must be non-missing numeric") } - for (sex in unique(table$sex)) { - rows <- table[table$sex == sex, , drop = FALSE] - rows <- rows[order(rows$age_min), , drop = FALSE] - if (nrow(rows) > 1L && - any(rows$age_min[-1L] <= rows$age_max[-nrow(rows)])) { - .stop("age classes overlap for sex ", sex) + for (field in by) { + if (anyNA(table[[field]])) .stop("by column ", field, " must be non-missing") + } + key <- .rate_key(table$sex, table[by]) + for (group in unique(key)) { + index <- which(key == group) + index <- index[order(table$age_min[index])] + if (length(index) > 1L && + any(table$age_min[index][-1L] <= table$age_max[index][-length(index)])) { + .stop("age classes overlap for ", .rate_stratum_label(table, index[[1L]], by)) } } + table +} + +# Ages with no class between the lowest and highest class of a stratum. +.rate_table_gaps <- function(table, by = NULL) { + key <- .rate_key(table$sex, table[by]) + gaps <- character() + for (group in unique(key)) { + index <- which(key == group) + index <- index[order(table$age_min[index])] + if (length(index) < 2L) next + after <- table$age_max[index][-length(index)] + 1 + before <- table$age_min[index][-1L] + for (hole in which(before > after)) { + gaps <- c(gaps, sprintf( + "%s has no class for age%s %s", + .rate_stratum_label(table, index[[1L]], by), + if (before[[hole]] - after[[hole]] > 1) "s" else "", + if (before[[hole]] - after[[hole]] > 1) { + paste0(after[[hole]], "-", before[[hole]] - 1) + } else { + format(after[[hole]]) + } + )) + } + } + gaps +} + +validate_age_sex_table <- function(table, value, by = NULL) { + .rate_table(table, value, by) invisible(table) } -age_sex_rate <- function(table, value, missing_sex = c("error", "zero")) { +.check_rate_coverage <- function(model, state, rates_used, newborn_fields, writes, label, releases) { + for (spec in rates_used) { + table <- .rate_table(model$rates[[spec$table]], spec$column, spec$by) + where <- paste0(label, ": rate(\"", spec$column, "\")") + gaps <- .rate_table_gaps(table, spec$by) + if (length(gaps)) .stop(where, " has an age gap: ", gaps[[1L]]) + + fields <- c("sex", "age", spec$by) + unknown <- setdiff(fields, names(state$population)) + if (length(unknown)) .stop(where, " needs population field '", unknown[[1L]], "'") + occupied <- as.data.frame(state$population[fields], stringsAsFactors = FALSE) + for (release in releases) { + if (!all(fields %in% names(release$fields))) next + values <- release$fields[fields] + limit <- if (is.numeric(release$count)) release$count else Inf + # Native releases recycle each field independently. One common period + # covers every combination, or the actual count if it stops earlier. + n <- 1 + for (size in unique(lengths(values))) { + a <- n + b <- size + while (b > 0) { + remainder <- a %% b + a <- b + b <- remainder + } + n <- min(limit, n / a * size) + if (n == limit) break + } + added <- as.data.frame(lapply(values, rep_len, length.out = n), stringsAsFactors = FALSE) + occupied <- rbind(occupied, added) + } + if (length(newborn_fields)) { + strata <- if (length(spec$by)) unique(occupied[spec$by]) else data.frame(row.names = 1L) + if (!nrow(strata)) strata <- unique(table[spec$by]) + for (defaults in newborn_fields) { + newborn <- strata + fixed <- intersect(spec$by, names(defaults)) + newborn[fixed] <- defaults[fixed] + newborn <- unique(newborn) + newborn$age <- rep(0L, nrow(newborn)) + for (sex in c("F", "M")) { + newborn$sex <- rep(sex, nrow(newborn)) + occupied <- rbind(occupied, newborn[fields]) + } + } + } + absent_by <- spec$by[vapply(occupied[spec$by], anyNA, logical(1))] + if (length(absent_by)) .stop(where, " has missing values for population field '", absent_by[[1L]], "'") + absent <- setdiff(unique(occupied$sex), table$sex) + if (length(absent) && spec$missing_sex == "error") { + .stop(where, " has no rows for sex ", absent[[1L]], ", which the model contains; add them, use sex = \"All\", ", + "or write rate(\"", spec$column, "\", missing_sex = \"zero\") to treat the rate as zero") + } + occupied <- unique(occupied[occupied$sex %in% table$sex, , drop = FALSE]) + classes <- split(seq_len(nrow(table)), .rate_key(table$sex, table[spec$by])) + keys <- .rate_key(occupied$sex, occupied[spec$by]) + for (key in unique(keys)) { + rows <- which(keys == key) + stratum <- .rate_stratum_label(occupied, rows[[1L]], spec$by) + bands <- classes[[key]] + if (!length(bands)) .stop(where, " has no rows for ", stratum) + ages <- occupied$age[rows] + outside <- which(ages < min(table$age_min[bands]) | ages > max(table$age_max[bands])) + if (length(outside)) { + .stop(where, " has no class for ", stratum, " at age ", ages[[outside[[1L]]]], + ", which the model starts with or creates") + } + } + if ("population.age" %in% writes) { + fixed_by <- spec$by[!paste0("population.", spec$by) %in% writes] + terminal <- if (length(fixed_by) == length(spec$by)) classes else + split(seq_len(nrow(table)), .rate_key(table$sex, table[fixed_by])) + for (bands in terminal) { + if (max(table$age_max[bands]) != Inf) { + .stop(where, " needs an open terminal age class for ", .rate_stratum_label(table, bands[[1L]], fixed_by), + " because the model has an age step") + } + } + } + } + invisible(TRUE) +} + +.rates_at_ages <- function(ages, classes, value, sex) { + index <- findInterval(ages, classes$age_min) + if (any(index == 0L) || any(ages > classes$age_max[index])) { + missing <- which(index == 0L | ages > classes$age_max[pmax.int(1L, index)])[[1L]] + .stop("no ", value, " class covers sex ", sex, " at age ", ages[[missing]]) + } + classes$value[index] +} + +age_sex_rate <- function(table, value, missing_sex = c("error", "zero"), by = NULL) { missing_sex <- match.arg(missing_sex) - validate_age_sex_table(table, value) - lookup <- lapply(split(table, as.character(table$sex)), function(rows) { - rows <- rows[order(rows$age_min), , drop = FALSE] + table <- .rate_table(table, value, by) + by <- .field_names(by, "by") + groups <- split(seq_len(nrow(table)), .rate_key(table$sex, table[by])) + lookup <- lapply(groups, function(index) { + index <- index[order(table$age_min[index])] list( - age_min = as.numeric(rows$age_min), - age_max = as.numeric(rows$age_max), - value = as.numeric(rows[[value]]) + age_min = as.numeric(table$age_min[index]), + age_max = as.numeric(table$age_max[index]), + value = as.numeric(table[[value]][index]) ) }) + sexes <- unique(table$sex) + rm(table, groups) + if (!length(by)) { + return(function(pop, state, context, params) { + out <- numeric(length(pop$id)) + for (sex in unique(pop$sex)) { + classes <- lookup[[sex]] + if (is.null(classes)) { + if (missing_sex == "error") .stop(value, " table has no entry for sex ", sex) + next + } + rows <- which(pop$sex == sex) + out[rows] <- .rates_at_ages(pop$age[rows], classes, value, sex) + } + out + }) + } function(pop, state, context, params) { out <- numeric(length(pop$id)) - for (sex in unique(pop$sex)) { - classes <- lookup[[sex]] + absent <- by[!by %in% names(pop)] + if (length(absent)) { + .stop(value, " table is stratified by population field ", absent[[1L]], + ", which the population does not carry") + } + group <- .rate_key(pop$sex, pop[by]) + for (stratum in unique(group)) { + classes <- lookup[[stratum]] + rows <- which(group == stratum) + sex <- pop$sex[[rows[[1L]]]] if (is.null(classes)) { - if (missing_sex == "error") { - .stop(value, " table has no entry for sex ", sex) + if (!sex %in% sexes) { + if (missing_sex == "error") { + .stop(value, " table has no entry for sex ", sex) + } + next } - next - } - rows <- which(pop$sex == sex) - class <- findInterval(pop$age[rows], classes$age_min) - covered <- class > 0L - covered[covered] <- pop$age[rows][covered] <= classes$age_max[class[covered]] - if (!all(covered)) { - missing <- rows[which(!covered)[[1L]]] - .stop("no ", value, " class covers sex ", sex, " at age ", pop$age[[missing]]) + .stop(value, " table has no entry for sex ", sex, " with ", + paste0(by, " = ", vapply(by, function(field) { + as.character(pop[[field]][[rows[[1L]]]]) + }, character(1)), collapse = ", ")) } - out[rows] <- classes$value[class] + out[rows] <- .rates_at_ages(pop$age[rows], classes, value, sex) } out } diff --git a/R/scenario.R b/R/scenario.R index e11d052..d167c35 100644 --- a/R/scenario.R +++ b/R/scenario.R @@ -66,7 +66,8 @@ run_scenario <- function( .stop("parallel must be TRUE or FALSE") } backend <- match.arg(backend) - validation <- match.arg(validation) + if (missing(validation) && !is.null(scenario$validation)) validation <- scenario$validation + validation <- match.arg(validation, c("strict", "fast")) if (!is.character(keep) || !all(keep %in% .keep_choices)) { .stop("keep must be a subset of: ", paste(.keep_choices, collapse = ", ")) } @@ -147,7 +148,8 @@ print.pva_run <- function(x, ...) { workers, backend, cluster, - preschedule) { + preschedule, + models = NULL) { if (!parallel || (workers < 2L && is.null(cluster))) { return(lapply(items, worker, payload = payload)) } @@ -188,7 +190,7 @@ print.pva_run <- function(x, ...) { parallel::clusterCall(cluster, ".libPaths", paths, include.site = FALSE) parallel::clusterCall(cluster, base::library, "OpenPVA", character.only = TRUE) callbacks <- if (is.null(payload$scenario)) { - payload[c("build", "summarise")] + list(if (is.null(models)) payload$build else models, payload$summarise) } else { payload$scenario[c("init_fun", "processes", "initial_census")] } @@ -426,3 +428,23 @@ print.pva_run <- function(x, ...) { } expr } + +.preview_call <- function(fun, args, user_code) { + .with_rng_restored({ + payload <- list(build = list(fun = fun, args = args), + header = .pva_rng_header(.GlobalEnv$.Random.seed[1L])) + # An R callback can call set.seed() or RNGkind(), which clears a pending + # Box-Muller normal even when .Random.seed points at a private stream. + if (user_code && RNGkind()[[2L]] == "Box-Muller") { + cluster <- parallel::makePSOCKcluster(1L, rscript_args = "--vanilla") + on.exit(parallel::stopCluster(cluster), add = TRUE) + return(.dispatch(1L, .preview_worker, payload, TRUE, 1L, "psock", cluster, TRUE)[[1L]]) + } + .preview_worker(1L, payload) + }) +} + +.preview_worker <- function(index, payload) { + .set_pva_seed(1L, payload$header) + do.call(payload$build$fun, payload$build$args) +} diff --git a/R/spatial.R b/R/spatial.R index 8543797..1fe2b34 100644 --- a/R/spatial.R +++ b/R/spatial.R @@ -86,7 +86,8 @@ dispersal_process <- function( ), requires = unique(c(paste0("population.", field), attr(count, "requires", exact = TRUE), requires)), writes = paste0("population.", field), - description = "Move eligible individuals among discrete patches." + description = "Move eligible individuals among discrete patches.", + role = .default_role("spatial") ) } diff --git a/R/state.R b/R/state.R index df8f638..640c598 100644 --- a/R/state.R +++ b/R/state.R @@ -97,7 +97,7 @@ pva_population <- function( population <- c( list( id = seq_len(n), - sex = as.character(sex), + sex = .normalize_sex(sex), age = .whole_field(recycle(age, "age"), "age"), alive = rep(TRUE, n), mother_id = .whole_field(recycle(mother_id, "mother_id"), "mother_id"), @@ -112,6 +112,7 @@ pva_population <- function( .as_population <- function(population) { if (is.data.frame(population)) { + if ("sex" %in% names(population)) population$sex <- .normalize_sex(population$sex) population <- as.list(population) population <- lapply(population, function(column) { if (is.factor(column)) as.character(column) else column @@ -401,7 +402,7 @@ add_individuals <- function( new <- c( list( id = seq.int(state$next_id, length.out = n), - sex = as.character(sex), + sex = .normalize_sex(sex), age = .whole_field(recycle(age, "age"), "age"), alive = rep(TRUE, n), mother_id = .whole_field(recycle(mother_id, "mother_id"), "mother_id"), diff --git a/R/survey.R b/R/survey.R index d2230f5..04f9bba 100644 --- a/R/survey.R +++ b/R/survey.R @@ -62,11 +62,15 @@ survey_process <- function(detection, eligible = NULL, when = TRUE, field = "sur params = list(detection = detection, eligible = eligible, when = .when_function(when), field = field, user = params), requires = requires, writes = paste0("globals.", field), - description = "Count independent individual detections on scheduled visits." + description = "Count independent individual detections on scheduled visits.", + role = .default_role("survey") ) } survey_quota <- function(rule, field = "survey", on_skip = "error") { + if (.any_authored(rule, field, on_skip)) { + return(.deferred("survey_quota", list(rule = rule, field = field, on_skip = on_skip))) + } if (!.is_name(field)) .stop("field must be one non-empty global name") if (!is.function(rule)) .stop("rule must be a function of (obs, state, context, params)") if (!.is_count(on_skip) && !identical(on_skip, "error") && !is.function(on_skip)) { @@ -94,5 +98,6 @@ survey_quota <- function(rule, field = "survey", on_skip = "error") { .as_count(value, "survey quota") } attr(quota, "requires") <- paste0("globals.", field) - quota + attr(quota, "survey_field") <- field + .helper_fn(quota, c("rule", "on_skip")) } diff --git a/README.md b/README.md index 03b896c..23ad320 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ > *The modeller defines the biological programme; OpenPVA supplies the execution engine, reusable processes, scientific contracts, and reproducible analysis machinery.* -**OpenPVA** is a composable, individual-based Population Viability Analysis (PVA) engine written in pure base R. Instead of locking your species into a fixed menu-driven lifecycle, you assemble an explicit, ordered list of ordinary R processes—declaring what each step reads, writes, and creates—while the engine protects interval time, individual IDs, exact pedigree inbreeding, cohort accounting, and bit-identical parallel random streams. +**OpenPVA** is a composable, individual-based Population Viability Analysis (PVA) engine written in pure base R. Instead of locking your species into a fixed menu-driven lifecycle, you write an explicit, ordered lifecycle: either as readable steps over your own parameter, vital-rate and cohort tables (`pva_model() |> step_*()`), or as ordinary R processes that declare what they read, write, and create. Both routes give the same process objects, and the engine protects interval time, individual IDs, exact pedigree inbreeding, cohort accounting, and bit-identical parallel random streams.

OpenPVA 3-panel output showing stochastic population trajectories, cumulative quasi-extinction risk with Wilson intervals, and an ensemble management comparison @@ -21,6 +21,7 @@ ## Why OpenPVA +- **Inputs apart from the lifecycle:** `pva_model()` takes parameter-evidence, vital-rate and cohort tables; `step_*()` adds ordered steps whose rules are short formulas such as `~ rate("p_surv")`. Every name is checked when the model is compiled, and `describe_model()` shows where each input goes before anything runs. - **Transparent, ordered biology:** A lifecycle is a plain R list of `pva_process()` objects. Repeat, reorder, omit, or add custom processes without touching the engine controller. - **Engine-owned scientific invariants:** Strict validation after every process reconciles births, deaths, removals, introductions, and cohort stocks; preassigned L'Ecuyer-CMRG streams make serial, fork, and PSOCK parallel runs bit-identical. - **Exact genetics & adaptive management out of the box:** Exact conditional pedigree inbreeding (dense matrix with automatic switch to level-batched sparse ancestor tracing), non-perturbing neutral-locus gene drop, kinship-aware and seasonal mating with cross-interval sire retention, and isolated-stream imperfect surveys driving management quotas. @@ -28,11 +29,18 @@ ## Installation -Install the latest version from GitHub: +OpenPVA is pure base R (no C/C++ compiler required). Install the latest release directly from GitHub with `devtools`, `remotes`, or `pak`: ```r -# Using remotes or pak -remotes::install_github("BWBrook/OpenPVA") +# Using devtools (or remotes::install_github("BWBrook/OpenPVA")) +devtools::install_github("BWBrook/OpenPVA") + +# Build the local vignettes too (cookbook, workflow, rosetta; requires litedown) +devtools::install_github("BWBrook/OpenPVA", build_vignettes = TRUE) + +# Or install with pak, or pin a specific release tag +# pak::pak("BWBrook/OpenPVA") +# devtools::install_github("BWBrook/OpenPVA@v2.4.0") ``` Or install directly from a local checkout: @@ -43,45 +51,44 @@ R CMD INSTALL . ## Quickstart -Build, run, check, and plot a two-sex stochastic PVA in ~25 lines of ordinary R: +Build, audit, run, and plot a two-sex stochastic PVA from three small tables and an ordered list of steps, with no functions to write: ```r library(OpenPVA) -survival <- survival_process( - probability = function(pop, state, context, params) { - ifelse(pop$age == 0, params$juvenile, params$adult) - }, - requires = "population.age", - params = list(juvenile = 0.52, adult = 0.88) -) - -breeding <- reproduction_process( - breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2), - litter_size = litter_poisson(1.2), - offspring_sex = offspring_sex_bernoulli(0.5), - mate = mate_random(function(pop, state, context, params) pop$age >= 2), - requires = "population.age" -) - -scenario <- scenario_spec( - name = "minimal-example", - n_runs = 200, - n_steps = 20, - init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 3), - processes = list(survival, age_process(), breeding, census_process()), - initial_census = census_process(), - seed = 2026 +rates <- data.frame( + age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.52, 0.88, 0.88), p_breed = c(0, 0, 1), litter = c(0, 0, 1.2) ) -result <- run_scenario(scenario) +model <- pva_model( + params = list(maturity = 2, capacity = 80), + rates = rates, + init = data.frame(age = 3, sex = c("F", "M"), n = 10), + n_steps = 20, name = "minimal-example" +) |> + step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, capacity)) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(0.5), mate = mate_random(~ age >= maturity)) |> + step_census() + +plot(model) # lifecycle diagram, before anything runs +describe_parameters(model) # where every input goes + +result <- model |> compile_scenario(n_runs = 200, seed = 2026) |> run_scenario() summarise_pva(result, threshold = 10) all(summarise_accounting(result)$reconciled) - plot(result, type = "trajectory", threshold = 10) + +# compare options on paired seeds: design columns override parameters by name +run_pva_ensemble(data.frame(capacity = c(40, 80, 160)), model, + n_runs = 200, seed = 2026, seed_by = TRUE) ``` -Custom biological or management rules compose through the exact same contract—no registration required: +A formula may use your parameters, the population fields (`age`, `sex`, ...), globals written by earlier steps, `time`, `N` and `rate("")`. A misspelled name, an override that cannot matter, or a rate table with a gap stops at `compile_scenario()` with a message naming the step. + +The model compiles to ordinary `pva_process()` objects, and the native API remains first-class. Custom biological or management rules compose through the exact same contract, with no registration, and `step_process()` drops one into an authored pipeline at any position: ```r harvest_oldest <- pva_process( @@ -95,6 +102,31 @@ harvest_oldest <- pva_process( requires = "population.age", writes = "population.alive" ) + +hunted <- pva_model(list(maturity = 2), rates, + data.frame(age = 3, sex = c("F", "M"), n = 10), n_steps = 20) |> + step_survival(~ rate("p_surv")) |> + step_process(harvest_oldest) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(0.5), mate = mate_random(~ age >= maturity)) |> + step_census() + +# the same lifecycle written directly as a process list +scenario <- scenario_spec( + name = "hand-written", n_runs = 200, n_steps = 20, seed = 2026, + init_fun = function() pva_population(sex = rep(c("F", "M"), each = 10), age = 3), + processes = list( + survival_process(age_sex_rate(rates, "p_surv")), + harvest_oldest, + age_process(), + reproduction_process(age_sex_rate(rates, "p_breed"), litter_poisson(age_sex_rate(rates, "litter")), + offspring_sex_bernoulli(0.5), + mate = mate_random(function(pop, state, context, params) pop$age >= 2)), + census_process() + ), + initial_census = census_process() +) ``` If a custom process forgets its `removal` event or mutates an undeclared field, strict validation halts immediately and names the process. @@ -103,6 +135,7 @@ If a custom process forgets its `removal` event or mutates an undeclared field, | Ecological layer | Key building blocks | |---|---| +| **Model authoring & audit** | `pva_model()`, `cohort_population()`, `step_survival()`, `step_reproduction()`, `step_environment()` and 12 more `step_*()`, `step_process()`, `compile_scenario()`, `describe_model()`, `describe_parameters()` | | **State & cohorts** | `pva_population()`, `pva_state()` (`pedigree`, `n_loci`, `mate_field`), `add_individuals()` | | **Demography & mating** | `survival_process()`, `staged_survival_process()`, `age_process()`, `reproduction_process()`, `pairing_process()`, `mating_process()`, `mate_random()`, `mate_min_kinship()`, `mate_from_field()` | | **Environment & space** | `environment_process()`, `env_ar1()`, `spatial_correlation()`, `env_trend()`, `catastrophe_process()`, `dispersal_process()`, `markov_dispersal_process()`, `shift_logit()`, `qbeta_norm()` | @@ -112,11 +145,12 @@ If a custom process forgets its `removal` event or mutates an undeclared field, ## Examples & documentation -- **Online documentation site:** [bwbrook.github.io/OpenPVA](https://bwbrook.github.io/OpenPVA/) (grouped reference for all 62 exports, rendered vignettes & changelog) +- **Online documentation site:** [bwbrook.github.io/OpenPVA](https://bwbrook.github.io/OpenPVA/) (grouped reference for all 82 exports, rendered vignettes & changelog) +- **Model-building cookbook:** `vignette("cookbook", package = "OpenPVA")` (tables and ordered steps, no functions: density, inbreeding, seasons, patches, surveys, paired ensembles and the escape hatch) - **Visual workflow walkthrough:** `vignette("workflow", package = "OpenPVA")` (lifecycle diagrams, life-table checks, accounting, adaptive surveys, ensembles & genetics) - **GAPPS / Vortex / Leslie translation guide:** `vignette("rosetta", package = "OpenPVA")` - **Agent modelling guide:** [For AI agents & script authors](https://github.com/BWBrook/OpenPVA/blob/main/docs/for-agents.md) -- **Grizzly bear seasonal lifecycle:** summer mating (`mating_process()`), autumn harvest, cross-interval sire retention, winter birth, and 3-year maternal dependency — [Grizzly model](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/grizzly/README.md) +- **Grizzly bear seasonal lifecycle:** summer mating (`mating_process()`), autumn harvest and winter birth within one annual interval, so a sire shot after mating still fathers the litter, plus 3-year maternal dependency. (Sire retention *across* intervals is shown by the seasonal herd in `vignette("rosetta")`.) — [Grizzly model](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/grizzly/README.md) - **Lord Howe Island woodhen recovery:** sex-specific survival, shared environmental stochasticity, territorial pairing, captive releases, and parameter-evidence table — [Woodhen model](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/woodhen/README.md) - **Design & heritage documents:** [Vision and scope](https://github.com/BWBrook/OpenPVA/blob/main/docs/vision_and_scope.md) · [Lifecycle-process contract](https://github.com/BWBrook/OpenPVA/blob/main/docs/design/lifecycle_process_contract.md) · [Public API](https://github.com/BWBrook/OpenPVA/blob/main/docs/reference/public_api.md) · [GAPPS heritage](https://github.com/BWBrook/OpenPVA/blob/main/docs/gapps_heritage.md) · [GAPPS evidence review](https://github.com/BWBrook/OpenPVA/blob/main/docs/literature/gapps_evidence_review.md) diff --git a/docs/design/lifecycle_process_contract.md b/docs/design/lifecycle_process_contract.md index feee1b6..1d6d474 100644 --- a/docs/design/lifecycle_process_contract.md +++ b/docs/design/lifecycle_process_contract.md @@ -53,10 +53,21 @@ pva_process( params = list(...), requires = c("population.age", "globals.weather"), writes = "population.alive", - creates = NULL + creates = NULL, + role = NULL ) ``` +- `role` is optional display metadata (`environment`, `demography`, `spatial`, + `management`, `survey`, `census` or `custom`). Lifecycle inspection uses a + role stored on a process as given and infers one only for a process that + stores none. A role passed to `pva_process()` is stored as stated. A + built-in constructor stores the role its process name and declared effects + indicate, which keeps lifecycle output on 2.3.0 models unchanged (a + `survival_process()` named `"autumn_harvest"` stays under management), and + falls back to the constructor's own role when they indicate none. It has no + effect on execution. + - `requires` and `writes` are state paths, `population.` or `globals.`. - A process that adds individuals declares `creates`: the fields it @@ -218,6 +229,24 @@ demography. Observation alone advances only the survey substream. `run_scenario(keep = ...)` chooses what a run returns: `census`, `events`, `accounting`, final `state` and the full `ledger`. The default retains census, events and accounting. Retention never changes what is computed. +## Authored models + +`pva_model()` and the `step_*()` builders are a front-end to this contract, not +a second engine. `compile_scenario()` calls the same constructors a hand-written +model calls and returns a `scenario_spec()`. One-sided formulas are resolved +once, at compile time, against the model's parameters, population fields, +globals, the context scalars `time`, `dt`, `n_steps` and `N`, and its rate +tables, and are rewritten into closures of the documented callback signatures +with parameter values written in. Those closures belong to the package +namespace (or a child of it that holds only rate-table lookups), so they +capture nothing from the caller's workspace, and each process's `requires` is +the set of paths its formulas read. A step with a `when` schedule keeps its +process's parameters and metadata and returns the state untouched, with no +events, in the intervals it skips; surveys and mating use their own `when`. +The tests in `tests/testthat/test-model-oracles.R` hold authored models +bit-identical to hand-written ones in census, events, accounting, final states +and ledgers. + ## Precedents and design inference - [VORTEX 10](https://scti.tools/manuals/Vortex10Manual.pdf) and diff --git a/docs/for-agents.md b/docs/for-agents.md index 838ef7b..38fde7f 100644 --- a/docs/for-agents.md +++ b/docs/for-agents.md @@ -12,6 +12,25 @@ This guide is for AI coding agents (and human script authors) building, checking 3. **Every process declares what it touches:** `requires`, `writes`, and `creates` (`population.` or `globals.`). In default `validation = "strict"`, undeclared mutations or unreconciled births/deaths/removals/introductions halt immediately and name the offending process. 4. **RNG is owned by the engine.** `run_scenario()` preassigns one L'Ecuyer-CMRG stream per replicate (`seed`), giving bit-identical results across serial, fork, and PSOCK workers while restoring the caller's `.Random.seed` and pending Box–Muller normal. Neutral-locus segregation uses an isolated substream; `survey_process()` uses isolated substream 5. +## 1a. Two ways to write the same model + +- **Authored (`pva_model() |> step_*()`), the default for routine biology.** Inputs (parameters, rate tables, initial cohorts, custom-field defaults) are held apart from an ordered pipeline of steps, and rules are one-sided formulas. `compile_scenario()` checks every name, derives each process's `requires`, and returns an ordinary `pva_scenario`. Prefer it whenever the rules are expressions over parameters, population fields, globals, `time`, `N` and `rate()` lookups: it removes the hand-typed `requires`, `params = list(...)` and `init_fun` that agents most often get wrong, and it gives a parameter-provenance audit for free. +- **Native (`scenario_spec(processes = list(...))`).** Use it for anything a pure formula cannot say: random draws beyond `env_ar1()`, stateful or iterative rules, bespoke selection. Mix the two freely: `step_process()` inserts a native or custom process at an exact position, and any step argument also accepts an R callback of the constructor's signature. + +Authored-model rules that matter: + +1. A formula may contain only: declared parameters; population fields; globals written by an earlier step or started in `pva_model(globals = )`; `time`, `dt`, `n_steps`, `N`; `rate("")` (options `table = `, `missing_sex = "zero"`, `by = `); operators, `[`, `if`/`ifelse`; and the pure functions listed in `?lifecycle_steps` (including `shift_logit()`, `inbreeding_multiplier()`, the density multipliers and `patch_counts(patches)`). Allowlisted functions may be namespace-qualified, for example `stats::plogis()`. Formulas reject assignments, function definitions and RNG calls. +2. Names must be unambiguous across parameters, fields, globals and the reserved words `time`, `dt`, `n_steps`, `N`, `observed`, `rate`. Do not name a parameter `age` or `N`. +3. `~` binds tighter than `<-` and `=`, so there is no way to write an assignment in a formula by accident; a formula must be one-sided. +4. A formula that reads only parameters is folded to a constant at compile time. Constructor-time helper arguments (`env_ar1(sd = ~env_sd)`, `litter_binomial(~size, ~mean)`, `step_pairing(capacity = ~K_pairs)`, `step_dispersal(transition = ~moves)`) must fold. +5. A comparison used as a probability is 0 or 1 (`~ age >= maturity`). Inside `survey_quota()`, `observed` and `obs$count` give the count. The record also exposes `obs$visited`, `obs$ids` and `obs$time`. Put the survey before its quota. +6. Declare every custom field once in `pva_model(fields = list(mate_id = NA_integer_))` with a typed default. Newborns and released animals get the defaults; use `inherit = "patch_id"` for fields copied from the mother. +7. `enabled = ~flag` selects steps at compile time. An enabled `step_process()` factory runs once per compilation and must construct its process deterministically. With a Box–Muller caller, OpenPVA inspects user initializers and factories in a fresh R worker so a callback that resets the RNG preserves the caller’s pending normal draw. `when` schedules a step by zero-based interval, formula or callback. A skipped survey records `survey_skip` and clears the observation. A skipped catastrophe writes `FALSE` to its flag. Give a scheduled environmental global an initial value in `globals` if later steps need to read it on every interval. +8. Overrides (`compile_scenario(model, overrides = list(...))`, or design columns in `run_pva_ensemble(design, build = model)`) must name a parameter **and** be able to matter: overriding a parameter used only by a disabled step is an error. In a design, set such cells to `NA`. Declared parameters take precedence over descriptive columns (`label`, `scenario`) and may also define a `seed_by` block. A named list of structural alternatives reserves `model` for selection. +9. In a parameter-evidence CSV, read `value` as text (for example, `read.csv(path, colClasses = c(value = "character"))`) and use `type = "character"` on rows containing codes such as `001`. Numeric and logical rows may specify their types too. +10. Cohort tables expand in row order; the `(age, females, males)` layout lists all females first. Random draws are taken in individual order, so two models are bit-identical only if their initial individuals are in the same order. +11. Bit-identity with a hand-written model is the expected standard, not an approximation: write the formula in the same arithmetic order as the native expression. + ## 2. Exact signatures and common parameter traps Verify argument names against live formals (`args(OpenPVA::fn)`). The most frequent signature mistakes agents make: @@ -23,9 +42,14 @@ Verify argument names against live formals (`args(OpenPVA::fn)`). The most frequ | `ceiling_density_multiplier()` | `ceiling_density_multiplier(n, capacity)` | Second argument is `capacity` (not `ceiling` or `K`). | | `beverton_holt_multiplier()` | `beverton_holt_multiplier(n, capacity, growth)` | Requires `growth >= 1` (`growth = 1` returns `1`). | | `reproduction_process()` | `reproduction_process(breeding_probability, litter_size, offspring_sex, mate = NULL, require_mate = !is.null(mate), newborn_fields = NULL, newborn_field_names = character(), inherit = character(), ...)` | When the population has custom user columns (e.g. `mate_id`, `patch_id`), list their names in `newborn_field_names` (or `inherit`) and return them from `newborn_fields`. | -| `age_sex_rate()` | `age_sex_rate(table, value, missing_sex = c("error", "zero"))` | Pass `missing_sex = "zero"` for female-only fecundity tables in a two-sex population. | +| `age_sex_rate()` | `age_sex_rate(table, value, missing_sex = c("error", "zero"), by = NULL)` | Pass `missing_sex = "zero"` for female-only fecundity tables in a two-sex population. Tables may use `age_min`/`age_max` or an `age` column (`"0"`, `"1-2"`, `"3+"`), and `sex = "All"`. | +| `pva_model()` | `pva_model(params = list(), rates = NULL, init, n_steps, fields = list(), globals = list(), name = "model", dt = 1, pedigree = FALSE, n_loci = 0L, mate_field = NULL, initial_census = TRUE)` | `init` and `n_steps` are required. `initial_census = TRUE` reuses the model's last `step_census()` for year zero. For a dynamic `init`, the compiler checks one isolated draw. Replicates call the initializer afresh. | +| `compile_scenario()` | `compile_scenario(model, overrides = list(), n_runs = 100L, seed = NULL, name = NULL, validation = c("strict", "fast"))` | Compilation always validates the field plan. The chosen mode becomes the scenario's default for `run_scenario()`, where an explicit `validation` argument overrides it. | +| `step_survival()` | `step_survival(model, probability, eligible = NULL, cause = "natural", stage = NULL, post_share = NULL, field = "survival_draw", name, when = TRUE, enabled = TRUE, requires = character(), uses = NULL)` | `stage = "pre"`/`"post"` with `post_share` gives staged survival. `requires` is needed only for R callbacks, never for formulas. | +| `step_introduce()` | `step_introduce(model, count, fields, source = "introduction", name = "introduction", ...)` | `fields` is a plain list recycled over the releases, e.g. `list(sex = c("F", "M"), age = 2L)`; model `fields` defaults fill the rest. | +| `step_process()` | `step_process(model, process, enabled = TRUE, when = TRUE, uses = NULL)` | Supply a `pva_process` or a deterministic factory `function(params)`. For indirect parameter reads, declare their names in `uses`. A callback needs `requires` for its state reads. Its actual outputs are checked during execution. | | `survey_process()` / `survey_quota()` | `survey_process(detection, eligible = NULL, when = TRUE, field = "survey", ...)` and `survey_quota(rule, field = "survey", on_skip = "error")` | Place `survey_process()` **before** the management process consuming `survey_quota()`. On unvisited intervals (`when`), `on_skip = "error"` intentionally errors unless set to a count (e.g. `0L`) or callback. | -| `run_pva_ensemble()` | `run_pva_ensemble(design, build, n_runs, summarise = NULL, seed = NULL, seed_by = NULL, ...)` | `build` takes **one** argument (`row`, a named list of the design row) and returns a list containing `init_fun`, `processes`, and `n_steps` (a `scenario_spec()` object works because it is such a list). | +| `run_pva_ensemble()` | `run_pva_ensemble(design, build, n_runs, summarise = NULL, seed = NULL, seed_by = NULL, ...)` | `build` is a `pva_model`, a named list of models (with a `model` design column), or a function of **one** argument (`row`, a named list of the design row) returning a list containing `init_fun`, `processes`, and `n_steps`. A builder that returns a `scenario_spec()` works because it is such a list, but its own `n_runs`, `seed` and `name` are ignored. | | `pva_state(..., mate_field = ...)` | `pva_state(population, globals = list(), pedigree = FALSE, kinship = NULL, max_dense_kinship = 2000L, n_loci = 0L, mate_field = NULL)` | Initial female `mate_field` IDs must reference living initial males. Use `mate_field` whenever sires may die between mating and birth across intervals. | ## 3. Standard agent verification workflow @@ -33,6 +57,7 @@ Verify argument names against live formals (`args(OpenPVA::fn)`). The most frequ Never present stochastic PVA results without running these five checks in order: 1. **Validate and visually inspect the lifecycle before simulating:** + For an authored model, `describe_model(model)` prints the cohorts, each step's formulas with bound values and the parameter table (check that nothing you meant to use is `unused`), and `describe_lifecycle(model)` / `plot(model)` give the process view. For a hand-written scenario: ```r init_state <- scenario$init_fun() if (!inherits(init_state, "pva_state")) init_state <- pva_state(init_state) @@ -51,12 +76,55 @@ Never present stochastic PVA results without running these five checks in order: ``` Only switch to `validation = "fast"` for large production runs *after* `strict` passes cleanly. 4. **Use common random numbers when comparing management or structural options:** - In `run_pva_ensemble()`, `seed_by = NULL` assigns a distinct seed to every row. To share common replicate streams across strategies, include a shared grouping column in `design` and pass it to `seed_by` (e.g., a constant column `pair = 1L` with `seed_by = "pair"` to pair every row, or `seed_by = "climate"` to pair management strategies within each climate regime). + In `run_pva_ensemble()`, `seed_by = NULL` assigns a distinct seed to every row. `seed_by = TRUE` pairs every row on one seed, and `seed_by = "climate"` pairs management strategies within each climate regime. Pairing aligns the *starting* replicate streams only: environmental draws share substream 0 with demography, so paired rows' environmental sequences diverge once their populations differ. Do not describe paired runs as experiencing identical years. 5. **Preserve provenance and uncertainty:** Report `p_ever_below` with Wilson limits (`p_ever_below_lower`, `p_ever_below_upper`), `ema` / `ema_mcse`, `n_runs`, `seed`, and `attr(ensemble, "provenance")`. Subsetting `ensemble[, cols]` retains class `pva_ensemble` and its `provenance` attribute. ## 4. Minimal composition templates +### Authored model: tables, steps, audit, paired ensemble + +```r +library(OpenPVA) + +rates <- data.frame(age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.55, 0.85, 0.85), p_breed = c(0, 0, 0.8), litter = c(0, 0, 1.15)) + +model <- pva_model( + params = list(env_sd = 0.35, env_phi = 0.4, capacity = 90, lethal_equivalents = 3.14, + maturity = 2, detect = 0.7, trigger = 24, release_size = 6, releases = TRUE), + rates = rates, + init = data.frame(sex = rep(c("F", "M"), each = 15L), age = rep(1:5, 6L)), + n_steps = 40L, pedigree = TRUE, n_loci = 10L, name = "island-adaptive" +) |> + step_environment(env = env_ar1(sd = ~ env_sd, phi = ~ env_phi)) |> + step_survival(~ shift_logit(rate("p_surv"), env) * + ceiling_density_multiplier(N, capacity) * + inbreeding_multiplier(pedigree_F, lethal_equivalents)) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(~ age >= maturity, max_kinship = 0.25)) |> + step_survey(~ detect, when = ~ time %% 2 == 0, field = "obs", enabled = ~ releases) |> + step_introduce(survey_quota(~ if (observed < trigger) release_size else 0, + field = "obs", on_skip = 0L), + fields = list(sex = c("F", "M"), age = 2L), + name = "adaptive_release", enabled = ~ releases) |> + step_census(genetic_metrics()) + +describe_model(model) # audit first +scenario <- compile_scenario(model, n_runs = 200L, seed = 2026L) +smoke <- run_scenario(scenario) +stopifnot(all(summarise_accounting(smoke)$reconciled)) + +design <- data.frame(label = c("no action", "release 6", "release 10"), + releases = c(FALSE, TRUE, TRUE), release_size = c(NA, 6, 10)) +ensemble <- run_pva_ensemble(design, model, n_runs = 200L, seed = 2026L, seed_by = TRUE, + summarise = function(run, row) summarise_pva(run, threshold = 15)) +``` + +The native template below builds the same kind of model by hand. + ### Two-sex stochastic model with environment, pedigree, and adaptive survey ```r diff --git a/docs/reference/public_api.md b/docs/reference/public_api.md index 6dd60f8..684b272 100644 --- a/docs/reference/public_api.md +++ b/docs/reference/public_api.md @@ -1,10 +1,13 @@ -# Public API (OpenPVA 2.3.0) +# Public API (OpenPVA 2.4.0) The help pages under `man/` are the reference; this page is the map. Every entry is exported. | Area | Functions | |---|---| +| Model authoring | `pva_model()`, `cohort_population()`, `compile_scenario()` | +| Lifecycle steps | `step_environment()`, `step_catastrophe()`, `step_survival()`, `step_age()`, `step_pairing()`, `step_mating()`, `step_reproduction()`, `step_dispersal()`, `step_survey()`, `step_remove()`, `step_ceiling()`, `step_introduce()`, `step_assign()`, `step_census()`, `step_process()` | +| Model audit | `describe_model()`, `describe_parameters()` | | State | `pva_population()`, `pva_state()`, `add_individuals()` | | Process contract | `pva_process()`, `pva_result()`, `pva_events()`, `validate_processes()`, `execute_processes()` | | Demography | `age_process()`, `survival_process()`, `staged_survival_process()`, `reproduction_process()`, `census_process()` | @@ -20,7 +23,41 @@ entry is exported. | Scenarios | `scenario_spec()`, `run_scenario()` | | Summaries and ensembles | `summarise_pva()`, `summarise_trajectory()`, `summarise_accounting()`, `run_pva_ensemble()` | | Lifecycle inspection | `describe_lifecycle()`, `format_lifecycle()` (`text`, `mermaid`, `dot`) | -| Plots and printing (S3 methods) | `plot()` for `pva_run`, `pva_ensemble`, `pva_scenario` and `pva_lifecycle`; `print()` methods; `[` for `pva_ensemble` | +| Plots and printing (S3 methods) | `plot()` for `pva_run`, `pva_ensemble`, `pva_scenario`, `pva_model` and `pva_lifecycle`; `print()` methods; `[` for `pva_ensemble` | + +## Authoring a model + +`pva_model(params, rates, init, n_steps, fields, globals, ...)` holds the +inputs; each `step_*()` appends one step and returns a new model; +`compile_scenario(model, overrides, n_runs, seed, validation = "strict")` +checks the process plan and returns a standard `pva_scenario`. Set +`validation = "fast"` to change its execution default. Step arguments take a constant, a one-sided formula or an R +callback. A formula may use parameters, population fields, globals written by +an earlier step (or started in `globals`), `time`, `dt`, `n_steps`, `N`, +`rate("")` (options `table`, `missing_sex`, `by`) and the pure +functions listed in `?lifecycle_steps`. Inside `survey_quota()`, `observed` +and `obs$count` give the survey count. Every step accepts `enabled` and +`when`. A skipped survey emits `survey_skip` and a skipped catastrophe +resets its flag to `FALSE`. An enabled `step_process()` factory runs once per +compilation. For indirect reads in a callback or factory, declare the parameter +names in `uses`. Use `uses = character()` when it forwards the list unread. +These callbacks receive all bound parameters. Declared and directly traced +names govern override checks and the audit. Helpers such as `env_ar1(sd = ~env_sd)` and +`litter_poisson(~ rate("litter"))` are bound to parameters at compile time. +`fields` defaults are given to the initial population, newborns and released +animals unless a step sets or inherits the field. A parameter-evidence table +may use `type = "character"` to preserve text such as `"001"`. The audit's +`base` and `value` list columns retain the original types and matrix cells. + +Compilation errors name the step and the symbol or value and never move the +caller's RNG. Overrides must name a parameter and must be able to affect the +scenario; unused base parameters are only reported, by `describe_parameters()` +(`status`: `active`, `inactive`, `unused`). `run_pva_ensemble(design, build = +model)` maps design columns to overrides, including declared parameters named +`label` or `scenario`. An `NA` cell keeps the base value. A named list such +as `build = list(a = m1, b = m2)` reserves the `model` column for structural +selection. Every row compiles before dispatch and each cached result records +its selected model. `seed_by = TRUE` pairs every row. ## Outputs of `run_scenario()` @@ -54,7 +91,7 @@ record a visit and the number detected. A missed visit emits `survey_skip`. ## Composing a species model -Use `mate_random()` for fresh two-sex mating or `mate_from_field()` for a recorded sire. Mating can precede a mortality process in the same interval. Use `mate_from_field(stale = "unpaired")` to treat an absent, unretained sire as unavailable for breeding. With `mate = NULL`, fecundity is female-dominant. A one-sex rate table requires `missing_sex = "zero"` to assign zero when the omitted sex is present. Environment variables evaluate in their listed order, so a shared weather draw can affect several rates. +Use `mate_random()` for fresh two-sex mating or `mate_from_field()` for a recorded sire. Mating can precede a mortality process in the same interval. Use `mate_from_field(stale = "unpaired")` to treat an absent, unretained sire as unavailable for breeding. With `mate = NULL`, fecundity is female-dominant. A one-sex rate table requires `missing_sex = "zero"` to assign zero when the omitted sex is present. Rate tables may give age classes as `age_min`/`age_max` or as an `age` column (`"0"`, `"1-2"`, `"3+"`), share a row between sexes with `sex = "All"`, and be stratified with `by`. Environment variables evaluate in their listed order, so a shared weather draw can affect several rates. For seasonal or patch-local weighted polygyny, use `mating_process()` before mortality. Set `pva_state(mate_field = "mate_id")` to retain a departed sire @@ -103,7 +140,7 @@ For correlated environments, supply `env_ar1()` to `environment_process()`. Name `plot(run)` draws the median with 50% and 90% trajectory ribbons. `plot(run, type = "risk")` gives cumulative first-passage risk with stepwise Wilson limits. The accounting view shows entries and losses and flags intervals with inconsistent receipts or negative cohort stocks. `plot(ensemble)` contrasts design rows and `print(ensemble)` gives the simulation count and root seed. Each plot returns its table invisibly. Use `abline()` or `legend()` in the active panel, or `plot(other_run, add = TRUE)` to overlay a run on the same axes. -`run_pva_ensemble()` accepts one design row per model and a builder and summary function. Fixed seeds reproduce the member and replicate streams across worker counts. Use `cache_key` to identify revisions of external data read by callbacks. See the [grizzly](../../inst/examples/grizzly/README.md) and [woodhen](../../inst/examples/woodhen/README.md) projects for runnable lifecycles. +`run_pva_ensemble()` accepts one design row per model and a builder (a function, a `pva_model` or a named list of models) and a summary function. `seed_by = TRUE` pairs all rows; pairing shares starting streams only, because environmental and demographic draws use the same substream. Fixed seeds reproduce the member and replicate streams across worker counts. Use `cache_key` to identify revisions of external data read by callbacks. See the [grizzly](../../inst/examples/grizzly/README.md) and [woodhen](../../inst/examples/woodhen/README.md) projects for runnable lifecycles. ## Documentation source diff --git a/docs/vision_and_scope.md b/docs/vision_and_scope.md index f0c06e5..aff08ee 100644 --- a/docs/vision_and_scope.md +++ b/docs/vision_and_scope.md @@ -37,15 +37,18 @@ without hiding assumptions. A modeller should be able to: -1. compose an ordered lifecycle from reusable or project-defined R processes; -2. replace, repeat, omit, or add a process without editing the engine controller; -3. inspect what each process requires and writes; -4. test stochastic simulations against independent expected-value calculations +1. author a model from parameter, vital-rate and cohort tables and an ordered + list of steps without writing functions, and see where every input goes + before anything runs; +2. compose an ordered lifecycle from reusable or project-defined R processes; +3. replace, repeat, omit, or add a process without editing the engine controller; +4. inspect what each process requires and writes; +5. test stochastic simulations against independent expected-value calculations where matched life-table or matrix assumptions permit it; -5. reproduce runs from explicit parameters, seeds, versions, and provenance; -6. validate transformations, accounting identities, special cases, hindcasts, +6. reproduce runs from explicit parameters, seeds, versions, and provenance; +7. validate transformations, accounting identities, special cases, hindcasts, and decision-relevant outputs; -7. retain replicate-level evidence rather than only polished summaries. +8. retain replicate-level evidence rather than only polished summaries. Community extension is a core acceptance condition: a third-party process must compose through the public contract without a new engine branch or central @@ -67,6 +70,16 @@ registry entry. - **No premature platform.** No YAML lifecycle DSL, plugin manager, dependency- injection system, global registry, or S4/R6 hierarchy until demonstrated use proves that simpler R composition is inadequate. +- **Authoring is R, not a second language.** The 2.4 authoring layer + (`pva_model()`, `step_*()`, `compile_scenario()`) exists because closure-heavy + syntax hid the biology from the ecologists who own it. It stays inside these + commitments: a model is a plain copy-on-modify value with no registry or + hidden state; its formulas are ordinary R expressions over a closed + vocabulary, checked and rewritten once into closures; and the compiled model + is the same list of `pva_process()` objects, run by the same engine, with + the same contract and no separate execution path. Inputs live in data frames + and lists that the user reads however they like; the package defines no + file format. - **Clean realignment.** Obsolete controller paths will be removed rather than preserved behind compatibility adapters when implementation is authorised. - **Locked lean defaults.** Replicate-level L'Ecuyer-CMRG streams, declared @@ -96,7 +109,10 @@ OpenPVA is: representation is not required for the first realignment; - a reproducible analysis substrate for uncertainty, sensitivity, hindcasting, scenario comparison, and reporting; -- designed for code-capable ecologists and extensible by community R packages. +- designed for practising conservation ecologists, who author models from + tables and ordered steps, and for code-capable ecologists, methodologists + and AI agents, who extend it with ordinary R processes and community + packages. Both groups work on the same objects. OpenPVA is not: @@ -123,6 +139,10 @@ abundance, designed ensembles, serial/fork/PSOCK L'Ecuyer-CMRG bit-parity, and base-graphics plotting. `docs/design/lifecycle_process_contract.md` is the engine contract. +OpenPVA 2.4 adds the authoring front-end over that unchanged engine: separated +inputs, piped lifecycle steps written as statically compiled formulas, +model-driven and structural ensembles, and parameter-provenance audits. + Empirical parameterisation, formal hindcasting, structured global sensitivity wrappers, and external calibration workflows remain deliberately outside the core execution loop and compose around `run_scenario()` and diff --git a/man/age_sex_rate.Rd b/man/age_sex_rate.Rd index 72ac508..72f9e4f 100644 --- a/man/age_sex_rate.Rd +++ b/man/age_sex_rate.Rd @@ -4,18 +4,22 @@ \alias{validate_age_sex_table} \title{Vital rates from age-by-sex tables} \usage{ -validate_age_sex_table(table, value) +validate_age_sex_table(table, value, by = NULL) -age_sex_rate(table, value, missing_sex = c("error", "zero")) +age_sex_rate(table, value, missing_sex = c("error", "zero"), by = NULL) } \arguments{ -\item{table}{Data frame with \code{age_min}, \code{age_max} (which may be \code{Inf}), \code{sex} and the value column.} +\item{table}{Data frame with \code{sex}, the value column and the age classes, given either as \code{age_min} and \code{age_max} (which may be \code{Inf}) or as one \code{age} column holding whole ages, ranges such as \code{"2-4"} or an open class such as \code{"5+"}. \code{sex} is \code{"F"}, \code{"M"} or \code{"All"} for a class shared by both sexes.} \item{value}{Name of the column holding the rate.} +\item{by}{Optional names of further table columns that stratify the rates, for example \code{"patch_id"} or a stage field. Each must also be a population field; an individual's rate is looked up within its own stratum.} \item{missing_sex}{When a living individual's sex has no rows in the table, \code{"error"} (the default) raises an error and \code{"zero"} returns zero for that individual. Use \code{"zero"} for a female-only fecundity table when males should receive zero.} } \description{ \code{age_sex_rate()} compiles a table into a vectorised rate function for \code{\link{survival_process}()} or \code{\link{reproduction_process}()}. An uncovered age for a represented sex raises an error in either mode. } +\details{ +Age classes must not overlap within a sex (and stratum). A gap between classes is found when an individual of that age is looked up; a \code{\link{pva_model}()} that uses the table through \code{rate()} rejects gaps, a missing sex and uncovered starting or newborn ages when it is compiled, before any replicate runs. +} \value{ \code{validate_age_sex_table()} returns the table invisibly. \code{age_sex_rate()} returns a function of \code{(pop, state, context, params)}. } @@ -26,4 +30,9 @@ rates <- data.frame( ) survival <- age_sex_rate(rates, "p_surv") survival(pva_population(sex = c("F", "F", "M"), age = c(0, 5, 2)), NULL, NULL, NULL) + +# the same idea in the shorthand an ecologist would type into a spreadsheet +shorthand <- data.frame(age = c("0", "1-2", "3+"), sex = "All", p_surv = c(0.5, 0.8, 0.9)) +age_sex_rate(shorthand, "p_surv")(pva_population(sex = c("F", "M"), age = c(2, 7)), + NULL, NULL, NULL) } diff --git a/man/demography_processes.Rd b/man/demography_processes.Rd index 4c0ef64..53595bc 100644 --- a/man/demography_processes.Rd +++ b/man/demography_processes.Rd @@ -67,10 +67,10 @@ census_process( \item{offspring_sex}{Function of \code{(mothers, pop, state, context, params)} returning \code{"F"} or \code{"M"} for each newborn; \code{mothers} holds one row index per newborn. Required: the engine supplies no default sex ratio.} \item{mate}{Optional function of \code{(pop, state, context, params)} returning, for each living individual, the row of its mate (the father of its offspring) or \code{NA}. See \code{\link{mate_random}()} and \code{\link{mate_from_field}()}.} \item{require_mate}{Whether a recorded mate is required. Supplying a mate function enables this by default. With mate = NULL, reproduction is female-dominant.} -\item{newborn_fields}{Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the newborns' non-core fields. Index the supplied \code{pop} with \code{mothers} and \code{fathers}. Departed sires needed by the litter appear after the living rows, with their attributes at exit and \code{alive = FALSE}. \code{state$population} contains the living population. An unknown sire has an \code{NA} index.} -\item{newborn_field_names}{Names of the fields \code{newborn_fields} returns.} +\item{newborn_fields}{Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the newborns' non-core fields. Index the supplied \code{pop} with \code{mothers} and \code{fathers}. Departed sires needed by the litter appear after the living rows, with their attributes at exit and \code{alive = FALSE}. \code{state$population} contains the living population. An unknown sire has an \code{NA} index. A named list of single values, such as \code{list(mate_id = NA_integer_)}, gives every newborn the same starting values.} +\item{newborn_field_names}{Names of the fields \code{newborn_fields} returns. When \code{newborn_fields} is a list its names are used.} \item{inherit}{Non-core fields copied from each mother to her offspring.} -\item{metrics}{Optional function of \code{(pop, state, context, params)} returning a named numeric vector. The default reports \code{n_alive}, \code{n_female} and \code{n_male}.} +\item{metrics}{Optional function of \code{(pop, state, context, params)} returning a named numeric vector, or a named list of such functions, each giving one number or a logical vector that is counted (a list of conditions). The default reports \code{n_alive}, \code{n_female} and \code{n_male}.} } \description{ Reusable demographic processes. All rate functions are vectorised over the living population. diff --git a/man/lifecycle.Rd b/man/lifecycle.Rd index f79cb02..6b3892a 100644 --- a/man/lifecycle.Rd +++ b/man/lifecycle.Rd @@ -4,6 +4,7 @@ \alias{describe_lifecycle} \alias{format_lifecycle} \alias{plot.pva_scenario} +\alias{plot.pva_model} \alias{plot.pva_lifecycle} \title{Inspect and diagram a model lifecycle} \usage{ @@ -19,10 +20,12 @@ format_lifecycle(x, format = c("text", "mermaid", "dot"), state = NULL) ... ) +\method{plot}{pva_model}(x, state = NULL, show_flows = TRUE, main = NULL, ...) + \method{plot}{pva_lifecycle}(x, show_flows = TRUE, main = NULL, ...) } \arguments{ -\item{x}{A \code{pva_scenario} from \code{\link{scenario_spec}()}, a \code{pva_run} from \code{\link{run_scenario}()}, a \code{pva_lifecycle} from \code{describe_lifecycle()}, or an ordered list of \code{\link{pva_process}()} objects.} +\item{x}{A \code{\link{pva_model}()}, a \code{pva_scenario} from \code{\link{scenario_spec}()} or \code{\link{compile_scenario}()}, a \code{pva_run} from \code{\link{run_scenario}()}, a \code{pva_lifecycle} from \code{describe_lifecycle()}, or an ordered list of \code{\link{pva_process}()} objects.} \item{state}{Optional \code{\link{pva_state}()} object used to annotate the summary and diagram with starting abundance, pedigree tracking, neutral loci and \code{mate_field} without invoking \code{init_fun()}.} \item{format}{Output format for \code{format_lifecycle()}: \code{"text"} for a console summary, \code{"mermaid"} for a Mermaid flowchart or \code{"dot"} for Graphviz DOT.} \item{show_flows}{Whether to draw dashed inter-process data-flow arcs inferred from declared \code{writes} and \code{requires} fields. \code{TRUE} (the default) suppresses broadcast \code{population.age} fans when three or more steps read age; use \code{"all"} to draw every arc or \code{FALSE} to omit arcs.} @@ -33,14 +36,16 @@ format_lifecycle(x, format = c("text", "mermaid", "dot"), state = NULL) Translate any OpenPVA process list, scenario or run into an ordered audit table, a base-graphics node-and-edge lifecycle flow diagram or a Mermaid/Graphviz specification. Inspection draws no random numbers. } \details{ -\code{describe_lifecycle()} classifies each process into an ecological role (\code{environment}, \code{demography}, \code{spatial}, \code{management}, \code{survey}, \code{census} or \code{custom}) and infers inter-process data flows from declared \code{writes} and \code{requires} paths. A field required before it is written later in the same interval is recorded as a \code{carryover} dependency for the next interval. +\code{describe_lifecycle()} classifies each process into an ecological role (\code{environment}, \code{demography}, \code{spatial}, \code{management}, \code{survey}, \code{census} or \code{custom}) and infers inter-process data flows from declared \code{writes} and \code{requires} paths. A field required before it is written later in the same interval is recorded as a \code{carryover} dependency for the next interval. A role stored on a process is used as given. \code{pva_process(role = )} sets one explicitly. A built-in constructor stores the role its process name and declared effects indicate, so a \code{survival_process()} named \code{"autumn_harvest"} is shown under management as in earlier versions, and falls back to the constructor's own role when they indicate none. A process with no stored role is classified from its name and declared effects each time it is inspected. + +A \code{pva_model} is compiled with its base parameters and described with its own initial state. For a model, or a scenario or run compiled from one, the result also carries an \code{"authoring"} attribute with each step's formulas and the parameter values bound into them, and the text summary lists them under "Authored steps". Mermaid, DOT and diagram output are the same for authored and hand-written lifecycles. \code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} render a pure-base-R node-and-edge flow diagram: a single left-to-right row for up to five interval processes, or a two-row clockwise cycle for six or more processes, with dashed data-flow arcs and an interval-return loop. \code{format_lifecycle()} returns a single character string ready to paste into Markdown/Quarto (\code{"mermaid"}), Graphviz (\code{"dot"}) or plain-text reports (\code{"text"}). } \value{ -\code{describe_lifecycle()} returns a data frame of class \code{pva_lifecycle} with one row per ordered step and \code{"edges"} and \code{"metadata"} attributes. \code{format_lifecycle()} returns a length-one character string. \code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} return the \code{pva_lifecycle} object invisibly. +\code{describe_lifecycle()} returns a data frame of class \code{pva_lifecycle} with one row per ordered step and \code{"edges"} and \code{"metadata"} attributes. \code{format_lifecycle()} returns a length-one character string. The \code{plot()} methods return the \code{pva_lifecycle} object invisibly. } \examples{ scenario <- scenario_spec( diff --git a/man/lifecycle_steps.Rd b/man/lifecycle_steps.Rd new file mode 100644 index 0000000..6b55583 --- /dev/null +++ b/man/lifecycle_steps.Rd @@ -0,0 +1,318 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{lifecycle_steps} +\alias{lifecycle_steps} +\alias{step_environment} +\alias{step_catastrophe} +\alias{step_survival} +\alias{step_age} +\alias{step_pairing} +\alias{step_mating} +\alias{step_reproduction} +\alias{step_dispersal} +\alias{step_survey} +\alias{step_remove} +\alias{step_ceiling} +\alias{step_introduce} +\alias{step_assign} +\alias{step_census} +\alias{step_process} +\title{Lifecycle steps for an authored model} +\usage{ +step_environment( + model, + ..., + name = "environment", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_catastrophe( + model, + probability, + mortality = NULL, + eligible = NULL, + name = "catastrophe", + global = name, + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_survival( + model, + probability, + eligible = NULL, + cause = "natural", + stage = NULL, + post_share = NULL, + field = "survival_draw", + name = if (is.null(stage)) "survival" else paste0("survival_", stage), + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_age( + model, + increment = 1L, + name = "age", + when = TRUE, + enabled = TRUE, + uses = NULL +) + +step_pairing( + model, + eligible, + capacity = Inf, + priority = "id", + max_kinship = Inf, + by = NULL, + field = "mate_id", + name = "pairing", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_mating( + model, + eligible = NULL, + male_capacity = Inf, + weights = NULL, + by = NULL, + field = "mate_id", + clear = TRUE, + name = "mating", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_reproduction( + model, + breeding_probability, + litter_size, + offspring_sex, + mate = NULL, + require_mate = !is.null(mate), + newborn_fields = NULL, + inherit = character(), + name = "reproduction", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_dispersal( + model, + transition = NULL, + destination = NULL, + patches = NULL, + eligible = NULL, + count = NULL, + weights = NULL, + field = "patch_id", + name = "dispersal", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_survey( + model, + detection, + eligible = NULL, + field = "survey", + name = "survey", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_remove( + model, + count = NULL, + probability = NULL, + select = NULL, + eligible = NULL, + weights = NULL, + order = "random", + cause = "removal", + name = "removal", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_ceiling( + model, + capacity, + eligible = NULL, + weights = NULL, + cause = "ceiling", + name = "ceiling", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_introduce( + model, + count, + fields, + source = "introduction", + name = "introduction", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_assign( + model, + field, + value, + count = NULL, + probability = NULL, + select = NULL, + eligible = NULL, + weights = NULL, + order = "random", + event = "assigned", + name = "assign", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_census( + model, + metrics = NULL, + name = "census", + when = TRUE, + enabled = TRUE, + requires = character(), + uses = NULL +) + +step_process(model, process, enabled = TRUE, when = TRUE, uses = NULL) +} +\arguments{ +\item{model}{A \code{\link{pva_model}()}.} +\item{\dots}{Named environment variables, drawn in the order given. Each is \code{\link{env_ar1}()}, \code{\link{env_trend}()}, a formula giving the variable's value for the interval, or a function of \code{(state, context, params)}. A formula may read variables listed before it.} +\item{name}{Process name used in events, accounting and error messages.} +\item{when}{When the step runs: every interval (\code{TRUE}), the listed zero-based intervals, a formula such as \code{~ time \%\% 2 == 0} or \code{~ release_years}, or a function of \code{(state, context, params)}. On a skipped interval, a survey emits \code{survey_skip} and clears its observation, and a catastrophe sets its flag to \code{FALSE}. Other skipped steps leave the state unchanged.} +\item{enabled}{Whether the step is part of the compiled lifecycle: \code{TRUE}, \code{FALSE}, or a formula naming a flag parameter, such as \code{~ releases}, so a scenario can switch the step by overriding that parameter.} +\item{requires}{Additional state paths read by any R function supplied to the step. Fields and globals read by formulas are declared automatically.} +\item{uses}{With the default \code{NULL}, the compiler traces direct reads such as \code{params$capacity} and \code{params[["capacity"]]}. If an enabled callback or factory reads or forwards \code{params} indirectly, declare the names it reads. Use \code{character()} if it forwards the list unread. Such callbacks receive the full parameter list with overrides applied. The declared and directly traced names determine which overrides are accepted and which uses appear in the audit.} +\item{probability}{Per-individual probability: of surviving the interval, of removal or assignment, or (for a catastrophe) the chance that the event occurs in an interval.} +\item{mortality}{Probability that an eligible individual dies when the catastrophe occurs.} +\item{eligible}{Condition selecting the individuals the step applies to. Omit it to apply the step to every living individual.} +\item{global}{Name of the global that records whether the catastrophe occurred.} +\item{cause}{Label stored with the step's accounting events, for example \code{"harvest"}.} +\item{stage}{\code{NULL} for ordinary survival. \code{"pre"} or \code{"post"} splits one interval's survival around a mid-interval event, as \code{\link{staged_survival_process}()} does.} +\item{post_share}{For a staged step, the share of the interval's mortality that falls after the mid-interval event.} +\item{field}{The population field or global the step uses: the mate field for pairing and mating, the patch field for dispersal, the field to set for \code{step_assign()}, the global holding the survey record, or the temporary global shared by staged survival steps.} +\item{increment}{Whole number of age units added.} +\item{capacity}{Maximum number of pairs for pairing, or of eligible individuals for a ceiling.} +\item{priority}{How pairs form; see \code{\link{pairing_process}()}.} +\item{max_kinship}{Largest admissible kinship within a pair.} +\item{by}{Optional population field; partners must share its value.} +\item{male_capacity}{Maximum number of females one male can sire in the step.} +\item{weights}{Relative weight of each individual for weighted selection; zero excludes it.} +\item{clear}{Whether mating first clears every recorded mate; see \code{\link{mating_process}()}.} +\item{breeding_probability}{Probability that a female breeds.} +\item{litter_size}{A litter helper such as \code{\link{litter_poisson}()}, \code{\link{litter_binomial}()} or \code{\link{litter_categorical}()}.} +\item{offspring_sex}{An offspring-sex helper such as \code{\link{offspring_sex_bernoulli}()}. Required: no sex ratio is assumed.} +\item{mate}{Optional mate helper: \code{\link{mate_random}()}, \code{\link{mate_min_kinship}()} or \code{\link{mate_from_field}()}.} +\item{require_mate}{Whether a female needs a mate to breed.} +\item{newborn_fields}{Named list of newborn values for custom fields, overriding the model's \code{fields} defaults, or a function as for \code{\link{reproduction_process}()}.} +\item{inherit}{Custom fields copied from each mother to her offspring.} +\item{transition}{Square matrix of movement probabilities with patch names on rows and columns; every eligible individual moves by its row.} +\item{destination}{Rule giving each individual's destination patch, as an alternative to a transition matrix.} +\item{patches}{Patch identifiers, needed with a destination rule.} +\item{count}{Number of individuals to move, remove, introduce or assign in the interval.} +\item{detection}{Per-individual detection probability.} +\item{select}{Condition choosing exactly which individuals to remove or assign.} +\item{order}{Take individuals at random (\code{"random"}) or by ascending identifier (\code{"id"}) when \code{count} is given.} +\item{fields}{Named list with \code{sex}, \code{age} and any custom field of the introduced individuals; values are recycled over them. The model's \code{fields} defaults fill what the list omits. A function as for \code{\link{introduction_process}()} is also accepted.} +\item{source}{Label stored with the introduction event.} +\item{value}{Value to assign: a constant, a formula evaluated for the selected individuals, or a function.} +\item{event}{Name of the event that counts assigned individuals.} +\item{metrics}{Census metrics: a named list of formulas, each giving one number or a condition to count (\code{list(n_alive = ~ N, adult_females = ~ sex == "F" & age >= 2)}); one formula returning a named vector; or a function as for \code{\link{census_process}()}. \code{NULL} reports \code{n_alive}, \code{n_female} and \code{n_male}.} +\item{process}{Any \code{pva_process}: the output of an OpenPVA constructor or of \code{\link{pva_process}()}. A deterministic factory of one argument, \code{params}, returning a process is called once per enabled step with the scenario's bound parameters.} +} +\description{ +Each \code{step_*()} adds one step to the end of a \code{\link{pva_model}()} and returns the new model, so a lifecycle reads top to bottom in a pipe. Order is biology: survival before ageing is pre-ageing mortality, and a census observes whatever precedes it. Every step compiles to the OpenPVA constructor of the same purpose, and \code{step_process()} inserts any hand-written or native process at that exact position. +} +\details{ +\strong{Values, formulas or functions.} Wherever a step takes a rate, condition, count or value you can give a constant, a one-sided formula, or an R function with the signature the underlying constructor documents. A formula is the closure-free form: \code{~ ifelse(age == 0, s_juvenile, s_adult)} instead of \code{function(pop, state, context, params) ifelse(pop$age == 0, params$s_juvenile, params$s_adult)}. + +\strong{What a formula may contain.} +\itemize{ +\item parameters declared in \code{pva_model(params = )}; +\item population fields: \code{age}, \code{sex}, \code{id}, \code{mother_id}, \code{father_id}, \code{pedigree_F} (with a pedigree) and the model's custom fields such as \code{mate_id} or \code{patch_id}; +\item globals written by an earlier step, such as an environment variable or a catastrophe flag, or given a starting value in \code{pva_model(globals = )}; +\item \code{time} (the zero-based interval), \code{dt}, \code{n_steps} and \code{N} (the number of living individuals); +\item \code{rate("")}, the age-and-sex lookup of that column of the model's rate table, with the options \code{table = }, \code{missing_sex = "zero"} and \code{by = } (see \code{\link{age_sex_rate}()}); +\item arithmetic, comparison and logical operators, indexing with \code{[}, \code{if}/\code{ifelse}, and the pure functions \code{abs}, \code{sqrt}, \code{exp}, \code{log}, \code{floor}, \code{ceiling}, \code{round}, \code{min}, \code{max}, \code{pmin}, \code{pmax}, \code{sum}, \code{mean}, \code{prod}, \code{any}, \code{all}, \code{which}, \code{length}, \code{c}, \code{rep}, \code{is.na}, \code{\%in\%}, \code{match}, \code{unique}, \code{cumsum}, \code{as.numeric} and relatives, \code{plogis}, \code{qlogis}, \code{pnorm}, \code{qnorm}, \code{pbeta}, \code{qbeta} and \code{median}; +\item the OpenPVA helpers \code{\link{shift_logit}()}, \code{\link{qbeta_norm}()}, \code{\link{inbreeding_multiplier}()}, \code{\link{ceiling_density_multiplier}()}, \code{\link{beverton_holt_multiplier}()}, \code{\link{ricker_multiplier}()}, \code{\link{sex_ratio_effective_size}()} and \code{patch_counts(patches)}, which counts the living population by patch. +} +Names must be unambiguous, so a parameter cannot share a name with a field, a global or one of the reserved words. Assignment, function definitions, random draws and anything with a side effect are rejected: write those as an R function or a \code{step_process()}. + +Functions in the allowlist may be namespace-qualified, for example \code{stats::plogis()} and \code{OpenPVA::shift_logit()}. A per-individual formula is evaluated once per step for the whole living population. Logical probabilities contribute 0 or 1. A formula that reads only parameters is evaluated when the model is compiled and passed on as a constant. + +\strong{Helpers inside steps.} \code{\link{env_ar1}()}, \code{\link{env_trend}()}, \code{\link{spatial_correlation}()}, the litter, offspring-sex and mate helpers and \code{\link{survey_quota}()} accept formulas for their own arguments when used in a step, for example \code{env_ar1(sd = ~ env_sd)}, \code{litter_poisson(~ rate("litter"))} or \code{mate_random(~ age >= maturity)}. They are then bound to the scenario's parameters at compile time. Inside \code{survey_quota()}, \code{observed} and \code{obs$count} give the survey count. The current observation also exposes \code{obs$visited}, \code{obs$ids} and \code{obs$time}. + +\strong{Fields of new individuals.} Newborns and released animals receive the model's \code{fields} defaults for every custom field a step does not set or inherit. A custom field with no default and no value on the step is reported when the model is compiled. + +\strong{Scheduling and switching.} \code{when} restricts a step to some intervals; \code{enabled} decides at compile time whether the step exists in a scenario at all. A step disabled through a flag parameter draws no random numbers and leaves no rows in the event or accounting tables. +} +\value{ +The \code{pva_model} with the step appended. +} +\seealso{ +\code{\link{pva_model}()}, \code{\link{compile_scenario}()} and \code{\link{describe_model}()}; the constructors each step compiles to, \code{\link{survival_process}()}, \code{\link{reproduction_process}()}, \code{\link{removal_process}()}, \code{\link{environment_process}()}, \code{\link{dispersal_process}()} and \code{\link{survey_process}()}. +} +\examples{ +model <- pva_model( + params = list(s_juvenile = 0.5, s_adult = 0.85, env_sd = 0.3, maturity = 2, + detect = 0.7, trigger = 12, release = 4), + init = data.frame(age = c(1, 3), sex = c("F", "M"), n = 8), + n_steps = 10, pedigree = TRUE +) |> + step_environment(weather = env_ar1(sd = ~ env_sd, phi = 0.4)) |> + step_survival(~ shift_logit(ifelse(age == 0, s_juvenile, s_adult), weather) * + inbreeding_multiplier(pedigree_F, 3.14)) |> + step_age() |> + step_reproduction(~ 0.8 * (age >= maturity), litter_poisson(1.3), + offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(~ age >= maturity)) |> + step_survey(~ detect, when = ~ time \%\% 2 == 0, field = "count") |> + step_introduce( + survey_quota(~ if (observed < trigger) release else 0, field = "count", on_skip = 0), + fields = list(sex = c("F", "M"), age = 2L), name = "release" + ) |> + step_process(pva_process( + "tag_oldest", function(state, context, params) pva_result(state), + requires = "population.age" + )) |> + step_census(list(n_alive = ~ N, breeders = ~ age >= maturity)) + +describe_lifecycle(model) +run <- run_scenario(compile_scenario(model, n_runs = 10, seed = 3)) +all(summarise_accounting(run)$reconciled) +} diff --git a/man/management_processes.Rd b/man/management_processes.Rd index ab55e7e..f5c52c4 100644 --- a/man/management_processes.Rd +++ b/man/management_processes.Rd @@ -94,8 +94,8 @@ mating_process( \item{params}{Named list of modeller parameters, passed unchanged to every supplied function as \code{params}.} \item{weights}{Optional function of \code{(pop, state, context, params)} returning a finite non-negative weight for each living individual, or a scalar. Zero excludes an individual.} \item{capacity}{Capacity: one number, or a function of \code{(state, context, params)}. For \code{ceiling_process()} the maximum number of eligible individuals; for \code{pairing_process()} the maximum number of pairs (territories).} -\item{fields}{Function of \code{(n, state, context, params)} returning a named list with \code{sex}, \code{age} and every non-core field of the \code{n} introduced individuals. Optional \code{mother_id} and \code{father_id} must both be missing when neutral loci are enabled.} -\item{creates}{Fields that \code{fields} initialises.} +\item{fields}{Function of \code{(n, state, context, params)} returning a named list with \code{sex}, \code{age} and every non-core field of the \code{n} introduced individuals, or such a list of plain values, each recycled over the introduced individuals (\code{list(sex = c("F", "M"), age = 2L)} releases alternating sexes at age two). Optional \code{mother_id} and \code{father_id} must both be missing when neutral loci are enabled.} +\item{creates}{Fields that \code{fields} initialises. The names of a \code{fields} list are added automatically.} \item{source}{Label stored with the introduction event.} \item{field}{Existing model field to assign, or the numeric field receiving mate identifiers.} \item{value}{Scalar to assign, or a function of \code{(rows, pop, state, context, params)} returning one value or one per selected row. Integer fields accept whole, representable doubles. An untyped \code{NA} takes the field's type on fields that support missing values.} diff --git a/man/model_audit.Rd b/man/model_audit.Rd new file mode 100644 index 0000000..a6fa023 --- /dev/null +++ b/man/model_audit.Rd @@ -0,0 +1,51 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{model_audit} +\alias{model_audit} +\alias{describe_model} +\alias{describe_parameters} +\title{Audit an authored model and its parameters} +\usage{ +describe_model(model, overrides = list(), life_table = NULL) + +describe_parameters(model, overrides = list()) +} +\arguments{ +\item{model}{A \code{\link{pva_model}()}.} +\item{overrides}{Named list of parameter overrides to audit, as for \code{\link{compile_scenario}()}.} +\item{life_table}{Optional list for a deterministic check of the authored rates with \code{\link{life_table_metrics}()}: \code{survival} and \code{fecundity} (daughters per female), each a numeric vector by age or a formula of parameters, \code{age} and \code{rate()}, evaluated for females of every age class; and optionally \code{timing}, \code{plus_group} and \code{max_age}.} +} +\description{ +\code{describe_model()} reports what a model will build before anything runs: the initial cohorts, custom fields, each step with its formulas and the parameter values bound into them, and the parameter table. \code{describe_parameters()} returns that table alone. Neither draws a random number. +} +\details{ +The parameter table has one row per declared parameter: its \code{base} value, the effective \code{value} once \code{overrides} are applied, whether it is \code{overridden}, the steps that use it (\code{used_by}), a \code{status}, and the evidence columns of the parameter table the model was built from. The status is \code{"active"} when an enabled step or a step switch uses the parameter, \code{"inactive"} when only disabled steps do, and \code{"unused"} when nothing does. For indirect parameter reads in a callback or factory, supply the names in the step's \code{uses} argument. The \code{base} and \code{value} columns are lists. Use \code{[[i]]} to extract row \code{i} in its original type, including matrix dimensions and dimnames. Evidence columns that share a name with an audit column receive the prefix \code{evidence.}. + +Unused base parameters are reported, not rejected, because a disabled step may legitimately leave a parameter idle. An \emph{override} of such a parameter is an error. +} +\value{ +\code{describe_parameters()} returns a data frame. \code{describe_model()} returns a list of class \code{pva_model_audit} with \code{name}, \code{settings}, \code{n_initial}, \code{initial} (counts by sex and age), \code{fields}, \code{globals}, \code{steps} (one row per step, including disabled ones), \code{parameters}, \code{unused} and, when requested, \code{life_table}; printing it gives a readable report. +} +\seealso{ +\code{\link{describe_lifecycle}()} and \code{plot()} for the process-level view of the same model. +} +\examples{ +rates <- data.frame(age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.5, 0.8, 0.9), p_breed = c(0, 0.6, 1), litter = c(0, 1.2, 2)) +model <- pva_model( + params = data.frame(parameter = c("capacity", "female_share", "spare"), + value = c(80, 0.5, 1), unit = c("animals", "proportion", "-")), + rates = rates, init = data.frame(age = 0:2, females = c(4, 3, 6), males = c(4, 3, 5)), + n_steps = 20 +) |> + step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, capacity)) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share)) |> + step_census() + +describe_parameters(model, overrides = list(capacity = 60)) +describe_model(model, life_table = list( + survival = ~ rate("p_surv"), + fecundity = ~ rate("p_breed") * rate("litter") * female_share +)) +} diff --git a/man/print.pva_state.Rd b/man/print.pva_state.Rd index 860d912..c655ccc 100644 --- a/man/print.pva_state.Rd +++ b/man/print.pva_state.Rd @@ -6,6 +6,10 @@ \alias{print.pva_lifecycle} \alias{print.pva_run} \alias{print.pva_ensemble} +\alias{print.pva_model} +\alias{print.pva_model_audit} +\alias{print.pva_formula} +\alias{print.pva_deferred} \alias{[.pva_ensemble} \alias{[.pva_lifecycle} \title{Print and subset OpenPVA objects} @@ -22,12 +26,20 @@ \method{print}{pva_ensemble}(x, ...) +\method{print}{pva_model}(x, ...) + +\method{print}{pva_model_audit}(x, ...) + +\method{print}{pva_formula}(x, ...) + +\method{print}{pva_deferred}(x, ...) + \method{[}{pva_ensemble}(x, ...) \method{[}{pva_lifecycle}(x, ...) } \arguments{ -\item{x}{An OpenPVA state, process, scenario, lifecycle, run or ensemble.} +\item{x}{An OpenPVA state, process, scenario, lifecycle, run, ensemble, model, model audit, or a formula or helper call stored in a model.} \item{\dots}{Additional arguments passed to the underlying data-frame print or subset method.} } \description{Summarise an OpenPVA object, subset a \code{pva_ensemble} data frame while preserving its provenance metadata, or slice a \code{pva_lifecycle} table into a plain data frame.} diff --git a/man/pva_model.Rd b/man/pva_model.Rd new file mode 100644 index 0000000..f4bd28d --- /dev/null +++ b/man/pva_model.Rd @@ -0,0 +1,102 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{pva_model} +\alias{pva_model} +\alias{cohort_population} +\alias{compile_scenario} +\title{Author a model from separated inputs} +\usage{ +pva_model( + params = list(), + rates = NULL, + init, + n_steps, + fields = list(), + globals = list(), + name = "model", + dt = 1, + pedigree = FALSE, + n_loci = 0L, + mate_field = NULL, + initial_census = TRUE +) + +cohort_population(counts, ...) + +compile_scenario( + model, + overrides = list(), + n_runs = 100L, + seed = NULL, + name = NULL, + validation = c("strict", "fast") +) +} +\arguments{ +\item{params}{Model parameters: a named list, or a parameter table (data frame, for example from \code{read.csv()}) with a \code{parameter} (or \code{name}) column, a \code{value} column and any further evidence columns such as \code{unit}, \code{source} or \code{notes}, which are kept for \code{\link{describe_parameters}()}. Values in a text column are read as numbers, \code{TRUE}/\code{FALSE} or text, one parameter per row. Set \code{type = "character"} to preserve a code such as \code{"001"} when the input value is text. A list may also hold vectors and matrices.} +\item{rates}{Vital-rate table for \code{rate("")} lookups in formulas, in any layout \code{\link{age_sex_rate}()} accepts, or a named list of such tables.} +\item{init}{The initial population: a cohort-count table as for \code{cohort_population()}; a founder table with one row per individual (\code{sex}, \code{age} and optionally \code{mother_id}, \code{father_id} and custom fields); a \code{\link{pva_population}()}; or a function of no arguments returning one of these.} +\item{n_steps}{Number of intervals to simulate.} +\item{fields}{Named list of default values for custom individual fields, for example \code{list(mate_id = NA_integer_)}. Each default is added to the initial population when absent, given to newborns by \code{\link{step_reproduction}()} and to released animals by \code{\link{step_introduce}()}, unless a step sets or inherits the field itself. A default needs an explicit type: write \code{NA_integer_}, not \code{NA}.} +\item{globals}{Named list of starting values for shared globals that a step reads before any step has written them.} +\item{name}{Model name, used as the default scenario name.} +\item{dt}{Duration of one interval.} +\item{pedigree}{Whether the engine tracks exact pedigree inbreeding; see \code{\link{pva_state}()}.} +\item{n_loci}{Number of unlinked neutral loci dropped through the pedigree.} +\item{mate_field}{Optional custom field in which females keep a sire across intervals; see \code{\link{pva_state}()}.} +\item{initial_census}{\code{TRUE} takes a year-zero census with the model's last \code{\link{step_census}()} (none if the model has no census), \code{FALSE} takes none, and a step name selects that census.} +\item{counts}{Cohort-count table with an \code{age} column and either \code{sex} and \code{n}, or \code{females} and \code{males}. Any further column, such as \code{patch_id}, becomes a population field with that row's value. Individuals are created in row order; the \code{females}/\code{males} layout lists all females before all males.} +\item{\dots}{Further fields given to every individual, as in \code{\link{pva_population}()}.} +\item{model}{A \code{pva_model}.} +\item{overrides}{Named list of parameter values that replace the model's base values for this scenario.} +\item{n_runs}{Number of replicate runs.} +\item{seed}{Optional root seed, as in \code{\link{scenario_spec}()}.} +\item{validation}{Default execution mode for \code{\link{run_scenario}()}. Choose \code{"strict"} for complete transition checks or \code{"fast"} for a previously validated model. Both modes check the compiled process list against the initial state. An explicit mode in \code{run_scenario()} overrides this default.} +} +\description{ +\code{pva_model()} holds a model's inputs apart from its lifecycle: parameters, vital-rate tables, the initial population and the custom individual fields. Steps are then added in order with the \code{\link[=lifecycle_steps]{step_*()}} functions, usually in a pipe. \code{compile_scenario()} turns the model into an ordinary \code{pva_scenario}, built from the same constructors a hand-written model uses, for \code{\link{run_scenario}()}. +} +\details{ +A \code{pva_model} is a plain value. Adding a step returns a new model; nothing is registered or stored elsewhere, and a stored formula keeps only its expression, never the environment it was written in. + +Compilation resolves every formula once against the model's parameters, population fields, globals, the context values \code{time}, \code{dt}, \code{n_steps} and \code{N}, and its \code{rate()} tables, and rewrites it into an ordinary closure with the parameter values written in (see \code{\link{lifecycle_steps}}). The closure is bound to the package namespace or a locked child environment holding its rate lookups, so it runs as fast as the hand-written equivalent and travels unchanged to fork and socket workers. The required fields of every process are derived from what its formulas read. + +Compilation fails, before any random number is drawn, on: a symbol that is not in the vocabulary; a name used for two things (say a parameter and a population field); a function outside the pure-function list, an assignment or a random draw in a formula; a rate table with overlapping or missing age classes in a sex or stratum, no open terminal age class for a sex and its fixed strata when ageing is enabled, or a probability outside [0, 1]; a step that reads a global written only by a disabled step, or a survey quota placed before its survey; an unknown override; and an override that cannot affect the scenario because only disabled steps use that parameter. The message names the step and the offending symbol or value. A base parameter that no step uses is not an error; \code{\link{describe_parameters}()} lists it as unused. + +\code{cohort_population()} is the population builder \code{pva_model()} applies to a cohort table; use it directly with \code{\link{pva_state}()} in hand-written models. +} +\value{ +\code{pva_model()} returns a \code{pva_model}. \code{cohort_population()} returns a population as \code{\link{pva_population}()} does. \code{compile_scenario()} returns a \code{pva_scenario} whose \code{authoring} element records each step's formulas and bound parameter values for \code{\link{describe_lifecycle}()}. +} +\seealso{ +\code{\link{lifecycle_steps}} for the steps and the formula vocabulary, \code{\link{describe_model}()} for the audit, and \code{\link{run_pva_ensemble}()}, which accepts a model directly. +} +\examples{ +parameters <- data.frame( + parameter = c("capacity", "female_share", "releases", "release_size"), + value = c("60", "0.5", "FALSE", "4"), + source = c("habitat map", "assumed", "scenario", "scenario") +) +rates <- data.frame( + age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.55, 0.80, 0.88), p_breed = c(0, 0.5, 0.9), litter = c(0, 1.2, 1.6) +) +cohorts <- data.frame(age = 0:2, females = c(6, 4, 8), males = c(6, 4, 7)) + +model <- pva_model(parameters, rates, cohorts, n_steps = 15, name = "island") |> + step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, capacity)) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share), + mate = mate_random(~ age >= 1)) |> + step_introduce(~ release_size, fields = list(sex = c("F", "M"), age = 1L), + name = "release", when = 0:4, enabled = ~ releases) |> + step_census() +model + +result <- run_scenario(compile_scenario(model, n_runs = 20, seed = 1)) +summarise_pva(result, threshold = 10)[c("p_ever_below", "final_mean")] + +# the same model with the release step switched on, paired on one seed +run_pva_ensemble(data.frame(releases = c(FALSE, TRUE)), model, n_runs = 20, + seed = 1, seed_by = TRUE)[c("releases", "final_mean", "ema")] +} diff --git a/man/pva_process.Rd b/man/pva_process.Rd index 0fe2b95..faec3ec 100644 --- a/man/pva_process.Rd +++ b/man/pva_process.Rd @@ -14,7 +14,8 @@ pva_process( requires = character(), writes = character(), creates = NULL, - description = NULL + description = NULL, + role = NULL ) pva_result(state, events = NULL, census = NULL) @@ -46,6 +47,7 @@ execute_processes( \item{writes}{State paths the process may change. Writing \code{population.alive} is how a process records deaths or removals.} \item{creates}{For a process that adds individuals: the population fields it initialises. Must include \code{sex} and \code{age} and cover every non-core field.} \item{description}{Optional one-line description.} +\item{role}{Optional ecological role shown by \code{\link{describe_lifecycle}()} and its diagrams: \code{"environment"}, \code{"demography"}, \code{"spatial"}, \code{"management"}, \code{"survey"}, \code{"census"} or \code{"custom"}. A role given here is used as stated, ahead of the role inferred from the process name and effects. Each built-in constructor stores a role on the process it returns: the one its name and effects indicate, which is the role earlier versions displayed, or failing that the constructor's own.} \item{state}{A \code{pva_state}.} \item{events}{\code{NULL} or events from \code{pva_events()}.} \item{census}{\code{NULL} or a named numeric vector of census metrics.} diff --git a/man/run_pva_ensemble.Rd b/man/run_pva_ensemble.Rd index bf1818f..cb9ff96 100644 --- a/man/run_pva_ensemble.Rd +++ b/man/run_pva_ensemble.Rd @@ -20,11 +20,11 @@ run_pva_ensemble( } \arguments{ \item{design}{Data frame with one row per ensemble member, for example the cross of structural variants, parameter draws and management options.} -\item{build}{Function of one design row (a named list) returning a list with \code{init_fun}, \code{processes} and \code{n_steps}, and optionally \code{initial_census}, \code{dt} and \code{keep}.} +\item{build}{What each design row builds. A \code{\link{pva_model}()}: every design column that names a model parameter overrides it for that row. A named list of models: the design column \code{model} selects one per row, for structural comparisons. Or a function of one design row (a named list) returning a list with \code{init_fun}, \code{processes} and \code{n_steps}, and optionally \code{initial_census}, \code{dt} and \code{keep}.} \item{n_runs}{Number of inner Monte Carlo replicates per member.} \item{summarise}{Function of \code{(result, row)} returning a data frame of summaries for one member. The default is \code{\link{summarise_pva}()}.} \item{seed}{Root seed from which member seeds are derived.} -\item{seed_by}{Optional design columns that define blocks sharing one seed (common random numbers), for example the structural and parametric columns when management options should be compared on paired streams.} +\item{seed_by}{\code{NULL} gives every row its own seed. \code{TRUE} pairs all rows on one seed (common random numbers). Design column names define blocks that share a seed, for example the structural and parametric columns when management options should be compared on paired streams within each block.} \item{workers}{Number of local worker processes.} \item{backend}{\code{"fork"}, \code{"psock"}, or \code{"auto"} (fork on Unix, PSOCK on Windows).} \item{cluster}{Optional cluster from \code{parallel::makePSOCKcluster()}. Use this to reuse workers or to initialise dependencies looked up dynamically.} @@ -33,10 +33,14 @@ run_pva_ensemble( \item{cache_key}{Optional revision string for model inputs read from external files or resolved dynamically.} } \description{ -Separates the outer design (structure, parameters, management) from the inner Monte Carlo replicates. Each member is built, run and reduced to its summary inside a worker, so memory use does not grow with the size of the design. +Separates the outer design (structure, parameters, management) from the inner Monte Carlo replicates. For an authored model, the coordinator compiles each design row once and passes the scenario to the worker. A function builder runs on the worker. Each worker returns the member summary. } \details{ The builder and summary draw on a reproducible member substream. Cache entries record callback code and statically referenced inputs, package and R versions, the row, member seed, full RNG specification (including the binomial generator when available), replicate count, validation mode and cache key. Member seeds are a deterministic function of \code{seed} and the design order, so the ensemble is reproducible and independent of the number of workers and of the backend. + +With a model as \code{build}, a design cell that is \code{NA} leaves the parameter at its base value, declared parameters take precedence over descriptive columns (\code{label} and \code{scenario}) and may also appear in \code{seed_by}. A named list of structural models reserves \code{model} for selection. Any other column that is not a parameter is an error, as is an override that cannot change the row's model (see \code{\link{compile_scenario}()}). Every row is compiled and validated before a seed is drawn or a worker started, and each cache entry records its own selected model's parameters, rate tables and steps. Editing one structure recomputes its members. + +A shared seed gives the rows the same replicate streams at the start of every run. Environmental draws and demography share one stream, so rows whose trajectories diverge then consume it differently: pairing removes between-row seed noise but does not hold the environmental sequence fixed. } \value{ A data frame of class \code{pva_ensemble}: the design rows, \code{member}, \code{member_seed} and the summary columns. Provenance is attached as an attribute. \code{\link[=plot.pva_ensemble]{plot()}} contrasts the members. diff --git a/scripts/build_rd.R b/scripts/build_rd.R index aaeb119..813b150 100644 --- a/scripts/build_rd.R +++ b/scripts/build_rd.R @@ -102,6 +102,10 @@ writeLines(c( "\\alias{print.pva_lifecycle}", "\\alias{print.pva_run}", "\\alias{print.pva_ensemble}", + "\\alias{print.pva_model}", + "\\alias{print.pva_model_audit}", + "\\alias{print.pva_formula}", + "\\alias{print.pva_deferred}", "\\alias{[.pva_ensemble}", "\\alias{[.pva_lifecycle}", "\\title{Print and subset OpenPVA objects}", @@ -118,12 +122,20 @@ writeLines(c( "", "\\method{print}{pva_ensemble}(x, ...)", "", + "\\method{print}{pva_model}(x, ...)", + "", + "\\method{print}{pva_model_audit}(x, ...)", + "", + "\\method{print}{pva_formula}(x, ...)", + "", + "\\method{print}{pva_deferred}(x, ...)", + "", "\\method{[}{pva_ensemble}(x, ...)", "", "\\method{[}{pva_lifecycle}(x, ...)", "}", "\\arguments{", - "\\item{x}{An OpenPVA state, process, scenario, lifecycle, run or ensemble.}", + "\\item{x}{An OpenPVA state, process, scenario, lifecycle, run, ensemble, model, model audit, or a formula or helper call stored in a model.}", "\\item{\\dots}{Additional arguments passed to the underlying data-frame print or subset method.}", "}", "\\description{Summarise an OpenPVA object, subset a \\code{pva_ensemble} data frame while preserving its provenance metadata, or slice a \\code{pva_lifecycle} table into a plain data frame.}", diff --git a/scripts/build_site.R b/scripts/build_site.R index 9922afc..36f7489 100644 --- a/scripts/build_site.R +++ b/scripts/build_site.R @@ -37,6 +37,8 @@ if (!all(ok)) { } pkg_name <- structure("OpenPVA", path = normalizePath(".", mustWork = TRUE)) +# litedown starts R in the output directory. Carry the resolved library paths into that session. +Sys.setenv(R_LIBS = paste(.libPaths(), collapse = .Platform$path.sep)) litedown::pkg_site(name = pkg_name, output = out_dir) # Remove build-only source files so out_dir holds deployable static assets only. diff --git a/scripts/check_r_floor.R b/scripts/check_r_floor.R index 844bdc1..ab5ec3a 100644 --- a/scripts/check_r_floor.R +++ b/scripts/check_r_floor.R @@ -83,6 +83,39 @@ herd <- scenario_spec( census_process() ) ) + +# 2.4.0: an authored model, built inside a function so nothing it needs can +# come from this script's global environment. Stratified rate lookups, +# compile-time helper binding, a scheduled survey and a quota all travel to +# the socket workers as compiled closures. +floor_authored <- function() { + rates <- data.frame(age = c("0", "1+", "0", "1+"), sex = "All", + patch_id = rep(c("shore", "ridge"), each = 2L), + p_surv = c(0.6, 0.85, 0.5, 0.8)) + pva_model( + params = list(env_sd = 0.3, capacity = 14, detect = 0.8, trigger = 9, releases = TRUE), + rates = rates, + init = data.frame(age = 2L, sex = rep(c("F", "M"), 2L), n = 3L, + patch_id = rep(c("shore", "ridge"), each = 2L), stringsAsFactors = FALSE), + fields = list(mate_id = NA_integer_), n_steps = 4L, pedigree = TRUE, n_loci = 3L, + name = "floor-authored" + ) |> + step_environment(weather = env_ar1(sd = ~ env_sd, phi = 0.4)) |> + step_survival(~ shift_logit(rate("p_surv", by = "patch_id"), weather) * + ceiling_density_multiplier(N, capacity)) |> + step_age() |> + step_pairing(~ age >= 1, priority = "kinship", by = "patch_id") |> + step_reproduction(~ !is.na(mate_id), litter_binomial(3L, 1.2), offspring_sex_bernoulli(0.5), + mate = mate_from_field(), inherit = "patch_id") |> + step_survey(~ detect, when = ~ time %% 2 == 0, field = "count", enabled = ~ releases) |> + step_introduce(survey_quota(~ if (observed < trigger) 2 else 0, field = "count", on_skip = 0L), + fields = list(sex = c("F", "M"), age = 1L, patch_id = "shore"), + name = "release", enabled = ~ releases) |> + step_census(list(n_alive = ~ N, on_shore = ~ patch_id == "shore")) +} +authored <- compile_scenario(floor_authored(), n_runs = 4L, seed = 41L) +authored_design <- data.frame(capacity = c(10, 14, 14), releases = c(TRUE, TRUE, FALSE)) + keep <- c("state", "events", "census", "accounting") season <- run_scenario(herd, keep = keep) events <- function(type) season$events$value[season$events$event_type == type] @@ -128,12 +161,27 @@ tryCatch({ stopifnot(identical(serial, socket), identical(season, socket_season), identical(before, .Random.seed), all(unlist(loaded) == find.package("OpenPVA", lib.loc = private_lib))) cat("Scenario results match serial and both workers loaded the private installation.\n") + authored_serial <- run_scenario(authored, keep = keep) + authored_socket <- run_scenario(authored, parallel = TRUE, cluster = cl, keep = keep) + stopifnot(identical(authored_serial, authored_socket), identical(before, .Random.seed), + all(summarise_accounting(authored_serial)$reconciled), + any(authored_serial$events$event_type == "survey_visit"), + sum(authored_serial$events$value[authored_serial$events$event_type == "birth"]) > 0) + cat("The authored model matches serial on both --vanilla workers.\n") }, finally = parallel::stopCluster(cl)) floor_summary <- function(result, row) { summary <- summarise_pva(result) summary$member_rng <- paste(result$provenance$rng_kind, collapse = "/") summary } +authored_serial_design <- run_pva_ensemble(authored_design, floor_authored(), 3L, floor_summary, + seed = 38L, seed_by = TRUE) +authored_socket_design <- run_pva_ensemble(authored_design, floor_authored(), 3L, floor_summary, + seed = 38L, seed_by = TRUE, workers = 2L, + backend = "psock") +stopifnot(identical(authored_serial_design, authored_socket_design), + length(unique(authored_serial_design$member_seed)) == 1L) +cat("The authored ensemble matches serial on fresh socket workers.\n") serial_design <- run_pva_ensemble(design, floor_components, 3L, floor_summary, seed = 37L) socket_design <- run_pva_ensemble(design, floor_components, 3L, floor_summary, seed = 37L, workers = 2L, backend = "psock") @@ -143,7 +191,9 @@ cat("Ensemble results match serial on a second, internally created PSOCK cluster if (.Platform$OS.type != "windows") { forked <- run_scenario(scenario, parallel = TRUE, workers = 2L, backend = "fork") fork_season <- run_scenario(herd, parallel = TRUE, workers = 2L, backend = "fork", keep = keep) - stopifnot(identical(forked, serial), identical(season, fork_season), identical(before, .Random.seed)) + fork_authored <- run_scenario(authored, parallel = TRUE, workers = 2L, backend = "fork", keep = keep) + stopifnot(identical(forked, serial), identical(season, fork_season), + identical(fork_authored, authored_serial), identical(before, .Random.seed)) cat("Forked and serial scenarios also agree.\n") } cat("All seeded calls restored the caller's RNG.\n") diff --git a/scripts/rd_topics.R b/scripts/rd_topics.R index 1b5ecbf..bc7233b 100644 --- a/scripts/rd_topics.R +++ b/scripts/rd_topics.R @@ -71,6 +71,7 @@ length(state$population$id))" writes = r"(State paths the process may change. Writing \code{population.alive} is how a process records deaths or removals.)", creates = r"(For a process that adds individuals: the population fields it initialises. Must include \code{sex} and \code{age} and cover every non-core field.)", description = "Optional one-line description.", + role = r"(Optional ecological role shown by \code{\link{describe_lifecycle}()} and its diagrams: \code{"environment"}, \code{"demography"}, \code{"spatial"}, \code{"management"}, \code{"survey"}, \code{"census"} or \code{"custom"}. A role given here is used as stated, ahead of the role inferred from the process name and effects. Each built-in constructor stores a role on the process it returns: the one its name and effects indicate, which is the role earlier versions displayed, or failing that the constructor's own.)", events = r"(\code{NULL} or events from \code{pva_events()}.)", census = r"(\code{NULL} or a named numeric vector of census metrics.)", event_type = r"(Character vector of event types. \code{"death"}, \code{"removal"}, \code{"birth"} and \code{"introduction"} are accounting events whose values must match the state change.)", @@ -130,12 +131,12 @@ out$accounting)" r"( returning, for each living individual, the row of its mate (the father of its offspring) or \code{NA}. See \code{\link{mate_random}()} and \code{\link{mate_from_field}()}.)" ), require_mate = "Whether a recorded mate is required. Supplying a mate function enables this by default. With mate = NULL, reproduction is female-dominant.", - newborn_fields = r"(Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the newborns' non-core fields. Index the supplied \code{pop} with \code{mothers} and \code{fathers}. Departed sires needed by the litter appear after the living rows, with their attributes at exit and \code{alive = FALSE}. \code{state$population} contains the living population. An unknown sire has an \code{NA} index.)", - newborn_field_names = r"(Names of the fields \code{newborn_fields} returns.)", + newborn_fields = r"(Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the newborns' non-core fields. Index the supplied \code{pop} with \code{mothers} and \code{fathers}. Departed sires needed by the litter appear after the living rows, with their attributes at exit and \code{alive = FALSE}. \code{state$population} contains the living population. An unknown sire has an \code{NA} index. A named list of single values, such as \code{list(mate_id = NA_integer_)}, gives every newborn the same starting values.)", + newborn_field_names = r"(Names of the fields \code{newborn_fields} returns. When \code{newborn_fields} is a list its names are used.)", inherit = "Non-core fields copied from each mother to her offspring.", metrics = paste0( "Optional function of ", callback, - " returning a named numeric vector. The default reports ", + " returning a named numeric vector, or a named list of such functions, each giving one number or a logical vector that is counted (a list of conditions). The default reports ", r"(\code{n_alive}, \code{n_female} and \code{n_male}.)" ) ), @@ -216,8 +217,8 @@ cubs(mothers = 1:2, pop = pop, state = NULL, context = NULL, params = NULL))" ), order = r"(Choose individuals at random or by ascending ID for count removals and assignments. Weights require random order.)", capacity = r"(Capacity: one number, or a function of \code{(state, context, params)}. For \code{ceiling_process()} the maximum number of eligible individuals; for \code{pairing_process()} the maximum number of pairs (territories).)", - fields = r"(Function of \code{(n, state, context, params)} returning a named list with \code{sex}, \code{age} and every non-core field of the \code{n} introduced individuals. Optional \code{mother_id} and \code{father_id} must both be missing when neutral loci are enabled.)", - creates = r"(Fields that \code{fields} initialises.)", + fields = r"(Function of \code{(n, state, context, params)} returning a named list with \code{sex}, \code{age} and every non-core field of the \code{n} introduced individuals, or such a list of plain values, each recycled over the introduced individuals (\code{list(sex = c("F", "M"), age = 2L)} releases alternating sexes at age two). Optional \code{mother_id} and \code{father_id} must both be missing when neutral loci are enabled.)", + creates = r"(Fields that \code{fields} initialises. The names of a \code{fields} list are added automatically.)", source = "Label stored with the introduction event.", priority = r"(Pair by identifier order (\code{"id"}), random order (\code{"lottery"}), minimum total within-pair kinship (\code{"kinship"}), or minimum total breeder mean kinship followed by minimum within-pair kinship (\code{"mean_kinship"}).)", max_kinship = r"(For either kinship priority, the largest admissible kinship within a pair. The default \code{Inf} admits every pair.)", @@ -485,16 +486,20 @@ all(summarise_accounting(run)$reconciled))" functions = "run_pva_ensemble", arguments = list( design = "Data frame with one row per ensemble member, for example the cross of structural variants, parameter draws and management options.", - build = r"(Function of one design row (a named list) returning a list with \code{init_fun}, \code{processes} and \code{n_steps}, and optionally \code{initial_census}, \code{dt} and \code{keep}.)", + build = r"(What each design row builds. A \code{\link{pva_model}()}: every design column that names a model parameter overrides it for that row. A named list of models: the design column \code{model} selects one per row, for structural comparisons. Or a function of one design row (a named list) returning a list with \code{init_fun}, \code{processes} and \code{n_steps}, and optionally \code{initial_census}, \code{dt} and \code{keep}.)", n_runs = "Number of inner Monte Carlo replicates per member.", summarise = r"(Function of \code{(result, row)} returning a data frame of summaries for one member. The default is \code{\link{summarise_pva}()}.)", seed = "Root seed from which member seeds are derived.", - seed_by = r"(Optional design columns that define blocks sharing one seed (common random numbers), for example the structural and parametric columns when management options should be compared on paired streams.)", + seed_by = r"(\code{NULL} gives every row its own seed. \code{TRUE} pairs all rows on one seed (common random numbers). Design column names define blocks that share a seed, for example the structural and parametric columns when management options should be compared on paired streams within each block.)", cache_dir = "Optional directory for resumable member summaries.", cache_key = "Optional revision string for model inputs read from external files or resolved dynamically." ), - description = "Separates the outer design (structure, parameters, management) from the inner Monte Carlo replicates. Each member is built, run and reduced to its summary inside a worker, so memory use does not grow with the size of the design.", - details = r"(The builder and summary draw on a reproducible member substream. Cache entries record callback code and statically referenced inputs, package and R versions, the row, member seed, full RNG specification (including the binomial generator when available), replicate count, validation mode and cache key. Member seeds are a deterministic function of \code{seed} and the design order, so the ensemble is reproducible and independent of the number of workers and of the backend.)", + description = "Separates the outer design (structure, parameters, management) from the inner Monte Carlo replicates. For an authored model, the coordinator compiles each design row once and passes the scenario to the worker. A function builder runs on the worker. Each worker returns the member summary.", + details = r"(The builder and summary draw on a reproducible member substream. Cache entries record callback code and statically referenced inputs, package and R versions, the row, member seed, full RNG specification (including the binomial generator when available), replicate count, validation mode and cache key. Member seeds are a deterministic function of \code{seed} and the design order, so the ensemble is reproducible and independent of the number of workers and of the backend. + +With a model as \code{build}, a design cell that is \code{NA} leaves the parameter at its base value, declared parameters take precedence over descriptive columns (\code{label} and \code{scenario}) and may also appear in \code{seed_by}. A named list of structural models reserves \code{model} for selection. Any other column that is not a parameter is an error, as is an override that cannot change the row's model (see \code{\link{compile_scenario}()}). Every row is compiled and validated before a seed is drawn or a worker started, and each cache entry records its own selected model's parameters, rate tables and steps. Editing one structure recomputes its members. + +A shared seed gives the rows the same replicate streams at the start of every run. Environmental draws and demography share one stream, so rows whose trajectories diverge then consume it differently: pairing removes between-row seed noise but does not hold the environmental sequence fixed.)", value = r"(A data frame of class \code{pva_ensemble}: the design rows, \code{member}, \code{member_seed} and the summary columns. Provenance is attached as an attribute. \code{\link[=plot.pva_ensemble]{plot()}} contrasts the members.)", examples = r"(design <- expand.grid(survival = c(0.7, 0.9), harvest = c(0, 2)) build <- function(row) { @@ -516,11 +521,13 @@ run_pva_ensemble(design, build, n_runs = 40, seed = 7, title = "Vital rates from age-by-sex tables", functions = c("validate_age_sex_table", "age_sex_rate"), arguments = list( - table = r"(Data frame with \code{age_min}, \code{age_max} (which may be \code{Inf}), \code{sex} and the value column.)", + table = r"(Data frame with \code{sex}, the value column and the age classes, given either as \code{age_min} and \code{age_max} (which may be \code{Inf}) or as one \code{age} column holding whole ages, ranges such as \code{"2-4"} or an open class such as \code{"5+"}. \code{sex} is \code{"F"}, \code{"M"} or \code{"All"} for a class shared by both sexes.)", + by = r"(Optional names of further table columns that stratify the rates, for example \code{"patch_id"} or a stage field. Each must also be a population field; an individual's rate is looked up within its own stratum.)", value = "Name of the column holding the rate.", missing_sex = r"(When a living individual's sex has no rows in the table, \code{"error"} (the default) raises an error and \code{"zero"} returns zero for that individual. Use \code{"zero"} for a female-only fecundity table when males should receive zero.)" ), description = r"(\code{age_sex_rate()} compiles a table into a vectorised rate function for \code{\link{survival_process}()} or \code{\link{reproduction_process}()}. An uncovered age for a represented sex raises an error in either mode.)", + details = r"(Age classes must not overlap within a sex (and stratum). A gap between classes is found when an individual of that age is looked up; a \code{\link{pva_model}()} that uses the table through \code{rate()} rejects gaps, a missing sex and uncovered starting or newborn ages when it is compiled, before any replicate runs.)", value = paste0( r"(\code{validate_age_sex_table()} returns the table invisibly. \code{age_sex_rate()} returns a function of )", callback, "." @@ -530,7 +537,12 @@ run_pva_ensemble(design, build, n_runs = 40, seed = 7, sex = c("F", "F", "M"), p_surv = c(0.5, 0.9, 0.8) ) survival <- age_sex_rate(rates, "p_surv") -survival(pva_population(sex = c("F", "F", "M"), age = c(0, 5, 2)), NULL, NULL, NULL))" +survival(pva_population(sex = c("F", "F", "M"), age = c(0, 5, 2)), NULL, NULL, NULL) + +# the same idea in the shorthand an ecologist would type into a spreadsheet +shorthand <- data.frame(age = c("0", "1-2", "3+"), sex = "All", p_surv = c(0.5, 0.8, 0.9)) +age_sex_rate(shorthand, "p_surv")(pva_population(sex = c("F", "M"), age = c(2, 7)), + NULL, NULL, NULL))" ), spatial = list( title = "Movement among discrete patches", @@ -636,9 +648,9 @@ plot(ensemble))" lifecycle = list( title = "Inspect and diagram a model lifecycle", functions = c("describe_lifecycle", "format_lifecycle"), - methods = c("plot.pva_scenario", "plot.pva_lifecycle"), + methods = c("plot.pva_scenario", "plot.pva_model", "plot.pva_lifecycle"), arguments = list( - x = r"(A \code{pva_scenario} from \code{\link{scenario_spec}()}, a \code{pva_run} from \code{\link{run_scenario}()}, a \code{pva_lifecycle} from \code{describe_lifecycle()}, or an ordered list of \code{\link{pva_process}()} objects.)", + x = r"(A \code{\link{pva_model}()}, a \code{pva_scenario} from \code{\link{scenario_spec}()} or \code{\link{compile_scenario}()}, a \code{pva_run} from \code{\link{run_scenario}()}, a \code{pva_lifecycle} from \code{describe_lifecycle()}, or an ordered list of \code{\link{pva_process}()} objects.)", state = r"(Optional \code{\link{pva_state}()} object used to annotate the summary and diagram with starting abundance, pedigree tracking, neutral loci and \code{mate_field} without invoking \code{init_fun()}.)", format = r"(Output format for \code{format_lifecycle()}: \code{"text"} for a console summary, \code{"mermaid"} for a Mermaid flowchart or \code{"dot"} for Graphviz DOT.)", show_flows = r"(Whether to draw dashed inter-process data-flow arcs inferred from declared \code{writes} and \code{requires} fields. \code{TRUE} (the default) suppresses broadcast \code{population.age} fans when three or more steps read age; use \code{"all"} to draw every arc or \code{FALSE} to omit arcs.)", @@ -646,12 +658,14 @@ plot(ensemble))" `...` = r"(Reserved for future graphical extensions.)" ), description = r"(Translate any OpenPVA process list, scenario or run into an ordered audit table, a base-graphics node-and-edge lifecycle flow diagram or a Mermaid/Graphviz specification. Inspection draws no random numbers.)", - details = r"(\code{describe_lifecycle()} classifies each process into an ecological role (\code{environment}, \code{demography}, \code{spatial}, \code{management}, \code{survey}, \code{census} or \code{custom}) and infers inter-process data flows from declared \code{writes} and \code{requires} paths. A field required before it is written later in the same interval is recorded as a \code{carryover} dependency for the next interval. + details = r"(\code{describe_lifecycle()} classifies each process into an ecological role (\code{environment}, \code{demography}, \code{spatial}, \code{management}, \code{survey}, \code{census} or \code{custom}) and infers inter-process data flows from declared \code{writes} and \code{requires} paths. A field required before it is written later in the same interval is recorded as a \code{carryover} dependency for the next interval. A role stored on a process is used as given. \code{pva_process(role = )} sets one explicitly. A built-in constructor stores the role its process name and declared effects indicate, so a \code{survival_process()} named \code{"autumn_harvest"} is shown under management as in earlier versions, and falls back to the constructor's own role when they indicate none. A process with no stored role is classified from its name and declared effects each time it is inspected. + +A \code{pva_model} is compiled with its base parameters and described with its own initial state. For a model, or a scenario or run compiled from one, the result also carries an \code{"authoring"} attribute with each step's formulas and the parameter values bound into them, and the text summary lists them under "Authored steps". Mermaid, DOT and diagram output are the same for authored and hand-written lifecycles. \code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} render a pure-base-R node-and-edge flow diagram: a single left-to-right row for up to five interval processes, or a two-row clockwise cycle for six or more processes, with dashed data-flow arcs and an interval-return loop. \code{format_lifecycle()} returns a single character string ready to paste into Markdown/Quarto (\code{"mermaid"}), Graphviz (\code{"dot"}) or plain-text reports (\code{"text"}).)", - value = r"(\code{describe_lifecycle()} returns a data frame of class \code{pva_lifecycle} with one row per ordered step and \code{"edges"} and \code{"metadata"} attributes. \code{format_lifecycle()} returns a length-one character string. \code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} return the \code{pva_lifecycle} object invisibly.)", + value = r"(\code{describe_lifecycle()} returns a data frame of class \code{pva_lifecycle} with one row per ordered step and \code{"edges"} and \code{"metadata"} attributes. \code{format_lifecycle()} returns a length-one character string. The \code{plot()} methods return the \code{pva_lifecycle} object invisibly.)", examples = r"(scenario <- scenario_spec( name = "island-adaptive", n_runs = 50, n_steps = 20, seed = 1, init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 2), @@ -676,5 +690,205 @@ lc <- describe_lifecycle(scenario) lc plot(scenario) cat(format_lifecycle(scenario, "mermaid"), "\n"))" + ), + pva_model = list( + title = "Author a model from separated inputs", + functions = c("pva_model", "cohort_population", "compile_scenario"), + arguments = list( + params = r"(Model parameters: a named list, or a parameter table (data frame, for example from \code{read.csv()}) with a \code{parameter} (or \code{name}) column, a \code{value} column and any further evidence columns such as \code{unit}, \code{source} or \code{notes}, which are kept for \code{\link{describe_parameters}()}. Values in a text column are read as numbers, \code{TRUE}/\code{FALSE} or text, one parameter per row. Set \code{type = "character"} to preserve a code such as \code{"001"} when the input value is text. A list may also hold vectors and matrices.)", + rates = r"(Vital-rate table for \code{rate("")} lookups in formulas, in any layout \code{\link{age_sex_rate}()} accepts, or a named list of such tables.)", + init = r"(The initial population: a cohort-count table as for \code{cohort_population()}; a founder table with one row per individual (\code{sex}, \code{age} and optionally \code{mother_id}, \code{father_id} and custom fields); a \code{\link{pva_population}()}; or a function of no arguments returning one of these.)", + n_steps = "Number of intervals to simulate.", + fields = r"(Named list of default values for custom individual fields, for example \code{list(mate_id = NA_integer_)}. Each default is added to the initial population when absent, given to newborns by \code{\link{step_reproduction}()} and to released animals by \code{\link{step_introduce}()}, unless a step sets or inherits the field itself. A default needs an explicit type: write \code{NA_integer_}, not \code{NA}.)", + globals = "Named list of starting values for shared globals that a step reads before any step has written them.", + name = "Model name, used as the default scenario name.", + dt = "Duration of one interval.", + pedigree = r"(Whether the engine tracks exact pedigree inbreeding; see \code{\link{pva_state}()}.)", + n_loci = "Number of unlinked neutral loci dropped through the pedigree.", + mate_field = r"(Optional custom field in which females keep a sire across intervals; see \code{\link{pva_state}()}.)", + initial_census = r"(\code{TRUE} takes a year-zero census with the model's last \code{\link{step_census}()} (none if the model has no census), \code{FALSE} takes none, and a step name selects that census.)", + counts = r"(Cohort-count table with an \code{age} column and either \code{sex} and \code{n}, or \code{females} and \code{males}. Any further column, such as \code{patch_id}, becomes a population field with that row's value. Individuals are created in row order; the \code{females}/\code{males} layout lists all females before all males.)", + `...` = r"(Further fields given to every individual, as in \code{\link{pva_population}()}.)", + model = r"(A \code{pva_model}.)", + overrides = "Named list of parameter values that replace the model's base values for this scenario.", + n_runs = "Number of replicate runs.", + seed = r"(Optional root seed, as in \code{\link{scenario_spec}()}.)", + validation = r"(Default execution mode for \code{\link{run_scenario}()}. Choose \code{"strict"} for complete transition checks or \code{"fast"} for a previously validated model. Both modes check the compiled process list against the initial state. An explicit mode in \code{run_scenario()} overrides this default.)" + ), + description = r"(\code{pva_model()} holds a model's inputs apart from its lifecycle: parameters, vital-rate tables, the initial population and the custom individual fields. Steps are then added in order with the \code{\link[=lifecycle_steps]{step_*()}} functions, usually in a pipe. \code{compile_scenario()} turns the model into an ordinary \code{pva_scenario}, built from the same constructors a hand-written model uses, for \code{\link{run_scenario}()}.)", + details = r"(A \code{pva_model} is a plain value. Adding a step returns a new model; nothing is registered or stored elsewhere, and a stored formula keeps only its expression, never the environment it was written in. + +Compilation resolves every formula once against the model's parameters, population fields, globals, the context values \code{time}, \code{dt}, \code{n_steps} and \code{N}, and its \code{rate()} tables, and rewrites it into an ordinary closure with the parameter values written in (see \code{\link{lifecycle_steps}}). The closure is bound to the package namespace or a locked child environment holding its rate lookups, so it runs as fast as the hand-written equivalent and travels unchanged to fork and socket workers. The required fields of every process are derived from what its formulas read. + +Compilation fails, before any random number is drawn, on: a symbol that is not in the vocabulary; a name used for two things (say a parameter and a population field); a function outside the pure-function list, an assignment or a random draw in a formula; a rate table with overlapping or missing age classes in a sex or stratum, no open terminal age class for a sex and its fixed strata when ageing is enabled, or a probability outside [0, 1]; a step that reads a global written only by a disabled step, or a survey quota placed before its survey; an unknown override; and an override that cannot affect the scenario because only disabled steps use that parameter. The message names the step and the offending symbol or value. A base parameter that no step uses is not an error; \code{\link{describe_parameters}()} lists it as unused. + +\code{cohort_population()} is the population builder \code{pva_model()} applies to a cohort table; use it directly with \code{\link{pva_state}()} in hand-written models.)", + value = r"(\code{pva_model()} returns a \code{pva_model}. \code{cohort_population()} returns a population as \code{\link{pva_population}()} does. \code{compile_scenario()} returns a \code{pva_scenario} whose \code{authoring} element records each step's formulas and bound parameter values for \code{\link{describe_lifecycle}()}.)", + seealso = r"(\code{\link{lifecycle_steps}} for the steps and the formula vocabulary, \code{\link{describe_model}()} for the audit, and \code{\link{run_pva_ensemble}()}, which accepts a model directly.)", + examples = r"(parameters <- data.frame( + parameter = c("capacity", "female_share", "releases", "release_size"), + value = c("60", "0.5", "FALSE", "4"), + source = c("habitat map", "assumed", "scenario", "scenario") +) +rates <- data.frame( + age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.55, 0.80, 0.88), p_breed = c(0, 0.5, 0.9), litter = c(0, 1.2, 1.6) +) +cohorts <- data.frame(age = 0:2, females = c(6, 4, 8), males = c(6, 4, 7)) + +model <- pva_model(parameters, rates, cohorts, n_steps = 15, name = "island") |> + step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, capacity)) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share), + mate = mate_random(~ age >= 1)) |> + step_introduce(~ release_size, fields = list(sex = c("F", "M"), age = 1L), + name = "release", when = 0:4, enabled = ~ releases) |> + step_census() +model + +result <- run_scenario(compile_scenario(model, n_runs = 20, seed = 1)) +summarise_pva(result, threshold = 10)[c("p_ever_below", "final_mean")] + +# the same model with the release step switched on, paired on one seed +run_pva_ensemble(data.frame(releases = c(FALSE, TRUE)), model, n_runs = 20, + seed = 1, seed_by = TRUE)[c("releases", "final_mean", "ema")])" + ), + lifecycle_steps = list( + title = "Lifecycle steps for an authored model", + functions = c( + "step_environment", "step_catastrophe", "step_survival", "step_age", "step_pairing", + "step_mating", "step_reproduction", "step_dispersal", "step_survey", "step_remove", + "step_ceiling", "step_introduce", "step_assign", "step_census", "step_process" + ), + arguments = list( + model = r"(A \code{\link{pva_model}()}.)", + `...` = r"(Named environment variables, drawn in the order given. Each is \code{\link{env_ar1}()}, \code{\link{env_trend}()}, a formula giving the variable's value for the interval, or a function of \code{(state, context, params)}. A formula may read variables listed before it.)", + when = r"(When the step runs: every interval (\code{TRUE}), the listed zero-based intervals, a formula such as \code{~ time \%\% 2 == 0} or \code{~ release_years}, or a function of \code{(state, context, params)}. On a skipped interval, a survey emits \code{survey_skip} and clears its observation, and a catastrophe sets its flag to \code{FALSE}. Other skipped steps leave the state unchanged.)", + enabled = r"(Whether the step is part of the compiled lifecycle: \code{TRUE}, \code{FALSE}, or a formula naming a flag parameter, such as \code{~ releases}, so a scenario can switch the step by overriding that parameter.)", + requires = r"(Additional state paths read by any R function supplied to the step. Fields and globals read by formulas are declared automatically.)", + uses = r"(With the default \code{NULL}, the compiler traces direct reads such as \code{params$capacity} and \code{params[["capacity"]]}. If an enabled callback or factory reads or forwards \code{params} indirectly, declare the names it reads. Use \code{character()} if it forwards the list unread. Such callbacks receive the full parameter list with overrides applied. The declared and directly traced names determine which overrides are accepted and which uses appear in the audit.)", + probability = "Per-individual probability: of surviving the interval, of removal or assignment, or (for a catastrophe) the chance that the event occurs in an interval.", + mortality = "Probability that an eligible individual dies when the catastrophe occurs.", + eligible = "Condition selecting the individuals the step applies to. Omit it to apply the step to every living individual.", + cause = r"(Label stored with the step's accounting events, for example \code{"harvest"}.)", + global = "Name of the global that records whether the catastrophe occurred.", + stage = r"(\code{NULL} for ordinary survival. \code{"pre"} or \code{"post"} splits one interval's survival around a mid-interval event, as \code{\link{staged_survival_process}()} does.)", + post_share = "For a staged step, the share of the interval's mortality that falls after the mid-interval event.", + field = r"(The population field or global the step uses: the mate field for pairing and mating, the patch field for dispersal, the field to set for \code{step_assign()}, the global holding the survey record, or the temporary global shared by staged survival steps.)", + increment = "Whole number of age units added.", + capacity = "Maximum number of pairs for pairing, or of eligible individuals for a ceiling.", + priority = r"(How pairs form; see \code{\link{pairing_process}()}.)", + max_kinship = "Largest admissible kinship within a pair.", + by = "Optional population field; partners must share its value.", + male_capacity = "Maximum number of females one male can sire in the step.", + weights = "Relative weight of each individual for weighted selection; zero excludes it.", + clear = r"(Whether mating first clears every recorded mate; see \code{\link{mating_process}()}.)", + breeding_probability = "Probability that a female breeds.", + litter_size = r"(A litter helper such as \code{\link{litter_poisson}()}, \code{\link{litter_binomial}()} or \code{\link{litter_categorical}()}.)", + offspring_sex = r"(An offspring-sex helper such as \code{\link{offspring_sex_bernoulli}()}. Required: no sex ratio is assumed.)", + mate = r"(Optional mate helper: \code{\link{mate_random}()}, \code{\link{mate_min_kinship}()} or \code{\link{mate_from_field}()}.)", + require_mate = "Whether a female needs a mate to breed.", + newborn_fields = r"(Named list of newborn values for custom fields, overriding the model's \code{fields} defaults, or a function as for \code{\link{reproduction_process}()}.)", + inherit = "Custom fields copied from each mother to her offspring.", + transition = "Square matrix of movement probabilities with patch names on rows and columns; every eligible individual moves by its row.", + destination = "Rule giving each individual's destination patch, as an alternative to a transition matrix.", + patches = "Patch identifiers, needed with a destination rule.", + count = "Number of individuals to move, remove, introduce or assign in the interval.", + detection = "Per-individual detection probability.", + select = "Condition choosing exactly which individuals to remove or assign.", + order = r"(Take individuals at random (\code{"random"}) or by ascending identifier (\code{"id"}) when \code{count} is given.)", + fields = r"(Named list with \code{sex}, \code{age} and any custom field of the introduced individuals; values are recycled over them. The model's \code{fields} defaults fill what the list omits. A function as for \code{\link{introduction_process}()} is also accepted.)", + source = "Label stored with the introduction event.", + value = "Value to assign: a constant, a formula evaluated for the selected individuals, or a function.", + event = "Name of the event that counts assigned individuals.", + metrics = r"(Census metrics: a named list of formulas, each giving one number or a condition to count (\code{list(n_alive = ~ N, adult_females = ~ sex == "F" & age >= 2)}); one formula returning a named vector; or a function as for \code{\link{census_process}()}. \code{NULL} reports \code{n_alive}, \code{n_female} and \code{n_male}.)", + process = r"(Any \code{pva_process}: the output of an OpenPVA constructor or of \code{\link{pva_process}()}. A deterministic factory of one argument, \code{params}, returning a process is called once per enabled step with the scenario's bound parameters.)" + ), + description = r"(Each \code{step_*()} adds one step to the end of a \code{\link{pva_model}()} and returns the new model, so a lifecycle reads top to bottom in a pipe. Order is biology: survival before ageing is pre-ageing mortality, and a census observes whatever precedes it. Every step compiles to the OpenPVA constructor of the same purpose, and \code{step_process()} inserts any hand-written or native process at that exact position.)", + details = r"(\strong{Values, formulas or functions.} Wherever a step takes a rate, condition, count or value you can give a constant, a one-sided formula, or an R function with the signature the underlying constructor documents. A formula is the closure-free form: \code{~ ifelse(age == 0, s_juvenile, s_adult)} instead of \code{function(pop, state, context, params) ifelse(pop$age == 0, params$s_juvenile, params$s_adult)}. + +\strong{What a formula may contain.} +\itemize{ +\item parameters declared in \code{pva_model(params = )}; +\item population fields: \code{age}, \code{sex}, \code{id}, \code{mother_id}, \code{father_id}, \code{pedigree_F} (with a pedigree) and the model's custom fields such as \code{mate_id} or \code{patch_id}; +\item globals written by an earlier step, such as an environment variable or a catastrophe flag, or given a starting value in \code{pva_model(globals = )}; +\item \code{time} (the zero-based interval), \code{dt}, \code{n_steps} and \code{N} (the number of living individuals); +\item \code{rate("")}, the age-and-sex lookup of that column of the model's rate table, with the options \code{table = }, \code{missing_sex = "zero"} and \code{by = } (see \code{\link{age_sex_rate}()}); +\item arithmetic, comparison and logical operators, indexing with \code{[}, \code{if}/\code{ifelse}, and the pure functions \code{abs}, \code{sqrt}, \code{exp}, \code{log}, \code{floor}, \code{ceiling}, \code{round}, \code{min}, \code{max}, \code{pmin}, \code{pmax}, \code{sum}, \code{mean}, \code{prod}, \code{any}, \code{all}, \code{which}, \code{length}, \code{c}, \code{rep}, \code{is.na}, \code{\%in\%}, \code{match}, \code{unique}, \code{cumsum}, \code{as.numeric} and relatives, \code{plogis}, \code{qlogis}, \code{pnorm}, \code{qnorm}, \code{pbeta}, \code{qbeta} and \code{median}; +\item the OpenPVA helpers \code{\link{shift_logit}()}, \code{\link{qbeta_norm}()}, \code{\link{inbreeding_multiplier}()}, \code{\link{ceiling_density_multiplier}()}, \code{\link{beverton_holt_multiplier}()}, \code{\link{ricker_multiplier}()}, \code{\link{sex_ratio_effective_size}()} and \code{patch_counts(patches)}, which counts the living population by patch. +} +Names must be unambiguous, so a parameter cannot share a name with a field, a global or one of the reserved words. Assignment, function definitions, random draws and anything with a side effect are rejected: write those as an R function or a \code{step_process()}. + +Functions in the allowlist may be namespace-qualified, for example \code{stats::plogis()} and \code{OpenPVA::shift_logit()}. A per-individual formula is evaluated once per step for the whole living population. Logical probabilities contribute 0 or 1. A formula that reads only parameters is evaluated when the model is compiled and passed on as a constant. + +\strong{Helpers inside steps.} \code{\link{env_ar1}()}, \code{\link{env_trend}()}, \code{\link{spatial_correlation}()}, the litter, offspring-sex and mate helpers and \code{\link{survey_quota}()} accept formulas for their own arguments when used in a step, for example \code{env_ar1(sd = ~ env_sd)}, \code{litter_poisson(~ rate("litter"))} or \code{mate_random(~ age >= maturity)}. They are then bound to the scenario's parameters at compile time. Inside \code{survey_quota()}, \code{observed} and \code{obs$count} give the survey count. The current observation also exposes \code{obs$visited}, \code{obs$ids} and \code{obs$time}. + +\strong{Fields of new individuals.} Newborns and released animals receive the model's \code{fields} defaults for every custom field a step does not set or inherit. A custom field with no default and no value on the step is reported when the model is compiled. + +\strong{Scheduling and switching.} \code{when} restricts a step to some intervals; \code{enabled} decides at compile time whether the step exists in a scenario at all. A step disabled through a flag parameter draws no random numbers and leaves no rows in the event or accounting tables.)", + value = r"(The \code{pva_model} with the step appended.)", + seealso = r"(\code{\link{pva_model}()}, \code{\link{compile_scenario}()} and \code{\link{describe_model}()}; the constructors each step compiles to, \code{\link{survival_process}()}, \code{\link{reproduction_process}()}, \code{\link{removal_process}()}, \code{\link{environment_process}()}, \code{\link{dispersal_process}()} and \code{\link{survey_process}()}.)", + examples = r"(model <- pva_model( + params = list(s_juvenile = 0.5, s_adult = 0.85, env_sd = 0.3, maturity = 2, + detect = 0.7, trigger = 12, release = 4), + init = data.frame(age = c(1, 3), sex = c("F", "M"), n = 8), + n_steps = 10, pedigree = TRUE +) |> + step_environment(weather = env_ar1(sd = ~ env_sd, phi = 0.4)) |> + step_survival(~ shift_logit(ifelse(age == 0, s_juvenile, s_adult), weather) * + inbreeding_multiplier(pedigree_F, 3.14)) |> + step_age() |> + step_reproduction(~ 0.8 * (age >= maturity), litter_poisson(1.3), + offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(~ age >= maturity)) |> + step_survey(~ detect, when = ~ time %% 2 == 0, field = "count") |> + step_introduce( + survey_quota(~ if (observed < trigger) release else 0, field = "count", on_skip = 0), + fields = list(sex = c("F", "M"), age = 2L), name = "release" + ) |> + step_process(pva_process( + "tag_oldest", function(state, context, params) pva_result(state), + requires = "population.age" + )) |> + step_census(list(n_alive = ~ N, breeders = ~ age >= maturity)) + +describe_lifecycle(model) +run <- run_scenario(compile_scenario(model, n_runs = 10, seed = 3)) +all(summarise_accounting(run)$reconciled))" + ), + model_audit = list( + title = "Audit an authored model and its parameters", + functions = c("describe_model", "describe_parameters"), + arguments = list( + model = r"(A \code{\link{pva_model}()}.)", + overrides = r"(Named list of parameter overrides to audit, as for \code{\link{compile_scenario}()}.)", + life_table = r"(Optional list for a deterministic check of the authored rates with \code{\link{life_table_metrics}()}: \code{survival} and \code{fecundity} (daughters per female), each a numeric vector by age or a formula of parameters, \code{age} and \code{rate()}, evaluated for females of every age class; and optionally \code{timing}, \code{plus_group} and \code{max_age}.)" + ), + description = r"(\code{describe_model()} reports what a model will build before anything runs: the initial cohorts, custom fields, each step with its formulas and the parameter values bound into them, and the parameter table. \code{describe_parameters()} returns that table alone. Neither draws a random number.)", + details = r"(The parameter table has one row per declared parameter: its \code{base} value, the effective \code{value} once \code{overrides} are applied, whether it is \code{overridden}, the steps that use it (\code{used_by}), a \code{status}, and the evidence columns of the parameter table the model was built from. The status is \code{"active"} when an enabled step or a step switch uses the parameter, \code{"inactive"} when only disabled steps do, and \code{"unused"} when nothing does. For indirect parameter reads in a callback or factory, supply the names in the step's \code{uses} argument. The \code{base} and \code{value} columns are lists. Use \code{[[i]]} to extract row \code{i} in its original type, including matrix dimensions and dimnames. Evidence columns that share a name with an audit column receive the prefix \code{evidence.}. + +Unused base parameters are reported, not rejected, because a disabled step may legitimately leave a parameter idle. An \emph{override} of such a parameter is an error.)", + value = r"(\code{describe_parameters()} returns a data frame. \code{describe_model()} returns a list of class \code{pva_model_audit} with \code{name}, \code{settings}, \code{n_initial}, \code{initial} (counts by sex and age), \code{fields}, \code{globals}, \code{steps} (one row per step, including disabled ones), \code{parameters}, \code{unused} and, when requested, \code{life_table}; printing it gives a readable report.)", + seealso = r"(\code{\link{describe_lifecycle}()} and \code{plot()} for the process-level view of the same model.)", + examples = r"(rates <- data.frame(age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.5, 0.8, 0.9), p_breed = c(0, 0.6, 1), litter = c(0, 1.2, 2)) +model <- pva_model( + params = data.frame(parameter = c("capacity", "female_share", "spare"), + value = c(80, 0.5, 1), unit = c("animals", "proportion", "-")), + rates = rates, init = data.frame(age = 0:2, females = c(4, 3, 6), males = c(4, 3, 5)), + n_steps = 20 +) |> + step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, capacity)) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share)) |> + step_census() + +describe_parameters(model, overrides = list(capacity = 60)) +describe_model(model, life_table = list( + survival = ~ rate("p_surv"), + fecundity = ~ rate("p_breed") * rate("litter") * female_share +)))" ) ) diff --git a/site/_litedown.yml b/site/_litedown.yml index af64a96..8390a55 100644 --- a/site/_litedown.yml +++ b/site/_litedown.yml @@ -2,6 +2,9 @@ site: rebuild: "always" exclude: ["code.Rmd", "playground"] manual: + Model Authoring & Audit: + desc: Separated parameter, vital-rate and cohort inputs, ordered lifecycle steps written as formulas, compilation to standard scenarios, and parameter-provenance audits. + contents: [pva_model, lifecycle_steps, model_audit] State & Process Contract: desc: Living-state constructors, individual allocation, and the ordered process execution contract. contents: [pva_state, pva_process] @@ -18,7 +21,7 @@ site: desc: Exact conditional pedigree kinship, inbreeding depression, and non-perturbing neutral-locus gene drop. contents: [inbreeding, markers] Execution, Ensembles & Summaries: - desc: Replicated scenario execution, designed multi-factor ensembles, viability risk, EMA, and cohort accounting. + desc: Replicated scenarios, paired and structural ensembles, resumable member summaries, viability risk, EMA, and cohort accounting. contents: [scenario, run_pva_ensemble, summaries] Visualisation & Printing: desc: Base-graphics trajectory, risk, accounting, ensemble and lifecycle flow diagrams, Mermaid/DOT export, plus print and subset methods. diff --git a/site/articles.Rmd b/site/articles.Rmd index 51a9cfe..eafdabd 100644 --- a/site/articles.Rmd +++ b/site/articles.Rmd @@ -16,7 +16,7 @@ litedown::reactor(echo = FALSE) Both worked models live under `inst/examples/`, use only the public OpenPVA API, and ship with runnable scripts: - **[Lord Howe Island woodhen (`inst/examples/woodhen/`)](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/woodhen/README.md)** — territorial island bird recovery with sex-specific survival, shared environmental variation, territorial pairing, captive releases, socket-cluster execution, and a structured parameter-evidence table. -- **[Grizzly bear (`inst/examples/grizzly/`)](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/grizzly/README.md)** — seasonal lifecycle combining summer `mating_process()`, autumn harvest, engine-owned cross-interval sire retention, winter birth, and three-year maternal dependency. +- **[Grizzly bear (`inst/examples/grizzly/`)](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/grizzly/README.md)** — seasonal lifecycle combining summer `mating_process()`, autumn harvest and winter birth within one annual interval (a sire shot after mating still fathers the litter), and three-year maternal dependency. Sire retention across intervals is shown by the seasonal herd in the rosetta vignette. ## Architecture, agent guide & heritage documents diff --git a/site/index.Rmd b/site/index.Rmd index 814c9dc..9304fd5 100644 --- a/site/index.Rmd +++ b/site/index.Rmd @@ -71,7 +71,7 @@ cat(sprintf(

Links
GitHub repository
Report an issue
- Function reference (62 exports)
+ Function reference (82 exports)
Vignettes & examples
', desc$Version diff --git a/site/manual.Rmd b/site/manual.Rmd index 571d6a4..00bdb6b 100644 --- a/site/manual.Rmd +++ b/site/manual.Rmd @@ -1,6 +1,6 @@ --- title: "Function reference" -subtitle: "All 62 exported functions and S3 methods grouped by ecological role" +subtitle: "All 82 exported functions and S3 methods grouped by ecological role" --- ```{r, include = FALSE} diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R new file mode 100644 index 0000000..02f456c --- /dev/null +++ b/tests/testthat/helper-models.R @@ -0,0 +1,340 @@ +# Hand-written native models and their authored pva_model() twins, used by the +# compilation-equivalence, parity and diagnostic tests. + +keep_all <- c("census", "events", "accounting", "state", "ledger") + +expect_same_run <- function(native, authored) { + for (part in c("census", "events", "accounting", "states", "ledgers")) { + testthat::expect_identical(authored[[part]], native[[part]], label = paste("authored", part)) + } +} + +# (a) README minimal model ------------------------------------------------- +native_minimal <- function(n_runs = 12L, seed = 2026L) { + scenario_spec( + name = "minimal", n_runs = n_runs, n_steps = 15L, seed = seed, + init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 3), + processes = list( + survival_process( + function(pop, state, context, params) ifelse(pop$age == 0, params$juvenile, params$adult), + requires = "population.age", params = list(juvenile = 0.52, adult = 0.88) + ), + age_process(), + reproduction_process( + breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2), + litter_size = litter_poisson(1.2), offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_random(function(pop, state, context, params) pop$age >= 2), + requires = "population.age" + ), + census_process() + ), + initial_census = census_process() + ) +} + +authored_minimal <- function() { + pva_model( + params = list(juvenile = 0.52, adult = 0.88, maturity = 2, litter = 1.2), + init = data.frame(sex = rep(c("F", "M"), 10), age = 3), + n_steps = 15L, name = "minimal" + ) |> + step_survival(~ ifelse(age == 0, juvenile, adult)) |> + step_age() |> + step_reproduction(~ age >= maturity, litter_poisson(~litter), offspring_sex_bernoulli(0.5), + mate = mate_random(~ age >= maturity)) |> + step_census() +} + +# (b) adaptive genetic island from the workflow vignette -------------------- +native_island <- function(strategy = c("status_quo", "adaptive", "fixed"), + n_runs = 6L, seed = 2026L, n_steps = 14L) { + strategy <- match.arg(strategy) + init_fun <- function() { + pva_state( + pva_population(sex = rep(c("F", "M"), each = 18L), age = rep(1:6, times = 6L)), + pedigree = TRUE, n_loci = 8L + ) + } + env_proc <- environment_process(list(env = env_ar1(sd = 0.42, phi = 0.45))) + cyclone <- catastrophe_process(probability = 0.06, mortality = 0.28, name = "cyclone") + surv_proc <- survival_process( + probability = function(pop, state, context, params) { + base <- ifelse(pop$age == 0L, 0.56, 0.84) + dens <- ceiling_density_multiplier(length(pop$id), capacity = 95) + inb <- inbreeding_multiplier(pop$pedigree_F, lethal_equivalents = 3.14) + shift_logit(base, state$globals$env) * dens * inb + }, + requires = c("population.age", "population.pedigree_F", "globals.env") + ) + breed_proc <- reproduction_process( + breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2L) * 0.78, + litter_size = litter_poisson(1.15), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship( + eligible = function(pop, state, context, params) pop$age >= 2L, max_kinship = 0.25 + ), + requires = "population.age" + ) + release_fields <- function(n, state, context, params) { + list(sex = rep(c("F", "M"), length.out = n), age = rep(2L, n)) + } + mgmt <- switch( + strategy, + status_quo = list(), + adaptive = list( + survey_process(detection = 0.70, when = seq.int(0L, 29L, by = 2L), field = "obs"), + introduction_process( + count = survey_quota( + rule = function(obs, state, context, params) if (obs$count < 26L) 6L else 0L, + field = "obs", on_skip = 0L + ), + fields = release_fields, name = "adaptive_release" + ) + ), + fixed = list( + introduction_process( + count = function(state, context, params) if (context$time < 12L) 4L else 0L, + fields = release_fields, name = "fixed_release" + ) + ) + ) + census <- census_process(genetic_metrics()) + scenario_spec( + name = strategy, n_runs = n_runs, n_steps = n_steps, init_fun = init_fun, + processes = c(list(env_proc, cyclone, surv_proc, age_process(), breed_proc), mgmt, list(census)), + initial_census = census, seed = seed + ) +} + +authored_island <- function(n_steps = 14L) { + pva_model( + params = data.frame( + parameter = c("env_sd", "env_phi", "cyclone_p", "cyclone_kill", "s0", "s1", "K", + "lethal_equivalents", "breed", "maturity", "litter", "max_kin", "detect", + "trigger", "release_n", "fixed_n", "fixed_years", "adaptive", "fixed"), + value = c("0.42", "0.45", "0.06", "0.28", "0.56", "0.84", "95", "3.14", "0.78", "2", + "1.15", "0.25", "0.70", "26", "6", "4", "12", "FALSE", "FALSE"), + source = "workflow vignette", stringsAsFactors = FALSE + ), + init = data.frame(sex = rep(c("F", "M"), each = 18L), age = rep(1:6, times = 6L)), + n_steps = n_steps, pedigree = TRUE, n_loci = 8L, name = "island" + ) |> + step_environment(env = env_ar1(sd = ~env_sd, phi = ~env_phi)) |> + step_catastrophe(~cyclone_p, mortality = ~cyclone_kill, name = "cyclone") |> + step_survival( + ~ shift_logit(ifelse(age == 0, s0, s1), env) * + ceiling_density_multiplier(N, capacity = K) * + inbreeding_multiplier(pedigree_F, lethal_equivalents = lethal_equivalents) + ) |> + step_age() |> + step_reproduction( + ~ as.numeric(age >= maturity) * breed, litter_poisson(~litter), + offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(eligible = ~ age >= maturity, max_kinship = ~max_kin) + ) |> + step_survey(~detect, when = seq.int(0L, 29L, by = 2L), field = "obs", enabled = ~adaptive) |> + step_introduce( + count = survey_quota(~ if (observed < trigger) release_n else 0, field = "obs", on_skip = 0L), + fields = list(sex = c("F", "M"), age = 2L), name = "adaptive_release", enabled = ~adaptive + ) |> + step_introduce( + count = ~ if (time < fixed_years) fixed_n else 0, + fields = list(sex = c("F", "M"), age = 2L), name = "fixed_release", enabled = ~fixed + ) |> + step_census(metrics = genetic_metrics()) +} + +# (c) seasonal grizzly: the shipped native example and a closure-free twin --- +grizzly_native_env <- function() { + env <- new.env() + sys.source(system.file("examples", "grizzly", "model.R", package = "OpenPVA"), env) + env +} + +authored_grizzly <- function(adult_female_mortality = 0, adult_male_mortality = 0, n_steps = 12L) { + pva_model( + params = list( + weaning_age = 3L, maturity_age = 5L, breeding_probability = 0.7, litter_mean = 2, + dependent_survival = 0.78, independent_survival = 0.93, + adult_female_mortality = adult_female_mortality, adult_male_mortality = adult_male_mortality + ), + init = data.frame( + sex = c(rep("F", 6L), rep("M", 4L), "F", "M"), age = c(rep(6L, 10L), 0L, 0L), + mother_id = c(rep(NA_integer_, 10L), 1L, 1L), father_id = c(rep(NA_integer_, 10L), 7L, 7L) + ), + fields = list(mate_id = NA_integer_), pedigree = TRUE, n_steps = n_steps, name = "grizzly" + ) |> + step_age(name = "spring_ageing") |> + step_survival(~ ifelse(age < weaning_age, dependent_survival, independent_survival), + name = "natural_survival") |> + step_mating( + eligible = ~ age >= maturity_age & (sex == "M" | !(id %in% mother_id[age < weaning_age])), + name = "summer_mating" + ) |> + step_survival(~ 1 - ifelse(sex == "F", adult_female_mortality, adult_male_mortality), + eligible = ~ age >= maturity_age, name = "autumn_harvest", cause = "harvest") |> + step_survival(0, eligible = ~ age < weaning_age & !(mother_id %in% id), + name = "orphan_loss", cause = "loss_of_mother") |> + step_reproduction(~breeding_probability, litter_binomial(3L, ~litter_mean, min_size = 1L), + offspring_sex_bernoulli(0.5), mate = mate_from_field(), + name = "winter_birth") |> + step_census(metrics = list( + n_alive = ~N, n_dependent = ~ age < weaning_age, + n_adult_female = ~ sex == "F" & age >= maturity_age + )) +} + +# (d) two correlated patches with dispersal --------------------------------- +native_two_patch <- function(capacity = 30, base_survival = 0.8, disperse = TRUE, + n_runs = 6L, seed = 77L, n_steps = 14L) { + patches <- c("A", "B") + adult <- function(pop, state, context, params) pop$age >= 1L + climate <- environment_process(list( + anomaly = env_ar1(sd = 0.5, phi = 0.6, cor = spatial_correlation(patches, rho = 0.7)), + climate = env_trend(function(time) c(A = 0, B = if (time >= 10) -0.8 else 0), + anomaly = "anomaly") + )) + moves <- matrix(c(0.9, 0.1, 0.1, 0.9), 2, byrow = TRUE, dimnames = list(patches, patches)) + processes <- list( + climate, + survival_process(function(pop, state, context, params) { + shift_logit(base_survival, state$globals$climate[pop$patch_id]) + }, requires = c("population.patch_id", "globals.climate")), + age_process(), + reproduction_process( + breeding_probability = function(pop, state, context, params) { + local <- patch_counts(pop, patches)[pop$patch_id] + 0.9 * (pop$age >= 1L) * beverton_holt_multiplier(local, capacity = capacity, growth = 2) + }, + litter_size = litter_poisson(1.3), offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(adult, by = "patch_id"), + inherit = "patch_id", requires = c("population.age", "population.patch_id") + ) + ) + if (disperse) { + processes <- c(processes, list(markov_dispersal_process( + moves, eligible = function(pop, state, context, params) pop$age == 1L, + requires = "population.age" + ))) + } + census <- census_process(function(pop, state, context, params) { + c(n_alive = length(pop$id), patch_counts(pop, patches)) + }) + scenario_spec( + name = "two_patch", n_runs = n_runs, n_steps = n_steps, seed = seed, + init_fun = function() { + pva_state(pva_population(sex = rep(c("F", "M"), 20), age = 2L, + patch_id = rep(patches, each = 20)), pedigree = TRUE) + }, + processes = c(processes, list(census)), initial_census = census + ) +} + +authored_two_patch <- function(disperse = TRUE, n_steps = 14L) { + patches <- c("A", "B") + pva_model( + params = list( + patches = patches, rho = 0.7, env_sd = 0.5, env_phi = 0.6, shift_year = 10, shift_B = -0.8, + base_survival = 0.8, breed = 0.9, capacity = 30, growth = 2, litter = 1.3, + moves = matrix(c(0.9, 0.1, 0.1, 0.9), 2, byrow = TRUE, dimnames = list(patches, patches)), + disperse = disperse + ), + init = data.frame(sex = rep(c("F", "M"), 20), age = 2L, patch_id = rep(patches, each = 20), + stringsAsFactors = FALSE), + pedigree = TRUE, n_steps = n_steps, name = "two_patch" + ) |> + step_environment( + anomaly = env_ar1(sd = ~env_sd, phi = ~env_phi, cor = spatial_correlation(~patches, rho = ~rho)), + climate = ~ c(A = 0, B = if (time >= shift_year) shift_B else 0) + anomaly + ) |> + step_survival(~ shift_logit(base_survival, climate[patch_id])) |> + step_age() |> + step_reproduction( + ~ breed * (age >= 1) * + beverton_holt_multiplier(patch_counts(patches)[patch_id], capacity = capacity, growth = growth), + litter_poisson(~litter), offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(~ age >= 1, by = "patch_id"), inherit = "patch_id" + ) |> + step_dispersal(transition = ~moves, eligible = ~ age == 1, enabled = ~disperse) |> + step_census(metrics = ~ c(n_alive = N, patch_counts(patches))) +} + +# (e) seasonal surveyed herd from the rosetta vignette: survey-driven cull, +# contraception, autumn rut with sires retained until spring fawning --------- +native_herd <- function(n_runs = 8L, seed = 1993L) { + autumn <- function(state, context, params) context$time %% 2L == 0L + survey <- survey_process(0.7, when = autumn) + cull <- removal_process( + count = survey_quota(function(obs, state, context, params) { + max(0L, round(obs$count / 0.7) - 30L) + }, on_skip = 0L), + weights = function(pop, ...) ifelse(pop$sex == "M", 3, 1), requires = "population.sex" + ) + untreated <- function(pop, state, context, params) { + pop$sex == "F" & pop$age >= 4L & pop$treated_until <= context$time + } + dart <- assign_process( + "treated_until", function(rows, pop, state, context, params) context$time + 4L, + count = function(state, context, params) 3L * autumn(state, context, params), + eligible = untreated, event = "contracepted", requires = c("population.sex", "population.age") + ) + rut <- mating_process( + when = autumn, male_capacity = 5L, weights = function(pop, ...) pop$age, + eligible = function(pop, state, context, params) { + (pop$sex == "M" & pop$age >= 4L) | untreated(pop, state, context, params) + }, requires = c("population.age", "population.treated_until") + ) + fawn <- reproduction_process( + function(pop, state, context, params) 0.9 * !autumn(state, context, params), + litter_poisson(1.2), offspring_sex_bernoulli(0.5), mate = mate_from_field(), + newborn_fields = function(...) list(mate_id = NA_integer_, treated_until = -1L), + newborn_field_names = c("mate_id", "treated_until") + ) + clear_sires <- assign_process("mate_id", NA, select = function(pop, state, context, params) { + !autumn(state, context, params) & !is.na(pop$mate_id) + }) + scenario_spec( + "seasonal herd", n_runs = n_runs, n_steps = 8L, dt = 0.5, seed = seed, + init_fun = function() pva_state( + pva_population(rep(c("F", "M"), c(22L, 8L)), rep(c(4L, 8L, 12L), 10L), + mate_id = NA_integer_, treated_until = -1L), + pedigree = TRUE, mate_field = "mate_id" + ), + processes = list(survey, cull, dart, rut, + survival_process(function(pop, ...) ifelse(pop$sex == "M", 0.85, 0.93), + requires = "population.sex"), + fawn, clear_sires, age_process(), census_process()), + initial_census = census_process() + ) +} + +authored_herd <- function() { + pva_model( + params = list(detect = 0.7, target = 30, cull_bias = 3, max_treated = 3, treatment = 4, + mature = 4, harem = 5L, s_male = 0.85, s_female = 0.93, fawning = 0.9, + litter = 1.2), + init = data.frame(sex = rep(c("F", "M"), c(22L, 8L)), age = rep(c(4L, 8L, 12L), 10L)), + fields = list(mate_id = NA_integer_, treated_until = -1L), + pedigree = TRUE, mate_field = "mate_id", n_steps = 8L, dt = 0.5, name = "seasonal herd" + ) |> + step_survey(~detect, when = ~ time %% 2 == 0) |> + step_remove( + count = survey_quota(~ max(0, round(observed / detect) - target), on_skip = 0L), + weights = ~ ifelse(sex == "M", cull_bias, 1) + ) |> + step_assign("treated_until", value = ~ time + treatment, + count = ~ max_treated * (time %% 2 == 0), + eligible = ~ sex == "F" & age >= mature & treated_until <= time, + event = "contracepted") |> + step_mating( + when = ~ time %% 2 == 0, male_capacity = ~harem, weights = ~age, + eligible = ~ (sex == "M" & age >= mature) | + (sex == "F" & age >= mature & treated_until <= time) + ) |> + step_survival(~ ifelse(sex == "M", s_male, s_female)) |> + step_reproduction(~ fawning * !(time %% 2 == 0), litter_poisson(~litter), + offspring_sex_bernoulli(0.5), mate = mate_from_field()) |> + step_assign("mate_id", NA, select = ~ !(time %% 2 == 0) & !is.na(mate_id)) |> + step_age() |> + step_census() +} diff --git a/tests/testthat/test-b4-compilation.R b/tests/testthat/test-b4-compilation.R new file mode 100644 index 0000000..b7607ee --- /dev/null +++ b/tests/testthat/test-b4-compilation.R @@ -0,0 +1,245 @@ +test_that("helper forwarding preserves parameter liveness for each step", { + base <- pva_model(params = list(active = FALSE, extra = 3L, spare = 9), + init = pva_population(c("F", "M"), 2L), n_steps = 1L) + model <- base |> + step_environment(w = env_ar1(0.4, 0.5), level = env_trend(0.5)) |> + step_reproduction(0.5, litter_poisson(1), offspring_sex_bernoulli(0.5), + mate = mate_min_kinship()) |> + step_reproduction(0.5, litter_binomial(3L, 2), offspring_sex_bernoulli(1), name = "late") |> + step_introduce(~ extra, list(sex = "F", age = 1L), enabled = ~ active) |> + step_census() + expect_error(compile_scenario(model, list(extra = 4L)), "extra.*only by the disabled") + expect_identical(describe_parameters(model)$status, + c("active", "inactive: only disabled steps use it", "unused")) + scenario <- compile_scenario(model) + expect_true(all(vapply(scenario$processes, function(p) !length(p$params$user), logical(1)))) + + indirect <- function(pop, state, context, params) params[[tolower("EXTRA")]] + tagged <- base |> + step_reproduction(1, litter_poisson(indirect), offspring_sex_bernoulli(), uses = "extra") |> + step_census() + scenario <- compile_scenario(tagged, list(extra = 2L), n_runs = 1L, seed = 4L) + expect_identical(scenario$processes[[1L]]$params$user, list(active = FALSE, extra = 2L, spare = 9)) + expect_true(all(summarise_accounting(run_scenario(scenario))$reconciled)) + undeclared <- base |> step_reproduction(1, litter_poisson(indirect), offspring_sex_bernoulli()) + expect_error(compile_scenario(undeclared), "reproduction.*uses") + expect_error(compile_scenario(tagged, list(spare = 4)), "spare.*no effect") + nested <- base |> + step_reproduction(1, litter_poisson(function(pop, state, context, params) params$extra), + offspring_sex_bernoulli()) + expect_identical(describe_parameters(nested)$used_by[[2L]], "reproduction") + expect_error(step_survival(base, 1, uses = "exrta"), "unknown parameter 'exrta'") + + factory <- function(p) removal_process(count = p[[tolower("EXTRA")]], order = "id") + expect_error(compile_scenario(base |> step_process(factory)), "step 1 'process'.*uses") + used <- base |> step_process(factory, uses = "extra") |> step_census() + run <- run_scenario(compile_scenario(used, list(extra = 1L), n_runs = 1L, seed = 4L)) + expect_equal(tail(run$census$n_alive, 1L), 1) +}) + +test_that("indirect callbacks bind the full list and declare their override dependencies", { + base <- pva_model(params = list(harsh = TRUE, s = 0.5, bonus = 0.25, spare = 1), + init = pva_population(rep("F", 20L), 1L), n_steps = 2L) + run <- function(model, ...) { + run_scenario(compile_scenario(model, overrides = list(...), n_runs = 1L, seed = 13L))$census + } + survival <- function(pop, state, context, params) { + cfg <- params + rep(if (isTRUE(cfg$harsh)) 0 else 1, length(pop$id)) + } + model <- function(...) step_survival(base, survival, ...) |> step_census() + expect_error(compile_scenario(model()), "step 1 'survival'.*uses = c.*uses = character") + declared <- model(uses = "harsh") + expect_equal(run(declared)$n_alive, c(20, 0, 0)) + expect_equal(run(declared, harsh = FALSE)$n_alive, c(20, 20, 20)) + expect_error(run(declared, spare = 0), "override 'spare' has no effect") + expect_equal(run(model(enabled = FALSE))$n_alive, c(20, 20, 20)) + + probability <- function(pop, state, context, params) params$s + sum(unlist(params["bonus"])) + metric <- function(...) step_census(base, list(n_alive = ~N, prob = probability), ...) + full <- metric(uses = c("s", "bonus")) + partial <- metric(uses = "s") + expect_equal(run(full)$prob, rep(0.75, 3L)) + expect_equal(run(partial)$prob, rep(0.75, 3L)) + expect_equal(run(full, bonus = 0.5)$prob, rep(1, 3L)) + expect_equal(run(partial, s = 0.25)$prob, rep(0.5, 3L)) + expect_error(run(partial, bonus = 0.5), "override 'bonus' has no effect") + expect_identical(describe_parameters(partial)$used_by, c("", "census", "", "")) + + keep_all <- function(pop, unused) rep(1, length(pop$id)) + forward <- function(pop, state, context, params) keep_all(pop, params) + unread <- base |> step_survival(forward, uses = character()) |> step_census() + expect_equal(run(unread)$n_alive, c(20, 20, 20)) + expect_error(run(unread, harsh = FALSE), "override 'harsh' has no effect") + + when <- function(state, context, params) isTRUE(as.list(params)$harsh) + scheduled <- function(...) step_process(base, survival_process(0), when = when, ...) |> step_census() + expect_error(compile_scenario(scheduled()), "step 1 'survival'.*uses") + expect_equal(run(scheduled(uses = "s"))$n_alive, c(20, 0, 0)) + + default_read <- function(pop, state, context, params, p = params$s) p + expect_equal(run(base |> step_survival(default_read) |> step_census(), s = 0)$n_alive, c(20, 0, 0)) + native_params <- function(params) { + survival_process(function(pop, state, context, params) do.call(min, params), + params = list(survival = 1)) + } + expect_equal(run(base |> step_process(native_params) |> step_census())$n_alive, c(20, 20, 20)) +}) + +test_that("factories run exactly once when enabled and cannot draw biology at compile time", { + calls <- 0L + make <- function(params) { + calls <<- calls + 1L + environment_process(list(w = env_ar1(0))) + } + base <- pva_model(init = pva_population("F", 2L), n_steps = 1L) + model <- base |> + step_process(function(params) stop("disabled factory ran"), enabled = FALSE) |> + step_process(make) |> step_survival(~ shift_logit(0.8, w)) + scenario <- compile_scenario(model) + expect_identical(calls, 1L) + expect_identical(scenario$processes[[2L]]$requires, c("population.alive", "globals.w")) + random <- base |> step_process(function(params) survival_process(stats::pnorm(stats::rnorm(1L)))) + for (seed in 1:2) { + set.seed(seed) + before <- .GlobalEnv$.Random.seed + expect_error(compile_scenario(random, seed = 99L), "step 1.*stochastic process factory") + expect_identical(.GlobalEnv$.Random.seed, before) + } +}) + +test_that("initializers and compile diagnostics preserve a pending Box-Muller draw", { + create <- function() pva_model( + init = function() pva_population("F", 2L, measurement = stats::rnorm(1L)), + n_steps = 2L + ) |> step_census() + model <- create() + broken <- model |> step_age(when = ~typo) + random <- model |> step_process(function(params) survival_process(stats::runif(1L))) + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + kind <- RNGkind() + on.exit(do.call(RNGkind, as.list(kind)), add = TRUE) + reseeded <- function() pva_model(init = function() { + set.seed(88L) + pva_population("F", 1L, measurement = stats::rnorm(1)) + }, n_steps = 1L) + reseeding_factory <- model |> step_process(function(p) { set.seed(88L); age_process() }) + actions <- list(create, reseeded, + function() expect_error(compile_scenario(reseeding_factory), "changed the RNG"), + function() compile_scenario(model), function() describe_model(model), + function() describe_parameters(model), function() describe_lifecycle(model), + function() plot(model), function() expect_error(compile_scenario(broken), "typo"), + function() expect_error(compile_scenario(random), "stochastic process factory")) + for (action in actions) { + set.seed(39L, normal.kind = "Box-Muller") + reference <- stats::rnorm(2L)[[2L]] + set.seed(39L, normal.kind = "Box-Muller") + stats::rnorm(1L) + before <- .GlobalEnv$.Random.seed + action() + expect_identical(.GlobalEnv$.Random.seed, before) + expect_identical(stats::rnorm(1L), reference) + } + run <- run_scenario(compile_scenario(model, n_runs = 3L, seed = 23L), keep = "state") + samples <- vapply(run$states, function(s) s$population$measurement, numeric(1)) + expect_length(unique(samples), 3L) +}) + +test_that("field plans distinguish schedules, survey records and the founder census", { + base <- pva_model(init = pva_population(rep("F", 20L), 1L), n_steps = 2L) + weather <- function(model) model |> + step_environment(w = env_ar1(0.2), when = ~time >= 1L) |> + step_survival(~shift_logit(0.8, w)) + expect_error(compile_scenario(weather(base)), "survival.*global 'w'.*scheduled") + first <- base |> step_environment(w = ~0, when = ~time == 0L) |> step_survival(~shift_logit(0.8, w)) + expect_s3_class(compile_scenario(first), "pva_scenario") + seasonal <- base |> step_environment(w = ~0, when = ~time >= 1L) |> + step_survival(~shift_logit(0.8, w), when = ~time >= 1L) |> step_census() + seasonal_run <- run_scenario(compile_scenario(seasonal, n_runs = 1L, seed = 8L)) + expect_equal(seasonal_run$census$n_alive[1:2], c(20, 20)) + initial <- base + initial$globals <- list(w = 0) + expect_s3_class(compile_scenario(weather(initial)), "pva_scenario") + expect_error(compile_scenario(base |> step_age(when = ~isTRUE(wet)) |> step_environment(wet = ~TRUE)), + "age.*global 'wet'.*before") + timed <- base |> step_environment(wet = ~TRUE) |> step_age(when = ~isTRUE(wet)) + expect_true("globals.wet" %in% compile_scenario(timed)$processes[[2L]]$requires) + quota <- survey_quota(~observed, field = "obs", on_skip = 0L) + expect_error(compile_scenario(base |> step_environment(obs = ~1) |> step_remove(count = quota)), + "removal.*survey_quota.*survey writer.*obs") + expect_error(compile_scenario(base |> step_survey(1, field = "obs") |> + step_environment(obs = ~1) |> step_remove(count = quota)), "survey writer.*obs") + census <- function(model) model |> step_environment(w = ~1) |> step_census(list(weather = ~w)) + expect_error(compile_scenario(census(base)), "initial_census.*census.*globals.w") + run <- run_scenario(compile_scenario(census(initial), n_runs = 1L, seed = 7L)) + expect_equal(run$census$weather, c(0, 1, 1)) +}) + +test_that("a skipped catastrophe clears its flag without further mortality", { + model <- pva_model(init = pva_population(rep("F", 1000L), 1L), n_steps = 3L) |> + step_catastrophe(1, name = "storm", when = ~time == 0L) |> + step_survival(~ifelse(storm, 0.5, 1)) |> step_census() + result <- run_scenario(compile_scenario(model, n_runs = 1L, seed = 1L), keep = c("census", "state")) + n <- result$census$n_alive + expect_equal(n[[1L]], 1000) + expect_true(n[[2L]] > 400 && n[[2L]] < 600) + expect_identical(n[2:4], rep(n[[2L]], 3L)) + expect_false(result$states[[1L]]$globals$storm) +}) + +test_that("the escape hatch preserves native survey schedules and substream five", { + base <- pva_model(params = list(last = 1), init = pva_population(rep("F", 40L), 2L), + n_steps = 3L) + watched <- base |> + step_process(survey_process(0.5, when = 1:2), + when = function(state, context, params) context$time <= params$last) |> + step_survival(0.8) |> step_census() + scenario <- compile_scenario(watched, n_runs = 1L, seed = 82L) + expect_identical(scenario$processes[[1L]]$run, OpenPVA:::.run_survey) + run <- run_scenario(scenario) + expect_identical(run$events$time[run$events$event_type == "survey_skip"], c(0L, 2L)) + expect_identical(run$events$time[run$events$event_type == "survey_visit"], 1L) + bare <- base |> step_survival(0.8) |> step_census() + control <- run_scenario(compile_scenario(bare, n_runs = 1L, seed = 82L)) + expect_identical(run$census$n_alive, control$census$n_alive) + expect_identical(run$events$value[run$events$event_type == "death"], + control$events$value[control$events$event_type == "death"]) +}) + +test_that("initial, newborn and release callbacks fill or override model field defaults", { + defaults <- list(tag = 3L, site = "west") + for (as_state in c(FALSE, TRUE)) { + init <- function() { + pop <- pva_population("F", 2L, tag = 9L) + if (as_state) pva_state(pop) else pop + } + model <- pva_model(init = init, fields = defaults, n_steps = 1L) |> + step_reproduction(1, litter_binomial(1L, 1), offspring_sex_bernoulli(1), + newborn_fields = function(...) list(site = "east")) |> + step_introduce(2L, fields = function(...) list(sex = "M", age = 4L, tag = 7L)) |> + step_census() + audit <- describe_model(model) + expect_equal(audit$n_initial, 1) + pop <- run_scenario(compile_scenario(model, n_runs = 1L, seed = 1L), keep = "state")$states[[1]]$population + expect_identical(pop$origin, c("initial", "birth", "introduction", "introduction")) + expect_identical(pop$tag, c(9L, 3L, 7L, 7L)) + expect_identical(pop$site, c("west", "east", "west", "west")) + } +}) + +test_that("compile validation chooses an execution default and always checks field plans", { + base <- pva_model(init = pva_population("F", 1L), n_steps = 1L) + model <- base |> step_census() + for (mode in c("strict", "fast")) { + other <- if (mode == "fast") "strict" else "fast" + scenario <- compile_scenario(model, n_runs = 1L, seed = 2L, validation = mode) + expect_identical(scenario$validation, mode) + expect_identical(run_scenario(scenario)$provenance$validation, mode) + expect_identical(run_scenario(scenario, validation = other)$provenance$validation, other) + bad <- base |> step_process(pva_process("missing", function(state, context, params) pva_result(state), + requires = "population.unknown")) + expect_error(compile_scenario(bad, validation = mode), "missing.*population.unknown") + } + expect_error(compile_scenario(model, validation = TRUE), "arg") +}) diff --git a/tests/testthat/test-b4-ensemble-audit.R b/tests/testthat/test-b4-ensemble-audit.R new file mode 100644 index 0000000..fd164f2 --- /dev/null +++ b/tests/testthat/test-b4-ensemble-audit.R @@ -0,0 +1,124 @@ +test_that("design parameters take precedence over descriptive and seed-block columns", { + model <- pva_model(params = list(scenario = 1, label = 1, model = 1), + init = data.frame(age = 2L, sex = "F", n = 20L), n_steps = 1L) |> + step_survival(~ scenario * label * model) |> step_census() + paired <- run_pva_ensemble(data.frame(scenario = 0:1), model, 2L, seed = 17, seed_by = TRUE) + expect_identical(paired$final_mean, c(0, 20)) + expect_length(unique(paired$member_seed), 1L) + + design <- data.frame(scenario = c(0, 0, 1, 1), label = c(1, 1, 0, 1)) + blocked <- run_pva_ensemble(design, model, 2L, seed = 17, seed_by = "scenario") + expect_identical(blocked$final_mean, c(0, 0, 0, 20)) + expect_identical(match(blocked$member_seed, unique(blocked$member_seed)), c(1L, 1L, 2L, 2L)) + single <- run_pva_ensemble(data.frame(model = 0:1), model, 1L, seed = 17) + expect_identical(single$final_mean, c(0, 20)) + expect_error(run_pva_ensemble(data.frame(model = "a"), list(a = model), 1L), + "structural model 'a'.*parameter 'model'.*reserved") +}) + +test_that("preflight constructs each member once and caches only its selected model", { + calls <- tempfile() + summaries <- tempfile() + cache <- tempfile() + make_model <- function(s) { + pva_model(init = data.frame(age = 2L, sex = "F", n = 5L), n_steps = 1L) |> + step_process(function(params) { + cat("built\n", file = calls, append = TRUE) + survival_process(s) + }) |> step_census() + } + report <- function(result, row) { + cat(row$model, "\n", file = summaries, append = TRUE, sep = "") + summarise_pva(result)["final_mean"] + } + design <- data.frame(model = c("a", "b")) + models <- list(a = make_model(1), b = make_model(1)) + run <- function(models) { + run_pva_ensemble(design, models, 1L, summarise = report, seed = 9, cache_dir = cache) + } + first <- run(models) + expect_identical(first$final_mean, c(5, 5)) + expect_length(readLines(calls), 2L) + expect_identical(run(models), first) + expect_length(readLines(calls), 4L) + expect_identical(readLines(summaries), c("a", "b")) + models$b <- make_model(0) + expect_identical(run(models)$final_mean, c(5, 0)) + expect_length(readLines(calls), 6L) + expect_identical(readLines(summaries), c("a", "b", "b")) +}) + +test_that("socket ensemble tasks carry only their own model and resolve caller callbacks", { + assign(".openpva_p1_survival", 1, envir = .GlobalEnv) + assign(".openpva_p1_metric", "n_alive", envir = .GlobalEnv) + on.exit(rm(".openpva_p1_survival", ".openpva_p1_metric", envir = .GlobalEnv)) + survival <- evalq(function(pop, state, context, params) params$s * .openpva_p1_survival, + .GlobalEnv) + model <- pva_model(params = list(s = 1), init = data.frame(age = 2L, sex = "F", n = 12L), + n_steps = 1L) |> step_survival(survival) + models <- list(a = step_census(model), b = step_census(step_age(model))) + design <- data.frame(model = c("a", "b", "a", "b"), s = c(0, 1, 0.5, 0.8)) + inspect <- evalq(function(result, row) { + worker <- Filter(function(frame) { + exists("item", frame, inherits = FALSE) && exists("payload", frame, inherits = FALSE) + }, sys.frames())[[1L]] + count_models <- function(x) { + if (inherits(x, c("pva_scenario", "pva_model"))) return(1L) + if (!is.list(x)) return(0L) + sum(vapply(x, count_models, integer(1))) + } + data.frame(n = mean(result$census[[.openpva_p1_metric]][result$census$phase == "interval"]), + shared_models = count_models(worker$payload), item_models = count_models(worker$item), + assigned = worker$item$scenario$name) + }, .GlobalEnv) + run <- function(...) run_pva_ensemble(design, models, 3L, inspect, seed = 19L, ...) + serial <- run() + socket <- run(workers = 2L, backend = "psock") + expect_identical(socket, serial) + expect_identical(socket$n[1:2], c(0, 12)) + expect_identical(socket$shared_models, rep(0L, 4L)) + expect_identical(socket$item_models, rep(1L, 4L)) + expect_identical(socket$assigned, paste0("member-", 1:4)) + if (.Platform$OS.type != "windows") expect_identical(run(workers = 2L, backend = "fork"), serial) +}) + +test_that("parameter audits preserve explicit character values and colliding evidence", { + evidence <- data.frame(parameter = "band", value = "001", type = "character", + base = "annex A", status = "measured", used_by = "field team", + overridden = "field season", parameter = "band number", + value = "original record", check.names = FALSE) + model <- pva_model(params = evidence, init = pva_population(character(), integer()), + n_steps = 1L) |> + step_census(list(n_alive = ~ N, marked = ~ N * (band == "001"))) + audit <- describe_model(model) + expect_output(print(audit), "N0 = 0") + expect_identical(audit$initial, data.frame(sex = character(), age = integer(), n = integer())) + values <- audit$parameters + expect_identical(values$base[[1L]], "001") + expect_identical(values$status, "active") + expect_identical(values$evidence.base, "annex A") + expect_identical(values$evidence.status, "measured") + expect_identical(values$evidence.used_by, "field team") + expect_identical(values$evidence.overridden, "field season") + expect_identical(values$evidence.parameter, "band number") + expect_identical(values$evidence.value, "original record") +}) + +test_that("audits distinguish literal survival and retain complete transition matrices", { + patches <- c("north", "south") + move <- matrix(c(0.6, 0.3, 0.4, 0.7), 2L, dimnames = list(patches, patches)) + stay <- diag(2L) + dimnames(stay) <- dimnames(move) + model <- pva_model(params = list(moves = move), init = pva_population("F", 1L, patch_id = "north"), + n_steps = 1L) |> step_dispersal(transition = ~ moves) + audit <- describe_model(model, list(moves = stay)) + expect_identical(audit$parameters$base[[1L]], move) + expect_identical(audit$parameters$value[[1L]], stay) + expect_output(print(audit), "<2 x 2 matrix>") + expect_output(print(audit$parameters), "<2 x 2 matrix>") + expect_output(print(audit$parameters[1L, c("parameter", "value")]), "<2 x 2 matrix>") + zero <- describe_model(step_survival(model, 0))$steps$equations[[2L]] + one <- describe_model(step_survival(model, 1))$steps$equations[[2L]] + expect_match(zero, "probability = 0") + expect_match(one, "probability = 1") +}) diff --git a/tests/testthat/test-b4-rates-formulas.R b/tests/testthat/test-b4-rates-formulas.R new file mode 100644 index 0000000..b41a4f3 --- /dev/null +++ b/tests/testthat/test-b4-rates-formulas.R @@ -0,0 +1,156 @@ +test_that("authored rates cover occupied strata, future ages and literal introductions", { + init <- data.frame(sex = "F", age = 2L, n = 3L, zone = "east") + table <- data.frame(sex = "F", age = "2-3", zone = "north", s = 1) + model <- function(table, age = FALSE) { + pva_model(init = init, rates = table, n_steps = 2L) |> + step_survival(~ rate("s", by = "zone")) |> step_age(enabled = age) |> step_census() + } + expect_error(compile_scenario(model(table)), "step 1 'survival'.*sex F, zone east") + table$zone <- "east" + expect_error(compile_scenario(model(table, TRUE)), "open terminal age class.*sex F, zone east") + expect_s3_class(compile_scenario(model(table)), "pva_scenario") + table$age <- "2+" + release <- model(table, TRUE) |> step_introduce(2L, list(age = 3L, sex = "F", zone = "east")) + expect_s3_class(compile_scenario(release), "pva_scenario") + pattern <- list(age = c(2L, 3L, 4L), sex = c("F", "M"), zone = "east") + first <- model(table) |> step_introduce(1L, pattern) + expect_s3_class(compile_scenario(first), "pva_scenario") + expect_error(compile_scenario(model(table) |> step_introduce(6L, pattern)), "no rows for sex M") + juveniles <- model(table) |> step_introduce(1L, list(age = 0L, sex = "F", zone = "east")) + expect_error(compile_scenario(juveniles), "sex F, zone east at age 0") + elsewhere <- model(table) |> step_introduce(1L, list(age = 3L, sex = "F", zone = "west")) + expect_error(compile_scenario(elsewhere), "sex F, zone west") + gap <- table[c(1L, 1L), ] + gap$age <- c("0", "2+") + expect_error(compile_scenario(model(gap)), "age gap.*sex F, zone east.*age 1") +}) + +test_that("stage rates follow newborn fields and an active maturation step", { + rates <- data.frame(age = c("0-1", "2+"), sex = "All", stage = c("juvenile", "adult"), s = 1) + founders <- data.frame(age = 2L, sex = c("F", "M"), stage = "adult") + lifecycle <- function(table = rates, default = "juvenile", mature = TRUE) { + pva_model(init = founders, fields = list(stage = default), rates = table, n_steps = 4L) |> + step_survival(~ rate("s", by = "stage")) |> step_age() |> + step_assign("stage", "adult", select = ~ age >= 2L, enabled = mature) + } + birth <- function(model, ...) { + step_reproduction(model, 1, litter_binomial(1L, 1L, min_size = 1L), offspring_sex_bernoulli(1), + when = ~ time == 0L, ...) + } + counts <- function(model) { + model <- model |> step_census(~ c(juveniles = sum(stage == "juvenile"), adults = sum(stage == "adult"))) + run_scenario(compile_scenario(model, n_runs = 1L, seed = 27L))$census + } + census <- counts(birth(lifecycle())) + expect_equal(census$juveniles, c(0, 1, 1, 0, 0)) + expect_equal(census$adults, c(2, 2, 2, 3, 3)) + explicit <- birth(lifecycle(default = "adult"), newborn_fields = list(stage = "juvenile")) + expect_identical(counts(explicit), census) + native <- reproduction_process(1, litter_binomial(1L, 1L), offspring_sex_bernoulli(1), + newborn_fields = list(stage = "juvenile")) + expect_identical(counts(lifecycle() |> step_process(native, when = ~ time == 0L)), census) + dynamic <- reproduction_process(1, litter_binomial(1L, 1L), offspring_sex_bernoulli(1), + newborn_fields = function(...) list(stage = "juvenile"), + newborn_field_names = "stage") + expect_error(compile_scenario(lifecycle() |> step_process(dynamic)), "stage adult at age 0") + expect_error(compile_scenario(birth(lifecycle(), inherit = "stage")), "stage adult at age 0") + second <- birth(birth(lifecycle()), name = "second brood", newborn_fields = list(stage = "nursery")) + expect_error(compile_scenario(second), "has no rows for sex F, stage nursery") + + expect_error(compile_scenario(birth(lifecycle(mature = FALSE))), "open terminal age class.*stage juvenile") + finite_males <- rbind(transform(rates, sex = "F"), transform(rates, sex = "M", age = c("0-1", "2-3"))) + expect_error(compile_scenario(birth(lifecycle(finite_males))), "open terminal age class for sex M") + + mixed <- rbind(transform(rates, patch_id = "north"), + transform(rates, patch_id = "south", age = c("0-1", "2-3"))) + patch_model <- pva_model(init = transform(founders, patch_id = c("north", "south")), + fields = list(stage = "juvenile"), rates = mixed, n_steps = 4L) |> + step_survival(~ rate("s", by = c("stage", "patch_id"))) |> step_age() |> + step_assign("stage", "adult", select = ~ age >= 2L) + expect_error(compile_scenario(birth(patch_model, inherit = "patch_id")), + "open terminal age class for sex F, patch_id south") +}) + +test_that("probability inputs follow the formals of pure functions", { + model <- pva_model(init = data.frame(sex = "F", age = 0L, n = 2L), + rates = data.frame(age = "0+", sex = "All", s = 1.2), n_steps = 1L) + invalid <- model |> step_survival(~ OpenPVA::shift_logit(deviation = 0, probability = rate("s"))) + expect_error(compile_scenario(invalid), "step 1 'survival'.*s.*probability.*1.2") + expect_error(compile_scenario(model |> step_survival(~ stats::qlogis(p = rate("s")))), + "step 1 'survival'.*s.*probability.*1.2") + valid <- model |> step_survival(~ stats::plogis(rate("s"))) |> + step_reproduction(0, litter_poisson(~ rate("s")), offspring_sex_bernoulli(0.5)) |> step_census() + expect_s3_class(compile_scenario(valid), "pva_scenario") + expect_error(compile_scenario(model |> step_survival(~ stats::shift_logit(1, 0))), + "stats::shift_logit") +}) + +test_that("logical F from CSV is unambiguous in cohorts, founders and rates", { + cohorts <- utils::read.csv(text = "sex,age,n\nF,0,2\nF,1,3") + expect_type(cohorts$sex, "logical") + expect_identical(cohort_population(cohorts)$sex, rep("F", 5L)) + founders <- cohorts[c("sex", "age")] + rates <- utils::read.csv(text = "sex,age,s\nF,0,0\nF,1+,1") + model <- pva_model(init = founders, rates = rates, n_steps = 1L) |> + step_survival(~ rate("s")) |> step_census() + scenario <- compile_scenario(model, n_runs = 1L, seed = 9L) + expect_identical(model$init$sex, c("F", "F")) + expect_equal(run_scenario(scenario)$census$n_alive, c(2, 1)) + scope <- environment(scenario$processes[[1L]]$params$probability) + expect_true(environmentIsLocked(scope)) + expect_true(bindingIsLocked(".rate1", scope)) + expect_false(exists("table", environment(scope$.rate1), inherits = FALSE)) + for (invalid in list(TRUE, NA)) { + rates$sex <- invalid + expect_error(age_sex_rate(rates, "s"), "logical sex") + } +}) + +test_that("scalar row destinations recycle and patch_counts matches positional fields", { + model <- pva_model(init = data.frame(sex = "F", age = 2L, n = 7L, zone = "north"), + n_steps = 1L) |> + step_dispersal(destination = ~ "south", patches = c("north", "south"), field = "zone") |> + step_census(~ OpenPVA::patch_counts(c("north", "south"), "zone")) + scenario <- compile_scenario(model, n_runs = 1L, seed = 4L) + expect_true("population.zone" %in% scenario$processes[[2L]]$requires) + census <- run_scenario(scenario)$census + expect_equal(census$north, c(7, 0)) + expect_equal(census$south, c(0, 7)) +}) + +test_that("probability and rate formulas coerce logical results and preserve missing errors", { + model <- pva_model(init = data.frame(age = 0:1, sex = "F", fertile = c(FALSE, TRUE)), n_steps = 1L) + counts <- function(formula) { + run <- run_scenario(compile_scenario(model |> step_survival(formula) |> step_census(), + n_runs = 1L, seed = 12L)) + run$census$n_alive + } + expect_equal(counts(~ ifelse(age > 0, TRUE, FALSE)), c(2, 1)) + expect_equal(counts(~ fertile), c(2, 1)) + expect_equal(counts(~ TRUE), c(2, 2)) + expect_equal(counts(TRUE), c(2, 2)) + expect_error(counts(~ ifelse(age > 0, NA, FALSE)), "non-missing") +}) + +test_that("time trends, scoped survey fields and name suggestions resolve precisely", { + model <- pva_model(init = data.frame(age = 1L, sex = "F", n = 3L), + params = list(slope = 0.5), n_steps = 2L, initial_census = FALSE) + trend <- model |> step_environment(anomaly = ~ 1, trend = env_trend(~ slope * time + dt, "anomaly")) |> + step_census(~ c(n_alive = N, signal = trend)) + expect_equal(run_scenario(compile_scenario(trend, n_runs = 1L, seed = 5L))$census$signal, + c(2, 2.5)) + missing <- model |> step_environment(trend = env_trend(~ slope * time, "anomaly")) + expect_error(compile_scenario(missing), "step 1 'environment'.*anomaly") + expect_error(compile_scenario(model |> step_environment(t = env_trend(~ slope * N))), + "env_trend.*N") + + surveyed <- model |> step_survey(1, field = "count") |> + step_remove(count = survey_quota( + ~ if (obs$visited && obs$time == 0 && length(obs$ids) == obs$count) observed - 1L else 0L, + field = "count")) |> step_census() + expect_equal(run_scenario(compile_scenario(surveyed, n_runs = 1L, seed = 5L))$census$n_alive, + c(1, 1)) + expect_error(compile_scenario(model |> step_census(~ obs$count)), "only inside survey_quota") + expect_error(compile_scenario(model |> step_survey(1, field = "count") |> + step_census(~ cnt)), "did you mean 'count'") +}) diff --git a/tests/testthat/test-model-authoring.R b/tests/testthat/test-model-authoring.R new file mode 100644 index 0000000..26243d8 --- /dev/null +++ b/tests/testthat/test-model-authoring.R @@ -0,0 +1,408 @@ +test_that("age_sex_rate() accepts age shorthand, shared sexes and strata", { + explicit <- data.frame( + age_min = c(0, 1, 2, 0, 1, 2), age_max = c(0, 1, Inf, 0, 1, Inf), + sex = rep(c("F", "M"), each = 3L), rate = rep(c(0.4, 0.7, 0.9), 2L) + ) + shorthand <- data.frame(age = c("0", "1", "2+"), sex = "All", rate = c(0.4, 0.7, 0.9)) + pop <- pva_population(sex = c("F", "M", "F", "M"), age = c(0L, 1L, 5L, 2L)) + expect_identical(age_sex_rate(shorthand, "rate")(pop, NULL, NULL, NULL), + age_sex_rate(explicit, "rate")(pop, NULL, NULL, NULL)) + ranged <- data.frame(age = c("0-1", "2-4", "5+"), sex = c("F", "F", "F"), rate = c(0.1, 0.2, 0.3)) + expect_identical(age_sex_rate(ranged, "rate", missing_sex = "zero")(pop, NULL, NULL, NULL), + c(0.1, 0, 0.3, 0)) + numeric_age <- data.frame(age = 0:2, sex = "F", rate = c(0.1, 0.2, 0.3)) + expect_identical(age_sex_rate(numeric_age, "rate")(pva_population("F", 2L), NULL, NULL, NULL), 0.3) + expect_invisible(validate_age_sex_table(shorthand, "rate")) + expect_error(age_sex_rate(data.frame(age = "old", sex = "F", rate = 1), "rate"), "whole ages, ranges") + expect_error(age_sex_rate(rbind(shorthand, data.frame(age = "1", sex = "F", rate = 0.5)), "rate"), + "overlap for sex F") + expect_error(age_sex_rate(data.frame(age = "0+", sex = "Both", rate = 1), "rate"), "'All'") + + by_patch <- data.frame( + age = "0+", sex = "All", patch_id = c("north", "south"), rate = c(0.9, 0.5) + ) + lookup <- age_sex_rate(by_patch, "rate", by = "patch_id") + placed <- pva_population(sex = c("F", "M", "F"), age = 1L, patch_id = c("south", "north", "south")) + expect_identical(lookup(placed, NULL, NULL, NULL), c(0.5, 0.9, 0.5)) + expect_error(lookup(pop, NULL, NULL, NULL), "stratified by population field patch_id") + elsewhere <- pva_population(sex = "F", age = 1L, patch_id = "east") + expect_error(lookup(elsewhere, NULL, NULL, NULL), "no entry for sex F with patch_id = east") + expect_error(age_sex_rate(by_patch, "rate"), "overlap") + expect_error(age_sex_rate(by_patch, "rate", by = "zone"), "by column") +}) + +test_that("cohort_population() expands both common count layouts without rep()", { + long <- cohort_population(data.frame(age = c(0L, 2L, 1L), sex = c("F", "M", "F"), n = c(2L, 1L, 0L))) + expect_identical(long$sex, c("F", "F", "M")) + expect_identical(long$age, c(0L, 0L, 2L)) + wide <- cohort_population(data.frame(age = 0:1, females = c(2, 1), males = c(1, 2), + patch_id = c("A", "B"), stringsAsFactors = FALSE), + mate_id = NA_integer_) + expect_identical(wide$sex, rep(c("F", "M"), each = 3L)) + expect_identical(wide$age, c(0L, 0L, 1L, 0L, 1L, 1L)) + expect_identical(wide$patch_id, c("A", "A", "B", "A", "B", "B")) + expect_identical(wide$mate_id, rep(NA_integer_, 6L)) + expect_identical(wide$id, 1:6) + expect_error(cohort_population(data.frame(age = 1, sex = "F", n = 0)), "no individuals") + expect_error(cohort_population(data.frame(age = 1, n = 2)), "\\(age, sex, n\\) or \\(age, females, males\\)") +}) + +test_that("pva_model() separates typed parameter evidence from the lifecycle", { + table <- data.frame( + parameter = c("s_adult", "releases", "label", "years"), + value = c("0.9", "TRUE", "north", "3"), + unit = c("probability", "flag", "text", "intervals"), + source = c("Smith 2020", "plan", "map", "plan"), stringsAsFactors = FALSE + ) + model <- pva_model(params = table, init = data.frame(age = 2L, females = 4L, males = 4L), + n_steps = 3L, fields = list(tag = 0L)) |> + step_survival(~ s_adult) |> + step_introduce(~ if (time < years) 1 else 0, fields = list(sex = "F", age = 1L), + enabled = ~ releases) |> + step_census() + expect_identical(model$params, list(s_adult = 0.9, releases = TRUE, label = "north", years = 3L)) + audit <- describe_parameters(model, overrides = list(s_adult = 0.8)) + expect_identical(names(audit), c("parameter", "base", "value", "overridden", "status", "used_by", + "unit", "source")) + expect_identical(audit$value[[1L]], 0.8) + expect_identical(audit$base[[1L]], 0.9) + expect_identical(audit$overridden, c(TRUE, FALSE, FALSE, FALSE)) + expect_identical(audit$status, c("active", "active", "unused", "active")) + expect_identical(audit$source[[1L]], "Smith 2020") + expect_identical(audit$used_by[[4L]], "introduction") + # the model is a value: adding a step returns a new model and leaves this one alone + longer <- step_age(model) + expect_length(model$steps, 3L) + expect_length(longer$steps, 4L) + state <- compile_scenario(model, n_runs = 1L)$init_fun() + expect_identical(state$population$tag, rep(0L, 8L)) + expect_output(print(model), " + step_remove(count = 2L, order = "id", name = "cull", when = ~ years, enabled = ~ cull) |> + step_census() + run <- run_scenario(compile_scenario(scheduled, n_runs = 2L, seed = 5L)) + removed <- run$events[run$events$event_type == "removal", ] + expect_identical(removed$time, c(0L, 2L, 0L, 2L)) + expect_identical(run$census$n_alive[run$census$run == 1L], c(20, 18, 18, 16, 16)) + expect_true(all(summarise_accounting(run)$reconciled)) + by_rule <- base |> + step_remove(count = 2L, order = "id", name = "cull", when = ~ time %% 2 == 0) |> step_census() + expect_identical(run_scenario(compile_scenario(by_rule, n_runs = 2L, seed = 5L))$census, run$census) + by_function <- base |> + step_remove(count = 2L, order = "id", name = "cull", + when = function(state, context, params) context$time %in% params$years) |> + step_census() + expect_identical(run_scenario(compile_scenario(by_function, n_runs = 2L, seed = 5L))$census, + run$census) + off <- compile_scenario(scheduled, overrides = list(cull = FALSE), n_runs = 2L, seed = 5L) + expect_identical(vapply(off$processes, `[[`, character(1), "name"), "census") + expect_error(step_age(base, enabled = "yes"), "enabled must be TRUE, FALSE or a formula") + expect_error(compile_scenario(base |> step_age(enabled = ~ years)), "must give one TRUE or FALSE") + # a scheduled random removal draws exactly as its hand-written count rule does + authored <- base |> step_remove(count = 3L, name = "cull", when = c(1, 3)) |> step_census() + native <- scenario_spec( + "native", n_runs = 3L, n_steps = 4L, seed = 6L, + init_fun = function() pva_population(rep(c("F", "M"), each = 10L), 3L), + processes = list( + removal_process(count = function(state, context, params) { + if (context$time %in% c(1, 3)) 3L else 0L + }, name = "cull"), + census_process() + ), initial_census = census_process() + ) + expect_identical( + run_scenario(compile_scenario(authored, n_runs = 3L, seed = 6L), keep = "ledger")$ledgers, + run_scenario(native, keep = "ledger")$ledgers + ) +}) + +test_that("staged survival, ceilings, pairing and rule-based dispersal compile to their constructors", { + model <- pva_model( + params = list(s = 0.8, share = 0.4, K = 14, K_pairs = 3, mature = 2), + init = data.frame(age = 2:3, females = 5L, males = 5L, patch_id = c("A", "B"), + stringsAsFactors = FALSE), + fields = list(mate_id = NA_integer_), n_steps = 5L, pedigree = TRUE + ) |> + step_survival(~ s, stage = "pre", post_share = ~ share) |> + step_ceiling(~ K) |> + step_survival(~ s, stage = "post", post_share = ~ share) |> + step_pairing(~ age >= mature, capacity = ~ K_pairs, priority = "kinship") |> + step_reproduction(~ !is.na(mate_id), litter_poisson(1.4), offspring_sex_bernoulli(0.5), + mate = mate_from_field(), inherit = "patch_id") |> + step_dispersal(destination = ~ ifelse(patch_id == "A", "B", "A"), patches = c("A", "B"), + eligible = ~ age == 0) |> + step_age() |> + step_census(metrics = list(n_alive = ~ N, pairs = ~ sex == "F" & !is.na(mate_id), + in_A = ~ patch_id == "A")) + scenario <- compile_scenario(model, n_runs = 4L, seed = 12L) + native <- scenario_spec( + "native", n_runs = 4L, n_steps = 5L, seed = 12L, + init_fun = function() pva_state( + pva_population(rep(c("F", "M"), each = 10L), c(rep(2:3, each = 5L), rep(2:3, each = 5L)), + patch_id = c(rep(c("A", "B"), each = 5L), rep(c("A", "B"), each = 5L)), + mate_id = NA_integer_), pedigree = TRUE + ), + processes = list( + staged_survival_process(0.8, 0.4, "pre"), + ceiling_process(14), + staged_survival_process(0.8, 0.4, "post"), + pairing_process(function(pop, state, context, params) pop$age >= 2, capacity = 3, + priority = "kinship", requires = "population.age"), + reproduction_process(function(pop, ...) as.numeric(!is.na(pop$mate_id)), litter_poisson(1.4), + offspring_sex_bernoulli(0.5), mate = mate_from_field(), + newborn_fields = list(mate_id = NA_integer_), inherit = "patch_id"), + dispersal_process(function(rows, pop, ...) ifelse(pop$patch_id[rows] == "A", "B", "A"), + c("A", "B"), eligible = function(pop, ...) pop$age == 0), + age_process(), + census_process(list(n_alive = function(pop, ...) length(pop$id), + pairs = function(pop, ...) pop$sex == "F" & !is.na(pop$mate_id), + in_A = function(pop, ...) pop$patch_id == "A")) + ), + initial_census = census_process(list(n_alive = function(pop, ...) length(pop$id), + pairs = function(pop, ...) pop$sex == "F" & !is.na(pop$mate_id), + in_A = function(pop, ...) pop$patch_id == "A")) + ) + expect_same_run(run_scenario(native, keep = keep_all), run_scenario(scenario, keep = keep_all)) + expect_identical(vapply(scenario$processes, `[[`, character(1), "name"), + c("survival_pre", "ceiling", "survival_post", "pairing", "reproduction", + "dispersal", "age", "census")) + expect_true(isTRUE(attr(scenario$processes[[4L]]$run, "resets_mate_field"))) + expect_error(step_survival(model, 0.5, stage = "pre"), "needs post_share") + expect_error(step_dispersal(model), "either a transition matrix or a destination rule") +}) + +test_that("step_process() drops native, custom and parameterised processes into a pipeline", { + harvest_oldest <- pva_process( + name = "harvest_oldest", + run = function(state, context, params) { + if (!length(state$population$id)) return(pva_result(state)) + oldest <- which.max(state$population$age) + state$population$alive[oldest] <- FALSE + pva_result(state, pva_events("removal", length(oldest), "harvest")) + }, + requires = "population.age", writes = "population.alive", role = "management" + ) + quota <- function(params) { + removal_process(count = params$quota, order = "id", name = "quota_cull") + } + model <- pva_model(params = list(s = 0.9, quota = 1, culling = TRUE), + init = data.frame(age = 1:4, sex = "F", n = 3L), n_steps = 3L) |> + step_survival(~ s) |> + step_process(harvest_oldest) |> + step_process(quota, enabled = ~ culling) |> + step_process(age_process()) |> + step_census() + scenario <- compile_scenario(model, n_runs = 3L, seed = 2L) + expect_identical(vapply(scenario$processes, `[[`, character(1), "name"), + c("survival", "harvest_oldest", "quota_cull", "age", "census")) + expect_identical(scenario$processes[[2L]], harvest_oldest) + run <- run_scenario(scenario) + expect_true(all(summarise_accounting(run)$reconciled)) + expect_identical(sum(run$events$value[run$events$process_name == "harvest_oldest"]), 9) + audit <- describe_parameters(model) + expect_identical(audit$used_by[audit$parameter == "quota"], "quota_cull") + lifecycle <- describe_lifecycle(model) + expect_identical(lifecycle$role[lifecycle$name == "harvest_oldest"], "management") + without <- compile_scenario(model, overrides = list(culling = FALSE), n_runs = 1L) + expect_identical(length(without$processes), 4L) + expect_error(compile_scenario(model, overrides = list(quota = 2, culling = FALSE)), + "override 'quota' has no effect") + expect_error(step_process(model, function(a, b) NULL), "function of one argument") + expect_error(compile_scenario(step_process(model, function(params) 1)), + "must return a pva_process") + + # the engine's inbreeding-proxy guard still sees the native process + proxy <- pva_model(init = data.frame(age = 2L, sex = c("F", "M"), n = 2L), n_steps = 2L, + globals = list(inbreeding_proxy = 0)) |> + step_process(inbreeding_proxy_process(function(pop, state, context, params) 10, + generation_time = 2)) |> + step_introduce(1L, fields = list(sex = "F", age = 1L)) |> + step_census() + expect_error(run_scenario(compile_scenario(proxy, n_runs = 1L, seed = 1L)), + "explicit migration function") +}) + +test_that("R callbacks inside steps receive the bound parameters and are traced", { + model <- pva_model(params = list(juvenile = 0.5, adult = 0.9, spare = 1), + init = data.frame(age = 0:1, sex = "F", n = 6L), n_steps = 3L) |> + step_survival(function(pop, state, context, params) { + ifelse(pop$age == 0L, params$juvenile, params[["adult"]]) + }, requires = "population.age") |> + step_age() |> step_census() + scenario <- compile_scenario(model, overrides = list(adult = 0.7), n_runs = 2L, seed = 3L) + expect_identical(scenario$processes[[1L]]$params$user, list(juvenile = 0.5, adult = 0.7)) + expect_true("population.age" %in% scenario$processes[[1L]]$requires) + native <- scenario_spec( + "native", n_runs = 2L, n_steps = 3L, seed = 3L, + init_fun = function() pva_population(rep("F", 12L), rep(0:1, each = 6L)), + processes = list(survival_process(function(pop, ...) ifelse(pop$age == 0L, 0.5, 0.7)), + age_process(), census_process()), + initial_census = census_process() + ) + expect_identical(run_scenario(scenario)$census, run_scenario(native)$census) + audit <- describe_parameters(model) + expect_identical(audit$used_by, c("survival", "survival", "")) + expect_error(compile_scenario(model, overrides = list(spare = 2)), "no step of model") + opaque <- pva_model(params = list(a = 1, spare = 1), + init = data.frame(age = 1L, sex = "F", n = 2L), n_steps = 1L) |> + step_survival(function(pop, state, context, params) do.call(min, params), + uses = c("a", "spare")) |> step_census() + lethal <- compile_scenario(opaque, overrides = list(spare = 0), n_runs = 1L, seed = 3L) + expect_equal(run_scenario(lethal)$census$n_alive, c(2, 0)) + expect_identical(describe_parameters(opaque)$used_by, c("survival", "survival")) +}) + +test_that("describe_model() audits inputs, equations, bindings and a life-table check", { + rates <- data.frame(age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.5, 0.8, 0.9), p_breed = c(0, 0.6, 1), litter = c(0, 1.2, 2.2)) + model <- pva_model( + params = list(female_share = 0.5, K = 80), rates = rates, + init = data.frame(age = 0:2, females = c(4L, 3L, 6L), males = c(4L, 3L, 5L)), + n_steps = 10L, name = "audited" + ) |> + step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, K)) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share)) |> + step_census() + audit <- describe_model(model, overrides = list(K = 60), life_table = list( + survival = ~ rate("p_surv"), fecundity = ~ rate("p_breed") * rate("litter") * female_share + )) + expect_s3_class(audit, "pva_model_audit") + expect_identical(audit$n_initial, 25L) + expect_identical(audit$initial$n[audit$initial$sex == "M"], c(4L, 3L, 5L)) + expect_identical(audit$steps$equations[[1L]], + "probability = ~rate(\"p_surv\") * ceiling_density_multiplier(N, K)") + expect_identical(audit$steps$parameters[[1L]], "K = 60") + expect_identical(audit$parameters$value[[which(audit$parameters$parameter == "K")]], 60) + expected <- life_table_metrics(c(0.5, 0.8, 0.9), c(0, 0.6 * 1.2 * 0.5, 1 * 2.2 * 0.5)) + expect_identical(audit$life_table$lambda, expected$lambda) + expect_identical(audit$life_table$survival, c(0.5, 0.8, 0.9)) + expect_output(print(audit), "Female life table from the authored rates: lambda") + expect_output(print(audit), "with K = 60") + expect_error(describe_model(model, life_table = list(survival = ~ rate("p_surv"))), + "survival and fecundity") + + lifecycle <- describe_lifecycle(model) + expect_s3_class(lifecycle, "pva_lifecycle") + expect_identical(lifecycle$role, c("census", "demography", "demography", "demography", "census")) + expect_identical(attr(lifecycle, "authoring")$parameters[[1L]], "K = 80") + expect_identical(attr(lifecycle, "metadata")$state$n_living, 25L) + text <- format_lifecycle(model) + expect_match(text, "Authored steps:", fixed = TRUE) + expect_match(text, "litter_poisson(mean = ~rate(\"litter\"))", fixed = TRUE) + expect_match(format_lifecycle(model, "mermaid"), "flowchart LR", fixed = TRUE) + expect_null(attr(lifecycle[, c("name", "role")], "authoring")) + # a compiled scenario and its run carry the same audit + scenario <- compile_scenario(model, n_runs = 2L, seed = 1L) + expect_identical(attr(describe_lifecycle(scenario), "authoring"), attr(lifecycle, "authoring")) + expect_identical(attr(describe_lifecycle(run_scenario(scenario)), "authoring"), + attr(lifecycle, "authoring")) +}) + +test_that("declared roles take precedence and native output is unchanged without them", { + silent <- function(state, context, params) pva_result(state) + expect_identical(describe_lifecycle(list(pva_process("harvest_tally", silent)))$role, "custom") + expect_identical( + describe_lifecycle(list(pva_process("harvest_tally", silent, role = "management")))$role, + "management" + ) + # Built-in constructors declare the role 2.3.0 displayed for them, so a + # renamed process keeps its place in existing lifecycle output. + expect_identical(survival_process(0.9)$role, "demography") + expect_identical( + describe_lifecycle(list(survival_process(0.9, name = "autumn_harvest")))$role, "management" + ) + expect_error(pva_process("x", silent, role = "ecology"), "role must be NULL or one of") + expect_false("role" %in% names(pva_process("x", silent))) + native <- list(survival_process(0.9), age_process(), census_process()) + expect_false(grepl("Authored steps", format_lifecycle(native), fixed = TRUE)) + expect_null(attr(describe_lifecycle(native), "authoring")) +}) + +test_that("native constructors accept plain lists for created fields and census conditions", { + state <- pva_state(pva_population(c("F", "M"), 3L, mate_id = NA_integer_)) + release <- introduction_process(3L, fields = list(sex = c("F", "M"), age = 2L, mate_id = NA_integer_)) + expect_identical(release$creates, c("sex", "age", "mate_id")) + after <- execute_processes(state, list(release))$state$population + expect_identical(after$sex, c("F", "M", "F", "M", "F")) + expect_identical(after$age, c(3L, 3L, 2L, 2L, 2L)) + expect_error(introduction_process(1L, fields = list(sex = "F")), "must include sex and age") + breeding <- reproduction_process(1, litter_poisson(3), offspring_sex_bernoulli(1), + newborn_fields = list(mate_id = NA_integer_)) + expect_identical(breeding$creates, c("sex", "age", "mother_id", "father_id", "mate_id")) + set.seed(1) + born <- execute_processes(state, list(breeding))$state$population + expect_true(all(is.na(born$mate_id))) + expect_error(reproduction_process(1, litter_poisson(3), offspring_sex_bernoulli(1), + newborn_fields = list(mate_id = c(1L, 2L))), "one value per field") + census <- census_process(list(females = function(pop, ...) pop$sex == "F", + oldest = function(pop, ...) max(pop$age))) + expect_identical(execute_processes(state, list(census))$census[c("females", "oldest")], + data.frame(females = 1, oldest = 3)) + expect_error(census_process(list(function(pop, ...) 1)), "uniquely named functions") + bad <- census_process(list(ages = function(pop, ...) pop$age)) + expect_error(execute_processes(state, list(bad)), "census metric ages must be one number") +}) + +test_that("deferred helpers bind constructor-time parameters at compile time", { + deferred <- env_ar1(sd = ~ env_sd, phi = 0.2) + expect_s3_class(deferred, "pva_deferred") + expect_output(print(deferred), "env_ar1\\(sd = ~env_sd, phi = 0.2") + expect_true(is.function(env_ar1(sd = 0.3, phi = 0.2))) + model <- pva_model(params = list(env_sd = 0.3, size = 3L, mean = 1.5), + init = data.frame(age = 2L, sex = c("F", "M"), n = 6L), n_steps = 3L) |> + step_environment(weather = env_ar1(sd = ~ env_sd, phi = 0.2)) |> + step_survival(~ shift_logit(0.8, weather)) |> + step_reproduction(0.5, litter_binomial(~ size, ~ mean), offspring_sex_bernoulli(0.5)) |> + step_census() + authored <- run_scenario(compile_scenario(model, list(env_sd = 0.6), n_runs = 3L, seed = 4L)) + native <- scenario_spec( + "native", n_runs = 3L, n_steps = 3L, seed = 4L, + init_fun = function() pva_population(rep(c("F", "M"), each = 6L), 2L), + processes = list( + environment_process(list(weather = env_ar1(sd = 0.6, phi = 0.2))), + survival_process(function(pop, state, ...) shift_logit(0.8, state$globals$weather)), + reproduction_process(0.5, litter_binomial(3L, 1.5), offspring_sex_bernoulli(0.5)), + census_process() + ), initial_census = census_process() + ) + expect_identical(authored$census, run_scenario(native)$census) + expect_error( + compile_scenario(model, list(env_sd = -1)), + "step 1 'environment' \\(weather\\): env_ar1\\(sd = ~env_sd, phi = 0.2.*sd must be finite" + ) + expect_error( + compile_scenario(pva_model(init = data.frame(age = 1L, sex = "F", n = 1L), n_steps = 1L) |> + step_environment(weather = env_ar1(sd = ~ N))), + "must depend on parameters only" + ) +}) + +test_that("a model does not depend on how its pipeline was spelled", { + core <- pva_model(params = list(s = 0.8), init = data.frame(age = 1L, sex = "F", n = 5L), + n_steps = 2L) |> + step_survival(~ s) + piped <- core |> step_census() + whole <- pva_model(params = list(s = 0.8), init = data.frame(age = 1L, sex = "F", n = 5L), + n_steps = 2L) |> + step_survival(~ s) |> + step_census() + expect_identical(piped, whole) +}) + +test_that("built-in constructors validate a process before resolving its role", { + expect_error(survival_process(0.9, name = c("a", "b")), + "process name must be one non-empty character value") +}) diff --git a/tests/testthat/test-model-diagnostics.R b/tests/testthat/test-model-diagnostics.R new file mode 100644 index 0000000..686c6a9 --- /dev/null +++ b/tests/testthat/test-model-diagnostics.R @@ -0,0 +1,265 @@ +# O3: every compile-time failure names the step and the offending symbol or +# value, and leaves the caller's random-number state exactly as it was. + +diag_rates <- data.frame(age = c("0", "1", "2+"), sex = "All", + p_surv = c(0.5, 0.8, 0.9), fecund = c(0, 1, 1.5)) + +diag_model <- function(rates = diag_rates, params = list(K = 50, b = 0.5), ...) { + pva_model(params = params, rates = rates, + init = data.frame(age = 1:2, sex = c("F", "M"), n = 5L), n_steps = 5L, ...) +} + +expect_compile_error <- function(object, pattern) { + kind <- RNGkind() + on.exit(do.call(RNGkind, as.list(kind))) + set.seed(4321, normal.kind = "Box-Muller") + next_normal <- stats::rnorm(2L)[[2L]] + set.seed(4321, normal.kind = "Box-Muller") + stats::rnorm(1L) + before <- .GlobalEnv$.Random.seed + expect_error(object, pattern) + expect_identical(.GlobalEnv$.Random.seed, before) + expect_identical(stats::rnorm(1L), next_normal) +} + +test_that("a valid model compiles and validates without touching the RNG", { + model <- diag_model() |> + step_survival(~ rate("p_surv")) |> step_age() |> + step_reproduction(~ b * (age >= 1), litter_poisson(~ rate("fecund")), + offspring_sex_bernoulli(0.5)) |> + step_census() + set.seed(9) + before <- .GlobalEnv$.Random.seed + scenario <- compile_scenario(model, n_runs = 2L, seed = 1L) + expect_identical(.GlobalEnv$.Random.seed, before) + expect_s3_class(scenario, "pva_scenario") + expect_identical(scenario$processes[[1L]]$requires, + c("population.alive", "population.age", "population.sex")) + expect_true(all(summarise_accounting(run_scenario(scenario))$reconciled)) +}) + +test_that("misspelled or unbound formula symbols are rejected with a suggestion", { + expect_compile_error( + compile_scenario(diag_model() |> step_survival(~ rate("p_surv") * (N < KK)) |> step_census()), + "step 1 'survival' \\(probability\\): unknown symbol 'KK'.*did you mean 'K'" + ) + expect_compile_error( + compile_scenario(diag_model() |> step_survival(~ rate("p_srv")) |> step_census()), + "step 1 'survival'.*no vital-rate table has a column 'p_srv'.*did you mean 'p_surv'" + ) + expect_compile_error( + compile_scenario(diag_model() |> step_survival(~ logistic(K)) |> step_census()), + "function 'logistic' is not available in formulas" + ) + expect_compile_error( + compile_scenario(diag_model() |> step_survival(0.9) |> + step_census(metrics = list(n = ~ observed))), + "'observed' is the survey count" + ) +}) + +test_that("name collisions across parameters, fields, globals and reserved names are rejected", { + expect_compile_error( + compile_scenario(diag_model(params = list(age = 2)) |> step_survival(0.5) |> step_census()), + "'age' is used as both a parameter and a population field" + ) + expect_compile_error( + compile_scenario(diag_model(params = list(env = 2)) |> + step_environment(env = env_ar1(0.2)) |> step_survival(0.5)), + "'env' is used as both a parameter and a global" + ) + expect_compile_error( + compile_scenario(diag_model(params = list(N = 2)) |> step_survival(0.5)), + "'N' is used as both a parameter and a reserved name" + ) + expect_compile_error( + compile_scenario(diag_model(fields = list(obs = 0L)) |> step_survey(0.5, field = "obs")), + "'obs' is used as both a population field and a global" + ) +}) + +test_that("unknown, stale and dead overrides are hard errors; unused base parameters are not", { + model <- diag_model(params = list(K = 50, b = 0.5, releases = FALSE, n_release = 2)) |> + step_survival(~ rate("p_surv")) |> + step_introduce(~ n_release, fields = list(sex = "F", age = 1L), name = "release", + enabled = ~ releases) |> + step_census() + expect_compile_error(compile_scenario(model, overrides = list(n_relase = 3)), + "override 'n_relase' is not a parameter.*did you mean 'n_release'") + expect_compile_error( + compile_scenario(model, overrides = list(n_release = 3)), + "override 'n_release' has no effect: it is used only by the disabled step 2 'release'" + ) + expect_compile_error(compile_scenario(model, overrides = list(K = 3)), + "override 'K' has no effect: no step of model") + expect_compile_error(compile_scenario(model, overrides = list(releases = "yes")), + "override 'releases' must be a non-missing flag") + # the same override is live once the step is enabled + on <- compile_scenario(model, overrides = list(n_release = 3, releases = TRUE), n_runs = 1L) + expect_identical(vapply(on$processes, `[[`, character(1), "name"), + c("survival", "release", "census")) + audit <- describe_parameters(model) + expect_identical(audit$status[audit$parameter %in% c("K", "b")], c("unused", "unused")) + expect_match(audit$status[audit$parameter == "n_release"], "inactive") + expect_identical(describe_model(model)$unused, c("K", "b")) +}) + +test_that("disabling a step whose global is needed downstream is rejected", { + model <- diag_model(params = list(weather = FALSE)) |> + step_environment(env = env_ar1(0.2), enabled = ~ weather) |> + step_survival(~ shift_logit(rate("p_surv"), env)) |> step_census() + expect_compile_error( + compile_scenario(model), + "step 2 'survival' needs global 'env', which is written only by the disabled step 1 'environment'" + ) + expect_s3_class(compile_scenario(model, overrides = list(weather = TRUE)), "pva_scenario") +}) + +test_that("malformed vital-rate tables are rejected before any run", { + survive <- function(rates, formula = ~ rate("p_surv")) { + compile_scenario(diag_model(rates) |> step_survival(formula) |> step_census()) + } + expect_compile_error(survive(data.frame(age = c("0", "2+"), sex = "All", p_surv = c(0.5, 0.9))), + "step 1 'survival': rate\\(\"p_surv\"\\) has an age gap: sex F has no class for age 1") + expect_compile_error(survive(data.frame(age = c("0-1", "1+"), sex = "All", p_surv = c(0.5, 0.9))), + "step 1 'survival'.*age classes overlap for sex F") + females <- data.frame(age = c("0", "1+"), sex = "F", p_surv = c(0.5, 0.9)) + expect_compile_error(survive(females), "has no rows for sex M.*missing_sex = \"zero\"") + expect_s3_class(survive(females, ~ rate("p_surv", missing_sex = "zero")), "pva_scenario") + expect_compile_error(survive(data.frame(age = c("0", "1+"), sex = "All", p_surv = c(0.5, 1.2))), + "rate\\(\"p_surv\"\\) is used as a probability, but the table holds 1.2") + expect_compile_error(survive(data.frame(age = c("young", "1+"), sex = "All", p_surv = c(0.5, 0.9))), + "age must be whole ages, ranges") + expect_compile_error( + compile_scenario(diag_model(params = list(s = 1.3)) |> step_survival(~ s) |> step_census()), + "step 1 'survival' \\(probability\\): a probability must lie in \\[0, 1\\], but the value is 1.3" + ) + no_newborn <- data.frame(age = "1+", sex = "All", p_surv = 0.9) + expect_compile_error( + compile_scenario(diag_model(no_newborn) |> step_survival(~ rate("p_surv")) |> + step_reproduction(0.5, litter_poisson(1), offspring_sex_bernoulli(0.5)) |> + step_census()), + "has no class for sex F at age 0" + ) +}) + +test_that("invalid cohort counts and incomplete field types are rejected at construction", { + expect_compile_error(pva_model(init = data.frame(age = 1, sex = "F", n = -2), n_steps = 2L), + "cohort counts must be non-negative whole numbers") + expect_compile_error(pva_model(init = data.frame(age = 1, sex = "F", n = NA), n_steps = 2L), + "cohort counts must be non-negative whole numbers") + expect_compile_error(pva_model(init = data.frame(age = 1.5, females = 2, males = 1), n_steps = 2L), + "cohort ages must be non-negative whole numbers") + expect_compile_error(pva_model(init = data.frame(age = 1, sex = "X", n = 2), n_steps = 2L), + "cohort sex must be 'F' or 'M'") + expect_compile_error( + pva_model(init = data.frame(age = 1, sex = "F", n = 2), fields = list(mate_id = NA), n_steps = 2L), + "field 'mate_id' needs one typed default value" + ) + expect_compile_error( + pva_model(init = data.frame(age = 1, sex = "F", tag = 1.5), fields = list(tag = 0L), n_steps = 2L), + "field 'tag' has default type integer but the initial population stores double" + ) + # a custom field that newborns would lack is caught by name at compile time + patchy <- pva_model(init = data.frame(age = 2L, sex = c("F", "M"), n = 4L, patch_id = "A"), + n_steps = 2L) |> + step_reproduction(0.5, litter_poisson(1), offspring_sex_bernoulli(0.5)) |> step_census() + expect_compile_error(compile_scenario(patchy), + "process 'reproduction' creates individuals without initialising: patch_id") +}) + +test_that("imperative or impure code inside a formula is rejected", { + impure <- list( + list(~ { x <- 1; x }, "code block"), + list(~ (K <- 2), "contains assignment \\('<-'\\)"), + list(~ (K <<- 2), "contains assignment \\('<<-'\\)"), + list(~ (b = 2), "contains assignment \\('='\\)"), + list(~ (function(x) x)(1), "a function definition"), + list(~ set.seed(1), "seeding the random-number generator \\('set.seed'\\)"), + list(~ runif(1), "a random draw \\('runif'\\)"), + list(~ base::set.seed(1), "set.seed"), + list(~ Sys.time(), "reading the clock") + ) + for (case in impure) { + expect_compile_error( + compile_scenario(diag_model() |> step_survival(case[[1L]]) |> step_census()), + paste0("step 1 'survival' \\(probability\\).*", case[[2L]]) + ) + } + expect_error(diag_model() |> step_survival(p ~ K), "one-sided") +}) + +test_that("a survey_quota placed before its survey is rejected", { + model <- diag_model(params = list(trigger = 5)) |> + step_survival(0.9) |> + step_introduce(survey_quota(~ if (observed < trigger) 2 else 0, field = "obs", on_skip = 0L), + fields = list(sex = "F", age = 1L)) |> + step_survey(0.7, field = "obs") |> + step_census() + expect_compile_error( + compile_scenario(model), + "step 2 'introduction' reads the survey record 'obs' before step 3 'survey' writes it" + ) +}) + +test_that("ensemble designs are validated row by row before any seed is drawn", { + model <- diag_model(params = list(K = 50, releases = FALSE, n_release = 2)) |> + step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, K)) |> + step_introduce(~ n_release, fields = list(sex = "F", age = 1L), name = "release", + enabled = ~ releases) |> + step_census() + expect_compile_error(run_pva_ensemble(data.frame(Kx = 1:2), model, n_runs = 2L), + "design column 'Kx' is not a parameter of any supplied model.*did you mean 'K'") + expect_compile_error( + run_pva_ensemble(data.frame(releases = c(TRUE, FALSE), n_release = c(2, 3)), model, n_runs = 2L), + "design row 2: override 'n_release' has no effect" + ) + expect_compile_error( + run_pva_ensemble(data.frame(K = c(40, 60)), list(a = model, b = model), n_runs = 2L), + "needs a design column 'model'" + ) + expect_compile_error( + run_pva_ensemble(data.frame(model = c("a", "c")), list(a = model, b = model), n_runs = 2L), + "design row 2: the design column 'model' must name one of: a, b" + ) + # NA cells mean "no override", so a release size can sit beside disabled rows + design <- data.frame(label = c("none", "release"), releases = c(FALSE, TRUE), + n_release = c(NA, 3), stringsAsFactors = FALSE) + ensemble <- run_pva_ensemble(design, model, n_runs = 3L, seed = 8L, seed_by = TRUE) + expect_identical(ensemble$label, c("none", "release")) + expect_length(unique(ensemble$member_seed), 1L) +}) + +test_that("the ensemble cache hits on an unchanged model and misses after an edit", { + receipt <- tempfile() + summarise <- function(run, row) { + cat("ran\n", file = receipt, append = TRUE) + summarise_pva(run)[c("final_mean", "ema")] + } + build <- function(rates = diag_rates, K = 50) { + diag_model(rates, params = list(K = K, s = 1)) |> + step_survival(~ s * rate("p_surv") * ceiling_density_multiplier(N, K)) |> step_age() |> + step_census() + } + cache <- tempfile("model-cache") + design <- data.frame(s = c(1, 0.9)) + run <- function(model) { + run_pva_ensemble(design, model, n_runs = 4L, summarise = summarise, seed = 3L, + seed_by = TRUE, cache_dir = cache) + } + receipts <- function() length(readLines(receipt)) + first <- run(build()) + expect_identical(receipts(), 2L) + expect_identical(run(build()), first) + expect_identical(receipts(), 2L) # cache hit: nothing re-ran + run(build(K = 12)) # edited parameter + expect_identical(receipts(), 4L) + edited <- diag_rates + edited$p_surv[[2L]] <- 0.6 # edited rate-table cell + changed <- run(build(edited)) + expect_identical(receipts(), 6L) + expect_false(identical(changed$final_mean, first$final_mean)) + run(build() |> step_ceiling(40L)) # edited model structure + expect_identical(receipts(), 8L) + expect_identical(run(build()), first) # original inputs: recomputed, same answer +}) diff --git a/tests/testthat/test-model-oracles.R b/tests/testthat/test-model-oracles.R new file mode 100644 index 0000000..9fc9816 --- /dev/null +++ b/tests/testthat/test-model-oracles.R @@ -0,0 +1,124 @@ +test_that("O1a: the authored minimal model is bit-identical to its native twin", { + native <- run_scenario(native_minimal(), keep = keep_all) + authored <- run_scenario(compile_scenario(authored_minimal(), n_runs = 12L, seed = 2026L), + keep = keep_all) + expect_same_run(native, authored) + expect_true(all(summarise_accounting(authored)$reconciled)) +}) + +test_that("O1b: the adaptive genetic island matches under every management strategy", { + model <- authored_island() + overrides <- list(status_quo = list(), adaptive = list(adaptive = TRUE), fixed = list(fixed = TRUE)) + for (strategy in names(overrides)) { + native <- run_scenario(native_island(strategy), keep = keep_all) + scenario <- compile_scenario(model, overrides[[strategy]], n_runs = 6L, seed = 2026L) + authored <- run_scenario(scenario, keep = keep_all) + expect_same_run(native, authored) + expect_identical( + vapply(scenario$processes, `[[`, character(1), "name"), + vapply(native_island(strategy)$processes, `[[`, character(1), "name") + ) + # kinship stores and neutral alleles are part of the compared final states + expect_false(is.null(authored$states[[1L]]$kinship)) + expect_identical(authored$states[[1L]]$markers$n_loci, 8L) + } +}) + +test_that("O1c: the closure-free grizzly matches the shipped native lifecycle", { + grizzly <- grizzly_native_env() + for (mortality in c(0, 0.25)) { + parameters <- grizzly$grizzly_parameters(adult_female_mortality = mortality, + adult_male_mortality = mortality / 2) + native <- run_scenario(grizzly$grizzly_scenario(parameters, n_runs = 10L, n_steps = 12L, + seed = 1987L), keep = keep_all) + model <- authored_grizzly(mortality, mortality / 2) + authored <- run_scenario(compile_scenario(model, n_runs = 10L, seed = 1987L), keep = keep_all) + expect_same_run(native, authored) + } + expect_true(any(native$events$event_type == "death" & native$events$label == "loss_of_mother" & + native$events$value > 0)) +}) + +test_that("O1d: two-patch dispersal matches as a run and as paired and structural ensembles", { + native <- run_scenario(native_two_patch(), keep = keep_all) + authored <- run_scenario(compile_scenario(authored_two_patch(), n_runs = 6L, seed = 77L), + keep = keep_all) + expect_same_run(native, authored) + expect_true(any(authored$events$event_type == "patch_transition")) + + summarise <- function(run, row) { + cbind(summarise_pva(run, threshold = 10), B_final = mean(run$census$B[run$census$time == 13L])) + } + design <- data.frame(capacity = c(30, 30, 18), base_survival = c(0.8, 0.7, 0.8)) + native_design <- cbind(design, pair = 1L) + native_ensemble <- run_pva_ensemble( + native_design, + build = function(row) native_two_patch(row$capacity, row$base_survival), + n_runs = 5L, summarise = summarise, seed = 404L, seed_by = "pair" + ) + authored_ensemble <- run_pva_ensemble( + design, build = authored_two_patch(), n_runs = 5L, summarise = summarise, + seed = 404L, seed_by = TRUE + ) + shared <- setdiff(names(authored_ensemble), "pair") + expect_identical(as.data.frame(authored_ensemble)[shared], + as.data.frame(native_ensemble)[shared]) + expect_length(unique(authored_ensemble$member_seed), 1L) + expect_true(isTRUE(attr(authored_ensemble, "provenance")$seed_by)) + + # structural comparison: the same parameters with and without the dispersal step + structural <- data.frame(model = c("connected", "isolated", "connected"), + capacity = c(30, 30, 18), stringsAsFactors = FALSE) + native_structural <- run_pva_ensemble( + cbind(structural, pair = 1L), + build = function(row) native_two_patch(row$capacity, disperse = row$model == "connected"), + n_runs = 5L, summarise = summarise, seed = 405L, seed_by = "pair" + ) + authored_structural <- run_pva_ensemble( + structural, + build = list(connected = authored_two_patch(), isolated = authored_two_patch(disperse = FALSE)), + n_runs = 5L, summarise = summarise, seed = 405L, seed_by = TRUE + ) + shared <- setdiff(names(authored_structural), "pair") + expect_identical(as.data.frame(authored_structural)[shared], + as.data.frame(native_structural)[shared]) + expect_false(identical(authored_structural$final_mean[[1L]], authored_structural$final_mean[[2L]])) +}) + +test_that("O1: step order is biology - releases after or before total mortality", { + base <- pva_model(init = data.frame(age = 2L, sex = c("F", "M"), n = 3L), n_steps = 1L) + release <- function(model) { + step_introduce(model, count = 2L, fields = list(sex = c("F", "M"), age = 1L), name = "release") + } + after <- base |> step_survival(0) |> release() |> step_census() + before <- base |> release() |> step_survival(0) |> step_census() + run_after <- run_scenario(compile_scenario(after, n_runs = 3L, seed = 1L)) + run_before <- run_scenario(compile_scenario(before, n_runs = 3L, seed = 1L)) + final <- function(run) run$census$n_alive[run$census$phase == "interval"] + expect_identical(final(run_after), rep(2, 3L)) + expect_identical(final(run_before), rep(0, 3L)) + expect_identical(sum(run_after$accounting$deaths_introduced), 0L) + expect_identical(sum(run_before$accounting$deaths_introduced), 6L) + expect_identical(sum(run_after$accounting$introductions), 6L) + expect_true(all(summarise_accounting(run_before)$reconciled)) +}) + +test_that("O1e: surveys, weighted quotas and retained sires survive compilation unchanged", { + native_scenario <- native_herd() + scenario <- compile_scenario(authored_herd(), n_runs = 8L, seed = 1993L) + native <- run_scenario(native_scenario, keep = keep_all) + authored <- run_scenario(scenario, keep = keep_all) + expect_same_run(native, authored) + # the engine still recognises the survey and the cross-interval sire lookup + execution <- OpenPVA:::.prepare_execution(scenario$processes) + reference <- OpenPVA:::.prepare_execution(native_scenario$processes) + expect_identical(execution$survey, reference$survey) + expect_identical(execution$sire_lookup, reference$sire_lookup) + expect_identical(execution$snapshot_sires, reference$snapshot_sires) + expect_true(execution$has_survey) + fawns <- do.call(rbind, authored$ledgers) + fawns <- fawns[fawns$origin == "birth", ] + expect_gt(nrow(fawns), 0L) + expect_identical(run_scenario(scenario, validation = "fast", keep = keep_all)$ledgers, + authored$ledgers) +}) diff --git a/tests/testthat/test-model-parity.R b/tests/testthat/test-model-parity.R new file mode 100644 index 0000000..8788866 --- /dev/null +++ b/tests/testthat/test-model-parity.R @@ -0,0 +1,138 @@ +# O2: authored models are compiled here inside local function scopes, never in +# the global environment, and must run identically on fresh --vanilla workers. + +compiled_closures <- function(scenario) { + found <- list() + visit <- function(x) { + if (is.function(x)) { + found[[length(found) + 1L]] <<- x + } else if (is.list(x)) { + for (part in x) visit(part) + } + } + visit(lapply(scenario$processes, `[[`, "params")) + found +} + +test_that("compiled closures capture nothing from the global environment", { + local({ + for (scenario in list( + compile_scenario(authored_island(), list(adaptive = TRUE), n_runs = 2L), + compile_scenario(authored_two_patch(), n_runs = 2L), + compile_scenario(authored_herd(), n_runs = 2L) + )) { + callbacks <- scenario[c("init_fun", "processes", "initial_census")] + expect_length(OpenPVA:::.callback_bindings(callbacks), 0L) + for (closure in compiled_closures(scenario)) { + scope <- environment(closure) + if (is.null(scope)) next + expect_false(identical(scope, globalenv())) + expect_identical(topenv(scope), asNamespace("OpenPVA")) + } + } + }) +}) + +test_that("authored scenarios match serial execution on PSOCK and fork workers", { + local({ + scenarios <- list( + island = compile_scenario(authored_island(), list(adaptive = TRUE), n_runs = 6L, seed = 31L), + patches = compile_scenario(authored_two_patch(), n_runs = 6L, seed = 32L), + herd = compile_scenario(authored_herd(), n_runs = 6L, seed = 33L), + grizzly = compile_scenario(authored_grizzly(0.2, 0.1), n_runs = 6L, seed = 34L) + ) + for (scenario in scenarios) { + serial <- run_scenario(scenario, keep = keep_all) + socket <- run_scenario(scenario, parallel = TRUE, workers = 2L, backend = "psock", + keep = keep_all) + expect_same_run(serial, socket) + if (.Platform$OS.type != "windows") { + fork <- run_scenario(scenario, parallel = TRUE, workers = 2L, backend = "fork", + keep = keep_all) + expect_same_run(serial, fork) + } + } + }) +}) + +test_that("authored ensembles match serial execution on PSOCK and fork workers", { + local({ + design <- data.frame(model = c("connected", "isolated", "connected", "isolated"), + capacity = c(30, 30, 18, 18), stringsAsFactors = FALSE) + models <- list(connected = authored_two_patch(), isolated = authored_two_patch(FALSE)) + run <- function(...) { + run_pva_ensemble(design, models, n_runs = 4L, seed = 71L, seed_by = TRUE, ...) + } + serial <- run() + expect_identical(run(workers = 2L, backend = "psock"), serial) + if (.Platform$OS.type != "windows") { + expect_identical(run(workers = 2L, backend = "fork"), serial) + } + paired_by_column <- run_pva_ensemble(design, models, n_runs = 4L, seed = 71L, + seed_by = "capacity") + expect_length(unique(paired_by_column$member_seed), 2L) + independent <- run_pva_ensemble(design, models, n_runs = 4L, seed = 71L) + expect_length(unique(independent$member_seed), 4L) + }) +}) + +test_that("authoring and audit functions leave the caller's RNG untouched", { + model <- authored_island() + grDevices::pdf(NULL) + on.exit(grDevices::dev.off(), add = TRUE) + actions <- list( + pva_model = function() authored_island(), + compile_scenario = function() compile_scenario(model, list(adaptive = TRUE), n_runs = 2L), + describe_model = function() describe_model(model, list(fixed = TRUE)), + describe_parameters = function() describe_parameters(model), + describe_lifecycle = function() describe_lifecycle(model), + format_lifecycle = function() format_lifecycle(model, "mermaid"), + plot = function() plot(model), + print = function() utils::capture.output(print(model)) + ) + kind <- RNGkind() + had_seed <- exists(".Random.seed", envir = globalenv(), inherits = FALSE) + saved <- if (had_seed) get(".Random.seed", envir = globalenv()) + on.exit({ + do.call(RNGkind, as.list(kind)) + if (had_seed) assign(".Random.seed", saved, envir = globalenv()) + }, add = TRUE) + for (label in names(actions)) { + # (i) a caller with no seed still has none afterwards + if (exists(".Random.seed", envir = globalenv(), inherits = FALSE)) { + rm(".Random.seed", envir = globalenv()) + } + actions[[label]]() + expect_false(exists(".Random.seed", envir = globalenv(), inherits = FALSE), label = label) + # (ii) a pending Box-Muller normal is neither consumed nor discarded + set.seed(2718, normal.kind = "Box-Muller") + reference <- stats::rnorm(2L) + set.seed(2718, normal.kind = "Box-Muller") + stats::rnorm(1L) + before <- .GlobalEnv$.Random.seed + actions[[label]]() + expect_identical(.GlobalEnv$.Random.seed, before, label = label) + expect_identical(stats::rnorm(1L), reference[[2L]], label = label) + } +}) + +test_that("neutral markers and passive surveys leave demographic histories bit-identical", { + history <- function(model, overrides = list()) { + run <- run_scenario(compile_scenario(model, overrides, n_runs = 5L, seed = 90L), + keep = c("census", "ledger", "state")) + list(n = run$census$n_alive, + ledgers = lapply(run$ledgers, function(ledger) ledger[c("id", "sex", "age", "mother_id", + "father_id", "exit_time", "exit_type")]), + F = lapply(run$states, function(state) state$population$pedigree_F)) + } + with_markers <- authored_island() + without_markers <- with_markers + without_markers$settings$n_loci <- 0L + expect_identical(history(with_markers), history(without_markers)) + # a survey that nothing acts on draws only from its own substream + watched <- authored_island() + watched$steps <- watched$steps[!vapply(watched$steps, function(step) { + step$name %in% c("adaptive_release", "fixed_release") + }, logical(1))] + expect_identical(history(watched, list(adaptive = TRUE)), history(with_markers)) +}) diff --git a/vignettes/cookbook.Rmd b/vignettes/cookbook.Rmd new file mode 100644 index 0000000..4ad0ecc --- /dev/null +++ b/vignettes/cookbook.Rmd @@ -0,0 +1,485 @@ +--- +title: "A Model-Building Cookbook: PVAs from Tables and Ordered Steps" +output: + html: + options: + toc: true +--- + + + +`{r} if (!capabilities("png")) invisible(litedown::reactor(dev = "pdf"))` + +```{r setup, include=FALSE} +library(OpenPVA) +litedown::reactor(fig.width = 7.2, fig.height = 4) +``` + +This cookbook builds population viability analyses without writing a single R +function. A model has two parts that you keep apart: + +- **inputs**: a parameter table, a vital-rate table and a table of starting + cohorts, the kind of thing you already keep in a spreadsheet; +- **a lifecycle**: an ordered list of steps (survive, age, breed, count ...) + that reads top to bottom. + +Wherever a step needs a rate or a rule you write a short formula such as +`~ rate("p_surv")` or `~ age >= maturity`. OpenPVA checks every name in it, +then compiles the model into the same process objects a hand-written model +uses, so every tool in the package works on the result. The recipes use small +replicate counts so the page builds in seconds; raise `n_runs` for real work. + +## 1. Three tables, one lifecycle + +### The inputs + +The tables are typed inline here; `read.csv("parameters.csv")` reads the same +thing from a file. One parameter table serves the whole cookbook, so each +model below uses only some of its rows. + +```{r inputs} +parameters <- read.csv(strip.white = TRUE, text = " +parameter, value, unit, source +female_share, 0.5, proportion, assumed even sex ratio at birth +maturity, 2, years, field notes 2019-2024 +capacity, 60, animals, habitat survey +env_sd, 0.35, logit SD, variation in annual survival +env_phi, 0.3, correlation, between successive years +cyclone_p, 0.05, per year, regional cyclone record +cyclone_kill, 0.3, proportion, counts after the 2011 cyclone +lethal_equivalents, 3.14, per genome, published mammal and bird average +area, 6, ratio, source study area / island area +releases, FALSE, flag, management option +detect, 0.7, probability, double-observer trial +trigger, 25, animals, recovery plan +release_size, 4, animals, captive stock available +") + +rates <- read.csv(strip.white = TRUE, text = " +age, sex, p_surv, p_breed, litter +0, All, 0.50, 0, 0 +1, All, 0.75, 0.30, 1.2 +2+, All, 0.86, 0.70, 1.4 +") + +cohorts <- read.csv(strip.white = TRUE, text = " +age, females, males +0, 6, 6 +1, 4, 4 +2, 8, 7 +") +``` + +Age classes can be written `0`, `1-2` or `2+`, and `sex = All` shares a row +between the sexes. The cohort table could equally have the columns +`age, sex, n`. + +### The lifecycle + +```{r basic} +basic <- pva_model(parameters, rates, cohorts, n_steps = 15, name = "island") |> + step_survival(~ rate("p_surv")) |> + step_age() |> + step_reproduction( + breeding_probability = ~ rate("p_breed"), + litter_size = litter_poisson(~ rate("litter")), + offspring_sex = offspring_sex_bernoulli(~ female_share) + ) |> + step_census() +basic +``` + +Order is biology. Survival before ageing is mortality over the year just +lived; breeding before the census makes this a post-breeding count that +includes newborns. + +### Audit before you run + +`plot()` draws the compiled lifecycle and `describe_model()` reports what the +model will build: the cohorts, each step's formula with the values bound into +it, and where every parameter goes. Neither draws a random number. + +```{r basic-plot, fig.width = 7.6, fig.height = 3.6} +plot(basic) +``` + +```{r basic-audit} +audit <- describe_model(basic, life_table = list( + survival = ~ rate("p_surv"), + fecundity = ~ rate("p_breed") * rate("litter") * female_share +)) +audit$steps[, c("step", "name", "equations", "parameters")] +audit$parameters[1:4, c("parameter", "value", "status", "used_by", "unit", "source")] +audit$unused +``` + +Only `female_share` is active so far; the other rows are flagged as unused +until a later recipe gives them a job. Unused inputs are reported, not hidden. + +The `life_table` argument evaluates the authored rates for females of each age +and passes them to `life_table_metrics()`, the deterministic projection of the +same life cycle. We can first check its growth rate against the rates entered directly. + +```{r basic-life-table} +by_hand <- life_table_metrics( + survival = c(0.50, 0.75, 0.86), + fecundity = c(0, 0.30 * 1.2 * 0.5, 0.70 * 1.4 * 0.5) +) +c(authored = audit$life_table$lambda, by_hand = by_hand$lambda, + generation_time = audit$life_table$generation_time) +``` + +For a check in animals per year, start with the six newborn, four yearling +and eight adult females in the cohort table. Surviving newborns breed at the +yearling rate. The older survivors breed at the adult rate. Multiplying each +group by its breeding probability, mean litter and female share gives the +expected number of daughters at the first census. + +```{r first-daughters} +daughters <- 6 * 0.50 * 0.30 * 1.2 * 0.5 + + (4 * 0.75 + 8 * 0.86) * 0.70 * 1.4 * 0.5 +projected <- sum(audit$life_table$matrix[1, ] * cohorts$females) +stopifnot(isTRUE(all.equal(daughters, projected))) +c(hand = daughters, life_table = projected) +``` + +### Run it + +`compile_scenario()` produces an ordinary scenario for `run_scenario()`. + +```{r basic-run} +run <- basic |> compile_scenario(n_runs = 20, seed = 1) |> run_scenario() +all(summarise_accounting(run)$reconciled) +summarise_pva(run, threshold = 10)[c("p_ever_below", "p_ever_below_lower", + "p_ever_below_upper", "final_mean", "final_mcse")] +``` + +With 20 replicates, one extra crossing changes the estimated risk by five +percentage points. Use the reported 95% interval for risk and the Monte Carlo +standard error for mean abundance to choose the precision your decision needs. +Quadrupling the replicate count roughly halves the Monte Carlo standard error. + +## 2. Bad years, cyclones, crowding and inbreeding + +The next model keeps the same three tables and adds steps. `core` stops before +the census so that later recipes can extend it; a model is a plain value, and +adding a step returns a new model without changing the old one. + +```{r stochastic} +core <- pva_model(parameters, rates, cohorts, n_steps = 15, pedigree = TRUE, + name = "island, ceiling") |> + step_environment(weather = env_ar1(sd = ~ env_sd, phi = ~ env_phi)) |> + step_catastrophe(~ cyclone_p, mortality = ~ cyclone_kill, name = "cyclone") |> + step_survival( + ~ shift_logit(rate("p_surv"), weather) * + inbreeding_multiplier(pedigree_F, lethal_equivalents) + ) |> + step_age() |> + step_reproduction( + ~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share), + mate = mate_min_kinship(~ age >= maturity) + ) |> + step_ceiling(~ capacity) + +ceiling_model <- core |> step_census() +``` + +- `step_environment()` draws one autocorrelated deviate per year and stores it + as `weather`. Any later formula can read it; here it shifts survival on the + logit scale for every age class at once. +- `step_catastrophe()` is a cyclone in 5% of years that kills 30% of animals. +- `pedigree = TRUE` gives every animal an exact inbreeding coefficient, + `pedigree_F`, and `inbreeding_multiplier()` turns it into a survival cost. +- `step_ceiling()` truncates the population at `capacity`. + +A ceiling is the bluntest density dependence. Brook et al. (2000) fitted +smoother curves in which each class's survival falls with the number of +females counted at the start of the year. Their GAPPS script `G_R1_SS.IN` +reads, for young females, + +``` +census (sexes(females) var(fempop)) +set (rsurv = 1 - nrand(1,1)) +set (f0surv = ((0.9824 / (1 + ((0.00530 * fempop)^9.6625))) + (0.0280 * rsurv))) +``` + +The same three lines as steps, with the four classes' coefficients in a second +rate table: + +```{r smooth} +density_rates <- read.csv(strip.white = TRUE, text = " +age, sex, s_max, crowd, shape, s_sd +0, F, 0.9824, 0.00530, 9.6625, 0.0280 +1+, F, 0.9411, 0.00373, 6.8658, 0.0480 +0, M, 0.9843, 0.00619, 7.3205, 0.1253 +1+, M, 0.8237, 0.00487, 13.5832, 0.0373 +") + +smooth_model <- pva_model(parameters, list(vital = rates, density = density_rates), + cohorts, n_steps = 15, pedigree = TRUE, + name = "island, smooth density") |> + step_environment( + females = ~ sum(sex == "F"), # census (sexes(females) var(fempop)) + year = env_ar1(sd = 1) # set (rsurv = 1 - nrand(1,1)) + ) |> + step_survival( + ~ pmin(1, pmax(0, rate("s_max") / (1 + (rate("crowd") * area * females)^rate("shape")) + + rate("s_sd") * year)) * + inbreeding_multiplier(pedigree_F, lethal_equivalents) + ) |> + step_age() |> + step_reproduction( + ~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share), + mate = mate_min_kinship(~ age >= maturity) + ) |> + step_census() +``` + +`females` is a filtered census held for the rest of the year, exactly what +`CENSUS ... VAR(fempop)` did, and `area` rescales the published crowding +coefficients to this smaller island. The curve is ordinary arithmetic on +table columns, so no function was needed. + +```{r stochastic-run, fig.width = 7.6, fig.height = 3.6} +run_ceiling <- ceiling_model |> compile_scenario(n_runs = 16, seed = 2) |> run_scenario() +run_smooth <- smooth_model |> compile_scenario(n_runs = 16, seed = 2) |> run_scenario() +op <- par(mar = c(4.2, 4.4, 2.2, 1), las = 1, bty = "l") +plot(run_ceiling, threshold = 10, runs = 0L, col = "#1B6B78", ylim = c(0, 90), + main = "Ceiling (teal) and smooth female density (orange)") +plot(run_smooth, threshold = 10, runs = 0L, col = "#C97A24", add = TRUE) +par(op) +``` + +## 3. Seasons, dependent young and two patches + +### A seasonal lifecycle with maternal care + +In this grizzly-style year, bears age in spring, mate in summer, are hunted in +autumn and give birth in winter. A female with cubs under three does not mate, +and a cub that loses its mother dies. Both rules are conditions on the +individual records; `mate_id` is a custom field with a declared default. + +```{r grizzly} +bears <- data.frame( + sex = c(rep("F", 6), rep("M", 4), "F", "M"), age = c(rep(6, 10), 0, 0), + mother_id = c(rep(NA, 10), 1, 1), father_id = c(rep(NA, 10), 7, 7) +) + +grizzly <- pva_model( + params = list(weaning_age = 3, maturity_age = 5, s_cub = 0.78, s_adult = 0.93, + breeding = 0.7, litter = 2, harvest_f = 0.10, harvest_m = 0.20), + init = bears, fields = list(mate_id = NA_integer_), pedigree = TRUE, + n_steps = 12, name = "grizzly" +) |> + step_age(name = "spring_ageing") |> + step_survival(~ ifelse(age < weaning_age, s_cub, s_adult), name = "natural_survival") |> + step_mating( + eligible = ~ age >= maturity_age & + (sex == "M" | !(id %in% mother_id[age < weaning_age])), + name = "summer_mating" + ) |> + step_survival(~ 1 - ifelse(sex == "F", harvest_f, harvest_m), + eligible = ~ age >= maturity_age, cause = "harvest", name = "autumn_harvest") |> + step_survival(0, eligible = ~ age < weaning_age & !(mother_id %in% id), + cause = "loss_of_mother", name = "orphan_loss") |> + step_reproduction(~ breeding, litter_binomial(3, ~ litter, min_size = 1), + offspring_sex_bernoulli(0.5), mate = mate_from_field(), + name = "winter_birth") |> + step_census(list(n_alive = ~ N, dependent = ~ age < weaning_age, + adult_females = ~ sex == "F" & age >= maturity_age)) + +bear_run <- grizzly |> compile_scenario(n_runs = 15, seed = 1987) |> run_scenario() +losses <- bear_run$events[bear_run$events$event_type == "death", ] +round(tapply(losses$value, losses$label, sum) / 15, 1) # deaths per replicate, by cause +``` + +The founder table has one row per animal because two cubs start with a known +mother and father. A mother shot in autumn leaves orphans in the next step, +and a sire shot after mating still fathers the winter litter: the engine keeps +him because `mate_from_field()` reads the recorded mate. + +### Two patches + +Space is one more field. Here `patch_id` comes from the cohort table, +`rate(..., by = "patch_id")` looks survival up by patch, newborns inherit +their mother's patch, and yearlings move by a transition matrix. The two +patches share correlated bad years. + +```{r patches} +patch_rates <- read.csv(strip.white = TRUE, text = " +age, sex, patch_id, p_surv +0+, All, north, 0.84 +0+, All, south, 0.74 +") +patches <- c("north", "south") +moves <- matrix(c(0.9, 0.1, 0.2, 0.8), 2, byrow = TRUE, dimnames = list(patches, patches)) + +two_patch <- pva_model( + params = list(patches = patches, moves = moves, rho = 0.7, local_capacity = 25), + rates = patch_rates, + init = data.frame(age = 2, sex = rep(c("F", "M"), 2), n = 8, + patch_id = rep(patches, each = 2)), + n_steps = 12, pedigree = TRUE, name = "two patches" +) |> + step_environment( + weather = env_ar1(sd = 0.4, phi = 0.5, cor = spatial_correlation(~ patches, rho = ~ rho)) + ) |> + step_survival(~ shift_logit(rate("p_surv", by = "patch_id"), weather[patch_id])) |> + step_age() |> + step_reproduction( + ~ 0.9 * (age >= 1) * + beverton_holt_multiplier(patch_counts(patches)[patch_id], local_capacity, growth = 2), + litter_poisson(1.3), offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(~ age >= 1, by = "patch_id"), inherit = "patch_id" + ) |> + step_dispersal(transition = ~ moves, eligible = ~ age == 1) |> + step_census(~ c(n_alive = N, patch_counts(patches))) + +patch_run <- two_patch |> compile_scenario(n_runs = 12, seed = 77) |> run_scenario() +sapply(c("north", "south"), function(patch) { + summarise_trajectory(patch_run, metric = patch)$median[c(1, 7, 13)] +}) +``` + +## 4. Imperfect surveys and paired comparisons + +Managers rarely know the true count. `step_survey()` detects each animal with +probability `detect` and stores the count; `survey_quota()` turns that count +(called `observed`) into a number of animals to release. Both steps are +switched by the flag parameter `releases`, which is `FALSE` in the table. + +```{r managed} +managed <- core |> + step_survey(~ detect, when = ~ time %% 2 == 0, field = "count", enabled = ~ releases) |> + step_introduce( + count = survey_quota(~ if (observed < trigger) release_size else 0, + field = "count", on_skip = 0), + fields = list(sex = c("F", "M"), age = 2L), name = "release", enabled = ~ releases + ) |> + step_census() +``` + +`run_pva_ensemble()` takes the model directly. Each design column that names a +parameter overrides it for that row. Here `label` names the strategies, and +`seed_by = TRUE` runs every row on the same replicate seeds. + +```{r ensemble} +design <- data.frame( + label = c("No action", "Release 4", "Release 8"), + releases = c(FALSE, TRUE, TRUE), + release_size = c(NA, 4, 8) +) +options <- run_pva_ensemble( + design, managed, n_runs = 16, seed = 2026, seed_by = TRUE, + summarise = function(run, row) summarise_pva(run, threshold = 15) +) +options[, c("label", "p_ever_below", "p_ever_below_mcse", "ema", "final_mean")] +``` + +`release_size` is `NA` in the first row because that row has no release step +to use it. Overriding a parameter that cannot matter is an error, not a silent +no-op (see the last section). + +The same call compares model *structures*. Give a named list of models and a +`model` column: + +```{r structural} +structures <- data.frame(model = c("ceiling", "smooth"), + label = c("Hard ceiling", "Smooth female density")) +compared <- run_pva_ensemble( + structures, list(ceiling = ceiling_model, smooth = smooth_model), + n_runs = 16, seed = 2026, seed_by = TRUE, + summarise = function(run, row) summarise_pva(run, threshold = 15) +) +compared[, c("label", "p_ever_below", "ema", "final_mean")] +``` + +```{r ensemble-plot, fig.width = 7.6, fig.height = 3.4} +op <- par(mfrow = c(1, 2), mar = c(4.2, 4.4, 2.2, 1), las = 1, bty = "l") +plot(options, y = "ema", by = "label", xlab = "", ylab = "Expected minimum abundance", + cex.axis = 0.75, main = "Management options") +plot(compared, y = "ema", by = "label", xlab = "", ylab = "Expected minimum abundance", + cex.axis = 0.75, main = "Model structure") +par(op) +``` + +**What pairing does and does not do.** `seed_by = TRUE` gives every row the +same starting random-number stream for replicate 1, replicate 2 and so on, +which removes seed-to-seed noise from the contrast. It does not freeze the +weather: environmental draws and demographic draws come from the same stream, +so once two rows' populations differ they use that stream differently and +their environmental sequences drift apart. Read paired contrasts as "same +seeds", not "same years". Survey detections and neutral-marker inheritance use +their own separate streams, which is why adding a survey that nobody acts on +leaves a population's history unchanged. + +## 5. When a formula is not enough + +A formula must be a pure expression. Anything else is an ordinary OpenPVA +process, and `step_process()` places it at an exact position in the pipeline. +This one removes the oldest animal each year, between survival and ageing: + +```{r escape} +harvest_oldest <- pva_process( + name = "harvest_oldest", + run = function(state, context, params) { + if (!length(state$population$id)) return(pva_result(state)) + oldest <- which.max(state$population$age) + state$population$alive[oldest] <- FALSE + pva_result(state, pva_events("removal", length(oldest), "trophy")) + }, + requires = "population.age", writes = "population.alive", role = "management" +) + +hunted <- pva_model(parameters, rates, cohorts, n_steps = 15, name = "island, hunted") |> + step_survival(~ rate("p_surv")) |> + step_process(harvest_oldest) |> + step_age() |> + step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")), + offspring_sex_bernoulli(~ female_share)) |> + step_census() + +describe_lifecycle(hunted)[, c("step", "name", "role", "writes")] +hunted_run <- hunted |> compile_scenario(n_runs = 20, seed = 1) |> run_scenario() +all(summarise_accounting(hunted_run)$reconciled) +``` + +The custom step is checked like any other: had it forgotten its `removal` +event, strict validation would stop the run and name the process. A step also +accepts an R function wherever it accepts a formula, and `step_process()` +accepts any native constructor, such as `inbreeding_proxy_process()`. + +## Mistakes are caught before anything runs + +Every name in a formula, every override and every table is checked when the +model is compiled. The message names the step and the problem. + +```{r failfast, error = TRUE} +compile_scenario(basic |> step_ceiling(~ capcity)) + +compile_scenario(managed, overrides = list(release_size = 8)) + +late_survey <- core |> + step_introduce(survey_quota(~ if (observed < trigger) release_size else 0, field = "count"), + fields = list(sex = "F", age = 2L)) |> + step_survey(~ detect, field = "count") +compile_scenario(late_survey) +``` + +The misspelled parameter, the override of a release that is switched off and +the quota placed before its survey are all refused at once, before a single +random number is drawn. + +## Where to go next + +- `?lifecycle_steps` lists every step and everything a formula may contain. +- `?pva_model` and `?describe_model` cover the inputs and the audit. +- `vignette("workflow", package = "OpenPVA")` goes further into checking and + comparing runs, and `vignette("rosetta", package = "OpenPVA")` maps GAPPS, + Vortex and Leslie-matrix idioms to OpenPVA processes. diff --git a/vignettes/rosetta.Rmd b/vignettes/rosetta.Rmd index 5c17202..5c2cf93 100644 --- a/vignettes/rosetta.Rmd +++ b/vignettes/rosetta.Rmd @@ -333,7 +333,8 @@ cull <- removal_process( count = survey_quota(function(obs, state, context, params) { max(0L, round(obs$count / 0.7) - 30L) }, on_skip = 0L), - weights = function(pop, ...) ifelse(pop$sex == "M", 3, 1) + weights = function(pop, ...) ifelse(pop$sex == "M", 3, 1), + requires = "population.sex" ) untreated <- function(pop, state, context, params) { pop$sex == "F" & pop$age >= 4L & pop$treated_until <= context$time @@ -341,7 +342,8 @@ untreated <- function(pop, state, context, params) { dart <- assign_process( "treated_until", function(rows, pop, state, context, params) context$time + 4L, count = function(state, context, params) 3L * autumn(state, context, params), - eligible = untreated, event = "contracepted" + eligible = untreated, event = "contracepted", + requires = c("population.sex", "population.age") ) ``` @@ -354,7 +356,7 @@ rut <- mating_process( when = autumn, male_capacity = 5L, weights = function(pop, ...) pop$age, eligible = function(pop, state, context, params) { (pop$sex == "M" & pop$age >= 4L) | untreated(pop, state, context, params) - } + }, requires = c("population.age", "population.treated_until") ) fawn <- reproduction_process( function(pop, state, context, params) 0.9 * !autumn(state, context, params), @@ -373,7 +375,8 @@ herd <- scenario_spec( pedigree = TRUE, mate_field = "mate_id" ), processes = list(survey, cull, dart, rut, - survival_process(function(pop, ...) ifelse(pop$sex == "M", 0.85, 0.93)), + survival_process(function(pop, ...) ifelse(pop$sex == "M", 0.85, 0.93), + requires = "population.sex"), fawn, clear_sires, age_process(), census_process()), initial_census = census_process() ) diff --git a/vignettes/workflow.Rmd b/vignettes/workflow.Rmd index b8b2f85..5940af4 100644 --- a/vignettes/workflow.Rmd +++ b/vignettes/workflow.Rmd @@ -44,7 +44,7 @@ adaptive releases**, and a **fixed 12-year release schedule**. ```{r model} build_island <- function(name, strategy = c("status_quo", "adaptive", "fixed"), - n_runs = 40L, seed = 2026L) { + n_runs = 20L, seed = 2026L) { strategy <- match.arg(strategy) init_fun <- function() { @@ -257,14 +257,14 @@ design <- data.frame( ens <- run_pva_ensemble( design = design, build = function(row) build_island(row$label, row$strategy), - n_runs = 40L, + n_runs = 20L, summarise = function(run, row) summarise_pva(run, threshold = 15), seed = 2026L, seed_by = "pair" ) stopifnot(length(unique(ens$member_seed)) == 1L) -ens[, c("label", "p_ever_below", "ema", "final_mean")] +ens[, c("label", "p_ever_below", "p_ever_below_lower", "p_ever_below_upper", "ema", "final_mean")] ``` Finally, contrast the three management options alongside neutral genetic @@ -290,7 +290,8 @@ legend("bottomleft", c("Survey-triggered", "Status quo"), par(op) ``` -Notice how survey-triggered supplementation both slashes 30-year quasi-extinction -risk and arrests the erosion of neutral heterozygosity—and every diagnostic -figure was drawn directly from reproducible base-R `OpenPVA` summaries with no -external plotting dependencies. +Each strategy has 20 replicates, so one additional run below 15 animals +changes its estimated 30-year risk by five percentage points. The table gives +the 95% Wilson interval for each risk estimate. The genetic trajectories show +median heterozygosity among surviving populations. More replicates would be +needed to estimate the size of a management effect with precision. From 9a0ce24478c1d0fc79549dae2b31f9a4ba151e80 Mon Sep 17 00:00:00 2001 From: "Barry W. Brook" Date: Fri, 4 Dec 2026 19:55:56 +1100 Subject: [PATCH 2/3] fix(R-4.1.0): guard unique() on 0-column newborn strata in .check_rate_coverage() --- R/rates.R | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/R/rates.R b/R/rates.R index 21da8fe..f15b139 100644 --- a/R/rates.R +++ b/R/rates.R @@ -166,13 +166,15 @@ validate_age_sex_table <- function(table, value, by = NULL) { occupied <- rbind(occupied, added) } if (length(newborn_fields)) { - strata <- if (length(spec$by)) unique(occupied[spec$by]) else data.frame(row.names = 1L) - if (!nrow(strata)) strata <- unique(table[spec$by]) + strata <- if (length(spec$by)) unique(occupied[spec$by, drop = FALSE]) else data.frame(row.names = 1L) + if (!nrow(strata) && length(spec$by)) strata <- unique(table[spec$by, drop = FALSE]) for (defaults in newborn_fields) { newborn <- strata - fixed <- intersect(spec$by, names(defaults)) - newborn[fixed] <- defaults[fixed] - newborn <- unique(newborn) + if (length(spec$by)) { + fixed <- intersect(spec$by, names(defaults)) + if (length(fixed)) newborn[fixed] <- defaults[fixed] + newborn <- unique(newborn) + } newborn$age <- rep(0L, nrow(newborn)) for (sex in c("F", "M")) { newborn$sex <- rep(sex, nrow(newborn)) From a301523e243f06a874a2155493a166478c9dc326 Mon Sep 17 00:00:00 2001 From: "Barry W. Brook" Date: Fri, 4 Dec 2026 19:56:50 +1100 Subject: [PATCH 3/3] fix(R-4.1.0): drop redundant drop=FALSE on 1-arg data-frame subsetting in R/rates.R --- R/rates.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/R/rates.R b/R/rates.R index f15b139..f3fda17 100644 --- a/R/rates.R +++ b/R/rates.R @@ -166,8 +166,8 @@ validate_age_sex_table <- function(table, value, by = NULL) { occupied <- rbind(occupied, added) } if (length(newborn_fields)) { - strata <- if (length(spec$by)) unique(occupied[spec$by, drop = FALSE]) else data.frame(row.names = 1L) - if (!nrow(strata) && length(spec$by)) strata <- unique(table[spec$by, drop = FALSE]) + strata <- if (length(spec$by)) unique(occupied[spec$by]) else data.frame(row.names = 1L) + if (!nrow(strata) && length(spec$by)) strata <- unique(table[spec$by]) for (defaults in newborn_fields) { newborn <- strata if (length(spec$by)) {