Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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"))
Expand All @@ -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
Expand Down
26 changes: 26 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down
73 changes: 73 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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("<column>")` 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
Expand Down
93 changes: 58 additions & 35 deletions R/ensemble.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)) {
Expand All @@ -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))
Expand All @@ -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))
Expand All @@ -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 {
Expand All @@ -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")
Expand Down
Loading
Loading