From 75211626a445da4687e7b696fe8315c61fc2e764 Mon Sep 17 00:00:00 2001 From: "Barry W. Brook" Date: Mon, 30 Nov 2026 11:31:23 +1100 Subject: [PATCH 1/4] OpenPVA 2.1.0: kinship mating, neutral gene-drop, correlated environments, plots, Rosetta vignette --- .github/workflows/ci-fast.yaml | 43 ++- AGENTS.md | 20 +- DESCRIPTION | 22 +- NAMESPACE | 11 + NEWS.md | 51 +++ R/ancestry.R | 51 ++- R/ensemble.R | 155 +++++--- R/markers.R | 287 +++++++++++++++ R/mating.R | 157 ++++++++ R/pedigree.R | 95 ++++- R/plot.R | 175 +++++++++ R/process.R | 39 +- R/processes_demography.R | 3 +- R/processes_environment.R | 203 ++++++++++ R/processes_management.R | 55 ++- R/scenario.R | 11 +- R/state.R | 52 ++- README.md | 23 +- docs/design/lifecycle_process_contract.md | 36 +- docs/dev_conventions_r.md | 7 +- docs/reference/public_api.md | 22 +- inst/CITATION | 2 +- man/environment_processes.Rd | 43 ++- man/inbreeding.Rd | 12 +- man/management_processes.Rd | 15 +- man/markers.Rd | 59 +++ man/plot.pva_run.Rd | 71 ++++ man/print.pva_state.Rd | 9 +- man/pva_state.Rd | 8 +- man/reproduction_helpers.Rd | 15 +- man/run_pva_ensemble.Rd | 2 +- man/summaries.Rd | 26 +- scripts/benchmark_kinship_mating.R | 95 +++++ scripts/build_rd.R | 23 +- scripts/check_r_floor.R | 36 +- scripts/rd_topics.R | 182 +++++++-- tests/testthat/helper-genetics.R | 138 +++++++ tests/testthat/test-environment.R | 208 +++++++++++ tests/testthat/test-kinship-mating.R | 313 ++++++++++++++++ tests/testthat/test-markers.R | 428 ++++++++++++++++++++++ tests/testthat/test-oracle-extinction.R | 2 +- tests/testthat/test-oracle-matrix.R | 5 +- tests/testthat/test-plots.R | 164 +++++++++ tests/testthat/test-rng-parity.R | 52 +++ tests/testthat/test-summaries-ensemble.R | 69 ++++ vignettes/rosetta.Rmd | 363 ++++++++++++++++++ 46 files changed, 3655 insertions(+), 203 deletions(-) create mode 100644 R/markers.R create mode 100644 R/mating.R create mode 100644 R/plot.R create mode 100644 man/markers.Rd create mode 100644 man/plot.pva_run.Rd create mode 100644 scripts/benchmark_kinship_mating.R create mode 100644 tests/testthat/helper-genetics.R create mode 100644 tests/testthat/test-environment.R create mode 100644 tests/testthat/test-kinship-mating.R create mode 100644 tests/testthat/test-markers.R create mode 100644 tests/testthat/test-plots.R create mode 100644 vignettes/rosetta.Rmd diff --git a/.github/workflows/ci-fast.yaml b/.github/workflows/ci-fast.yaml index 20aacdf..5ee1c5a 100644 --- a/.github/workflows/ci-fast.yaml +++ b/.github/workflows/ci-fast.yaml @@ -16,6 +16,9 @@ jobs: os: [ubuntu-24.04, macos-latest, windows-latest] r: [release] include: + - os: ubuntu-24.04 + r: release + manual: true - os: ubuntu-24.04 r: '4.1.0' defaults: @@ -31,13 +34,43 @@ jobs: run: | sudo apt-get update sudo apt-get install -y --no-install-recommends libuv1-dev - - name: Install test dependencies - run: Rscript --vanilla -e 'install.packages("testthat", repos = "https://cloud.r-project.org"); stopifnot(requireNamespace("testthat", quietly = TRUE))' - - name: Build and check + - name: Install a LaTeX distribution for the PDF manual + if: matrix.manual + uses: r-lib/actions/setup-tinytex@v2 + - name: Install HTML validators for the Linux release check + if: matrix.manual + run: | + sudo apt-get install -y --no-install-recommends tidy libnode-dev + Rscript --vanilla -e 'install.packages("V8", repos = "https://cloud.r-project.org"); stopifnot(requireNamespace("V8", quietly = TRUE))' + - name: Install LaTeX packages for the PDF manual + if: matrix.manual + run: tlmgr install inconsolata helvetic makeindex + - name: Install test and vignette dependencies + run: Rscript --vanilla -e 'install.packages(c("testthat", "litedown"), repos = "https://cloud.r-project.org"); stopifnot(requireNamespace("testthat", quietly = TRUE), requireNamespace("litedown", quietly = TRUE))' + - name: Build with the vignette run: | - R CMD build --no-build-vignettes . - R CMD check --as-cran --no-manual OpenPVA_*.tar.gz + R CMD build . + tar -tzf OpenPVA_*.tar.gz | grep 'inst/doc/rosetta.html' + - name: Check + env: + _R_CHECK_SYSTEM_CLOCK_: "0" + run: | + R CMD check --as-cran ${{ matrix.manual && ' ' || '--no-manual' }} OpenPVA_*.tar.gz if grep -Eq '^Status:.*(ERROR|WARNING)' OpenPVA.Rcheck/00check.log; then exit 1; fi + - name: Verify Linux release check notes + if: matrix.manual + run: | + Rscript --vanilla - <<'RS' + log <- readLines("OpenPVA.Rcheck/00check.log") + if (!"Status: OK" %in% log) { + stopifnot("Status: 1 NOTE" %in% log) + incoming <- grep("^\\* checking CRAN incoming feasibility .* NOTE$", log) + stopifnot(length(incoming) == 1L) + body <- tail(log, -incoming) + body <- trimws(head(body, match(TRUE, startsWith(body, "* ")) - 1L)) + stopifnot(identical(body[nzchar(body) & !startsWith(body, "Maintainer:")], "New submission")) + } + RS - name: Verify the minimum interpreter and clean socket workers if: matrix.r == '4.1.0' run: | diff --git a/AGENTS.md b/AGENTS.md index 41767d0..fe016ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,14 +12,15 @@ 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.0.0) +## Core architecture (OpenPVA 2.1.0) - **One unified, pure-base-R engine:** `NeedsCompilation: no`, `Depends: R (>= 4.1.0)`, and runtime `Imports` restricted to base/recommended packages (`codetools`, - `parallel`, `stats`, `tools`, `utils`). Do not add `dplyr`, `tibble`, `renv` - boilerplate, a lifecycle DSL, a global registry, an S4/R6 hierarchy, or a - second compiled sidecar engine unless a measured, unavoidable bottleneck proves - pure R inadequate. + `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 + measured, unavoidable bottleneck proves pure R inadequate. - **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. @@ -29,10 +30,11 @@ inspectable, individual-based Population Viability Analyses in ordinary R. a shared pre-process state. - **Engine-owned invariants:** The engine owns interval time, consecutive IDs, preassigned per-replicate L'Ecuyer-CMRG RNG streams (bit-identical across - serial, fork, and PSOCK workers; caller `.Random.seed` restored on explicit - seeds), cohort-by-origin accounting, and exact conditional pedigree inbreeding + serial, fork, and PSOCK workers; caller `.Random.seed` and Box–Muller cache + preserved), cohort-by-origin accounting, exact conditional pedigree inbreeding (value-semantic dense kinship store up to `max_dense_kinship`, switching cleanly - to sparse ancestor tracing in `R/ancestry.R` above that threshold). + to sparse ancestor tracing in `R/ancestry.R` above that threshold), and optional + non-perturbing neutral-locus gene-drop genotypes (`R/markers.R`). ## Development and verification rules @@ -47,7 +49,7 @@ inspectable, individual-based Population Viability Analyses in ordinary R. - **Standard local checks:** ```sh Rscript --vanilla scripts/run_tests.R - R CMD build --no-build-vignettes . + R CMD build . R CMD check --as-cran --no-manual OpenPVA_*.tar.gz bash scripts/benchmark_gate.sh ``` diff --git a/DESCRIPTION b/DESCRIPTION index 7654b2f..b2d7aa9 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,8 +1,8 @@ Package: OpenPVA Title: Composable Individual-Based Population Viability Analysis -Version: 2.0.1 +Version: 2.1.0 Authors@R: - person("Barry W.", "Brook", email = "bwbrook@users.noreply.github.com", + person("Barry W.", "Brook", email = "barry.brook@utas.edu.au", role = c("aut", "cre", "cph")) Description: An execution engine for individual-based population viability analysis in which a life cycle is a direct ordered list of ordinary R @@ -11,23 +11,31 @@ Description: An execution engine for individual-based population viability random-number streams, cohort-level accounting, exact pedigree inbreeding coefficients and provenance. Reusable processes cover survival, reproduction with several litter-size distributions, pairing - and territory limits, removals, introductions, environmental variation, - catastrophes, density feedback and inbreeding depression. Ensemble - helpers separate structural and parametric designs from Monte Carlo - replicates and report viability summaries with Monte Carlo standard - errors. + and territory limits, kinship-aware mate choice, removals, + introductions, temporally and spatially correlated environmental + variation, catastrophes, density feedback and inbreeding depression. + Optional neutral loci are dropped through the simulated pedigree to + report heterozygosity, allelic retention and founder representation. + 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 trajectories, + risk and accounting. License: MIT + file LICENSE Encoding: UTF-8 Depends: R (>= 4.1.0) Imports: codetools, + graphics, + grDevices, parallel, stats, tools, utils NeedsCompilation: no Suggests: + litedown, testthat (>= 3.0.0) +VignetteBuilder: litedown Config/testthat/edition: 3 URL: https://github.com/BWBrook/OpenPVA BugReports: https://github.com/BWBrook/OpenPVA/issues diff --git a/NAMESPACE b/NAMESPACE index d933803..8b0e12a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,3 +1,6 @@ +S3method(plot,pva_ensemble) +S3method(plot,pva_run) +S3method(print,pva_ensemble) S3method(print,pva_process) S3method(print,pva_run) S3method(print,pva_scenario) @@ -12,8 +15,11 @@ export(ceiling_density_multiplier) export(ceiling_process) export(census_process) export(dispersal_process) +export(env_ar1) +export(env_trend) export(environment_process) export(execute_processes) +export(genetic_metrics) export(inbreeding_multiplier) export(inbreeding_proxy_process) export(introduction_process) @@ -21,9 +27,12 @@ export(kinship_matrix) export(litter_binomial) export(litter_categorical) export(litter_poisson) +export(marker_founder_shares) export(markov_dispersal_process) export(mate_from_field) +export(mate_min_kinship) export(mate_random) +export(mean_kinship) export(offspring_sex_bernoulli) export(pairing_process) export(patch_counts) @@ -40,7 +49,9 @@ export(run_scenario) export(scenario_spec) export(sex_ratio_effective_size) export(shift_logit) +export(spatial_correlation) export(summarise_accounting) +export(summarise_markers) export(summarise_pedigree) export(summarise_pva) export(summarise_trajectory) diff --git a/NEWS.md b/NEWS.md index c286a07..3221dd0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,56 @@ # OpenPVA news +## OpenPVA 2.1.0 + +- Kinship-aware mating. `mate_min_kinship()` gives each female the least + related eligible male, up to `max_kinship`. `pairing_process(priority = + "kinship")` solves an exact assignment: the largest number of pairs that + `capacity` and `max_kinship` allow and, among those, the smallest total + kinship. With `priority = "mean_kinship"`, scarce territories go first to + breeders with low mean kinship to the living population. Pair kinship + breaks ties. Both mating rules accept `by = "patch_id"` for local mating. + The dense and traced stores resolve half-grid ties consistently on the + 2^-30 comparison grid. +- `mean_kinship()` returns each individual's mean kinship with the living + population. `summarise_pedigree()` adds founder genome equivalents, + computed from the sum of living kinships, and `kinship_matrix(against = )` + returns a rectangular block for two sets of IDs. +- Optional neutral-locus gene drop: `pva_state(n_loci = )`. The engine owns + the genotypes and draws segregation from a stream of its own, so enabling + loci changes no demographic outcome of a seeded run. `summarise_markers()`, + `marker_founder_shares()` and `genetic_metrics()` report heterozygosity, + allelic richness, retention of the starting alleles and founder shares. + Initialization and subsequent segregation have distinct substreams even + for a family built inside an ensemble builder. Marker draws preserve the + caller's Box–Muller normal cache. Introductions bring new alleles. +- `summarise_trajectory()` accepts metrics that are missing for extinct + replicates and reports `n_observed`, `n_extant` and the quartiles. All + replicates contribute to cumulative crossing risk and its Wilson limits. + `summarise_accounting()` checks each process receipt and cohort stock. +- Correlated environments. `env_ar1()` generates anomalies that are + autocorrelated in time and correlated among patches or rates, with a + stationary start and a pivoted Cholesky factor that accepts perfect + synchrony. Named inputs align by component. `spatial_correlation()` + supplies equicorrelation or exponential distance decay. `env_trend()` + accepts time-indexed levels and callbacks. + `environment_process()` passes each variable its name as + `context$variable`. +- Base-graphics `plot()` methods for `pva_run` (trajectory fan, cumulative + risk and accounting views) and for ensembles. `run_pva_ensemble()` now + returns class `pva_ensemble` with a print method. Run plots support + `add = TRUE`, and annotations use the plotted coordinates. +- A vignette, "A GAPPS, Vortex and Leslie-matrix Rosetta Stone for OpenPVA", + built with `litedown`. +- Traced kinship blocks use vectorised passes over the ancestor graph. +- *Development provenance:* Developed under Barry W. Brook's direction using + independent multi-model sessions coordinated through `BWBrook/research-advisor`: + 2.1.0 backbone architecture and final B5 diff audit by Anthropic Claude + Fable 5.2; B4 hardening, harvest integration, and R 4.1.0/CRAN verification + by OpenAI Codex (`gpt-6.2-astra`); cross-critique and targeted feature design + (`spatial_correlation()`, patch-stratified `by` mating, `add = TRUE`, + `print.pva_ensemble()`) from Google Gemini 4 Carbon (High); independent + verification and adjudication by Google Gemini 4 Neon. + ## OpenPVA 2.0.1 - `age_sex_rate()` now reports an error when a living individual's sex is diff --git a/R/ancestry.R b/R/ancestry.R index 2fae91f..bb97b55 100644 --- a/R/ancestry.R +++ b/R/ancestry.R @@ -38,7 +38,7 @@ .graph_covariance <- function(graph, source, target) { n <- length(graph$rows) weight <- numeric(n + 1L) - weight[source] <- 1 / length(source) + weight[source] <- 1 for (i in rev(graph$children)) { half <- 0.5 * weight[i] m <- graph$mother[i] @@ -92,14 +92,48 @@ ped } +# Kinship of every source with every target in one pass over the graph. Each +# step is vectorised over sources, which are taken in blocks to bound memory. +.graph_block <- function(graph, source, target) { + n <- length(graph$rows) + out <- matrix(0, length(source), length(target)) + size <- max(1L, 4e6 %/% (n + 1L)) + mother <- graph$mother + father <- graph$father + b <- graph$base + for (first in seq.int(1L, length.out = ceiling(length(source) / size), by = size)) { + block <- seq.int(first, min(length(source), first + size - 1L)) + s <- length(block) + weight <- matrix(0, s, n + 1L) + weight[cbind(seq_len(s), source[block])] <- 1 + for (i in rev(graph$children)) { + half <- 0.5 * weight[, i] + weight[, mother[i]] <- weight[, mother[i]] + half + weight[, father[i]] <- weight[, father[i]] + half + } + value <- weight * rep(c(graph$d, 0), each = s) + if (length(b)) value[, b] <- weight[, b, drop = FALSE] %*% graph$base_K + for (i in graph$children) { + value[, i] <- value[, i] + 0.5 * (value[, mother[i]] + value[, father[i]]) + } + out[block, ] <- value[, target, drop = FALSE] + } + out +} + +.ancestry_block <- function(ped, a, b) { + if (!length(a) || !length(b)) return(matrix(0, length(a), length(b))) + graph <- .ancestor_graph(ped, c(a, b)) + a <- match(a, graph$rows) + b <- match(b, graph$rows) + forward <- .graph_block(graph, a, b) + reverse <- if (identical(a, b)) forward else .graph_block(graph, b, a) + 0.5 * (forward + t(reverse)) +} + .ancestry_matrix <- function(ped, ids) { rows <- match(ids, ped$id) - graph <- .ancestor_graph(ped, rows) - local <- match(rows, graph$rows) - n <- length(rows) - out <- matrix(0, n, n) - for (i in seq_len(n)) out[, i] <- .graph_covariance(graph, local[i], local) - out + .ancestry_block(ped, rows, rows) } .initial_ancestry <- function(pop) { @@ -109,9 +143,6 @@ if (any(m == 0L & !is.na(pop$mother_id)) || any(f == 0L & !is.na(pop$father_id))) { .stop("unresolvable initial parent ID: supply an aligned initial kinship matrix") } - if (any(pop$sex[m] != "F") || any(pop$sex[f] != "M")) { - .stop("initial parentage has a non-female mother or non-male father") - } rows <- which(m == 0L & f == 0L) ped <- .ancestry_base(pop$id[rows]) position <- integer(n) diff --git a/R/ensemble.R b/R/ensemble.R index 23eeb54..5689980 100644 --- a/R/ensemble.R +++ b/R/ensemble.R @@ -1,4 +1,5 @@ -.census_matrix <- function(result, metric, process_name, include_initial, occurrence) { +.census_matrix <- function(result, metric, process_name, include_initial, occurrence, + allow_extinct = FALSE) { complete_run <- inherits(result, "pva_run") census <- if (complete_run) result$census else result if (!is.data.frame(census) || @@ -8,62 +9,84 @@ if (!.is_name(metric) || !is.numeric(census[[metric]])) { .stop("metric must name one numeric census column") } - interval <- census[census$phase == "interval", , drop = FALSE] - if (!nrow(interval)) { + interval <- which(census$phase == "interval") + if (!length(interval)) { .stop("the census has no interval rows; add a census_process() to the lifecycle") } runs <- if (complete_run) seq_len(result$scenario$n_runs) else sort(unique(census$run)) - times <- if (complete_run) seq_len(result$scenario$n_steps) - 1L else sort(unique(interval$time)) + times <- if (complete_run) seq_len(result$scenario$n_steps) - 1L else sort(unique(census$time[interval])) if (is.null(process_name)) { - process_name <- unique(interval$process_name) + process_name <- unique(census$process_name[interval]) if (length(process_name) != 1L) { .stop("multiple interval census processes; select one with process_name") } } - if (!.is_name(process_name) || !(process_name %in% interval$process_name)) { + if (!.is_name(process_name) || !(process_name %in% census$process_name[interval])) { .stop("process_name must identify an interval census process") } - interval <- interval[interval$process_name == process_name, , drop = FALSE] - if (is.null(interval$occurrence)) interval$occurrence <- 1L + interval <- interval[census$process_name[interval] == process_name] + positions <- if (is.null(census$occurrence)) rep.int(1L, length(interval)) else census$occurrence[interval] if (is.null(occurrence)) { - occurrence <- unique(interval$occurrence) + occurrence <- unique(positions) if (length(occurrence) != 1L) { .stop("census process '", process_name, "' is repeated; select an occurrence") } } occurrence <- .as_count(occurrence, "occurrence", minimum = 1L) - interval <- interval[interval$occurrence == occurrence, , drop = FALSE] - index <- match(interval$run, runs) + (match(interval$time, times) - 1) * length(runs) + interval <- interval[positions == occurrence] + index <- match(census$run[interval], runs) + (match(census$time[interval], times) - 1) * length(runs) if (length(index) != length(runs) * length(times) || anyNA(index) || anyDuplicated(index)) { .stop("census process '", process_name, "' must report exactly once per interval and run") } - values <- matrix(NA_real_, length(runs), length(times)) - values[index] <- interval[[metric]] + rows <- matrix(NA_integer_, length(runs), length(times)) + rows[index] <- interval years <- times + 1L if (is.null(include_initial)) { include_initial <- if (complete_run) !is.null(result$scenario$initial_census) else any(census$phase == "initial") } if (!.is_flag(include_initial)) .stop("include_initial must be TRUE, FALSE or NULL") if (include_initial) { - initial <- census[census$phase == "initial", , drop = FALSE] - index <- match(runs, initial$run) - if (nrow(initial) != length(runs) || anyNA(index) || !isTRUE(all(initial$time == 0))) { + initial <- which(census$phase == "initial") + index <- match(runs, census$run[initial]) + if (length(initial) != length(runs) || anyNA(index) || !isTRUE(all(census$time[initial] == 0))) { .stop("include_initial = TRUE needs exactly one initial census row per run") } - values <- cbind(initial[[metric]][index], values) + rows <- cbind(initial[index], rows) years <- c(0L, years) } - if (any(!is.finite(values))) .stop("selected census metric must be finite for every observation") - list(values = values, years = years, process_name = process_name, occurrence = occurrence) + values <- matrix(as.numeric(census[[metric]][rows]), nrow = length(runs)) + n_extant <- rep.int(NA_integer_, ncol(values)) + invalid <- !is.finite(values) + if (allow_extinct && "n_alive" %in% names(census)) { + abundance <- matrix(census[["n_alive"]][rows], nrow = length(runs)) + if (!is.numeric(abundance) || any(!is.finite(abundance))) { + .stop("n_alive must be finite for every selected census observation") + } + n_extant <- as.integer(colSums(abundance > 0)) + invalid <- invalid & !(is.na(values) & !is.nan(values) & abundance == 0) + } + if (any(invalid)) { + .stop("selected census metric must be finite for every observation", + if (allow_extinct) "; NA is allowed only when the same census records n_alive = 0") + } + list(values = values, years = years, process_name = process_name, occurrence = occurrence, + n_extant = n_extant) } -.proportion_summary <- function(indicator, prefix) { - n <- length(indicator) - p <- mean(indicator) +# Wilson score interval for a Monte Carlo proportion p estimated from n runs. +.wilson <- function(p, n) { z <- stats::qnorm(0.975) centre <- (p + z^2 / (2 * n)) / (1 + z^2 / n) half <- z * sqrt(p * (1 - p) / n + z^2 / (4 * n^2)) / (1 + z^2 / n) - out <- list(p, sqrt(p * (1 - p) / n), max(0, centre - half), min(1, centre + half)) + list(lower = ifelse(p == 0, 0, pmax(0, centre - half)), + upper = ifelse(p == 1, 1, pmin(1, centre + half))) +} + +.proportion_summary <- function(indicator, prefix) { + n <- length(indicator) + p <- mean(indicator) + interval <- .wilson(p, n) + out <- list(p, sqrt(p * (1 - p) / n), interval$lower, interval$upper) names(out) <- paste0(prefix, c("", "_mcse", "_lower", "_upper")) out } @@ -126,28 +149,43 @@ summarise_trajectory <- function( if (!is.numeric(threshold) || length(threshold) != 1L || is.na(threshold)) { .stop("threshold must be one number") } - census <- .census_matrix(result, metric, process_name, include_initial, occurrence) + census <- .census_matrix(result, metric, process_name, include_initial, occurrence, + allow_extinct = TRUE) values <- census$values n_runs <- nrow(values) - quantiles <- apply(values, 2L, stats::quantile, probs = c(0.05, 0.5, 0.95), names = FALSE) + n_observed <- colSums(!is.na(values)) + quantiles <- apply(values, 2L, stats::quantile, probs = c(0.05, 0.25, 0.5, 0.75, 0.95), + names = FALSE, na.rm = TRUE) below <- values < threshold - ever <- t(apply(below, 1L, cummax)) - if (ncol(values) == 1L) { - ever <- matrix(ever, ncol = 1L) + crossed <- rep.int(FALSE, n_runs) + p_ever <- numeric(ncol(values)) + for (year in seq_len(ncol(values))) { + crossed <- crossed | (!is.na(below[, year]) & below[, year]) + p_ever[year] <- mean(crossed) } + centre <- colMeans(values, na.rm = TRUE) + prevalence <- colMeans(below, na.rm = TRUE) + centre[n_observed == 0L] <- prevalence[n_observed == 0L] <- NA_real_ + interval <- .wilson(p_ever, n_runs) data.frame( year = census$years, metric = metric, census_process = census$process_name, census_occurrence = census$occurrence, n_runs = n_runs, - mean = colMeans(values), - mcse = apply(values, 2L, stats::sd) / sqrt(n_runs), + n_extant = census$n_extant, + n_observed = as.integer(n_observed), + mean = centre, + mcse = apply(values, 2L, stats::sd, na.rm = TRUE) / sqrt(n_observed), q05 = quantiles[1L, ], - median = quantiles[2L, ], - q95 = quantiles[3L, ], - p_below = colMeans(below), - p_ever_below = colMeans(ever), + q25 = quantiles[2L, ], + median = quantiles[3L, ], + q75 = quantiles[4L, ], + q95 = quantiles[5L, ], + p_below = prevalence, + p_ever_below = p_ever, + p_ever_below_lower = interval$lower, + p_ever_below_upper = interval$upper, stringsAsFactors = FALSE ) } @@ -161,30 +199,49 @@ summarise_accounting <- function(result) { accounting$run <- 1L } key <- interaction(accounting$run, accounting$time, drop = TRUE, lex.order = TRUE) + key <- match(key, unique(key)) + sequence <- order(key, accounting$process_index, method = "radix") + if (is.unsorted(sequence)) { + accounting <- accounting[sequence, , drop = FALSE] + key <- key[sequence] + } first <- !duplicated(key) last <- !duplicated(key, fromLast = TRUE) - total <- function(field) as.integer(rowsum(accounting[[field]], key, reorder = FALSE)[, 1L]) + flows <- accounting[.accounting_columns[4:11]] + running <- function(delta) stats::ave(as.numeric(delta), key, FUN = cumsum) + n_start <- accounting$n_before[first] + resident <- n_start[key] - running(flows$deaths_resident + flows$removals_resident) + born <- running(flows$births - flows$deaths_born - flows$removals_born) + introduced <- running(flows$introductions - flows$deaths_introduced - flows$removals_introduced) + expected <- resident + born + introduced + broken <- resident < 0 | born < 0 | introduced < 0 | accounting$n_after != expected + following <- which(!first) + broken[following] <- broken[following] | + accounting$n_before[following] != accounting$n_after[following - 1L] + broken[is.na(broken)] <- TRUE out <- data.frame( run = accounting$run[first], time = accounting$time[first], - n_start = accounting$n_before[first], - births = total("births"), - introductions = total("introductions"), - deaths_resident = total("deaths_resident"), - deaths_born = total("deaths_born"), - deaths_introduced = total("deaths_introduced"), - removals_resident = total("removals_resident"), - removals_born = total("removals_born"), - removals_introduced = total("removals_introduced"), - n_end = accounting$n_after[last] + n_start = n_start, + rowsum(flows, key, reorder = FALSE), + n_end = accounting$n_after[last], + expected_end = expected[last] ) - losses <- with(out, deaths_resident + deaths_born + deaths_introduced + - removals_resident + removals_born + removals_introduced) - out$reconciled <- out$n_start + out$births + out$introductions - losses == out$n_end + out$residual <- out$n_end - out$expected_end + out$reconciled <- rowsum(as.integer(broken), key, reorder = FALSE)[, 1L] == 0L rownames(out) <- NULL out } +print.pva_ensemble <- function(x, ...) { + prov <- attr(x, "provenance") + cat(sprintf("\n", + nrow(x), if (is.null(prov$n_runs)) "?" else prov$n_runs, + if (is.null(prov$root_seed)) "?" else prov$root_seed)) + NextMethod("print") + invisible(x) +} + .default_ensemble_summary <- function(result, row) summarise_pva(result) run_pva_ensemble <- function( @@ -271,9 +328,11 @@ run_pva_ensemble <- function( .rbind_frames(summaries) ) rownames(out) <- NULL + class(out) <- c("pva_ensemble", "data.frame") attr(out, "provenance") <- list( root_seed = seed, n_runs = n_runs, + design = names(design), seed_by = seed_by, validation = validation, package_version = version, diff --git a/R/markers.R b/R/markers.R new file mode 100644 index 0000000..c6f951e --- /dev/null +++ b/R/markers.R @@ -0,0 +1,287 @@ +# Neutral-locus gene drop. The engine owns state$markers, a list with +# n_loci number of unlinked neutral loci; +# id individuals with a stored genotype: the living, plus those lost +# earlier in the current interval (a sire may die before birth); +# alleles integer matrix with one row per id; columns 1..L hold the +# maternally inherited copy of each locus and L+1..2L the paternal; +# source for every allele label, the individual it entered with; +# n_native labels issued to the initial population (labels 1..n_native); +# seed state of a marker-only L'Ecuyer stream. +# Segregation draws come from that stream, so enabling markers never moves the +# demographic stream. With n_loci = 0 the slot is NULL and nothing here runs. +# +# Substreams of one L'Ecuyer stream, counted from its start: 0 demography, +# 1 ensemble builders, 2 initial gene drop in init_fun, 3 initial gene drop +# in a builder, 4 subsequent segregation in each replicate's own stream. + +.marker_stream <- function(seed, ahead) { + for (step in seq_len(ahead)) seed <- parallel::nextRNGSubStream(seed) + seed +} + +.with_marker_rng <- function(expr) { + old <- .GlobalEnv$.Random.seed + if (is.null(old)) { + stats::runif(1L) + initial <- .GlobalEnv$.Random.seed + on.exit({ + # Restore the uniform generator R will use when no binding exists. + assign(".Random.seed", initial, envir = .GlobalEnv) + stats::runif(1L) + rm(".Random.seed", envir = .GlobalEnv) + }) + } else { + on.exit(assign(".Random.seed", old, envir = .GlobalEnv)) + } + expr +} + +.marker_seed <- function() { + seed <- .GlobalEnv$.Random.seed + if (!is.null(seed) && seed[1L] %% 100L == 7L) return(.marker_stream(seed, 2L)) + .with_marker_rng({ + # Positive 31-bit words satisfy both CMRG moduli and seed each component. + words <- as.integer(stats::runif(6L, 1, .Machine$integer.max)) + c(.GlobalEnv$.Random.seed[1L] %/% 100L * 100L + 7L, words) + }) +} + +.marker_uniform <- function(seed, n) { + .with_marker_rng({ + # Changing only the uniform kind preserves Box-Muller's cached normal, + # which R keeps outside .Random.seed. Keep the stored stream portable. + header <- seed[1L] + seed[1L] <- .GlobalEnv$.Random.seed[1L] %/% 100L * 100L + 7L + assign(".Random.seed", seed, envir = .GlobalEnv) + u <- stats::runif(n) + advanced <- .GlobalEnv$.Random.seed + advanced[1L] <- header + list(u = u, seed = advanced) + }) +} + +.marker_init <- function(population, n_loci) { + mother <- match(population$mother_id, population$id, 0L) + father <- match(population$father_id, population$id, 0L) + if (any(mother == 0L & !is.na(population$mother_id)) || + any(father == 0L & !is.na(population$father_id))) { + .stop("neutral loci need every initial parent ID to identify an initial individual") + } + markers <- list( + n_loci = n_loci, id = integer(), alleles = matrix(0L, 0L, 2L * n_loci), + source = integer(), n_native = 0L, seed = .marker_seed() + ) + done <- logical(length(population$id)) + while (!all(done)) { + resolved <- c(TRUE, done) + ready <- which(!done & resolved[mother + 1L] & resolved[father + 1L]) + if (!length(ready)) .stop("cyclic initial parentage") + markers <- .marker_add(markers, population$id[ready], + population$mother_id[ready], population$father_id[ready]) + done[ready] <- TRUE + } + markers <- .marker_release(markers, population$id) + markers$n_native <- length(markers$source) + markers +} + +# Each offspring copy is one of that parent's two copies, drawn independently +# per locus. An unknown parent contributes one new allele label. +.marker_add <- function(markers, ids, mother_id, father_id) { + n <- length(ids) + n_loci <- markers$n_loci + new <- matrix(NA_integer_, n, 2L * n_loci) + parents <- list(mother_id, father_id) + for (side in 1:2) { + unknown <- is.na(parents[[side]]) + parent <- match(parents[[side]], markers$id) + if (anyNA(parent[!unknown])) { + .stop("a parent has no stored genotype: parents must be living or lost in this interval") + } + value <- rep(NA_integer_, n * n_loci) + if (!all(unknown)) { + # One draw per known parent and locus, from the marker stream only. + known <- parent[!unknown] + draw <- .marker_uniform(markers$seed, length(known) * n_loci) + markers$seed <- draw$seed + column <- rep(seq_len(n_loci), each = length(known)) + n_loci * (draw$u >= 0.5) + value[rep(!unknown, n_loci)] <- markers$alleles[cbind(rep(known, n_loci), column)] + } + if (any(unknown)) { + issued <- length(markers$source) + if (issued > .Machine$integer.max - sum(unknown)) { + .stop("the allele label allocator would overflow") + } + markers$source <- c(markers$source, ids[unknown]) + value[rep(unknown, n_loci)] <- rep(issued + seq_len(sum(unknown)), n_loci) + } + new[, (side - 1L) * n_loci + seq_len(n_loci)] <- value + } + markers$id <- c(markers$id, ids) + markers$alleles <- rbind(markers$alleles, new) + markers +} + +.marker_release <- function(markers, ids) { + if (!identical(markers$id, ids)) { + markers$alleles <- markers$alleles[match(ids, markers$id), , drop = FALSE] + markers$id <- ids + } + markers +} + +.marker_living <- function(state) { + .marker_release(state$markers, state$population$id)$alleles +} + +.valid_marker_seed <- function(seed) { + if (!is.integer(seed) || !is.null(dim(seed)) || length(seed) != 7L || + !seed[1L] %in% c(7L + (0:5) * 100L, 10007L + (0:5) * 100L)) return(FALSE) + # R stores the unsigned words as signed integers, including the NA bit pattern. + words <- as.double(seed[-1L]) + words[is.na(words)] <- 2^31 + negative <- words < 0 + words[negative] <- words[negative] + 2^32 + first <- words[1:3] + last <- words[4:6] + all(first < 4294967087) && all(last < 4294944443) && any(first > 0) && any(last > 0) +} + +.validate_markers <- function(markers, population, next_id, at_entry) { + ids <- population$id + if (!is.list(markers) || !.is_count(markers$n_loci, 1L) || !is.integer(markers$id) || + !is.null(dim(markers$id)) || anyNA(markers$id) || any(markers$id < 1L | markers$id >= next_id) || + is.unsorted(markers$id, strictly = TRUE) || anyNA(match(ids, markers$id)) || + (at_entry && !identical(ids, markers$id)) || + !is.matrix(markers$alleles) || !is.integer(markers$alleles) || + !all(dim(markers$alleles) == c(length(markers$id), 2 * markers$n_loci)) || + anyNA(markers$alleles) || any(markers$alleles < 1L | markers$alleles > length(markers$source)) || + !is.integer(markers$source) || !is.null(dim(markers$source)) || anyNA(markers$source) || + any(markers$source < 1L | markers$source >= next_id) || + anyDuplicated(markers$source[duplicated(markers$source)]) || + !.is_count(markers$n_native) || markers$n_native > length(markers$source) || + !.valid_marker_seed(markers$seed)) { + .stop("invalid neutral-locus store") + } + native <- markers$n_native + if (native && native < length(markers$source) && + max(markers$source[seq_len(native)]) >= min(markers$source[-seq_len(native)])) { + .stop("invalid neutral-locus store: native and later sources overlap") + } + rows <- match(ids, markers$id) + maternal <- is.na(population$mother_id) + paternal <- is.na(population$father_id) + issued <- tabulate(match(markers$source, ids, 0L), length(ids)) + if (any(issued != maternal + paternal) || + any(markers$source[markers$alleles[rows[maternal], 1L]] != ids[maternal]) || + any(markers$source[markers$alleles[rows[paternal], markers$n_loci + 1L]] != ids[paternal])) { + .stop("invalid neutral-locus store: allele sources disagree with recorded parentage") + } + invisible(markers) +} + +# A supplied founder kinship matrix is accepted with markers only when recorded +# parentage explains it; otherwise unique founder alleles would misstate it. +.check_explained_kinship <- function(population, kinship) { + n <- length(population$id) + .validate_kinship(kinship, n) + implied <- .ancestry_matrix(.initial_ancestry(population), population$id) + if (n && max(abs(implied - kinship)) > 1e-12) { + .stop( + "neutral loci need starting kinship explained by recorded parentage: ", + "the supplied kinship matrix implies other founder relationships" + ) + } + invisible(TRUE) +} + +.marker_metric_names <- c( + "observed_heterozygosity", "expected_heterozygosity", "allelic_richness", + "allelic_retention", "native_share" +) + +.marker_summary <- function(alleles, n_loci, n_native) { + n <- nrow(alleles) + out <- stats::setNames(rep(NA_real_, 5L), .marker_metric_names) + if (!n) { + out["allelic_richness"] <- 0 + if (n_native > 0L) out["allelic_retention"] <- 0 + return(out) + } + loci <- seq_len(n_loci) + span <- max(alleles) + 1 + key <- sort.int(as.vector(alleles) + span * rep(rep(loci - 1L, each = n), 2L)) + first <- c(TRUE, key[-1L] != key[-length(key)]) + count <- diff(c(which(first), length(key) + 1L)) + native <- key[first] %% span <= n_native + copies <- 2 * n + out[] <- c( + mean(alleles[, loci] != alleles[, n_loci + loci]), + 1 - sum(count^2) / (n_loci * copies^2), + length(count) / n_loci, + if (n_native) sum(native) / (n_loci * n_native) else NA_real_, + sum(count[native]) / (n_loci * copies) + ) + out +} + +.require_markers <- function(state) { + state <- .validate_state(state) + if (is.null(state$markers)) { + .stop("neutral loci are not enabled for this state; use pva_state(n_loci = ...)") + } + state +} + +summarise_markers <- function(state) { + state <- .require_markers(state) + markers <- state$markers + cbind( + data.frame( + n_living = length(state$population$id), + n_loci = markers$n_loci, + n_native_alleles = markers$n_native + ), + as.list(.marker_summary(.marker_living(state), markers$n_loci, markers$n_native)) + ) +} + +marker_founder_shares <- function(state) { + state <- .require_markers(state) + markers <- state$markers + alleles <- .marker_living(state) + count <- tabulate(alleles, nbins = length(markers$source)) + total <- rowsum(count, markers$source) + id <- as.integer(rownames(total)) + native <- id %in% markers$source[seq_len(markers$n_native)] + share <- if (length(alleles)) total[, 1L] / length(alleles) else rep(NA_real_, length(id)) + keep <- native | total[, 1L] > 0 + data.frame(id = id[keep], native = native[keep], share = unname(share[keep])) +} + +genetic_metrics <- function() { + function(pop, state, context, params) { + n <- length(pop$id) + out <- c(n_alive = n) + if (!is.null(state$kinship)) { + total <- if (n) sum(.kinship_row_sums(state, seq_len(n))) else NA_real_ + kinship <- total / n^2 + out <- c( + out, + mean_inbreeding = if (n) mean(pop$pedigree_F) else NA_real_, + mean_kinship = kinship, + gene_diversity = 1 - kinship, + founder_genome_equivalents = n^2 / (2 * total) + ) + } + if (!is.null(state$markers)) { + out <- c(out, .marker_summary( + .marker_living(state), state$markers$n_loci, state$markers$n_native + )) + } + if (length(out) == 1L) { + .stop("genetic_metrics() needs pva_state(pedigree = TRUE) or n_loci > 0") + } + out + } +} diff --git a/R/mating.R b/R/mating.R new file mode 100644 index 0000000..18d93ac --- /dev/null +++ b/R/mating.R @@ -0,0 +1,157 @@ +# Kinship-aware mate choice. Scores are kinships on the 2^-30 grid (whole +# numbers held as doubles), so all comparisons and sums below are exact. + +mate_min_kinship <- function(eligible = NULL, max_kinship = Inf, ties = c("random", "id"), + by = NULL) { + .check_optional_function(eligible, "eligible") + limit <- .kinship_limit(max_kinship) + ties <- match.arg(ties) + requirement <- .mating_group_requirement(by) + chooser <- function(pop, state, context, params) { + .require_kinship(state, "mate_min_kinship()") + n <- length(pop$id) + out <- rep(NA_integer_, n) + females <- which(pop$sex == "F") + males <- .eligible_rows(eligible, pop, state, context, params) + males <- males[pop$sex[males] == "M"] + # One draw per female whatever the kinship store or the number of ties. + pick <- if (ties == "random") stats::runif(length(females)) else numeric(length(females)) + if (!length(females) || !length(males)) { + return(out) + } + score <- .kinship_score(.kinship_block(state, females, males)) + score <- .restrict_mating_group(score, pop, by, females, males) + best <- score[, 1L] + for (j in seq_along(males)[-1L]) best <- pmin(best, score[, j]) + tied <- score == best + wanted <- floor(pick * rowSums(tied)) + 1 + seen <- numeric(length(females)) + choice <- integer(length(females)) + for (j in seq_along(males)) { + seen <- seen + tied[, j] + hit <- tied[, j] & seen == wanted + choice[hit] <- j + } + admissible <- is.finite(best) & best <= limit + out[females[admissible]] <- males[choice[admissible]] + out + } + attr(chooser, "mate_requires") <- requirement + chooser +} + +.mating_group_requirement <- function(by) { + if (is.null(by)) return(NULL) + if (!.is_name(by)) .stop("by must be NULL or one population field name") + paste0("population.", by) +} + +.restrict_mating_group <- function(score, pop, by, females, males) { + if (is.null(by)) return(score) + group <- pop[[by]] + if (is.null(group) || anyNA(group)) { + .stop("population field ", by, " must be present and non-missing") + } + score[outer(group[females], group[males], "!=")] <- Inf + score +} + +.kinship_limit <- function(max_kinship) { + if (!is.numeric(max_kinship) || length(max_kinship) != 1L || is.na(max_kinship) || + max_kinship < 0) { + .stop("max_kinship must be one non-negative number (Inf for no limit)") + } + .kinship_score(max_kinship) +} + +# Minimum-cost assignment of every row to a distinct column (rows <= columns), +# by shortest augmenting paths with row and column potentials. Each step of +# the inner loop is vectorised over columns. Ties resolve to the lowest column. +.assignment <- function(cost, dual = FALSE) { + n_rows <- nrow(cost) + n_cols <- ncol(cost) + by_row <- t(cost) + u <- numeric(n_rows) + v <- numeric(n_cols) + owner <- integer(n_cols) + for (i in seq_len(n_rows)) { + way <- integer(n_cols) + reach <- rep(Inf, n_cols) + used <- logical(n_cols) + row <- i + col <- 0L + repeat { + free <- which(!used) + reduced <- by_row[free, row] - u[row] - v[free] + better <- reduced < reach[free] + reach[free[better]] <- reduced[better] + way[free[better]] <- col + nearest <- free[which.min(reach[free])] + delta <- reach[nearest] + tree <- c(i, owner[used]) + u[tree] <- u[tree] + delta + v[used] <- v[used] - delta + reach[free] <- reach[free] - delta + col <- nearest + used[col] <- TRUE + row <- owner[col] + if (row == 0L) break + } + repeat { + previous <- way[col] + owner[col] <- if (previous == 0L) i else owner[previous] + col <- previous + if (col == 0L) break + } + } + if (dual) list(row = u, column = v) else match(seq_len(n_rows), owner) +} + +# Pairs (row, column) of a score matrix in which Inf marks an inadmissible +# pair. The result has the largest possible number of admissible pairs not +# exceeding `capacity` and, among all such sets, the smallest total score. +.min_kinship_pairs <- function(score, capacity, breeder_cost = NULL) { + flipped <- nrow(score) > ncol(score) + if (flipped) { + score <- t(score) + if (!is.null(breeder_cost)) breeder_cost <- t(breeder_cost) + } + a <- nrow(score) + b <- ncol(score) + wanted <- as.integer(min(capacity, a)) + empty <- matrix(0L, 0L, 2L) + if (wanted < 1L || !b) { + return(empty) + } + admissible <- is.finite(score) + blocked <- !all(admissible) + # A row left without a real partner costs more than any set of real pairs. + cost <- if (is.null(breeder_cost)) score else breeder_cost + alone <- wanted * max(0, cost[admissible]) + 1 + cost[!admissible] <- 2 * alone + # Rows beyond the capacity are parked at a cost below any real pair. + cost <- cbind( + cost, + matrix(-1, a, a - wanted), + if (blocked) matrix(alone, a, wanted) + ) + if (!is.null(breeder_cost)) { + # An assignment minimises breeder cost exactly when it uses only tight + # edges and covers every column with negative dual potential. Among those + # assignments minimise pair kinship on its original integer grid. + dual <- .assignment(cost, dual = TRUE) + tight <- cost == outer(dual$row, dual$column, "+") + cost[,] <- 0 + cost[, seq_len(b)] <- score + mandatory <- dual$column < 0 + bonus <- wanted * max(0, score[admissible]) + 1 + cost[, mandatory] <- cost[, mandatory, drop = FALSE] - bonus + cost[!tight] <- Inf + } + column <- .assignment(cost) + rows <- which(column <= b) + rows <- rows[admissible[cbind(rows, column[rows])]] + pairs <- cbind(rows, column[rows]) + if (flipped) pairs <- pairs[order(pairs[, 2L]), 2:1, drop = FALSE] + unname(pairs) +} diff --git a/R/pedigree.R b/R/pedigree.R index 97d7cf7..8b997a9 100644 --- a/R/pedigree.R +++ b/R/pedigree.R @@ -57,7 +57,8 @@ store } -.kinship_births <- function(store, pop, n_before, context, dead_females, limit) { +# Known parents are living, or were lost earlier in the same interval. +.check_parents <- function(pop, n_before, context, dead_females) { new <- seq.int(n_before + 1L, length(pop$id)) m <- pop$mother_id[new] f <- pop$father_id[new] @@ -69,6 +70,13 @@ .stop("process '", context$process_name, "' supplied an unknown parent ID, non-female mother or non-male father in this interval") } + invisible(TRUE) +} + +.kinship_births <- function(store, pop, n_before, limit) { + new <- seq.int(n_before + 1L, length(pop$id)) + m <- pop$mother_id[new] + f <- pop$father_id[new] if (!is.null(store$values)) { store <- .dense_materialise(store) occupied <- which(!is.na(store$ids)) @@ -124,16 +132,68 @@ state } -kinship_matrix <- function(state, ids = state$population$id) { - store <- state$kinship - if (is.null(store)) .stop("pedigree tracking is not enabled for this state") - rows <- match(ids, state$population$id) +.living_kinship_rows <- function(ids, living) { + rows <- match(ids, living) if (anyNA(rows) || anyDuplicated(rows)) .stop("ids must identify distinct living individuals") - if (is.matrix(store)) return(store[rows, rows, drop = FALSE]) - if (is.null(store$values)) return(.ancestry_matrix(store, ids)) + rows +} + +kinship_matrix <- function(state, ids = state$population$id, against = ids) { + if (is.null(state$kinship)) .stop("pedigree tracking is not enabled for this state") + living <- state$population$id + rows <- .living_kinship_rows(ids, living) + columns <- if (missing(against)) rows else .living_kinship_rows(against, living) + .kinship_block(state, rows, columns) +} + +# Kinship of population rows a with rows b, without building the full matrix. +.kinship_block <- function(state, a, b) { + store <- state$kinship + ids <- state$population$id + if (is.matrix(store)) return(store[a, b, drop = FALSE]) + if (is.null(store$values)) { + return(.ancestry_block(store, match(ids[a], store$id), match(ids[b], store$id))) + } store <- .dense_materialise(store) - slots <- match(ids, store$ids) - store$values[slots, slots, drop = FALSE] + store$values[match(ids[a], store$ids), match(ids[b], store$ids), drop = FALSE] +} + +# Sum of kinships with every living individual, itself included. +.kinship_row_sums <- function(state, rows) { + store <- state$kinship + living <- seq_along(state$population$id) + if (is.list(store) && is.null(store$values)) { + all <- match(state$population$id, store$id) + graph <- .ancestor_graph(store, all) + local <- match(all, graph$rows) + return(.graph_covariance(graph, local, local[rows])) + } + rowSums(.kinship_block(state, rows, living)) +} + +# The dense recurrence and traced covariance can differ by a few ulps at an +# exact half-grid boundary. Resolve that numerical tie with round-to-even. +.kinship_score <- function(kinship) { + scaled <- kinship * 1073741824 + half <- floor(scaled) + 0.5 + tied <- is.finite(scaled) & abs(scaled - half) <= 8 * .Machine$double.eps * abs(scaled) + scaled[tied] <- half[tied] + round(scaled) +} + +.require_kinship <- function(state, caller) { + if (is.null(state$kinship)) { + .stop(caller, " needs exact kinship: create the state with pva_state(pedigree = TRUE)") + } + invisible(state) +} + +mean_kinship <- function(state, ids = state$population$id) { + state <- .validate_state(state) + if (is.null(state$kinship)) .stop("pedigree tracking is not enabled for this state") + rows <- .living_kinship_rows(ids, state$population$id) + if (!length(rows)) return(numeric()) + .kinship_row_sums(state, rows) / length(state$population$id) } summarise_pedigree <- function(state) { @@ -147,27 +207,22 @@ summarise_pedigree <- function(state) { mean_inbreeding = NA_real_, max_inbreeding = NA_real_, mean_kinship = NA_real_, - gene_diversity = NA_real_ + gene_diversity = NA_real_, + founder_genome_equivalents = NA_real_ )) } coefficient <- state$population$pedigree_F founders <- is.na(state$population$mother_id) & is.na(state$population$father_id) - store <- state$kinship - mean_kinship <- if (is.list(store) && is.null(store$values)) { - rows <- match(state$population$id, store$id) - graph <- .ancestor_graph(store, rows) - living <- match(rows, graph$rows) - mean(.graph_covariance(graph, living, living)) - } else { - mean(kinship_matrix(state)) - } + total_kinship <- sum(.kinship_row_sums(state, seq_len(n))) + mean_kinship <- total_kinship / n^2 data.frame( n_living = n, n_founders = as.integer(sum(founders)), mean_inbreeding = mean(coefficient), max_inbreeding = max(coefficient), mean_kinship = mean_kinship, - gene_diversity = 1 - mean_kinship + gene_diversity = 1 - mean_kinship, + founder_genome_equivalents = n^2 / (2 * total_kinship) ) } diff --git a/R/plot.R b/R/plot.R new file mode 100644 index 0000000..30a9b22 --- /dev/null +++ b/R/plot.R @@ -0,0 +1,175 @@ +.plot_frame <- function(x, y, defaults, dots, add = FALSE) { + if (add) return(invisible(NULL)) + settings <- utils::modifyList(defaults, dots) + do.call(graphics::plot.default, c(list(x = x, y = y, type = "n"), settings)) +} + +.plot_range <- function(..., fallback = c(0, 1)) { + values <- c(...) + values <- values[is.finite(values)] + if (length(values)) range(values) else fallback +} + +# A ribbon between two curves, drawn separately over each run of years in +# which both are defined. +.plot_ribbon <- function(x, lower, upper, col, step = FALSE) { + if (step) { + corners <- rep(seq_along(x), each = 2L) + x <- x[corners[-1L]] + heights <- corners[-length(corners)] + lower <- lower[heights] + upper <- upper[heights] + } + ok <- !is.na(lower) & !is.na(upper) + group <- cumsum(c(TRUE, diff(ok) != 0L)) + for (piece in unique(group[ok])) { + rows <- which(group == piece) + if (length(rows) > 1L) { + graphics::polygon(c(x[rows], rev(x[rows])), c(lower[rows], rev(upper[rows])), + col = col, border = NA) + } else { + graphics::segments(x[rows], lower[rows], x[rows], upper[rows], col = col, lwd = 3) + } + } +} + +plot.pva_run <- function( + x, + type = c("trajectory", "risk", "accounting"), + metric = "n_alive", + threshold = 1, + runs = 20L, + process_name = NULL, + include_initial = NULL, + occurrence = NULL, + add = FALSE, + ...) { + type <- match.arg(type) + runs <- .as_count(runs, "runs") + if (!.is_flag(add)) .stop("add must be TRUE or FALSE") + dots <- list(...) + ink <- if (is.null(dots[["col"]])) "#1F4E79" else dots[["col"]][1L] + band <- grDevices::adjustcolor(ink, alpha.f = 0.25) + if (type == "accounting") { + table <- summarise_accounting(x) + time <- sort(unique(table$time)) + n_runs <- length(unique(table$run)) + index <- match(table$time, time) + average <- function(value) as.vector(rowsum(value, index)) / n_runs + births <- average(table$births) + released <- average(table$introductions) + deaths <- average(table$deaths_resident + table$deaths_born + table$deaths_introduced) + removed <- average(table$removals_resident + table$removals_born + + table$removals_introduced) + net <- average(table$n_end - table$n_start) + failed <- as.vector(rowsum(as.integer(!table$reconciled), index)) + .plot_frame( + time + 1L, net, + list(xlab = "Year", ylab = "Mean individuals per replicate", + main = paste0(x$scenario$name, ": accounting"), + xlim = range(time + 1L) + c(-0.5, 0.5), + ylim = .plot_range(births + released, -(deaths + removed), net)), + dots, add + ) + fills <- c(births = "#4C9F70", introductions = "#A6D8B7", + deaths = "#B5533C", removals = "#E3A792") + left <- time + 1L - 0.4 + right <- time + 1L + 0.4 + graphics::rect(left, 0, right, births, col = fills[[1L]], border = NA) + graphics::rect(left, births, right, births + released, col = fills[[2L]], border = NA) + graphics::rect(left, -deaths, right, 0, col = fills[[3L]], border = NA) + graphics::rect(left, -(deaths + removed), right, -deaths, col = fills[[4L]], border = NA) + graphics::abline(h = 0, col = "grey40") + graphics::points(time + 1L, net, pch = 21, bg = "white", type = "b") + bad <- failed > 0 + if (any(bad)) { + graphics::points(time[bad] + 1L, net[bad], pch = 4, col = "red", lwd = 2, cex = 1.6) + } + if (!add) { + graphics::legend( + "topright", bty = "n", cex = 0.8, + legend = c(names(fills), "net change", + sprintf("unreconciled intervals: %d", sum(bad))), + fill = c(fills, NA, NA), border = NA, + pch = c(rep(NA, 4L), 21, 4), col = c(rep(NA, 4L), "black", "red") + ) + } + return(invisible(table)) + } + table <- summarise_trajectory(x, metric, threshold, process_name, include_initial, occurrence) + year <- table$year + shape <- if (length(year) > 1L) "l" else "p" + if (type == "risk") { + .plot_frame( + year, table$p_ever_below, + list(xlab = "Year", ylim = c(0, 1), + ylab = sprintf("P(%s has fallen below %g)", metric, threshold), + main = paste0(x$scenario$name, ": cumulative risk")), + dots, add + ) + .plot_ribbon(year, table$p_ever_below_lower, table$p_ever_below_upper, band, step = TRUE) + graphics::lines(year, table$p_ever_below, type = if (shape == "l") "s" else "p", + col = ink, lwd = 2, pch = 16) + return(invisible(table)) + } + paths <- .census_matrix(x, metric, process_name, include_initial, occurrence, + allow_extinct = TRUE)$values + paths <- paths[seq_len(min(runs, nrow(paths))), , drop = FALSE] + .plot_frame( + year, table$median, + list(xlab = "Year", ylab = metric, main = paste0(x$scenario$name, ": trajectories"), + ylim = .plot_range(table$q05, table$q95, paths, threshold)), + dots, add + ) + .plot_ribbon(year, table$q05, table$q95, band) + .plot_ribbon(year, table$q25, table$q75, grDevices::adjustcolor(ink, alpha.f = 0.4)) + for (run in seq_len(nrow(paths))) { + graphics::lines(year, paths[run, ], type = shape, pch = 1, col = "grey60", lwd = 0.6) + } + graphics::lines(year, table$median, type = shape, pch = 16, col = ink, lwd = 2) + graphics::abline(h = threshold, lty = 2, col = "grey30") + invisible(table) +} + +plot.pva_ensemble <- function(x, y = "p_ever_below", by = NULL, ...) { + if (!.is_name(y) || !is.numeric(x[[y]])) { + .stop("y must name one numeric summary column of the ensemble") + } + if (is.null(by)) by <- attr(x, "provenance")$design + if (!is.character(by) || !length(by) || !all(by %in% names(x))) { + .stop("by must name one or more columns of the ensemble") + } + estimate <- x[[y]] + spread <- sub("_mean$", "", y) + lower <- x[[paste0(y, "_lower")]] + upper <- x[[paste0(y, "_upper")]] + if (is.null(lower) || is.null(upper)) { + error <- x[[paste0(spread, "_mcse")]] + half <- if (is.null(error)) NA_real_ else stats::qnorm(0.975) * error + lower <- estimate - half + upper <- estimate + half + } + label <- do.call(paste, c(unname(lapply(by, function(column) format(x[[column]]))), sep = " | ")) + table <- data.frame( + label = label, estimate = estimate, lower = lower, upper = upper, + stringsAsFactors = FALSE + ) + position <- seq_len(nrow(table)) + dots <- list(...) + xaxt <- if (is.null(dots$xaxt)) graphics::par("xaxt") else dots$xaxt + dots$xaxt <- "n" + .plot_frame( + position, estimate, + list(xlab = paste(by, collapse = " | "), ylab = y, + xlim = c(0.5, nrow(table) + 0.5), + ylim = .plot_range(estimate, lower, upper)), + dots + ) + if (xaxt != "n" && !isFALSE(dots$axes)) { + graphics::axis(1L, at = position, labels = label, xaxt = xaxt) + } + ok <- !is.na(lower) & !is.na(upper) + graphics::segments(position[ok], lower[ok], position[ok], upper[ok], col = "#1F4E79", lwd = 2) + graphics::points(position, estimate, pch = 21, bg = "white", col = "#1F4E79", cex = 1.3) + invisible(table) +} diff --git a/R/process.R b/R/process.R index f82d4f1..dc18208 100644 --- a/R/process.R +++ b/R/process.R @@ -129,7 +129,7 @@ validate_processes <- function(processes, state = NULL) { } processes <- lapply(processes, .validate_process) if (!is.null(state)) { - .validate_field_plan(processes, .validate_state(state)) + .validate_field_plan(processes, .validate_state(state, at_entry = TRUE)) } invisible(processes) } @@ -181,13 +181,13 @@ validate_processes <- function(processes, state = NULL) { if (length(state$globals)) paste0("globals.", names(state$globals)) ) population_fields <- names(state$population) - creator_fields <- setdiff( + creator_fields <- .absent( population_fields, c(.engine_owned_fields, "alive", "mother_id", "father_id") ) for (process in processes) { label <- paste0("process '", process$name, "'") - missing <- setdiff(process$requires, available) + missing <- .absent(process$requires, available) if (length(missing)) { .stop( label, " requires field(s) that are neither in the initial state nor ", @@ -195,7 +195,7 @@ validate_processes <- function(processes, state = NULL) { ) } written <- process$writes[startsWith(process$writes, "population.")] - unknown <- setdiff(sub("population.", "", written, fixed = TRUE), population_fields) + unknown <- .absent(sub("population.", "", written, fixed = TRUE), population_fields) if (length(unknown)) { .stop( label, " writes population field(s) absent from the initial state: ", @@ -203,14 +203,14 @@ validate_processes <- function(processes, state = NULL) { ) } if (!is.null(process$creates)) { - uninitialised <- setdiff(creator_fields, process$creates) + uninitialised <- .absent(creator_fields, process$creates) if (length(uninitialised)) { .stop( label, " creates individuals without initialising: ", paste(uninitialised, collapse = ", ") ) } - unknown <- setdiff(process$creates, population_fields) + unknown <- .absent(process$creates, population_fields) if (length(unknown)) { .stop( label, " creates field(s) absent from the initial state: ", @@ -218,7 +218,7 @@ validate_processes <- function(processes, state = NULL) { ) } } - available <- union(available, process$writes) + available <- c(available, .absent(process$writes, available)) } invisible(TRUE) } @@ -304,6 +304,9 @@ validate_processes <- function(processes, state = NULL) { if (!identical(after$max_dense_kinship, before$max_dense_kinship)) { .stop(label, " changed the engine-owned max_dense_kinship limit") } + if (!identical(after$markers, before$markers)) { + .stop(label, " changed the engine-owned neutral-locus store") + } if (n_new) { if (is.null(process$creates)) { .stop(label, " created individuals without a creates declaration") @@ -390,6 +393,8 @@ validate_processes <- function(processes, state = NULL) { census <- vector("list", n_processes) ledger <- if (keep_ledger) vector("list", n_processes) else NULL pedigree <- !is.null(state$kinship) + markers <- !is.null(state$markers) + parentage <- pedigree || markers dead_males <- dead_females <- integer() for (index in seq_len(n_processes)) { @@ -439,13 +444,24 @@ validate_processes <- function(processes, state = NULL) { population$origin[created] <- if (introduced) "introduction" else "birth" population$entry_time[created] <- time accounting[index, if (introduced) 5L else 4L] <- n_new + if (parentage) .check_parents(population, n_before, context, dead_females) if (pedigree) { births <- .kinship_births( - after$kinship, population, n_before, context, dead_females, state$max_dense_kinship + after$kinship, population, n_before, state$max_dense_kinship ) after$kinship <- births$store population$pedigree_F[created] <- births$F } + if (markers) { + if (introduced && (any(!is.na(population$mother_id[created])) || + any(!is.na(population$father_id[created])))) { + .stop("neutral-locus introductions must have NA mother_id and father_id") + } + after$markers <- .marker_add( + after$markers, population$id[created], + population$mother_id[created], population$father_id[created] + ) + } } if (n_lost > 0L) { entered <- population$entry_time[lost] == time @@ -465,7 +481,7 @@ validate_processes <- function(processes, state = NULL) { } male <- population$sex[lost] == "M" dead_males <- c(dead_males, population$id[lost[male]]) - if (pedigree) dead_females <- c(dead_females, population$id[lost[!male]]) + if (parentage) dead_females <- c(dead_females, population$id[lost[!male]]) keep <- population$alive population <- lapply(population, `[`, keep) } @@ -482,6 +498,9 @@ validate_processes <- function(processes, state = NULL) { if (pedigree) { state$kinship <- .kinship_release(state$kinship, c(dead_males, dead_females)) } + if (markers) { + state$markers <- .marker_release(state$markers, state$population$id) + } if (execution$closed_proxy && any(accounting[, 5L] > 0L)) { msg <- "introductions with an inbreeding proxy require an explicit migration function" if (strict) .stop(msg) else warning(msg, call. = FALSE) @@ -612,7 +631,7 @@ execute_processes <- function( dt = 1, validation = c("strict", "fast")) { validation <- match.arg(validation) - state <- .validate_state(state) + state <- .validate_state(state, at_entry = TRUE) execution <- .prepare_execution(validate_processes(processes)) .validate_field_plan(execution$processes, state) time <- .as_count(time, "time") diff --git a/R/processes_demography.R b/R/processes_demography.R index eb4fe7b..959281f 100644 --- a/R/processes_demography.R +++ b/R/processes_demography.R @@ -331,7 +331,8 @@ reproduction_process <- function( user = params ), requires = unique(c("population.sex", "population.alive", - if (!is.null(mate_field)) paste0("population.", mate_field), requires)), + if (!is.null(mate_field)) paste0("population.", mate_field), + 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." diff --git a/R/processes_environment.R b/R/processes_environment.R index 1eb5cf0..fa1dd22 100644 --- a/R/processes_environment.R +++ b/R/processes_environment.R @@ -12,6 +12,7 @@ environment_process <- function( name = name, run = function(state, context, params) { for (variable in names(params$variables)) { + context$variable <- variable state$globals[[variable]] <- params$variables[[variable]](state, context, params$user) } @@ -24,6 +25,208 @@ environment_process <- function( ) } +# Correlated environmental anomalies. Components may be patches, vital rates +# 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 (!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") + } + if (!is.numeric(sd) || !is.null(dim(sd)) || !length(sd) || + any(!is.finite(sd)) || any(sd < 0)) { + .stop("sd must be finite, non-negative stationary standard deviations") + } + cor_names <- NULL + if (!is.null(cor)) { + if (!is.matrix(cor) || !is.numeric(cor) || nrow(cor) != ncol(cor) || !nrow(cor) || + any(!is.finite(cor))) { + .stop("cor must be a non-empty, finite numeric square matrix") + } + tol <- nrow(cor) * .Machine$double.eps + if (any(abs(diag(cor) - 1) > tol) || any(abs(cor - t(cor)) > tol)) { + .stop("cor must be a symmetric correlation matrix with a unit diagonal") + } + cor_names <- .environment_dimnames(cor, "cor") + } + size <- if (is.null(cor)) max(length(sd), length(names)) else nrow(cor) + if (!(length(sd) %in% c(1L, size))) .stop("sd must have length one or one value per component") + if (is.null(names)) names <- cor_names + if (is.null(names) && length(sd) == size) names <- base::names(sd) + if (!is.null(names)) { + if (length(names) != size) .stop("names must give one name per component") + names <- .field_names(as.character(names), "component names") + if (!is.null(cor_names) && !identical(cor_names, names)) { + if (!setequal(cor_names, names)) .stop("names must match the components of cor") + cor <- cor[names, names, drop = FALSE] + } + } + if (length(sd) > 1L) sd <- .align_environment(sd, names, "sd") + sd <- rep_len(as.numeric(sd), size) + loading <- if (!is.null(cor)) { + if (any(abs(cor) > 1 + tol)) { + .stop("cor must be positive semi-definite") + } + chol_tol <- max(1e-8, 8 * tol) + upper <- suppressWarnings(chol(unname(cor), pivot = TRUE, tol = chol_tol)) + rank <- attr(upper, "rank") + factor <- upper[seq_len(rank), order(attr(upper, "pivot")), drop = FALSE] + # A rank warning can also indicate an indefinite matrix. + if (rank < size) { + for (i in seq_len(size)) { + if (any(abs(colSums(factor * factor[, i]) - cor[, i]) > chol_tol)) { + .stop("cor must be positive semi-definite") + } + } + } + t(factor) + } + n_draws <- if (is.null(loading)) size else ncol(loading) + innovation <- sqrt(1 - phi^2) + function(state, context, params) { + if (!.is_name(context$variable)) { + .stop("env_ar1() must be used as a variable of environment_process()") + } + draws <- stats::rnorm(n_draws) + shock <- if (is.null(loading)) { + draws + } else { + # Accumulate in R, not through BLAS, so the result is thread-independent. + total <- numeric(size) + for (j in seq_len(n_draws)) total <- total + loading[, j] * draws[[j]] + total + } + previous <- state$globals[[context$variable]] + value <- if (is.null(previous)) { + sd * shock + } else { + if (!is.numeric(previous) || !is.null(dim(previous)) || length(previous) != size || + any(!is.finite(previous))) { + .stop("globals.", context$variable, " must hold one finite lagged value per component") + } + previous <- .align_environment(previous, names, "lagged value") + phi * as.vector(previous) + innovation * sd * shock + } + names(value) <- names + value + } +} + +.environment_dimnames <- function(x, label) { + labels <- rownames(x) + if (!identical(labels, colnames(x))) { + .stop(label, " row and column names must be identical") + } + if (!is.null(labels)) .field_names(labels, paste(label, "row and column names")) + labels +} + +.align_environment <- function(x, components, label) { + if (!is.null(components) && !is.null(names(x)) && !identical(names(x), components)) { + if (!setequal(names(x), components)) .stop(label, " names must match the components") + x <- x[components] + } + x +} + +spatial_correlation <- function(patches = NULL, rho = NULL, distances = NULL, scale = NULL) { + has_rho <- !is.null(rho) + has_distance <- !is.null(distances) || !is.null(scale) + if (has_rho == has_distance) { + .stop("supply either rho with patches or distances with scale") + } + if (!is.null(patches)) patches <- .field_names(as.character(patches), "patches") + if (has_rho) { + size <- length(patches) + if (!size) .stop("patches must identify each component for equicorrelation") + lower <- if (size > 1L) -1 / (size - 1L) else -1 + if (!is.numeric(rho) || !is.null(dim(rho)) || length(rho) != 1L || + !is.finite(rho) || rho < lower - 1e-12 || rho > 1) { + .stop("rho must lie in [", signif(lower, 6L), ", 1] for ", size, " patches") + } + out <- matrix(max(lower, rho), size, size) + } else { + if (!is.matrix(distances) || !is.numeric(distances) || !nrow(distances) || + nrow(distances) != ncol(distances) || any(!is.finite(distances)) || any(distances < 0) || + any(abs(distances - t(distances)) > 1e-10) || any(abs(diag(distances)) > 1e-10)) { + .stop("distances must be a finite symmetric non-negative matrix with zero diagonal") + } + if (!is.numeric(scale) || !is.null(dim(scale)) || length(scale) != 1L || + is.na(scale) || scale <= 0) { + .stop("scale must be positive (or Inf for perfect synchrony)") + } + labels <- .environment_dimnames(distances, "distances") + if (is.null(patches)) patches <- labels + if (!is.null(patches) && length(patches) != nrow(distances)) { + .stop("patches must identify each row of distances") + } + if (!is.null(labels) && !identical(labels, patches)) { + if (!setequal(labels, patches)) .stop("patches must match distance matrix names") + distances <- distances[patches, patches, drop = FALSE] + } + out <- exp(-(0.5 * distances + 0.5 * t(distances)) / scale) + } + diag(out) <- 1 + if (!is.null(patches)) dimnames(out) <- list(patches, patches) + out +} + +# A deterministic level by interval, optionally plus an anomaly drawn earlier +# 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 (is.function(level)) { + arguments <- names(formals(level)) + pass_dt <- any(c("dt", "...") %in% arguments) + pass_params <- any(c("params", "...") %in% arguments) + } else { + if (!is.numeric(level) || !length(level) || any(!is.finite(level)) || + (!is.null(dim(level)) && !is.matrix(level))) { + .stop("level must be a time function, one number, an interval series or an interval-by-component matrix") + } + if (!is.matrix(level) && length(level) > 1L && !is.null(names(level))) { + intervals <- as.character(seq_along(level) - 1L) + if (!setequal(names(level), intervals)) { + .stop("named level series must identify intervals 0, 1, ...; supply patch levels with a function or matrix") + } + level <- unname(level[intervals]) + } + } + if (!is.null(anomaly) && !.is_name(anomaly)) { + .stop("anomaly must be NULL or the name of an environment variable") + } + function(state, context, params) { + step <- context$time + 1L + value <- if (is.function(level)) { + args <- list(context$time) + if (pass_dt) args$dt <- context$dt + if (pass_params) args["params"] <- list(params) + do.call(level, args) + } else if (is.matrix(level)) { + if (step > nrow(level)) .stop("level has no row for interval ", context$time) + level[step, ] + } else if (length(level) == 1L) { + level + } else { + if (step > length(level)) .stop("level has no value for interval ", context$time) + level[[step]] + } + if (!is.numeric(value) || !is.null(dim(value)) || !length(value) || any(!is.finite(value))) { + .stop("level must evaluate to finite numbers") + } + if (is.null(anomaly)) { + return(value) + } + deviation <- state$globals[[anomaly]] + if (!is.numeric(deviation) || !is.null(dim(deviation)) || !length(deviation) || + any(!is.finite(deviation)) || !(length(value) %in% c(1L, length(deviation)))) { + .stop("globals.", anomaly, " must be drawn before this variable and match its length") + } + if (length(value) > 1L) value <- .align_environment(value, names(deviation), "level") + value + deviation + } +} + catastrophe_process <- function( probability, mortality = NULL, diff --git a/R/processes_management.R b/R/processes_management.R index cd8f349..e1a4507 100644 --- a/R/processes_management.R +++ b/R/processes_management.R @@ -216,16 +216,24 @@ introduction_process <- function( pairing_process <- function( eligible, capacity = Inf, - priority = c("id", "lottery"), + priority = c("id", "lottery", "kinship", "mean_kinship"), field = "mate_id", name = "pairing", requires = character(), - params = list()) { + params = list(), + max_kinship = Inf, + by = NULL) { if (!is.function(eligible)) { .stop("eligible must be a function of (pop, state, context, params)") } capacity <- .count_function(capacity, "capacity") priority <- match.arg(priority) + limit <- .kinship_limit(max_kinship) + genetic <- priority %in% c("kinship", "mean_kinship") + if (!genetic && is.finite(limit)) { + .stop("max_kinship needs priority = 'kinship' or 'mean_kinship'") + } + requirement <- .mating_group_requirement(by) if (!.is_name(field)) { .stop("field must be one non-empty name") } @@ -241,11 +249,39 @@ pairing_process <- function( .stop("capacity must evaluate to one non-negative number") } n_pairs <- as.integer(min(floor(limit), length(females), length(males))) - order <- if (params$priority == "id") "id" else "random" - females <- .pick_rows(females, n_pairs, order) - males <- .pick_rows(males, n_pairs, order) - if (order == "random" && n_pairs > 1L) { - males <- males[sample.int(n_pairs)] + if (params$genetic) .require_kinship(state, "kinship-aware pairing") + if (!n_pairs) { + females <- males <- integer() + } else if (params$genetic || !is.null(params$by)) { + breeder_cost <- NULL + if (params$genetic) { + score <- .kinship_score(.kinship_block(state, females, males)) + score[score > params$max_kinship] <- Inf + } else { + if (params$priority == "lottery") { + females <- females[sample.int(length(females))] + males <- males[sample.int(length(males))] + } + score <- outer(seq_along(females), seq_along(males), "+") + } + score <- .restrict_mating_group(score, pop, params$by, females, males) + all_breed <- n_pairs == length(females) && n_pairs == length(males) && all(is.finite(score)) + if (params$priority == "mean_kinship" && !all_breed) { + rows <- c(females, males) + mk <- .kinship_score(.kinship_row_sums(state, rows) / length(pop$id)) + breeder_cost <- outer(mk[seq_along(females)], mk[length(females) + seq_along(males)], "+") + } + pairs <- .min_kinship_pairs(score, n_pairs, breeder_cost) + n_pairs <- nrow(pairs) + females <- females[pairs[, 1L]] + males <- males[pairs[, 2L]] + } else { + order <- if (params$priority == "id") "id" else "random" + females <- .pick_rows(females, n_pairs, order) + males <- .pick_rows(males, n_pairs, order) + if (order == "random" && n_pairs > 1L) { + males <- males[sample.int(n_pairs)] + } } mate <- rep(NA_integer_, length(pop$id)) mate[females] <- pop$id[males] @@ -263,11 +299,14 @@ pairing_process <- function( eligible = eligible, capacity = capacity, priority = priority, + genetic = genetic, + max_kinship = limit, + by = by, field = field, user = params ), requires = unique(c( - "population.sex", "population.alive", paste0("population.", field), requires + "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." diff --git a/R/scenario.R b/R/scenario.R index ec8cbda..6e18b2f 100644 --- a/R/scenario.R +++ b/R/scenario.R @@ -261,7 +261,8 @@ print.pva_run <- function(x, ...) { initial_execution = payload$initial_execution, run_id = run_id, strict = payload$strict, - keep = payload$keep + keep = payload$keep, + stream = payload$streams[[run_id]] ) }) } @@ -272,13 +273,17 @@ print.pva_run <- function(x, ...) { initial_execution, run_id, strict, - keep) { + keep, + stream) { initial <- scenario$init_fun() state <- if (inherits(initial, "pva_state")) { - .validate_state(initial) + .validate_state(initial, at_entry = TRUE) } else { pva_state(initial) } + if (!is.null(state$markers)) { + state$markers$seed <- .marker_stream(stream, 4L) + } .validate_field_plan(execution$processes, state) state <- .open_kinship(state) keep_events <- "events" %in% keep diff --git a/R/state.R b/R/state.R index 4a9f88d..1a89fda 100644 --- a/R/state.R +++ b/R/state.R @@ -13,10 +13,19 @@ .reserved_fields <- c(names(.core_field_types), "pedigree_F") +.state_fields <- c( + "population", "globals", "next_id", "kinship", "max_dense_kinship", "markers" +) + .stop <- function(...) { stop(..., call. = FALSE) } +# Elements of x that are not in table, for duplicate-free name vectors. It is +# setdiff() without the coercion and de-duplication, which dominate the cost +# of checks repeated for every replicate. +.absent <- function(x, table) x[is.na(match(x, table))] + .is_count <- function(value, minimum = 0) { is.numeric(value) && length(value) == 1L && is.finite(value) && value >= minimum && value == floor(value) && value <= .Machine$integer.max @@ -126,7 +135,7 @@ pva_population <- function( if (is.null(fields) || anyDuplicated(fields) || any(!nzchar(fields))) { .stop("population fields must have unique non-empty names") } - missing <- setdiff(names(.core_field_types), fields) + missing <- .absent(names(.core_field_types), fields) if (length(missing)) { .stop("population is missing core field(s): ", paste(missing, collapse = ", ")) } @@ -189,7 +198,8 @@ pva_state <- function( globals = list(), pedigree = FALSE, kinship = NULL, - max_dense_kinship = 2000L) { + max_dense_kinship = 2000L, + n_loci = 0L) { if (inherits(population, "pva_state")) { .stop("population is already a pva_state") } @@ -200,6 +210,7 @@ pva_state <- function( .stop("kinship can be supplied only when pedigree = TRUE") } max_dense_kinship <- .as_count(max_dense_kinship, "max_dense_kinship", minimum = 1L) + n_loci <- .as_count(n_loci, "n_loci") population <- .as_population(population) if ("pedigree_F" %in% names(population)) { .stop("pedigree_F is engine-owned; request it with pedigree = TRUE") @@ -207,6 +218,13 @@ pva_state <- function( if (!all(population$alive)) { .stop("the initial population can contain living individuals only") } + if (pedigree || n_loci > 0L) { + sex <- population$sex + if (any(sex[match(population$mother_id, population$id, 0L)] != "F") || + any(sex[match(population$father_id, population$id, 0L)] != "M")) { + .stop("initial parentage has a non-female mother or non-male father") + } + } if (!is.list(globals) || (length(globals) && (is.null(names(globals)) || any(!nzchar(names(globals))) || anyDuplicated(names(globals))))) { @@ -218,11 +236,18 @@ pva_state <- function( globals = globals, next_id = if (n) max(population$id) + 1L else 1L, kinship = NULL, - max_dense_kinship = max_dense_kinship + max_dense_kinship = max_dense_kinship, + markers = NULL ) + if (n_loci > 0L) { + if (!is.null(kinship)) { + .check_explained_kinship(population, kinship) + } + state$markers <- .marker_init(population, n_loci) + } if (pedigree) { if (!is.null(kinship)) { - .validate_kinship(kinship, n) + kinship <- .validate_kinship(kinship, n, symmetrise = TRUE) state$kinship <- if (n > max_dense_kinship) { .ancestry_base(population$id, unname(kinship)) } else unname(kinship) @@ -241,11 +266,12 @@ pva_state <- function( state } -.validate_kinship <- function(kinship, n) { +.validate_kinship <- function(kinship, n, symmetrise = FALSE) { if (!is.matrix(kinship) || !is.double(kinship) || !identical(dim(kinship), c(n, n))) { .stop("kinship must be a double matrix with one row and column per living individual") } error <- "kinship must be symmetric, in [0, 1], with self-kinship of at least 0.5" + asymmetry <- 0 if (n) { if (anyNA(kinship) || min(kinship) < 0 || max(kinship) > 1 || min(diag(kinship)) < 0.5) { .stop(error) @@ -254,15 +280,17 @@ pva_state <- function( for (first in seq.int(1L, n, by = 128L)) { block <- seq.int(first, min(n, first + 127L)) delta <- kinship[, block, drop = FALSE] - t(kinship[block, , drop = FALSE]) - if (max(abs(delta)) > 100 * .Machine$double.eps) .stop(error) + asymmetry <- max(asymmetry, abs(delta)) + if (asymmetry > 100 * .Machine$double.eps) .stop(error) } } + if (symmetrise && asymmetry > 0) kinship <- 0.5 * (kinship + t(kinship)) invisible(kinship) } -.validate_state <- function(state) { +.validate_state <- function(state, at_entry = FALSE) { if (!inherits(state, "pva_state") || - !identical(names(state), c("population", "globals", "next_id", "kinship", "max_dense_kinship"))) { + !identical(names(state), .state_fields)) { .stop("state must be created by pva_state()") } pedigree <- !is.null(state$kinship) @@ -277,16 +305,20 @@ pva_state <- function( } else if (pedigree && !is.list(state$kinship)) { .stop("invalid pedigree store") } + if (!is.null(state$markers)) { + .validate_markers(state$markers, state$population, state$next_id, at_entry) + } state } print.pva_state <- function(x, ...) { cat(sprintf( - "\n", + "\n", sum(x$population$alive), paste(names(x$population), collapse = ", "), length(x$globals), - if (is.null(x$kinship)) "off" else "exact" + if (is.null(x$kinship)) "off" else "exact", + if (is.null(x$markers)) "" else sprintf(" | neutral loci: %d", x$markers$n_loci) )) invisible(x) } diff --git a/README.md b/README.md index 508454e..8844117 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # OpenPVA -OpenPVA 2.0.0 is a modular, individual-based engine for population viability +OpenPVA 2.1.0 is a modular, individual-based engine for population viability analysis in R. A model specifies a population, the order of biological processes within each interval, and the census that defines the risk endpoint. Processes declare the fields they read, write and create. The engine assigns individual @@ -30,11 +30,26 @@ recommended R packages and supports R 4.1.0 and later. `inbreeding_proxy_process()`, dispersal among patches, and `census_process()`. - Helpers: age-by-sex rate tables, Beverton–Holt, Ricker and ceiling density multipliers, lethal-equivalent inbreeding depression. +- Choose mates by pair kinship or give scarce territories to breeders with + low mean kinship to the living population. Both mating rules accept + `by = "patch_id"` for local mating. `summarise_pedigree()` reports founder + genome equivalents. `pva_state(n_loci = )` tracks neutral alleles on + independent segregation substreams, including in ensembles that start + from a shared family. +- `spatial_correlation()` supplies common or distance-dependent correlations + for `env_ar1()`. Named standard deviations follow their patches. + `env_trend()` adds deterministic changes or regime shifts. - `run_scenario()`, `summarise_pva()` (first-crossing and horizon risk, time to threshold and final abundance with Monte Carlo standard errors), `summarise_trajectory()`, `summarise_accounting()` and `run_pva_ensemble()`, which separates a structural, parametric and management design from the inner Monte Carlo replicates. +- Base graphics show 50% and 90% trajectory ribbons, cumulative risk with + stepwise Wilson intervals, cohort accounting and ensemble contrasts. + Each plot returns its data and accepts annotations in the plotted coordinates. + +The vignette `vignette("rosetta", package = "OpenPVA")` translates GAPPS, +Vortex-style and Leslie-matrix idioms into process lists. ## A minimal model @@ -132,9 +147,13 @@ illustrate model construction and management comparisons. ```sh Rscript scripts/run_tests.R # install to a temporary library and run all tests Rscript scripts/build_rd.R # regenerate man/*.Rd from scripts/rd_topics.R -R CMD build --no-build-vignettes . && R CMD check --as-cran --no-manual OpenPVA_*.tar.gz +R CMD build . && R CMD check --as-cran OpenPVA_*.tar.gz ``` +Building needs the suggested package `litedown` for the vignette. Run the +build in a scratch directory so the tarball and check directory stay out of +the checkout. + Documentation is generated by `scripts/build_rd.R`, which builds every usage section from the functions' formals, so `roxygen2` is not required. diff --git a/docs/design/lifecycle_process_contract.md b/docs/design/lifecycle_process_contract.md index 69cd8c5..b7f0d21 100644 --- a/docs/design/lifecycle_process_contract.md +++ b/docs/design/lifecycle_process_contract.md @@ -2,7 +2,7 @@ ## Status -This is the active engine contract for OpenPVA 2.0.0. It describes what a +This is the active engine contract for OpenPVA 2.1.0. It describes what a process may do, what the engine owns and what strict validation checks. The package tests in `tests/testthat/` are its executable form. @@ -24,6 +24,8 @@ branch, global registry, lifecycle DSL, plugin manager or class hierarchy. A - `kinship`: the kinship of the living population when pedigree tracking is on, otherwise `NULL` (see Pedigree). - `max_dense_kinship` sets the maximum number of dense slots per replicate. +- `markers`: the neutral genotypes of the living population when + `n_loci > 0`, otherwise `NULL` (see Neutral loci). Core population fields are `id`, `sex`, `age`, `alive`, `mother_id`, `father_id`, `origin` and `entry_time`. Any other field is the modeller's, with @@ -32,7 +34,7 @@ state: a process cannot add or drop a field. The engine owns `id`, `origin` (`initial`, `birth` or `introduction`), `entry_time` (the interval of entry; -1 for the initial population), -`pedigree_F`, `next_id` and `kinship`. A process cannot declare them in +`pedigree_F`, `next_id`, `kinship` and `markers`. A process cannot declare them in `writes`, and strict validation rejects any change to them. Mortality and removal are recorded by setting `alive` to `FALSE`. After the @@ -61,6 +63,9 @@ pva_process( identifiers and refuses an incomplete set of fields. - `context` is read-only: `run`, `time`, `dt`, `phase`, `n_steps`, `process_index`, `process_name`, `occurrence` and `departed_males` (IDs lost earlier in the interval). + A variable function of `environment_process()` also receives its own name + as `context$variable`, which lets a generator such as `env_ar1()` read its + lagged value from `state$globals` and keep no state of its own. - `pva_result(state, events, census)` returns the new state, optional events from `pva_events(event_type, value, label)` and an optional named numeric census vector. @@ -92,7 +97,7 @@ through the ordered list against the initial state: - `next_id` advanced by exactly the number of new records, new identifiers are the allocated ones, and new records are alive and carry no engine-owned values; -- the engine-owned pedigree and slot limit retain their values during callbacks, including element-wise assignments; +- the engine-owned pedigree, slot limit and neutral genotypes retain their values during callbacks, including element-wise assignments; - **cohort accounting**: the number of existing individuals that stopped living equals the `death` plus `removal` event values, and the number of created individuals equals the `birth` plus `introduction` event values. The two are @@ -138,6 +143,31 @@ with nonzero mutual kinship retain a dense covariance block. Request selected li ancestry calculation in compact mode. Returning the full living matrix still requires quadratic space. +## Neutral loci + +With `pva_state(n_loci = L)` the engine drops `L` unlinked neutral loci +through the pedigree. An initial individual without recorded parents carries +two unique alleles at every locus. A newborn takes one of each parent's two +copies at each locus; an unknown parent contributes one new allele. The engine +adds genotypes where it records births and introductions, so a parent lost +earlier in the interval still transmits, and it drops the genotypes of the +dead when the interval ends. A supplied kinship matrix is accepted with +`n_loci > 0` only when recorded initial parentage reproduces it. + +Segregation draws come from marker-only L'Ecuyer substreams. Counting from +the start of a replicate's stream, demography uses substream 0, ensemble +builders 1, genotypes dropped while a state is constructed 2, and segregation +during the replicate 3. `run_scenario()` assigns substream 3 of each +replicate's own stream, so replicates segregate independently even when +`init_fun` returns one state built beforehand. The demographic stream is never +advanced, so a seeded run gives identical census, events, accounting and +ledger with and without loci. With `n_loci = 0` the slot is `NULL` and no +marker code runs. + +Kinship-aware mate choice compares kinships after rounding to a grid of +2^-30. The dense and traced stores agree to rounding error, and the grid +makes them rank and admit the same mates. + ## Random numbers `run_scenario()` assigns one L'Ecuyer-CMRG stream to each replicate before any diff --git a/docs/dev_conventions_r.md b/docs/dev_conventions_r.md index ed6c81a..86d30ff 100644 --- a/docs/dev_conventions_r.md +++ b/docs/dev_conventions_r.md @@ -52,6 +52,9 @@ so PSOCK workers load the same code as the parent. Build and check in a temporary directory: ```sh -R CMD build --no-build-vignettes . -R CMD check --as-cran --no-manual OpenPVA_*.tar.gz +R CMD build . +R CMD check --as-cran OpenPVA_*.tar.gz ``` + +The build runs the `litedown` vignette, which must stay deterministic and +finish in well under 15 seconds. diff --git a/docs/reference/public_api.md b/docs/reference/public_api.md index c46dcda..b171a5e 100644 --- a/docs/reference/public_api.md +++ b/docs/reference/public_api.md @@ -1,4 +1,4 @@ -# Public API (OpenPVA 2.0.0) +# Public API (OpenPVA 2.1.0) The help pages under `man/` are the reference; this page is the map. Every entry is exported. @@ -8,15 +8,17 @@ entry is exported. | 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()` | -| Reproduction helpers | `litter_poisson()`, `litter_binomial()`, `litter_categorical()`, `offspring_sex_bernoulli()`, `mate_random()`, `mate_from_field()` | +| Reproduction helpers | `litter_poisson()`, `litter_binomial()`, `litter_categorical()`, `offspring_sex_bernoulli()`, `mate_random()`, `mate_from_field()`, `mate_min_kinship()` | | Management and limits | `removal_process()`, `ceiling_process()`, `introduction_process()`, `pairing_process()` | -| Environment | `environment_process()`, `catastrophe_process()`, `beta_shapes()`, `shift_logit()` | +| Environment | `environment_process()`, `env_ar1()`, `env_trend()`, `spatial_correlation()`, `catastrophe_process()`, `beta_shapes()`, `shift_logit()` | | Density feedback | `ceiling_density_multiplier()`, `beverton_holt_multiplier()`, `ricker_multiplier()` | -| Inbreeding | `summarise_pedigree()`, `kinship_matrix()`, `inbreeding_multiplier()`, `inbreeding_proxy_process()`, `sex_ratio_effective_size()` | +| Inbreeding and kinship | `summarise_pedigree()`, `kinship_matrix()`, `mean_kinship()`, `inbreeding_multiplier()`, `inbreeding_proxy_process()`, `sex_ratio_effective_size()` | +| Neutral loci | `summarise_markers()`, `marker_founder_shares()`, `genetic_metrics()` | | Rates | `validate_age_sex_table()`, `age_sex_rate()` | | Space | `patch_counts()`, `dispersal_process()`, `markov_dispersal_process()` | | Scenarios | `scenario_spec()`, `run_scenario()` | | Summaries and ensembles | `summarise_pva()`, `summarise_trajectory()`, `summarise_accounting()`, `run_pva_ensemble()` | +| Plots (S3 methods) | `plot()` for a `pva_run` and for a `pva_ensemble` | ## Outputs of `run_scenario()` @@ -29,7 +31,7 @@ A `pva_run` is a list with: `occurrence`, `event_type`, `value`, `label`, `origin_patch_id` and `destination_patch_id`; - `accounting`: one row per run, interval and process, with `n_before`, `births`, `introductions`, `deaths_*` and `removals_*` by cohort, `n_after`; -- `states`: the final `pva_state` of each run; +- `states`: the final `pva_state` of each run, including its neutral genotypes; - `ledgers`: for each run, every individual that ever lived, with `exit_time`, `exit_process` and `exit_type` (`NA` for survivors); - `provenance`: root seed, generator kinds, the replicate streams, validation @@ -49,7 +51,15 @@ always zero), `pairs_formed`, `unpaired_eligible`, `catastrophe` and 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 a sire lost in a previous interval as absent 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 `pva_state(pedigree = TRUE)` when known parentage or supplementation matters. Inspect `pedigree_F` for individual fitness costs and `kinship_matrix(state, ids)` for selected living pairs. A supplied matrix specifies related or inbred initial animals. The scalar effective-size approximation instead requires generation time in model intervals and explicit migration when introductions occur. +Use `pva_state(pedigree = TRUE)` for exact kinship. Inspect `pedigree_F` for individual fitness costs. `kinship_matrix(state, ids, against = ids)` returns coancestries in the requested row and column order. A supplied matrix specifies related or inbred initial animals. The scalar effective-size approximation requires generation time in model intervals and explicit migration when introductions occur. + +`mate_min_kinship()` gives each female the least related eligible male. Its default considers all living males. For monogamy, `pairing_process(priority = "kinship")` maximises pair count subject to `capacity` and `max_kinship`, then minimises total pair kinship. With `priority = "mean_kinship"`, the second objective is the selected breeders' summed mean kinship to the living population, with total pair kinship breaking ties. The comparison grid is 2^-30. Both mating rules accept `by = "patch_id"` and declare the grouping field as a requirement. + +`pva_state(n_loci = L)` tracks neutral alleles. Each unknown parent contributes a new allele per locus. Introductions require two unknown parents. Initial families and offspring segregate on distinct substreams. `census_process(genetic_metrics())` records marker and pedigree metrics. At extinction, richness is zero and retention is zero if the initial population contributed alleles. Heterozygosity and founder genome equivalents are undefined. `summarise_trajectory()` accepts missing values only alongside zero abundance and reports both observations and extant replicates. Cumulative risk retains crossings through subsequent rescue. + +For correlated environments, supply `env_ar1()` to `environment_process()`. Named stationary standard deviations follow the component labels. `spatial_correlation(patches, rho = ...)` supplies equicorrelation and `spatial_correlation(distances = ..., scale = ...)` supplies exponential decay. Add a deterministic level with `env_trend(level, anomaly = "")`. Supply levels by interval in a vector or interval-by-patch matrix, or use a function of time with optional `dt` and `params`. + +`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. diff --git a/inst/CITATION b/inst/CITATION index 7e00237..4045638 100644 --- a/inst/CITATION +++ b/inst/CITATION @@ -5,6 +5,6 @@ bibentry( title = "OpenPVA: Composable Individual-Based Population Viability Analysis", author = person("Barry W.", "Brook"), year = "2026", - note = "R package version 2.0.0", + note = paste("R package version", meta$Version), url = "https://github.com/BWBrook/OpenPVA" ) diff --git a/man/environment_processes.Rd b/man/environment_processes.Rd index fd8eba5..2f7199e 100644 --- a/man/environment_processes.Rd +++ b/man/environment_processes.Rd @@ -2,6 +2,9 @@ \name{environment_processes} \alias{environment_processes} \alias{environment_process} +\alias{env_ar1} +\alias{env_trend} +\alias{spatial_correlation} \alias{catastrophe_process} \alias{beta_shapes} \alias{shift_logit} @@ -14,6 +17,12 @@ environment_process( params = list() ) +env_ar1(sd = 1, phi = 0, cor = NULL, names = NULL) + +env_trend(level, anomaly = NULL) + +spatial_correlation(patches = NULL, rho = NULL, distances = NULL, scale = NULL) + catastrophe_process( probability, mortality = NULL, @@ -29,23 +38,39 @@ beta_shapes(mean, sd) shift_logit(probability, deviation) } \arguments{ -\item{variables}{Named list of functions of \code{(state, context, params)}. Each value is written to the global of the same name, in order, so later functions can read earlier ones.} +\item{variables}{Named list of functions of \code{(state, context, params)}. Each value is written to the global of the same name, in order, so later functions can read earlier ones. The variable's own name is supplied as \code{context$variable}.} \item{name}{Process name used in events, accounting and error messages.} \item{requires}{Additional state paths (\code{population.} or \code{globals.}) read by the supplied functions; checked before a run starts.} \item{params}{Named list of modeller parameters, passed unchanged to every supplied function as \code{params}.} +\item{sd}{For \code{beta_shapes()}: standard deviation of the beta distribution. For \code{env_ar1()}: the stationary standard deviation of each component (one value, or one per component).} +\item{phi}{Lag-one autocorrelation of the anomaly, strictly between -1 and 1.} +\item{cor}{Optional correlation matrix among the components (patches, vital rates or both). It may be singular: perfect synchrony is allowed. \code{NULL} gives independent components.} +\item{names}{Optional component order for the returned vector. The default uses matrix dimnames, then names on \code{sd}. Named inputs must match the component names.} +\item{level}{One constant, a vector indexed by successive intervals (optionally named 0, 1, ...), a matrix with one row per interval and one column per component, or a function of \code{time} accepting optional \code{dt} and \code{params}. Use a matrix or function for patch-specific levels.} +\item{anomaly}{Optional name of an environment variable listed earlier in the same \code{environment_process()}, added to the level.} +\item{patches}{Unique patch identifiers in component order.} +\item{rho}{Common correlation between distinct patches, at least -1/(p-1) for p > 1 and at most 1.} +\item{distances}{Symmetric, non-negative matrix of distances between patches with zero diagonal.} +\item{scale}{Positive distance scale for \eqn{\exp(-d/\mathrm{scale})}. Use \code{Inf} for perfect synchrony.} \item{probability}{For \code{catastrophe_process()}: the per-interval probability of a catastrophe, as one number or a function of \code{(state, context, params)}. For \code{shift_logit()}: probabilities to shift.} \item{mortality}{Optional direct mortality applied when a catastrophe occurs: one probability, or a function of \code{(pop, state, context, params)}.} \item{eligible}{Optional function of \code{(pop, state, context, params)} returning one logical value per living individual. \code{NULL} means every living individual.} \item{global}{Name of the logical global that records whether the catastrophe occurred this interval.} \item{mean}{Mean of the beta distribution, in (0, 1).} -\item{sd}{Standard deviation of the beta distribution.} \item{deviation}{Deviation added on the logit scale. Structural probabilities zero and one remain fixed even under infinite shifts.} } \description{ -\code{environment_process()} draws the interval's shared environmental conditions into globals, where rate functions read them. \code{catastrophe_process()} draws a Bernoulli catastrophe flag and can apply direct mortality. \code{beta_shapes()} converts a mean and standard deviation to beta shape parameters, and \code{shift_logit()} perturbs probabilities on the logit scale. +\code{environment_process()} draws the interval's shared environmental conditions into globals, where rate functions read them. \code{catastrophe_process()} draws a Bernoulli catastrophe flag and can apply direct mortality. \code{beta_shapes()} converts a mean and standard deviation to beta shape parameters, and \code{shift_logit()} perturbs probabilities on the logit scale. \code{env_ar1()} and \code{env_trend()} build variables for \code{environment_process()}: a temporally autocorrelated, cross-correlated anomaly and a deterministic trend or regime shift. +} +\details{ +\code{env_ar1()} generates \eqn{z_t = \phi z_{t-1} + \sqrt{1 - \phi^2}\,\sigma\,L\epsilon_t}, where \eqn{LL^\top} is \code{cor} and \eqn{\epsilon_t} is standard normal. The first value is drawn from the stationary distribution, so every interval has mean zero, standard deviation \code{sd} and correlation \code{cor}, and the covariance at lag \eqn{k} is \eqn{\phi^k} times the lag-zero covariance. Changing \code{phi} changes the temporal correlation while preserving the stationary standard deviations. Named standard deviations and lagged values follow the component labels. Named correlation matrices must have identical, unique row and column names. The lagged value is read from the variable's own global, so supplying that global in the initial state conditions the first interval on it. The generator draws a fixed number of normal deviates per interval and keeps no state of its own, which keeps replicates bit-identical across serial, fork and PSOCK execution. + +\code{spatial_correlation()} constructs a matrix for \code{cor} using a common \code{rho} across patches or exponential decay with distance. + +\code{env_trend()} returns the level for the current interval and, when \code{anomaly} is named, adds that interval's anomaly. Because the level is added after the autoregression, a trend or regime shift takes full effect in its own interval. } \value{ -The process constructors return a \code{pva_process}. \code{beta_shapes()} returns a list with \code{shape1} and \code{shape2}; \code{shift_logit()} returns probabilities. +The process constructors return a \code{pva_process}. \code{spatial_correlation()} returns a square numeric matrix. \code{env_ar1()} and \code{env_trend()} return functions for \code{variables}; their values are numeric vectors with one element per component. \code{beta_shapes()} returns a list with \code{shape1} and \code{shape2}; \code{shift_logit()} returns probabilities. } \examples{ weather <- environment_process( @@ -64,4 +89,14 @@ state <- pva_state( ) set.seed(3) execute_processes(state, list(weather, cyclone, survival, census_process()))$census + +# Red noise shared by two patches (correlation 0.6) around a warming step. +climate <- environment_process(list( + anomaly = env_ar1(sd = 0.3, phi = 0.5, + cor = spatial_correlation(c("a", "b"), rho = 0.6)), + climate = env_trend(function(time) if (time >= 1) 0.5 else 0, anomaly = "anomaly") +)) +state <- pva_state(pva_population(sex = c("F", "M"), age = 2)) +state <- execute_processes(state, list(climate), time = 0)$state +execute_processes(state, list(climate), time = 1)$state$globals } diff --git a/man/inbreeding.Rd b/man/inbreeding.Rd index 640e991..63eea55 100644 --- a/man/inbreeding.Rd +++ b/man/inbreeding.Rd @@ -3,6 +3,7 @@ \alias{inbreeding} \alias{summarise_pedigree} \alias{kinship_matrix} +\alias{mean_kinship} \alias{inbreeding_multiplier} \alias{inbreeding_proxy_process} \alias{sex_ratio_effective_size} @@ -10,7 +11,9 @@ \usage{ summarise_pedigree(state) -kinship_matrix(state, ids = state$population$id) +kinship_matrix(state, ids = state$population$id, against = ids) + +mean_kinship(state, ids = state$population$id) inbreeding_multiplier(inbreeding, lethal_equivalents) @@ -28,7 +31,8 @@ sex_ratio_effective_size(n_females, n_males) } \arguments{ \item{state}{A \code{pva_state}.} -\item{ids}{Distinct living IDs, in desired matrix order. Defaults to every living individual.} +\item{ids}{Distinct living IDs, in the desired row order. Defaults to every living individual.} +\item{against}{Distinct living IDs for the matrix columns, in the desired order. Defaults to \code{ids}.} \item{inbreeding}{Inbreeding coefficients in [0, 1].} \item{lethal_equivalents}{Slope \code{B} of the log-linear cost \code{exp(-B * F)}.} \item{effective_size}{Function of \code{(pop, state, context, params)} returning the interval's effective population size.} @@ -42,13 +46,13 @@ sex_ratio_effective_size(n_females, n_males) \item{n_males}{Number of breeding males.} } \description{ -\code{summarise_pedigree()} reports exact mean and maximum individual inbreeding, mean living kinship (including self-kinship) and gene diversity. \code{kinship_matrix(state, ids)} returns coancestry for the requested living individuals. The retained ancestry grows with the recorded pedigree. Starting animals with nonzero mutual kinship retain a covariance block. A full returned matrix requires quadratic space. \code{inbreeding_multiplier()} scales a particular fitness component by \code{exp(-B * F)} using lethal equivalents for that component and period. +\code{summarise_pedigree()} reports exact mean and maximum individual inbreeding, mean living kinship (including self-kinship), gene diversity and founder genome equivalents, \eqn{1 / (2 \bar{K})}, where \eqn{\bar{K}} averages every living pair including each individual with itself; \eqn{N} unrelated, non-inbred founders give exactly \eqn{N}. \code{mean_kinship(state, ids)} returns each requested individual's mean kinship with every living individual, itself included. \code{kinship_matrix(state, ids, against)} returns the coancestry block for the two sets of living IDs in their supplied order. The retained ancestry grows with the recorded pedigree. Starting animals with nonzero mutual kinship retain a covariance block. A full returned matrix requires quadratic space. \code{inbreeding_multiplier()} scales a particular fitness component by \code{exp(-B * F)} using lethal equivalents for that component and period. } \details{ The scalar proxy converts per-generation drift to per-interval drift \eqn{d = 1 - (1 - 1/(2N_e))^{1/G}}, with generation time \eqn{G}. The per-generation drift is capped at one, and zero effective size leaves drift at zero. The update is \eqn{(d + (1-d)F)(1-m)^2}, where \eqn{m} is the interval's immigrant gene fraction. Initialise the target global with a coefficient in [0, 1]. An interval with introductions and no migration function raises an error in strict mode and a warning in fast mode. This scalar approximation misses F1 heterosis under supplementation. Use \code{pedigree = TRUE} to distinguish the kinships of individual matings. \code{sex_ratio_effective_size()} gives \eqn{4N_fN_m/(N_f+N_m)}. } \value{ -\code{summarise_pedigree()} returns a one-row data frame; \code{kinship_matrix()} a numeric matrix; \code{inbreeding_multiplier()} and \code{sex_ratio_effective_size()} numeric vectors; \code{inbreeding_proxy_process()} a \code{pva_process}. +\code{summarise_pedigree()} returns a one-row data frame; \code{kinship_matrix()} a numeric matrix; \code{mean_kinship()}, \code{inbreeding_multiplier()} and \code{sex_ratio_effective_size()} numeric vectors; \code{inbreeding_proxy_process()} a \code{pva_process}. } \examples{ inbreeding_multiplier(c(0, 0.125, 0.25), lethal_equivalents = 3) diff --git a/man/management_processes.Rd b/man/management_processes.Rd index 0a28614..9ba4c7e 100644 --- a/man/management_processes.Rd +++ b/man/management_processes.Rd @@ -41,11 +41,13 @@ introduction_process( pairing_process( eligible, capacity = Inf, - priority = c("id", "lottery"), + priority = c("id", "lottery", "kinship", "mean_kinship"), field = "mate_id", name = "pairing", requires = character(), - params = list() + params = list(), + max_kinship = Inf, + by = NULL ) } \arguments{ @@ -59,15 +61,20 @@ pairing_process( \item{requires}{Additional state paths (\code{population.} or \code{globals.}) read by the supplied functions; checked before a run starts.} \item{params}{Named list of modeller parameters, passed unchanged to every supplied function as \code{params}.} \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 (and optionally \code{mother_id} and \code{father_id}) of the \code{n} introduced individuals.} +\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{source}{Label stored with the introduction event.} -\item{priority}{Which eligible individuals obtain a pair when capacity is limiting: lowest identifiers first (\code{"id"}) or a random draw (\code{"lottery"}).} +\item{priority}{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"}).} \item{field}{Integer population field that receives each paired individual's mate identifier.} +\item{max_kinship}{For either kinship priority, the largest admissible kinship within a pair. The default \code{Inf} admits every pair.} +\item{by}{Optional population field for mating groups. Partners must share a non-missing value of this field, for example \code{"patch_id"}. The process declares the field as a requirement.} } \description{ \code{removal_process()} takes individuals out of the population as accounted removals (harvest, culling, capture). \code{ceiling_process()} imposes a hard abundance ceiling by random deaths. \code{introduction_process()} adds individuals (supplementation, release, immigration). \code{pairing_process()} forms monogamous pairs each interval up to a capacity, leaving surplus eligible individuals as unpaired floaters; with unlimited capacity it is a pair (mate) limitation, with finite capacity a territory limit. } +\details{ +\code{pairing_process()} forms a new set of pairs each time it runs. With \code{priority = "kinship"} it needs \code{pva_state(pedigree = TRUE)} and solves an exact assignment: it forms the largest number of pairs allowed by \code{capacity} and \code{max_kinship} and, among all such sets, one with the smallest sum of within-pair kinships. With \code{priority = "mean_kinship"} the same limits apply. Among maximum-size matchings, the process first minimises the summed mean kinship of the selected breeders to the entire living population, including themselves. Total within-pair kinship breaks ties. Kinships are compared on a grid of \eqn{2^{-30}}; values within eight ulp of a half-grid midpoint snap consistently across dense and traced storage. The solution uses no random numbers and equally good sets resolve by identifier order. Solving takes time cubic in the number of eligible individuals of the rarer sex. +} \value{ A \code{pva_process}. } diff --git a/man/markers.Rd b/man/markers.Rd new file mode 100644 index 0000000..55f34d1 --- /dev/null +++ b/man/markers.Rd @@ -0,0 +1,59 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{markers} +\alias{markers} +\alias{summarise_markers} +\alias{marker_founder_shares} +\alias{genetic_metrics} +\title{Neutral-locus gene drop and genetic census metrics} +\usage{ +summarise_markers(state) + +marker_founder_shares(state) + +genetic_metrics() +} +\arguments{ +\item{state}{A \code{pva_state}.} +} +\description{ +\code{pva_state(n_loci = L)} drops \eqn{L} unlinked neutral loci through the simulated pedigree. \code{summarise_markers()} reports heterozygosity, allelic richness and the retention of the starting population's alleles; \code{marker_founder_shares()} reports the share of the living gene pool that descends from each source individual; \code{genetic_metrics()} supplies both pedigree and marker metrics to \code{\link{census_process}()}. +} +\details{ +Every initial individual without recorded parents carries two unique alleles at every locus. An offspring inherits, independently at each locus, one of its mother's two copies and one of its father's two. An unknown parent contributes one new allele. Introductions must have two unknown parents and bring two novel alleles. A birth with only an unrecorded sire brings one. A parent lost earlier in the same interval still transmits its alleles. The alleles issued to the initial population are the \emph{native} alleles. + +Member builders, initial gene drops and subsequent segregation in each replicate use distinct L'Ecuyer substreams. When \code{init_fun} returns a prebuilt family, replicates share its initial genotypes and draw offspring independently. Repeated direct \code{pva_state(n_loci = )} calls from the same caller RNG position draw the same initial gene drop because state construction does not advance the caller's stream. Enabling neutral loci therefore leaves every demographic outcome of a seeded run unchanged, and with \code{n_loci = 0} nothing is stored or drawn. The genotypes are engine-owned: a process cannot change them. A supplied starting \code{kinship} matrix is accepted together with \code{n_loci > 0} only if recorded initial parentage reproduces it, because unique founder alleles would otherwise contradict the stated relationships. + +The metrics are: \code{observed_heterozygosity}, the proportion of living individual-locus genotypes with two different alleles; \code{expected_heterozygosity}, \eqn{1 - \frac{1}{L}\sum_{l,a} p_{l,a}^2} with \eqn{p} the allele frequencies among the living (no small-sample correction); \code{allelic_richness}, the mean number of distinct alleles per locus; \code{allelic_retention}, the mean proportion of native alleles still present, which later introductions cannot raise; and \code{native_share}, the proportion of living gene copies that are native. Conditional on the pedigree, expected heterozygosity has mean \eqn{1 - \bar{K}} and observed heterozygosity mean \eqn{1 - \bar{F}} when the founders are unrelated. At extinction richness is zero. Retention is zero when the initial population contributed alleles and otherwise undefined. Heterozygosity, native share and founder genome equivalents are undefined (\code{NA}). + +\code{genetic_metrics()} returns \code{n_alive}, then, with \code{pedigree = TRUE}, \code{mean_inbreeding}, \code{mean_kinship}, \code{gene_diversity} and \code{founder_genome_equivalents}, then the five marker metrics when \code{n_loci > 0}. +} +\value{ +\code{summarise_markers()} returns a one-row data frame. \code{marker_founder_shares()} returns one row per source individual with its \code{id}, whether its alleles are \code{native}, and its \code{share}; every native source is listed, including those whose alleles are lost. \code{genetic_metrics()} returns a function for the \code{metrics} argument of \code{census_process()}. +} +\examples{ +scenario <- scenario_spec( + name = "gene_drop", n_runs = 20, n_steps = 10, seed = 5, + init_fun = function() { + pva_state(pva_population(sex = rep(c("F", "M"), 4), age = 2), + pedigree = TRUE, n_loci = 20) + }, + processes = list( + survival_process(0.8), + age_process(), + reproduction_process( + breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2), + litter_size = litter_poisson(1.5), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(function(pop, state, context, params) pop$age >= 2), + requires = "population.age" + ), + census_process(genetic_metrics()) + ), + initial_census = census_process(genetic_metrics()) +) +run <- run_scenario(scenario, keep = c("census", "state")) +summarise_trajectory(run, metric = "expected_heterozygosity")[ + c(1, 11), c("year", "n_observed", "mean", "q05", "q95")] +summarise_markers(run$states[[1]]) +head(marker_founder_shares(run$states[[1]]), 3) +} diff --git a/man/plot.pva_run.Rd b/man/plot.pva_run.Rd new file mode 100644 index 0000000..dce7c74 --- /dev/null +++ b/man/plot.pva_run.Rd @@ -0,0 +1,71 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{plot.pva_run} +\alias{plot.pva_run} +\alias{plot.pva_ensemble} +\title{Diagnostic plots of runs and ensembles} +\usage{ +\method{plot}{pva_run}( + x, + type = c("trajectory", "risk", "accounting"), + metric = "n_alive", + threshold = 1, + runs = 20L, + process_name = NULL, + include_initial = NULL, + occurrence = NULL, + add = FALSE, + ... +) + +\method{plot}{pva_ensemble}(x, y = "p_ever_below", by = NULL, ...) +} +\arguments{ +\item{x}{A \code{pva_run} from \code{\link{run_scenario}}, or a \code{pva_ensemble} from \code{\link{run_pva_ensemble}}.} +\item{type}{The view to draw. \code{"trajectory"} shows central 50 and 90 percent ribbons with the median and sample replicates, \code{"risk"} shows cumulative first-crossing probability and its Wilson interval as steps or \code{"accounting"} (mean entries and losses per interval against the net change).} +\item{metric}{Name of the census metric to summarise.} +\item{threshold}{Quasi-extinction threshold: a run is below threshold when \code{metric < threshold}.} +\item{runs}{Number of individual replicate trajectories to overlay (the first ones, so no random numbers are drawn).} +\item{process_name}{Select the interval census by name when more than one is recorded.} +\item{include_initial}{Whether year zero counts. The default includes it when the scenario supplies an initial census.} +\item{occurrence}{Select the scheduled occurrence (1, 2, ...) when the same census name appears several times.} +\item{add}{Draw this run in the current panel using its existing axes and limits.} +\item{\dots}{Further arguments for \code{\link[graphics]{plot.default}}, such as \code{main}, \code{ylim} or \code{log}.} +\item{y}{Name of the numeric summary column to contrast among ensemble members.} +\item{by}{Design columns that label the members. The default uses every design column.} +} +\description{ +Base-graphics views of a run or an ensemble. Each view draws one exported summary and returns it, so the numbers behind a figure are always available. +} +\details{ +The trajectory and risk views plot \code{\link{summarise_trajectory}()}. A metric that is missing for extinct replicates is summarised over the extant ones. The accounting view plots \code{\link{summarise_accounting}()}: births and introductions above zero, deaths and removals below, the mean net change as points, and a cross on any interval in which a replicate fails to reconcile. + +\code{plot.pva_ensemble()} shows one point per ensemble row with an interval: \code{_lower} and \code{_upper} when the summary has them (as the proportions of \code{\link{summarise_pva}()} do), otherwise 1.96 Monte Carlo standard errors from \code{_mcse}. + +The methods preserve styling, respect the current layout and leave the plotted coordinates active for \code{abline()}, \code{lines()} or \code{legend()}. Use \code{plot(other_run, add = TRUE)} to overlay a second run. Plotting draws no random numbers. +} +\value{ +Invisibly, the plotted table: \code{summarise_trajectory()} for the trajectory and risk views, \code{summarise_accounting()} for the accounting view, and for an ensemble a data frame with \code{label}, \code{estimate}, \code{lower} and \code{upper}. +} +\examples{ +scenario <- scenario_spec( + name = "decline", n_runs = 60, n_steps = 15, seed = 42, + init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 1), + processes = list(survival_process(0.85), age_process(), census_process()), + initial_census = census_process() +) +run <- run_scenario(scenario) +plot(run, threshold = 4) +risk <- plot(run, type = "risk", threshold = 4) +tail(risk[, c("year", "p_ever_below", "p_ever_below_lower", "p_ever_below_upper")], 2) +plot(run, type = "accounting") + +design <- data.frame(survival = c(0.75, 0.85, 0.95)) +build <- function(row) { + list(n_steps = 15, + init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 1), + processes = list(survival_process(row$survival), census_process())) +} +ensemble <- run_pva_ensemble(design, build, n_runs = 60, seed = 7, + summarise = function(result, row) summarise_pva(result, threshold = 4)) +plot(ensemble) +} diff --git a/man/print.pva_state.Rd b/man/print.pva_state.Rd index 7ac06b2..3dd664d 100644 --- a/man/print.pva_state.Rd +++ b/man/print.pva_state.Rd @@ -4,6 +4,7 @@ \alias{print.pva_process} \alias{print.pva_scenario} \alias{print.pva_run} +\alias{print.pva_ensemble} \title{Print OpenPVA objects} \usage{ \method{print}{pva_state}(x, ...) @@ -13,10 +14,12 @@ \method{print}{pva_scenario}(x, ...) \method{print}{pva_run}(x, ...) + +\method{print}{pva_ensemble}(x, ...) } \arguments{ -\item{x}{An OpenPVA state, process, scenario or run.} -\item{\dots}{Ignored.} +\item{x}{An OpenPVA state, process, scenario, run or ensemble.} +\item{\dots}{For ensembles, arguments passed to the data-frame print method.} } -\description{One-line summaries of OpenPVA objects.} +\description{Summarise an OpenPVA object. For ensembles, print the run count and root seed above the design and summary rows.} \value{\code{x}, invisibly.} diff --git a/man/pva_state.Rd b/man/pva_state.Rd index feb1533..2d3be1b 100644 --- a/man/pva_state.Rd +++ b/man/pva_state.Rd @@ -12,7 +12,8 @@ pva_state( globals = list(), pedigree = FALSE, kinship = NULL, - max_dense_kinship = 2000L + max_dense_kinship = 2000L, + n_loci = 0L ) add_individuals( @@ -35,6 +36,7 @@ add_individuals( \item{pedigree}{Whether the engine tracks exact pedigree inbreeding. When \code{TRUE} the population gains the engine-owned field \code{pedigree_F}.} \item{kinship}{Optional matrix of starting coancestries in population order. It takes precedence over recorded initial parentage.} \item{max_dense_kinship}{Maximum number of dense pedigree slots per replicate (default 2000). Once the required slots exceed this limit, the engine uses exact sparse ancestor tracing for the rest of that replicate, even if the population later falls below the limit.} +\item{n_loci}{Number of unlinked neutral loci to drop through the pedigree. The default \code{0} stores no genotypes and draws no random numbers. See \code{\link{summarise_markers}}.} \item{state}{A \code{pva_state}.} } \description{ @@ -43,10 +45,10 @@ The population is columnar: a named list of equal-length vectors with one elemen \details{ Core fields are \code{id}, \code{sex}, \code{age}, \code{alive}, \code{mother_id}, \code{father_id}, \code{origin} and \code{entry_time}. The engine owns \code{id}, \code{origin} (\code{"initial"}, \code{"birth"} or \code{"introduction"}), \code{entry_time} (the interval of entry, \code{-1} for the initial population) and \code{pedigree_F}; processes cannot write them. A process records mortality by setting \code{alive} to \code{FALSE}. After each process the engine moves those records out of the living table into the optional ledger, so every process starts with living individuals only. -Without a supplied matrix, initial parent IDs must resolve inside the initial population in an acyclic pedigree. Each unknown parent is an unrelated, non-inbred contribution. A newborn's inbreeding coefficient is its parents' kinship. Known parents can be living or can have died earlier in the same interval. Use \code{\link{kinship_matrix}} for living pairs in either storage mode. +When pedigree or markers are enabled, an initial mother must be female and an initial father male whenever their IDs are present. Without a supplied matrix, initial parent IDs must resolve inside the initial population in an acyclic pedigree. Each unknown parent is an unrelated, non-inbred contribution. A newborn's inbreeding coefficient is its parents' kinship. Known parents can be living or can have died earlier in the same interval. Use \code{\link{kinship_matrix}} for living pairs in either storage mode. } \value{ -\code{pva_population()} returns the columnar population. \code{pva_state()} returns a \code{pva_state} with elements \code{population}, \code{globals}, \code{next_id}, \code{kinship} and \code{max_dense_kinship}. \code{add_individuals()} returns the state with the new records appended and \code{next_id} advanced. +\code{pva_population()} returns the columnar population. \code{pva_state()} returns a \code{pva_state} with elements \code{population}, \code{globals}, \code{next_id}, \code{kinship}, \code{max_dense_kinship} and \code{markers}. \code{add_individuals()} returns the state with the new records appended and \code{next_id} advanced. } \examples{ population <- pva_population(sex = c("F", "F", "M"), age = c(3, 1, 4), patch_id = 1L) diff --git a/man/reproduction_helpers.Rd b/man/reproduction_helpers.Rd index da70330..825119a 100644 --- a/man/reproduction_helpers.Rd +++ b/man/reproduction_helpers.Rd @@ -7,6 +7,7 @@ \alias{offspring_sex_bernoulli} \alias{mate_random} \alias{mate_from_field} +\alias{mate_min_kinship} \title{Litter-size, offspring-sex and mating helpers} \usage{ litter_poisson(mean) @@ -20,6 +21,13 @@ offspring_sex_bernoulli(female_probability = 0.5) mate_random(eligible) mate_from_field(field = "mate_id", stale = c("error", "unpaired")) + +mate_min_kinship( + eligible = NULL, + max_kinship = Inf, + ties = c("random", "id"), + by = NULL +) } \arguments{ \item{mean}{Mean litter size: one number, or a function of \code{(pop, state, context, params)} returning one mean per living individual.} @@ -28,15 +36,20 @@ mate_from_field(field = "mate_id", stale = c("error", "unpaired")) \item{sizes}{Distinct litter sizes of the categorical distribution.} \item{probabilities}{Probabilities of \code{sizes}; they must sum to one.} \item{female_probability}{Probability that a newborn is female.} -\item{eligible}{Function of \code{(pop, state, context, params)} returning one logical value per living individual; males flagged TRUE can sire offspring.} +\item{eligible}{Function of \code{(pop, state, context, params)} returning one logical value per living individual. Males flagged TRUE can sire offspring. For mate_min_kinship(), NULL makes every living male eligible.} \item{field}{Name of the population field holding recorded mate IDs. Initialise unpaired individuals with \code{NA_integer_}.} \item{stale}{How to handle a female's recorded sire ID when the sire is absent and did not depart in the current interval. The default \code{"error"} rejects that ID. With \code{"unpaired"}, reproduction treats the female as having no mate and preserves the field.} +\item{max_kinship}{Largest admissible kinship between a female and her sire. A female with no eligible male at or below it receives \code{NA}, so she skips breeding when \code{require_mate = TRUE}.} +\item{ties}{How \code{mate_min_kinship()} chooses among equally unrelated males: one uniform draw per living female (\code{"random"}) or the lowest identifier (\code{"id"}).} +\item{by}{Optional population field for mating groups. Partners must share a non-missing value of this field, for example \code{"patch_id"}. The process declares the field as a requirement.} } \description{ Building blocks for \code{\link{reproduction_process}()}. Litter size can be Poisson, bounded binomial (under-dispersed, with a maximum) or an explicit categorical distribution. \code{mate_random()} gives each female a sire drawn at random from the eligible males, so breeding is limited only when no eligible male is alive. A bounded binomial litter adds \code{min_size} to a binomial draw with \code{size - min_size} trials, giving the specified conditional mean. } \details{ \code{mate_from_field()} reads a vector of positive integer IDs or \code{NA}. A female's living sire must be male. A sire who died or was removed earlier in the current interval still fathers her offspring in either mode. The offspring retain his ID and pedigree, and \code{newborn_fields} receives \code{NA} for his living row. With \code{stale = "unpaired"}, any other absent sire is treated as \code{NA} for this breeding event. An unpaired female skips breeding unless \code{require_mate = FALSE}, in which case her offspring have an unknown sire. + +\code{mate_min_kinship()} gives each female the eligible male with whom her kinship is lowest (polygyny: a male can sire several litters). It needs \code{pva_state(pedigree = TRUE)}. Kinships are compared on a grid of \eqn{2^{-30}}, so the dense and traced pedigree stores choose the same sires, and the number of random draws does not depend on the store or on the number of ties. } \value{ A function suitable for the corresponding argument of \code{\link{reproduction_process}()}. diff --git a/man/run_pva_ensemble.Rd b/man/run_pva_ensemble.Rd index ed5e694..e8eb8a9 100644 --- a/man/run_pva_ensemble.Rd +++ b/man/run_pva_ensemble.Rd @@ -39,7 +39,7 @@ Separates the outer design (structure, parameters, management) from the inner Mo 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, 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. } \value{ -A data frame: the design rows, \code{member}, \code{member_seed} and the summary columns. Provenance is attached as an attribute. +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{ design <- expand.grid(survival = c(0.7, 0.9), harvest = c(0, 2)) diff --git a/man/summaries.Rd b/man/summaries.Rd index c747b79..ba4196d 100644 --- a/man/summaries.Rd +++ b/man/summaries.Rd @@ -40,8 +40,32 @@ summarise_accounting(result) \details{ Proportions carry a binomial Monte Carlo standard error and a 95 percent Wilson interval. The restricted mean time to threshold counts runs that never cross as reaching the horizon. Year \code{t} is the census taken in interval \code{t - 1}; year 0 is the initial census. Both risk functions apply the same year-zero and census selection. Passing the whole run checks every scheduled run and interval, including extinct replicates. A bare census table only identifies runs and times present in that table. -\code{summarise_accounting()} checks \code{n_start + births + introductions - deaths - removals = n_end} for each run and interval and reports losses separately for residents, individuals born in the interval and individuals introduced in the interval. +\code{summarise_accounting()} checks each process against the preceding receipt and the running stocks of residents, newborns and introductions. It reports losses by cohort, the expected final stock and the residual (observed minus expected). An interval reconciles only if the receipts join, stocks stay non-negative and each recorded stock agrees with the flows. + +\code{summarise_trajectory()} requires finite recorded abundances and accepts a missing metric only alongside \code{n_alive = 0}. Each year reports \code{n_observed} values, their 5th, 25th, 50th, 75th and 95th percentiles, and \code{n_extant} runs with positive abundance (unknown when abundance was not recorded). Cumulative risk counts observed threshold crossings among all runs, including crossings before rescue. \code{summarise_pva()} requires a finite value for every run and interval. } \value{ \code{summarise_pva()} returns a one-row data frame, \code{summarise_trajectory()} one row per year, and \code{summarise_accounting()} one row per run and interval with a logical \code{reconciled}. } +\examples{ +scenario <- scenario_spec( + name = "small_population", n_runs = 60, n_steps = 12, seed = 11, + init_fun = function() pva_population(sex = rep(c("F", "M"), 5), age = 1), + processes = list( + survival_process(0.75), + age_process(), + reproduction_process( + breeding_probability = 0.5, litter_size = litter_poisson(1.1), + offspring_sex = offspring_sex_bernoulli(0.5) + ), + census_process() + ), + initial_census = census_process() +) +run <- run_scenario(scenario) +summarise_pva(run, threshold = 5)[, c("p_ever_below", "p_ever_below_lower", + "p_ever_below_upper", "final_median")] +tail(summarise_trajectory(run, threshold = 5)[, c("year", "median", "q05", "q95", + "p_ever_below")], 3) +all(summarise_accounting(run)$reconciled) +} diff --git a/scripts/benchmark_kinship_mating.R b/scripts/benchmark_kinship_mating.R new file mode 100644 index 0000000..04b93e5 --- /dev/null +++ b/scripts/benchmark_kinship_mating.R @@ -0,0 +1,95 @@ +# Rscript --vanilla scripts/benchmark_kinship_mating.R (installed OpenPVA) +# Times kinship-aware mating with 200 eligible females and 200 eligible males +# after ten discrete generations of random mating, under the dense store and +# under ancestor tracing, and checks that both stores choose the same mates. +library(OpenPVA) + +everyone <- function(pop, state, context, params) rep(TRUE, length(pop$id)) +generation <- pva_process( + "generation", function(state, context, params) { + pop <- state$population + dams <- which(pop$sex == "F") + sires <- which(pop$sex == "M") + n <- length(pop$id) + state <- add_individuals( + state, rep(c("F", "M"), n / 2L), 0L, mate_id = NA_integer_, + mother_id = pop$id[dams[sample.int(length(dams), n, replace = TRUE)]], + father_id = pop$id[sires[sample.int(length(sires), n, replace = TRUE)]] + ) + pva_result(state, pva_events("birth", n)) + }, creates = c("age", "sex", "mate_id") +) +replace_adults <- removal_process(select = function(pop, state, context, params) pop$age > 0L) +life <- list(generation, replace_adults, age_process()) + +build <- function(limit, generations = 10L) { + set.seed(20261127L) + state <- pva_state(pva_population(rep(c("F", "M"), 200L), 1L, mate_id = NA_integer_), + pedigree = TRUE, max_dense_kinship = limit) + for (step in seq_len(generations)) { + state <- execute_processes(state, life, time = step - 1L, validation = "fast")$state + } + state +} + +pairing <- pairing_process(everyone, priority = "kinship") +polygyny <- mate_min_kinship(everyone, ties = "id") +cat(R.version.string, "| OpenPVA", as.character(packageVersion("OpenPVA")), "\n") +results <- list() +for (store in c("dense", "traced")) { + state <- build(if (store == "dense") 2000L else 1L) + stopifnot(is.matrix(state$kinship) == (store == "dense"), length(state$population$id) == 400L) + seconds <- function(expr) system.time(expr)[["elapsed"]] + for (priority in c("kinship", "mean_kinship")) { + full <- pairing_process(everyone, priority = priority) + limited <- pairing_process(everyone, capacity = 150, priority = priority, max_kinship = 0.02) + t_pair <- seconds(paired <- execute_processes(state, list(full), validation = "fast")) + t_limited <- seconds(capped <- execute_processes(state, list(limited), validation = "fast")) + mates <- paired$state$population$mate_id + capped <- capped$state$population$mate_id + results[[store]][[priority]] <- list(pairs = mates, capped = capped) + cat(sprintf(paste0("%-6s | %-12s | 200 x 200 %.3f s (%d pairs) | ", + "capacity 150, max_kinship 0.02: %.3f s (%d pairs)\n"), + store, priority, t_pair, sum(!is.na(mates)) / 2L, + t_limited, sum(!is.na(capped)) / 2L)) + } + t_mate <- seconds(sires <- polygyny(state$population, state, NULL, NULL)) + t_mean <- seconds(mk <- mean_kinship(state)) + results[[store]]$sires <- sires + results[[store]]$mk <- mk + cat(sprintf("%-6s | mate_min_kinship %.3f s | mean_kinship %.3f s | mean kinship %.5f\n", + store, t_mate, t_mean, mean(mk))) +} +stopifnot( + identical(results$dense$kinship, results$traced$kinship), + identical(results$dense$mean_kinship, results$traced$mean_kinship), + identical(results$dense$sires, results$traced$sires), + max(abs(results$dense$mk - results$traced$mk)) < 1e-13 +) +cat("Dense and traced stores chose identical mates.\n") + +# Traced queries beyond the benchmark size: 1,000 females by 1,000 males. +large <- local({ + set.seed(20261127L) + state <- pva_state(pva_population(rep(c("F", "M"), 1000L), 1L, mate_id = NA_integer_), + pedigree = TRUE, max_dense_kinship = 1L) + for (step in 1:6) { + state <- execute_processes(state, life, time = step - 1L, validation = "fast")$state + } + state +}) +stopifnot(!is.matrix(large$kinship), length(large$population$id) == 2000L) +t_mate <- system.time(polygyny(large$population, large, NULL, NULL))[["elapsed"]] +t_pair <- system.time(execute_processes(large, list(pairing), validation = "fast"))[["elapsed"]] +cat(sprintf("traced | 1000 x 1000 after 6 generations: mate_min_kinship %.3f s | exact pairing %.3f s\n", + t_mate, t_pair)) + +# The solver alone on dense random scores, with and without constraints. +set.seed(1L) +score <- matrix(as.numeric(sample.int(2^20, 200L * 200L, replace = TRUE)), 200L) +t_free <- system.time(free <- OpenPVA:::.min_kinship_pairs(score, 200))[["elapsed"]] +blocked <- score +blocked[score > 2^18] <- Inf +t_blocked <- system.time(some <- OpenPVA:::.min_kinship_pairs(blocked, 150))[["elapsed"]] +cat(sprintf("solver 200 x 200: unconstrained %.3f s (%d pairs); 75%% inadmissible, capacity 150: %.3f s (%d pairs)\n", + t_free, nrow(free), t_blocked, nrow(some))) diff --git a/scripts/build_rd.R b/scripts/build_rd.R index 4292550..7f8df10 100644 --- a/scripts/build_rd.R +++ b/scripts/build_rd.R @@ -24,15 +24,23 @@ usage_for <- function(name) { ) } }, character(1)) - one_line <- paste0(name, "(", paste(pieces, collapse = ", "), ")") + # An S3 method is written as \method{generic}{class}, as R CMD check requires. + call <- name + if (name %in% s3_methods) { + parts <- strsplit(name, ".", fixed = TRUE)[[1L]] + call <- paste0("\\method{", parts[[1L]], "}{", paste(parts[-1L], collapse = "."), "}") + } + one_line <- paste0(call, "(", paste(pieces, collapse = ", "), ")") if (nchar(one_line) <= 80L) { return(one_line) } - paste0(name, "(\n ", paste(pieces, collapse = ",\n "), "\n)") + paste0(call, "(\n ", paste(pieces, collapse = ",\n "), "\n)") } +s3_methods <- unlist(lapply(topics, `[[`, "methods")) + write_topic <- function(file, topic) { - functions <- topic$functions + functions <- c(topic$functions, topic$methods) arguments <- unique(unlist(lapply(functions, function(name) { names(formals(get(name, envir = namespace))) }))) @@ -92,6 +100,7 @@ writeLines(c( "\\alias{print.pva_process}", "\\alias{print.pva_scenario}", "\\alias{print.pva_run}", + "\\alias{print.pva_ensemble}", "\\title{Print OpenPVA objects}", "\\usage{", "\\method{print}{pva_state}(x, ...)", @@ -101,12 +110,14 @@ writeLines(c( "\\method{print}{pva_scenario}(x, ...)", "", "\\method{print}{pva_run}(x, ...)", + "", + "\\method{print}{pva_ensemble}(x, ...)", "}", "\\arguments{", - "\\item{x}{An OpenPVA state, process, scenario or run.}", - "\\item{\\dots}{Ignored.}", + "\\item{x}{An OpenPVA state, process, scenario, run or ensemble.}", + "\\item{\\dots}{For ensembles, arguments passed to the data-frame print method.}", "}", - "\\description{One-line summaries of OpenPVA objects.}", + "\\description{Summarise an OpenPVA object. For ensembles, print the run count and root seed above the design and summary rows.}", "\\value{\\code{x}, invisibly.}" ), "man/print.pva_state.Rd") diff --git a/scripts/check_r_floor.R b/scripts/check_r_floor.R index fae0634..ecfd464 100644 --- a/scripts/check_r_floor.R +++ b/scripts/check_r_floor.R @@ -7,11 +7,32 @@ private_lib <- normalizePath(args[[1L]], mustWork = TRUE) library(OpenPVA, lib.loc = private_lib) cat(R.version.string, "\nOpenPVA", as.character(packageVersion("OpenPVA")), "\n") -floor_population <- function() pva_state(pva_population(rep(c("F", "M"), 4L), 2L), - pedigree = TRUE) +floor_population <- function() pva_state( + pva_population(rep(c("F", "M"), 4L), 2L, mate_id = NA_integer_, + patch_id = rep(c("shore", "ridge"), each = 4L)), + pedigree = TRUE, n_loci = 4L +) +floor_everyone <- function(pop, state, context, params) rep(TRUE, length(pop$id)) floor_components <- function(row) { + # Exercises the 2.1.0 additions: correlated environments, kinship-aware + # pairing and mating, neutral loci and the genetic census. list(init_fun = floor_population, n_steps = 4L, - processes = list(survival_process(row$p), census_process())) + processes = list( + environment_process(list(weather = env_ar1( + sd = c(ridge = 0.3, shore = 0.15), phi = 0.5, + cor = spatial_correlation(c("shore", "ridge"), rho = 0.5) + ))), + survival_process(function(pop, state, context, params) { + shift_logit(params$p, state$globals$weather[pop$patch_id]) + }, requires = c("globals.weather", "population.patch_id"), params = list(p = row$p)), + pairing_process(floor_everyone, priority = "mean_kinship", max_kinship = 0.3, + by = "patch_id"), + reproduction_process(0.5, litter_poisson(1), offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(by = "patch_id"), inherit = "patch_id", + newborn_fields = function(...) list(mate_id = NA_integer_), + newborn_field_names = "mate_id"), + census_process(genetic_metrics()) + )) } design <- data.frame(p = c(0.7, 0.9)) scenario <- do.call(scenario_spec, c(list(name = "floor", n_runs = 4L, seed = 23L), @@ -21,12 +42,15 @@ Sys.unsetenv(c("R_LIBS", "R_LIBS_USER", "R_LIBS_SITE")) cl <- parallel::makePSOCKcluster(2L, rscript_args = "--vanilla") tryCatch({ workers <- parallel::clusterCall(cl, function() { - list(version = as.character(getRversion()), paths = .libPaths()) + .libPaths(.Library, include.site = FALSE) + list(version = as.character(getRversion()), paths = .libPaths(), + loaded = "OpenPVA" %in% loadedNamespaces(), found = nzchar(system.file(package = "OpenPVA"))) }) for (worker in workers) { - stopifnot(identical(worker$version, "4.1.0"), !private_lib %in% worker$paths) + stopifnot(identical(worker$version, "4.1.0"), identical(worker$paths, .Library), + !worker$loaded, !worker$found) } - cat("Both fresh PSOCK workers run R 4.1.0 and start outside the private library.\n") + cat("Both --vanilla R 4.1.0 workers have only the base library and cannot find OpenPVA.\n") set.seed(521L) before <- .Random.seed serial <- run_scenario(scenario) diff --git a/scripts/rd_topics.R b/scripts/rd_topics.R index 05f2c1b..36a881c 100644 --- a/scripts/rd_topics.R +++ b/scripts/rd_topics.R @@ -12,6 +12,7 @@ common_arguments <- list( ), state = r"(A \code{pva_state}.)", field = "Name of the population field the process reads or writes.", + by = r"(Optional population field for mating groups. Partners must share a non-missing value of this field, for example \code{"patch_id"}. The process declares the field as a requirement.)", cause = r"(Label stored with the accounting event, for example \code{"natural"} or \code{"harvest"}.)", result = r"(A \code{pva_run} from \code{\link{run_scenario}}.)", validation = r"(\code{"strict"} checks every process transition (declared writes, types, engine-owned fields and cohort accounting). \code{"fast"} skips those checks and gives bit-identical output for a valid model.)", @@ -41,13 +42,14 @@ topics <- list( globals = "Named list of shared dynamic values, such as the year's environmental deviates.", pedigree = r"(Whether the engine tracks exact pedigree inbreeding. When \code{TRUE} the population gains the engine-owned field \code{pedigree_F}.)", kinship = "Optional matrix of starting coancestries in population order. It takes precedence over recorded initial parentage.", - max_dense_kinship = "Maximum number of dense pedigree slots per replicate (default 2000). Once the required slots exceed this limit, the engine uses exact sparse ancestor tracing for the rest of that replicate, even if the population later falls below the limit." + max_dense_kinship = "Maximum number of dense pedigree slots per replicate (default 2000). Once the required slots exceed this limit, the engine uses exact sparse ancestor tracing for the rest of that replicate, even if the population later falls below the limit.", + n_loci = r"(Number of unlinked neutral loci to drop through the pedigree. The default \code{0} stores no genotypes and draws no random numbers. See \code{\link{summarise_markers}}.)" ), description = r"(The population is columnar: a named list of equal-length vectors with one element per \emph{living} individual. \code{pva_population()} builds it, \code{pva_state()} wraps it with shared globals and the identifier allocator, and \code{add_individuals()} is the only way for a process to create individuals.)", details = r"(Core fields are \code{id}, \code{sex}, \code{age}, \code{alive}, \code{mother_id}, \code{father_id}, \code{origin} and \code{entry_time}. The engine owns \code{id}, \code{origin} (\code{"initial"}, \code{"birth"} or \code{"introduction"}), \code{entry_time} (the interval of entry, \code{-1} for the initial population) and \code{pedigree_F}; processes cannot write them. A process records mortality by setting \code{alive} to \code{FALSE}. After each process the engine moves those records out of the living table into the optional ledger, so every process starts with living individuals only. -Without a supplied matrix, initial parent IDs must resolve inside the initial population in an acyclic pedigree. Each unknown parent is an unrelated, non-inbred contribution. A newborn's inbreeding coefficient is its parents' kinship. Known parents can be living or can have died earlier in the same interval. Use \code{\link{kinship_matrix}} for living pairs in either storage mode.)", - value = r"(\code{pva_population()} returns the columnar population. \code{pva_state()} returns a \code{pva_state} with elements \code{population}, \code{globals}, \code{next_id}, \code{kinship} and \code{max_dense_kinship}. \code{add_individuals()} returns the state with the new records appended and \code{next_id} advanced.)", +When pedigree or markers are enabled, an initial mother must be female and an initial father male whenever their IDs are present. Without a supplied matrix, initial parent IDs must resolve inside the initial population in an acyclic pedigree. Each unknown parent is an unrelated, non-inbred contribution. A newborn's inbreeding coefficient is its parents' kinship. Known parents can be living or can have died earlier in the same interval. Use \code{\link{kinship_matrix}} for living pairs in either storage mode.)", + value = r"(\code{pva_population()} returns the columnar population. \code{pva_state()} returns a \code{pva_state} with elements \code{population}, \code{globals}, \code{next_id}, \code{kinship}, \code{max_dense_kinship} and \code{markers}. \code{add_individuals()} returns the state with the new records appended and \code{next_id} advanced.)", examples = r"(population <- pva_population(sex = c("F", "F", "M"), age = c(3, 1, 4), patch_id = 1L) state <- pva_state(population, globals = list(year_quality = 1), pedigree = TRUE) state @@ -162,7 +164,8 @@ summarise_pva(run_scenario(scenario), threshold = 10))" title = "Litter-size, offspring-sex and mating helpers", functions = c( "litter_poisson", "litter_binomial", "litter_categorical", - "offspring_sex_bernoulli", "mate_random", "mate_from_field" + "offspring_sex_bernoulli", "mate_random", "mate_from_field", + "mate_min_kinship" ), arguments = list( mean = paste0( @@ -178,11 +181,15 @@ summarise_pva(run_scenario(scenario), threshold = 10))" stale = r"(How to handle a female's recorded sire ID when the sire is absent and did not depart in the current interval. The default \code{"error"} rejects that ID. With \code{"unpaired"}, reproduction treats the female as having no mate and preserves the field.)", eligible = paste0( "Function of ", callback, - " returning one logical value per living individual; males flagged TRUE can sire offspring." - ) + " returning one logical value per living individual. Males flagged TRUE can sire offspring. For mate_min_kinship(), NULL makes every living male eligible." + ), + max_kinship = r"(Largest admissible kinship between a female and her sire. A female with no eligible male at or below it receives \code{NA}, so she skips breeding when \code{require_mate = TRUE}.)", + ties = r"(How \code{mate_min_kinship()} chooses among equally unrelated males: one uniform draw per living female (\code{"random"}) or the lowest identifier (\code{"id"}).)" ), description = r"(Building blocks for \code{\link{reproduction_process}()}. Litter size can be Poisson, bounded binomial (under-dispersed, with a maximum) or an explicit categorical distribution. \code{mate_random()} gives each female a sire drawn at random from the eligible males, so breeding is limited only when no eligible male is alive. A bounded binomial litter adds \code{min_size} to a binomial draw with \code{size - min_size} trials, giving the specified conditional mean.)", - details = r"(\code{mate_from_field()} reads a vector of positive integer IDs or \code{NA}. A female's living sire must be male. A sire who died or was removed earlier in the current interval still fathers her offspring in either mode. The offspring retain his ID and pedigree, and \code{newborn_fields} receives \code{NA} for his living row. With \code{stale = "unpaired"}, any other absent sire is treated as \code{NA} for this breeding event. An unpaired female skips breeding unless \code{require_mate = FALSE}, in which case her offspring have an unknown sire.)", + details = r"(\code{mate_from_field()} reads a vector of positive integer IDs or \code{NA}. A female's living sire must be male. A sire who died or was removed earlier in the current interval still fathers her offspring in either mode. The offspring retain his ID and pedigree, and \code{newborn_fields} receives \code{NA} for his living row. With \code{stale = "unpaired"}, any other absent sire is treated as \code{NA} for this breeding event. An unpaired female skips breeding unless \code{require_mate = FALSE}, in which case her offspring have an unknown sire. + +\code{mate_min_kinship()} gives each female the eligible male with whom her kinship is lowest (polygyny: a male can sire several litters). It needs \code{pva_state(pedigree = TRUE)}. Kinships are compared on a grid of \eqn{2^{-30}}, so the dense and traced pedigree stores choose the same sires, and the number of random draws does not depend on the store or on the number of ties.)", value = r"(A function suitable for the corresponding argument of \code{\link{reproduction_process}()}.)", examples = r"(cubs <- litter_categorical(sizes = 1:3, probabilities = c(0.2, 0.6, 0.2)) pop <- pva_population(sex = c("F", "F", "M"), age = 6) @@ -206,10 +213,11 @@ cubs(mothers = 1:2, pop = pop, state = NULL, context = NULL, params = NULL))" ), order = r"(How a \code{count} removal chooses individuals: at random, or lowest identifiers first.)", 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 (and optionally \code{mother_id} and \code{father_id}) of the \code{n} introduced individuals.)", + 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.)", source = "Label stored with the introduction event.", - priority = r"(Which eligible individuals obtain a pair when capacity is limiting: lowest identifiers first (\code{"id"}) or a random draw (\code{"lottery"}).)", + 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.)", eligible = paste0( "Function of ", callback, r"( returning one logical value per living individual. Optional (\code{NULL} means everyone) except for \code{pairing_process()}.)" @@ -217,6 +225,7 @@ cubs(mothers = 1:2, pop = pop, state = NULL, context = NULL, params = NULL))" field = "Integer population field that receives each paired individual's mate identifier." ), description = r"(\code{removal_process()} takes individuals out of the population as accounted removals (harvest, culling, capture). \code{ceiling_process()} imposes a hard abundance ceiling by random deaths. \code{introduction_process()} adds individuals (supplementation, release, immigration). \code{pairing_process()} forms monogamous pairs each interval up to a capacity, leaving surplus eligible individuals as unpaired floaters; with unlimited capacity it is a pair (mate) limitation, with finite capacity a territory limit.)", + details = r"(\code{pairing_process()} forms a new set of pairs each time it runs. With \code{priority = "kinship"} it needs \code{pva_state(pedigree = TRUE)} and solves an exact assignment: it forms the largest number of pairs allowed by \code{capacity} and \code{max_kinship} and, among all such sets, one with the smallest sum of within-pair kinships. With \code{priority = "mean_kinship"} the same limits apply. Among maximum-size matchings, the process first minimises the summed mean kinship of the selected breeders to the entire living population, including themselves. Total within-pair kinship breaks ties. Kinships are compared on a grid of \eqn{2^{-30}}; values within eight ulp of a half-grid midpoint snap consistently across dense and traced storage. The solution uses no random numbers and equally good sets resolve by identifier order. Solving takes time cubic in the number of eligible individuals of the rarer sex.)", value = r"(A \code{pva_process}.)", examples = r"(state <- pva_state(pva_population( sex = rep(c("F", "M"), each = 4), age = 2, mate_id = NA_integer_ @@ -240,10 +249,20 @@ out$events[, c("process_name", "event_type", "value")])" environment_processes = list( title = "Environmental variation and catastrophes", functions = c( - "environment_process", "catastrophe_process", "beta_shapes", "shift_logit" + "environment_process", "env_ar1", "env_trend", "spatial_correlation", "catastrophe_process", + "beta_shapes", "shift_logit" ), arguments = list( - variables = r"(Named list of functions of \code{(state, context, params)}. Each value is written to the global of the same name, in order, so later functions can read earlier ones.)", + variables = r"(Named list of functions of \code{(state, context, params)}. Each value is written to the global of the same name, in order, so later functions can read earlier ones. The variable's own name is supplied as \code{context$variable}.)", + phi = "Lag-one autocorrelation of the anomaly, strictly between -1 and 1.", + cor = r"(Optional correlation matrix among the components (patches, vital rates or both). It may be singular: perfect synchrony is allowed. \code{NULL} gives independent components.)", + names = r"(Optional component order for the returned vector. The default uses matrix dimnames, then names on \code{sd}. Named inputs must match the component names.)", + level = r"(One constant, a vector indexed by successive intervals (optionally named 0, 1, ...), a matrix with one row per interval and one column per component, or a function of \code{time} accepting optional \code{dt} and \code{params}. Use a matrix or function for patch-specific levels.)", + patches = "Unique patch identifiers in component order.", + rho = "Common correlation between distinct patches, at least -1/(p-1) for p > 1 and at most 1.", + distances = "Symmetric, non-negative matrix of distances between patches with zero diagonal.", + scale = r"(Positive distance scale for \eqn{\exp(-d/\mathrm{scale})}. Use \code{Inf} for perfect synchrony.)", + anomaly = r"(Optional name of an environment variable listed earlier in the same \code{environment_process()}, added to the level.)", probability = r"(For \code{catastrophe_process()}: the per-interval probability of a catastrophe, as one number or a function of \code{(state, context, params)}. For \code{shift_logit()}: probabilities to shift.)", mortality = paste0( "Optional direct mortality applied when a catastrophe occurs: one probability, or a function of ", @@ -251,11 +270,16 @@ out$events[, c("process_name", "event_type", "value")])" ), global = "Name of the logical global that records whether the catastrophe occurred this interval.", mean = "Mean of the beta distribution, in (0, 1).", - sd = "Standard deviation of the beta distribution.", + sd = r"(For \code{beta_shapes()}: standard deviation of the beta distribution. For \code{env_ar1()}: the stationary standard deviation of each component (one value, or one per component).)", deviation = "Deviation added on the logit scale. Structural probabilities zero and one remain fixed even under infinite shifts." ), - description = r"(\code{environment_process()} draws the interval's shared environmental conditions into globals, where rate functions read them. \code{catastrophe_process()} draws a Bernoulli catastrophe flag and can apply direct mortality. \code{beta_shapes()} converts a mean and standard deviation to beta shape parameters, and \code{shift_logit()} perturbs probabilities on the logit scale.)", - value = r"(The process constructors return a \code{pva_process}. \code{beta_shapes()} returns a list with \code{shape1} and \code{shape2}; \code{shift_logit()} returns probabilities.)", + description = r"(\code{environment_process()} draws the interval's shared environmental conditions into globals, where rate functions read them. \code{catastrophe_process()} draws a Bernoulli catastrophe flag and can apply direct mortality. \code{beta_shapes()} converts a mean and standard deviation to beta shape parameters, and \code{shift_logit()} perturbs probabilities on the logit scale. \code{env_ar1()} and \code{env_trend()} build variables for \code{environment_process()}: a temporally autocorrelated, cross-correlated anomaly and a deterministic trend or regime shift.)", + details = r"(\code{env_ar1()} generates \eqn{z_t = \phi z_{t-1} + \sqrt{1 - \phi^2}\,\sigma\,L\epsilon_t}, where \eqn{LL^\top} is \code{cor} and \eqn{\epsilon_t} is standard normal. The first value is drawn from the stationary distribution, so every interval has mean zero, standard deviation \code{sd} and correlation \code{cor}, and the covariance at lag \eqn{k} is \eqn{\phi^k} times the lag-zero covariance. Changing \code{phi} changes the temporal correlation while preserving the stationary standard deviations. Named standard deviations and lagged values follow the component labels. Named correlation matrices must have identical, unique row and column names. The lagged value is read from the variable's own global, so supplying that global in the initial state conditions the first interval on it. The generator draws a fixed number of normal deviates per interval and keeps no state of its own, which keeps replicates bit-identical across serial, fork and PSOCK execution. + +\code{spatial_correlation()} constructs a matrix for \code{cor} using a common \code{rho} across patches or exponential decay with distance. + +\code{env_trend()} returns the level for the current interval and, when \code{anomaly} is named, adds that interval's anomaly. Because the level is added after the autoregression, a trend or regime shift takes full effect in its own interval.)", + value = r"(The process constructors return a \code{pva_process}. \code{spatial_correlation()} returns a square numeric matrix. \code{env_ar1()} and \code{env_trend()} return functions for \code{variables}; their values are numeric vectors with one element per component. \code{beta_shapes()} returns a list with \code{shape1} and \code{shape2}; \code{shift_logit()} returns probabilities.)", examples = r"(weather <- environment_process( variables = list(survival_deviate = function(state, context, params) rnorm(1, 0, 0.3)) ) @@ -271,7 +295,17 @@ state <- pva_state( globals = list(survival_deviate = 0, cyclone = FALSE) ) set.seed(3) -execute_processes(state, list(weather, cyclone, survival, census_process()))$census)" +execute_processes(state, list(weather, cyclone, survival, census_process()))$census + +# Red noise shared by two patches (correlation 0.6) around a warming step. +climate <- environment_process(list( + anomaly = env_ar1(sd = 0.3, phi = 0.5, + cor = spatial_correlation(c("a", "b"), rho = 0.6)), + climate = env_trend(function(time) if (time >= 1) 0.5 else 0, anomaly = "anomaly") +)) +state <- pva_state(pva_population(sex = c("F", "M"), age = 2)) +state <- execute_processes(state, list(climate), time = 0)$state +execute_processes(state, list(climate), time = 1)$state$globals)" ), density_multipliers = list( title = "Density-feedback multipliers", @@ -292,11 +326,12 @@ ceiling_density_multiplier(n, capacity = 100))" inbreeding = list( title = "Pedigree summaries and inbreeding depression", functions = c( - "summarise_pedigree", "kinship_matrix", "inbreeding_multiplier", + "summarise_pedigree", "kinship_matrix", "mean_kinship", "inbreeding_multiplier", "inbreeding_proxy_process", "sex_ratio_effective_size" ), arguments = list( - ids = "Distinct living IDs, in desired matrix order. Defaults to every living individual.", + ids = "Distinct living IDs, in the desired row order. Defaults to every living individual.", + against = r"(Distinct living IDs for the matrix columns, in the desired order. Defaults to \code{ids}.)", generation_time = "Generation time in model intervals. Required for the effective-size approximation.", inbreeding = "Inbreeding coefficients in [0, 1].", lethal_equivalents = r"(Slope \code{B} of the log-linear cost \code{exp(-B * F)}.)", @@ -311,9 +346,9 @@ ceiling_density_multiplier(n, capacity = 100))" n_females = "Number of breeding females.", n_males = "Number of breeding males." ), - description = r"(\code{summarise_pedigree()} reports exact mean and maximum individual inbreeding, mean living kinship (including self-kinship) and gene diversity. \code{kinship_matrix(state, ids)} returns coancestry for the requested living individuals. The retained ancestry grows with the recorded pedigree. Starting animals with nonzero mutual kinship retain a covariance block. A full returned matrix requires quadratic space. \code{inbreeding_multiplier()} scales a particular fitness component by \code{exp(-B * F)} using lethal equivalents for that component and period.)", + description = r"(\code{summarise_pedigree()} reports exact mean and maximum individual inbreeding, mean living kinship (including self-kinship), gene diversity and founder genome equivalents, \eqn{1 / (2 \bar{K})}, where \eqn{\bar{K}} averages every living pair including each individual with itself; \eqn{N} unrelated, non-inbred founders give exactly \eqn{N}. \code{mean_kinship(state, ids)} returns each requested individual's mean kinship with every living individual, itself included. \code{kinship_matrix(state, ids, against)} returns the coancestry block for the two sets of living IDs in their supplied order. The retained ancestry grows with the recorded pedigree. Starting animals with nonzero mutual kinship retain a covariance block. A full returned matrix requires quadratic space. \code{inbreeding_multiplier()} scales a particular fitness component by \code{exp(-B * F)} using lethal equivalents for that component and period.)", details = r"(The scalar proxy converts per-generation drift to per-interval drift \eqn{d = 1 - (1 - 1/(2N_e))^{1/G}}, with generation time \eqn{G}. The per-generation drift is capped at one, and zero effective size leaves drift at zero. The update is \eqn{(d + (1-d)F)(1-m)^2}, where \eqn{m} is the interval's immigrant gene fraction. Initialise the target global with a coefficient in [0, 1]. An interval with introductions and no migration function raises an error in strict mode and a warning in fast mode. This scalar approximation misses F1 heterosis under supplementation. Use \code{pedigree = TRUE} to distinguish the kinships of individual matings. \code{sex_ratio_effective_size()} gives \eqn{4N_fN_m/(N_f+N_m)}.)", - value = r"(\code{summarise_pedigree()} returns a one-row data frame; \code{kinship_matrix()} a numeric matrix; \code{inbreeding_multiplier()} and \code{sex_ratio_effective_size()} numeric vectors; \code{inbreeding_proxy_process()} a \code{pva_process}.)", + value = r"(\code{summarise_pedigree()} returns a one-row data frame; \code{kinship_matrix()} a numeric matrix; \code{mean_kinship()}, \code{inbreeding_multiplier()} and \code{sex_ratio_effective_size()} numeric vectors; \code{inbreeding_proxy_process()} a \code{pva_process}.)", examples = r"(inbreeding_multiplier(c(0, 0.125, 0.25), lethal_equivalents = 3) scenario <- scenario_spec( name = "one_pair", n_runs = 1, n_steps = 4, seed = 2, @@ -374,8 +409,30 @@ all(summarise_accounting(run)$reconciled))" description = r"(\code{summarise_pva()} reports the probability of being below the threshold at the horizon, the probability of ever falling below it (first crossing), time to threshold and final abundance, each with a Monte Carlo standard error or interval. \code{summarise_trajectory()} gives the same quantities by year. \code{summarise_accounting()} reconciles every interval by cohort.)", details = r"(Proportions carry a binomial Monte Carlo standard error and a 95 percent Wilson interval. The restricted mean time to threshold counts runs that never cross as reaching the horizon. Year \code{t} is the census taken in interval \code{t - 1}; year 0 is the initial census. Both risk functions apply the same year-zero and census selection. Passing the whole run checks every scheduled run and interval, including extinct replicates. A bare census table only identifies runs and times present in that table. -\code{summarise_accounting()} checks \code{n_start + births + introductions - deaths - removals = n_end} for each run and interval and reports losses separately for residents, individuals born in the interval and individuals introduced in the interval.)", - value = r"(\code{summarise_pva()} returns a one-row data frame, \code{summarise_trajectory()} one row per year, and \code{summarise_accounting()} one row per run and interval with a logical \code{reconciled}.)" +\code{summarise_accounting()} checks each process against the preceding receipt and the running stocks of residents, newborns and introductions. It reports losses by cohort, the expected final stock and the residual (observed minus expected). An interval reconciles only if the receipts join, stocks stay non-negative and each recorded stock agrees with the flows. + +\code{summarise_trajectory()} requires finite recorded abundances and accepts a missing metric only alongside \code{n_alive = 0}. Each year reports \code{n_observed} values, their 5th, 25th, 50th, 75th and 95th percentiles, and \code{n_extant} runs with positive abundance (unknown when abundance was not recorded). Cumulative risk counts observed threshold crossings among all runs, including crossings before rescue. \code{summarise_pva()} requires a finite value for every run and interval.)", + value = r"(\code{summarise_pva()} returns a one-row data frame, \code{summarise_trajectory()} one row per year, and \code{summarise_accounting()} one row per run and interval with a logical \code{reconciled}.)", + examples = r"(scenario <- scenario_spec( + name = "small_population", n_runs = 60, n_steps = 12, seed = 11, + init_fun = function() pva_population(sex = rep(c("F", "M"), 5), age = 1), + processes = list( + survival_process(0.75), + age_process(), + reproduction_process( + breeding_probability = 0.5, litter_size = litter_poisson(1.1), + offspring_sex = offspring_sex_bernoulli(0.5) + ), + census_process() + ), + initial_census = census_process() +) +run <- run_scenario(scenario) +summarise_pva(run, threshold = 5)[, c("p_ever_below", "p_ever_below_lower", + "p_ever_below_upper", "final_median")] +tail(summarise_trajectory(run, threshold = 5)[, c("year", "median", "q05", "q95", + "p_ever_below")], 3) +all(summarise_accounting(run)$reconciled))" ), run_pva_ensemble = list( title = "Run a designed ensemble of scenarios", @@ -392,7 +449,7 @@ all(summarise_accounting(run)$reconciled))" ), 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, 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.)", - value = r"(A data frame: the design rows, \code{member}, \code{member_seed} and the summary columns. Provenance is attached as an attribute.)", + 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) { list( @@ -447,5 +504,86 @@ state <- pva_state(pva_population(sex = rep(c("F", "M"), 10), age = 2, patch_id set.seed(4) moved <- execute_processes(state, list(markov_dispersal_process(transition))) patch_counts(moved$state$population, c("north", "south")))" + ), + markers = list( + title = "Neutral-locus gene drop and genetic census metrics", + functions = c("summarise_markers", "marker_founder_shares", "genetic_metrics"), + arguments = list(), + description = r"(\code{pva_state(n_loci = L)} drops \eqn{L} unlinked neutral loci through the simulated pedigree. \code{summarise_markers()} reports heterozygosity, allelic richness and the retention of the starting population's alleles; \code{marker_founder_shares()} reports the share of the living gene pool that descends from each source individual; \code{genetic_metrics()} supplies both pedigree and marker metrics to \code{\link{census_process}()}.)", + details = r"(Every initial individual without recorded parents carries two unique alleles at every locus. An offspring inherits, independently at each locus, one of its mother's two copies and one of its father's two. An unknown parent contributes one new allele. Introductions must have two unknown parents and bring two novel alleles. A birth with only an unrecorded sire brings one. A parent lost earlier in the same interval still transmits its alleles. The alleles issued to the initial population are the \emph{native} alleles. + +Member builders, initial gene drops and subsequent segregation in each replicate use distinct L'Ecuyer substreams. When \code{init_fun} returns a prebuilt family, replicates share its initial genotypes and draw offspring independently. Repeated direct \code{pva_state(n_loci = )} calls from the same caller RNG position draw the same initial gene drop because state construction does not advance the caller's stream. Enabling neutral loci therefore leaves every demographic outcome of a seeded run unchanged, and with \code{n_loci = 0} nothing is stored or drawn. The genotypes are engine-owned: a process cannot change them. A supplied starting \code{kinship} matrix is accepted together with \code{n_loci > 0} only if recorded initial parentage reproduces it, because unique founder alleles would otherwise contradict the stated relationships. + +The metrics are: \code{observed_heterozygosity}, the proportion of living individual-locus genotypes with two different alleles; \code{expected_heterozygosity}, \eqn{1 - \frac{1}{L}\sum_{l,a} p_{l,a}^2} with \eqn{p} the allele frequencies among the living (no small-sample correction); \code{allelic_richness}, the mean number of distinct alleles per locus; \code{allelic_retention}, the mean proportion of native alleles still present, which later introductions cannot raise; and \code{native_share}, the proportion of living gene copies that are native. Conditional on the pedigree, expected heterozygosity has mean \eqn{1 - \bar{K}} and observed heterozygosity mean \eqn{1 - \bar{F}} when the founders are unrelated. At extinction richness is zero. Retention is zero when the initial population contributed alleles and otherwise undefined. Heterozygosity, native share and founder genome equivalents are undefined (\code{NA}). + +\code{genetic_metrics()} returns \code{n_alive}, then, with \code{pedigree = TRUE}, \code{mean_inbreeding}, \code{mean_kinship}, \code{gene_diversity} and \code{founder_genome_equivalents}, then the five marker metrics when \code{n_loci > 0}.)", + value = r"(\code{summarise_markers()} returns a one-row data frame. \code{marker_founder_shares()} returns one row per source individual with its \code{id}, whether its alleles are \code{native}, and its \code{share}; every native source is listed, including those whose alleles are lost. \code{genetic_metrics()} returns a function for the \code{metrics} argument of \code{census_process()}.)", + examples = r"(scenario <- scenario_spec( + name = "gene_drop", n_runs = 20, n_steps = 10, seed = 5, + init_fun = function() { + pva_state(pva_population(sex = rep(c("F", "M"), 4), age = 2), + pedigree = TRUE, n_loci = 20) + }, + processes = list( + survival_process(0.8), + age_process(), + reproduction_process( + breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2), + litter_size = litter_poisson(1.5), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(function(pop, state, context, params) pop$age >= 2), + requires = "population.age" + ), + census_process(genetic_metrics()) + ), + initial_census = census_process(genetic_metrics()) +) +run <- run_scenario(scenario, keep = c("census", "state")) +summarise_trajectory(run, metric = "expected_heterozygosity")[ + c(1, 11), c("year", "n_observed", "mean", "q05", "q95")] +summarise_markers(run$states[[1]]) +head(marker_founder_shares(run$states[[1]]), 3))" + ), + plot.pva_run = list( + title = "Diagnostic plots of runs and ensembles", + functions = character(), + methods = c("plot.pva_run", "plot.pva_ensemble"), + arguments = list( + x = r"(A \code{pva_run} from \code{\link{run_scenario}}, or a \code{pva_ensemble} from \code{\link{run_pva_ensemble}}.)", + type = r"(The view to draw. \code{"trajectory"} shows central 50 and 90 percent ribbons with the median and sample replicates, \code{"risk"} shows cumulative first-crossing probability and its Wilson interval as steps or \code{"accounting"} (mean entries and losses per interval against the net change).)", + add = r"(Draw this run in the current panel using its existing axes and limits.)", + runs = "Number of individual replicate trajectories to overlay (the first ones, so no random numbers are drawn).", + y = "Name of the numeric summary column to contrast among ensemble members.", + by = "Design columns that label the members. The default uses every design column.", + `...` = r"(Further arguments for \code{\link[graphics]{plot.default}}, such as \code{main}, \code{ylim} or \code{log}.)" + ), + description = r"(Base-graphics views of a run or an ensemble. Each view draws one exported summary and returns it, so the numbers behind a figure are always available.)", + details = r"(The trajectory and risk views plot \code{\link{summarise_trajectory}()}. A metric that is missing for extinct replicates is summarised over the extant ones. The accounting view plots \code{\link{summarise_accounting}()}: births and introductions above zero, deaths and removals below, the mean net change as points, and a cross on any interval in which a replicate fails to reconcile. + +\code{plot.pva_ensemble()} shows one point per ensemble row with an interval: \code{_lower} and \code{_upper} when the summary has them (as the proportions of \code{\link{summarise_pva}()} do), otherwise 1.96 Monte Carlo standard errors from \code{_mcse}. + +The methods preserve styling, respect the current layout and leave the plotted coordinates active for \code{abline()}, \code{lines()} or \code{legend()}. Use \code{plot(other_run, add = TRUE)} to overlay a second run. Plotting draws no random numbers.)", + value = r"(Invisibly, the plotted table: \code{summarise_trajectory()} for the trajectory and risk views, \code{summarise_accounting()} for the accounting view, and for an ensemble a data frame with \code{label}, \code{estimate}, \code{lower} and \code{upper}.)", + examples = r"(scenario <- scenario_spec( + name = "decline", n_runs = 60, n_steps = 15, seed = 42, + init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 1), + processes = list(survival_process(0.85), age_process(), census_process()), + initial_census = census_process() +) +run <- run_scenario(scenario) +plot(run, threshold = 4) +risk <- plot(run, type = "risk", threshold = 4) +tail(risk[, c("year", "p_ever_below", "p_ever_below_lower", "p_ever_below_upper")], 2) +plot(run, type = "accounting") + +design <- data.frame(survival = c(0.75, 0.85, 0.95)) +build <- function(row) { + list(n_steps = 15, + init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 1), + processes = list(survival_process(row$survival), census_process())) +} +ensemble <- run_pva_ensemble(design, build, n_runs = 60, seed = 7, + summarise = function(result, row) summarise_pva(result, threshold = 4)) +plot(ensemble))" ) ) diff --git a/tests/testthat/helper-genetics.R b/tests/testthat/helper-genetics.R new file mode 100644 index 0000000..c9d978b --- /dev/null +++ b/tests/testthat/helper-genetics.R @@ -0,0 +1,138 @@ +# A random pedigree in identifier order: four unrelated founders, then +# individuals whose parents are drawn from everyone earlier, so matings +# between close relatives (and inbred parents) are common. +random_pedigree <- function(seed, n = 18L) { + set.seed(seed) + sex <- c("F", "M", "F", "M", sample(c("F", "M"), n - 4L, replace = TRUE)) + mother <- father <- rep(NA_integer_, n) + for (i in seq.int(5L, n)) { + earlier <- seq_len(i - 1L) + dams <- earlier[sex[earlier] == "F"] + sires <- earlier[sex[earlier] == "M"] + mother[i] <- dams[sample.int(length(dams), 1L)] + father[i] <- sires[sample.int(length(sires), 1L)] + } + data.frame(id = seq_len(n), sex = sex, mother_id = mother, father_id = father, + stringsAsFactors = FALSE) +} + +# Independent tabular kinship of a pedigree listed in identifier order. +tabular_kinship <- function(pedigree) dense_relationship(pedigree) / 2 + +pedigree_state <- function(pedigree, limit = 2000L, n_loci = 0L) { + pva_state( + pva_population(pedigree$sex, 2L, mother_id = pedigree$mother_id, + father_id = pedigree$father_id, mate_id = NA_integer_), + pedigree = TRUE, max_dense_kinship = limit, n_loci = n_loci + ) +} + +kinship_grid <- function(kinship) round(kinship * 2^30) + +# Exhaustive optimum over every matching, by dynamic programming over the set +# of used columns: the largest number of admissible pairs up to `capacity`, +# and the smallest total score among matchings of that size. +exhaustive_matching <- function(score, capacity) { + n_cols <- ncol(score) + best <- rep(Inf, 2^n_cols) + best[1L] <- 0 + for (i in seq_len(nrow(score))) { + updated <- best + for (mask in which(is.finite(best)) - 1L) { + for (j in seq_len(n_cols)) { + bit <- bitwShiftL(1L, j - 1L) + if (bitwAnd(mask, bit) == 0L && is.finite(score[i, j])) { + target <- bitwOr(mask, bit) + 1L + updated[target] <- min(updated[target], best[mask + 1L] + score[i, j]) + } + } + } + best <- updated + } + size <- vapply(seq_along(best) - 1L, function(mask) sum(bitwAnd(mask, 2^(0:(n_cols - 1L))) > 0), 1) + reachable <- is.finite(best) & size <= capacity + pairs <- max(size[reachable]) + c(pairs = pairs, cost = min(best[reachable & size == pairs])) +} + +# The same optimum by listing every matching explicitly (small cases only). +enumerated_matching <- function(score, capacity) { + best <- c(pairs = 0, cost = 0) + visit <- function(row, used, pairs, cost) { + if (row > nrow(score)) { + if (pairs <= capacity && (pairs > best[["pairs"]] || + (pairs == best[["pairs"]] && cost < best[["cost"]]))) { + best <<- c(pairs = pairs, cost = cost) + } + return(invisible()) + } + visit(row + 1L, used, pairs, cost) + for (j in which(!used & is.finite(score[row, ]))) { + taken <- used + taken[j] <- TRUE + visit(row + 1L, taken, pairs + 1, cost + score[row, j]) + } + } + visit(1L, logical(ncol(score)), 0, 0) + best +} + +# A small managed population that exercises both kinship rules, releases and a +# harvest that can remove a sire between pairing and birth. +managed_scenario <- function(limit = 2000L, n_loci = 0L, n_runs = 3L, n_steps = 8L, + seed = 31L, census = census_process()) { + breeder <- function(pop, state, context, params) pop$age >= 1L + scenario_spec( + name = "managed", n_runs = n_runs, n_steps = n_steps, seed = seed, + init_fun = function() { + pva_state( + pva_population(rep(c("F", "M"), 5L), 2L, mate_id = NA_integer_), + pedigree = TRUE, max_dense_kinship = limit, n_loci = n_loci + ) + }, + processes = list( + age_process(), + pairing_process(breeder, capacity = 4, priority = "kinship", max_kinship = 0.2, + requires = "population.age"), + removal_process(probability = 0.15, cause = "harvest", name = "harvest", + eligible = function(pop, state, context, params) pop$sex == "M"), + reproduction_process( + breeding_probability = function(pop, state, context, params) { + as.numeric(!is.na(pop$mate_id)) + }, + litter_size = litter_poisson(1.8), offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_from_field(stale = "unpaired"), + newborn_fields = function(mothers, fathers, pop, state, context, params) { + list(mate_id = NA_integer_) + }, + newborn_field_names = "mate_id", name = "pair_births", + requires = "population.mate_id" + ), + reproduction_process( + breeding_probability = function(pop, state, context, params) { + 0.4 * (pop$age >= 1L & is.na(pop$mate_id)) + }, + litter_size = litter_poisson(1.2), offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(breeder, max_kinship = 0.3), + newborn_fields = function(mothers, fathers, pop, state, context, params) { + list(mate_id = NA_integer_) + }, + newborn_field_names = "mate_id", name = "floater_births", + requires = c("population.age", "population.mate_id") + ), + introduction_process( + count = function(state, context, params) if (context$time == 3L) 2L else 0L, + fields = function(n, state, context, params) { + list(sex = c("F", "M"), age = 1L, mate_id = NA_integer_) + }, + creates = c("sex", "age", "mate_id") + ), + survival_process(function(pop, state, context, params) { + c(0.6, 0.8)[1L + (pop$age > 0L)] + }, requires = "population.age"), + ceiling_process(capacity = 26), + census + ), + initial_census = census + ) +} diff --git a/tests/testthat/test-environment.R b/tests/testthat/test-environment.R new file mode 100644 index 0000000..0b8d934 --- /dev/null +++ b/tests/testthat/test-environment.R @@ -0,0 +1,208 @@ +# Drive a generator directly: `steps` successive values of one chain, each fed +# back through state$globals as environment_process() does. +ar1_chain <- function(generator, steps) { + state <- list(globals = list()) + out <- NULL + for (step in seq_len(steps)) { + value <- generator(state, list(variable = "z", time = step - 1L), NULL) + state$globals$z <- value + out <- rbind(out, value) + } + out +} + +test_that("the first two steps through a regime shift are exactly the stated recursion", { + patches <- c("north", "mid", "south") + cor <- matrix(c(1, 0.6, 0.2, 0.6, 1, 0.4, 0.2, 0.4, 1), 3L, + dimnames = list(patches, patches)) + sd <- c(0.5, 1, 2) + phi <- 0.7 + level <- function(time) if (time >= 1L) c(5, -3, 0.25) else c(0, 0, 0) + climate <- environment_process(list( + anomaly = env_ar1(sd = sd, phi = phi, cor = cor), + climate = env_trend(level, anomaly = "anomaly") + )) + state <- pva_state(adult_population(1L, 1L)) + set.seed(808L) + first <- execute_processes(state, list(climate), time = 0L)$state + second <- execute_processes(first, list(climate), time = 1L)$state + after <- .Random.seed + + # Replay with the pivoted Cholesky factor, checked to reproduce cor. + upper <- chol(cor, pivot = TRUE) + lower <- t(upper[, order(attr(upper, "pivot"))]) + expect_equal(unname(lower %*% t(lower)), unname(cor), tolerance = 1e-14) + combine <- function(draws) { + as.vector(lower[, 1L] * draws[1L] + lower[, 2L] * draws[2L] + lower[, 3L] * draws[3L]) + } + set.seed(808L) + z0 <- sd * combine(rnorm(3L)) + z1 <- phi * z0 + sqrt(1 - phi^2) * sd * combine(rnorm(3L)) + expect_identical(.Random.seed, after) + expect_identical(unname(first$globals$anomaly), z0) + expect_identical(unname(second$globals$anomaly), z1) + expect_identical(names(first$globals$anomaly), c("north", "mid", "south")) + # The level acts in its own interval: no part of the shift is lagged. + expect_identical(first$globals$climate, first$globals$anomaly) + expect_identical(second$globals$climate, c(5, -3, 0.25) + second$globals$anomaly) + expect_identical(unname(second$globals$anomaly), + phi * unname(first$globals$anomaly) + + (unname(second$globals$anomaly) - phi * unname(first$globals$anomaly))) + + # Without cor and with phi = 0 the generator is sd * rnorm(k), bit for bit. + white <- env_ar1(sd = c(2, 3), phi = 0) + set.seed(4L) + values <- ar1_chain(white, 3L) + set.seed(4L) + expect_identical(unname(values), rbind(c(2, 3) * rnorm(2L), c(2, 3) * rnorm(2L), + c(2, 3) * rnorm(2L))) + + # Vector, matrix and constant levels index the interval. + context <- function(time) list(time = time, variable = "x") + expect_identical(env_trend(c(1, 2, 4))(state, context(2L), NULL), 4) + expect_identical(env_trend(matrix(1:6, 3L))(state, context(1L), NULL), c(2L, 5L)) + expect_identical(env_trend(7)(state, context(30L), NULL), 7) + expect_error(env_trend(c(1, 2))(state, context(2L), NULL), "interval 2") + expect_error(env_trend(1, anomaly = "missing")(state, context(0L), NULL), "drawn before") +}) + +test_that("independent chains have the stated mean, variance, lag and cross correlation", { + partial <- matrix(c(1, 0.6, -0.3, 0.6, 1, 0.2, -0.3, 0.2, 1), 3L) + sd <- c(0.5, 1, 2) + n <- 2500L + steps <- 4L + cases <- list(list(-0.5, partial), list(0, partial), list(0.7, partial), + list(0.7, matrix(1, 3L, 3L))) + for (case in cases) { + phi <- case[[1L]] + cor <- case[[2L]] + generator <- env_ar1(sd = sd, phi = phi, cor = cor) + set.seed(1000L + round(10 * phi) + sum(cor)) + chains <- array(NA_real_, c(n, steps, 3L)) + for (chain in seq_len(n)) chains[chain, , ] <- ar1_chain(generator, steps) + covariance <- cor * outer(sd, sd) + for (step in seq_len(steps)) { + x <- chains[, step, ] + # Stationary from the first value: mean zero and the lag-zero covariance. + expect_lt(max(abs(colMeans(x)) / (sd / sqrt(n))), 4.5) + error <- sqrt((outer(sd^2, sd^2) + covariance^2) / n) + expect_lt(max(abs(stats::cov(x) - covariance) / error), 4.5) + # Lag-k covariance is phi^k times the lag-zero covariance. + for (lag in seq_len(step - 1L)) { + lagged <- stats::cov(chains[, step - lag, ], x) + expect_lt(max(abs(lagged - phi^lag * covariance) / error), 4.5) + } + } + expect_lt(max(abs(stats::cor(chains[, steps, ]) - cor)), 0.08) + } +}) + +test_that("perfect synchrony is exact and invalid inputs are rejected", { + synchronised <- env_ar1(sd = 1, phi = 0.4, cor = matrix(1, 3L, 3L)) + set.seed(9L) + values <- ar1_chain(synchronised, 50L) + expect_identical(values[, 2L], values[, 1L]) + expect_identical(values[, 3L], values[, 1L]) + set.seed(9L) + scaled <- ar1_chain(env_ar1(sd = c(1, 3), phi = 0.4, cor = matrix(1, 2L, 2L)), 50L) + expect_lt(max(abs(scaled[, 2L] - 3 * scaled[, 1L])), 1e-12) + expect_identical(scaled[, 1L], values[, 1L]) + # One normal deviate per step: the factor has rank one. + set.seed(9L) + draws <- rnorm(50L) + expect_identical(unname(values[1L, 1L]), draws[1L]) + expect_equal(unname(values[2L, 1L]), 0.4 * draws[1L] + sqrt(1 - 0.16) * draws[2L], + tolerance = 1e-14) + + # A singular but imperfect matrix (the third patch is the mean of two). + base <- cbind(c(1, 0, 1 / sqrt(2)), c(0, 1, 1 / sqrt(2))) + singular <- tcrossprod(base) + set.seed(2L) + mixed <- ar1_chain(env_ar1(cor = singular), 40L) + expect_lt(max(abs(mixed[, 3L] - (mixed[, 1L] + mixed[, 2L]) / sqrt(2))), 1e-12) + + expect_error(env_ar1(phi = 1), "phi") + expect_error(env_ar1(phi = -1.2), "phi") + expect_error(env_ar1(sd = -1), "sd") + expect_error(env_ar1(cor = matrix(c(1, 2, 2, 1), 2L)), "positive semi-definite") + expect_error(env_ar1(cor = matrix(c(1, 0.5, 0.2, 1), 2L)), "symmetric") + expect_error(env_ar1(sd = c(1, 2, 3), cor = diag(2L)), "one value per component") + expect_error(env_ar1()(list(globals = list()), list(time = 0L), NULL), "environment_process") + expect_error( + env_ar1(sd = c(1, 1))(list(globals = list(z = 1)), list(time = 0L, variable = "z"), NULL), + "lagged value" + ) + # A supplied starting value conditions the first interval on it. + set.seed(3L) + conditioned <- env_ar1(phi = 0.5)(list(globals = list(z = 4)), list(variable = "z"), NULL) + set.seed(3L) + expect_identical(conditioned, 0.5 * 4 + sqrt(0.75) * rnorm(1L)) +}) + +test_that("AR(1) deviations and lagged values follow patch names", { + patches <- c("A", "B") + for (rho in c(0.4, 1)) { + correlation <- spatial_correlation(patches, rho) + set.seed(86L) + ordered <- ar1_chain(env_ar1(c(A = 1, B = 3), cor = correlation), 10L) + set.seed(86L) + reversed <- ar1_chain(env_ar1(c(B = 3, A = 1), cor = correlation), 10L) + expect_identical(reversed, ordered) + expect_identical(colnames(reversed), patches) + if (rho == 1) expect_identical(reversed[, "B"], 3 * reversed[, "A"]) + } + lagged <- list(globals = list(z = c(B = -4, A = 6))) + lag <- env_ar1(0, phi = 0.5, cor = correlation) + expect_identical(lag(lagged, list(variable = "z"), NULL), c(A = 3, B = -2)) + expect_error(env_ar1(c(C = 1, A = 1), cor = correlation), "sd names") + dimnames(correlation) <- list(patches, rev(patches)) + expect_error(env_ar1(cor = correlation), "row and column names") + dimnames(correlation) <- list(patches, NULL) + expect_error(env_ar1(cor = correlation), "row and column names") + dimnames(correlation) <- list(c("A", "A"), c("A", "A")) + expect_error(env_ar1(cor = correlation), "unique") + almost <- matrix(c(1, 1 + 1e-10, 1 + 1e-10, 1), 2L) + expect_error(env_ar1(cor = almost), "positive semi-definite") + set.seed(123L) + rounded <- signif(stats::cor(matrix(stats::rnorm(12L), 3L, 4L)), 12L) + diag(rounded) <- 1 + rounded <- 0.5 * (rounded + t(rounded)) + expect_true(is.function(env_ar1(cor = rounded))) +}) + +test_that("patch levels are supplied by a callback or interval-by-patch matrix", { + state <- list(globals = list(anomaly = c(A = 1, B = -1))) + context <- list(time = 1L, dt = 0.25) + expect_error(env_trend(c(B = -1, A = 7)), "patch levels") + series <- env_trend(c("1" = 3, "0" = 7)) + expect_identical(series(state, context, NULL), 3) + matrix_level <- rbind(c(B = 31, A = 8), c(B = 32, A = 9)) + expect_identical(env_trend(matrix_level, "anomaly")(state, context, NULL), c(A = 10, B = 31)) + level <- function(time, dt, params) c(B = -2, A = time * dt + params$offset) + climate <- environment_process(list(local = env_trend(level, "anomaly")), + params = list(offset = 3)) + initial <- pva_state(adult_population(1L, 1L), globals = state$globals) + realised <- execute_processes(initial, list(climate), time = 1L, dt = 0.25) + expect_identical(realised$state$globals$local, c(A = 4.25, B = -3)) +}) + +test_that("spatial correlations use equicorrelation or exponential distance decay", { + patches <- c("lower", "upper", "ridge") + distances <- as.matrix(stats::dist(stats::setNames(c(0, 2, 5), patches))) + dimnames(distances) <- list(patches, patches) + expect_equal(spatial_correlation(distances = distances, scale = 2), exp(-distances / 2)) + expect_equal(spatial_correlation(rev(patches), distances = distances, scale = 2), + exp(-distances[rev(patches), rev(patches)] / 2)) + expect_error(spatial_correlation(c("X", "Y", "Z"), distances = distances, scale = 2), + "match distance matrix names") + expect_identical(spatial_correlation(distances = distances, scale = Inf), + spatial_correlation(patches, rho = 1)) + boundary <- spatial_correlation(patches, rho = -0.5) + set.seed(37L) + expect_lt(max(abs(rowSums(ar1_chain(env_ar1(cor = boundary), 5L)))), 1e-14) + expect_error(spatial_correlation(patches, rho = -0.6), "rho") + expect_error(spatial_correlation(patches, rho = 0, distances = distances), "either") + expect_error(spatial_correlation(distances = distances, scale = 0), "scale") + distances[1, 3] <- 1 + expect_error(spatial_correlation(distances = distances, scale = 2), "symmetric") +}) diff --git a/tests/testthat/test-kinship-mating.R b/tests/testthat/test-kinship-mating.R new file mode 100644 index 0000000..a496524 --- /dev/null +++ b/tests/testthat/test-kinship-mating.R @@ -0,0 +1,313 @@ +eligible_ids <- function(pop, state, context, params) pop$id %in% params$ids + +test_that("exact kinship and mean kinship match an independent tabular pedigree in every store", { + for (seed in 1:4) { + pedigree <- random_pedigree(seed) + expected <- tabular_kinship(pedigree) + for (limit in c(2000L, 1L, 3L)) { + state <- pedigree_state(pedigree, limit) + expect_lt(max(abs(kinship_matrix(state) - expected)), 1e-13) + expect_lt(max(abs(mean_kinship(state) - rowMeans(expected))), 1e-13) + expect_lt(max(abs(mean_kinship(state, c(7L, 3L)) - rowMeans(expected)[c(7L, 3L)])), 1e-13) + block <- kinship_matrix(state, 5:9, against = c(2L, 12:18)) + expect_lt(max(abs(block - expected[5:9, c(2L, 12:18)])), 1e-13) + expect_identical(block, t(kinship_matrix(state, c(2L, 12:18), 5:9))) + summary <- summarise_pedigree(state) + expect_equal(summary$founder_genome_equivalents, 1 / (2 * mean(expected)), tolerance = 1e-13) + } + # The pedigrees are related and inbred, so the oracle has something to find. + expect_gt(max(2 * diag(expected) - 1), 0.1) + } + expect_error(mean_kinship(pva_state(adult_population())), "not enabled") + expect_error(mean_kinship(pedigree_state(random_pedigree(1L)), 99L), "living") + expect_identical(dim(kinship_matrix(state, c(7L, 1L), integer())), c(2L, 0L)) + expect_error(kinship_matrix(state, 3L, c(2L, 2L)), "distinct living") + expect_error(kinship_matrix(state, 3L, 99L), "living") +}) + +test_that("N unrelated founders have exactly N founder genome equivalents", { + for (n in c(2L, 7L, 30L, 49L)) { + for (limit in c(2000L, 1L)) { + state <- pva_state(pva_population(rep(c("F", "M"), length.out = n), 1L), + pedigree = TRUE, max_dense_kinship = limit) + expect_identical(summarise_pedigree(state)$founder_genome_equivalents, as.numeric(n)) + expect_identical(mean_kinship(state), rep(1 / (2 * n), n)) + } + } + empty <- pva_state(pva_population(character(), integer()), pedigree = TRUE) + expect_true(is.na(summarise_pedigree(empty)$founder_genome_equivalents)) +}) + +test_that("the assignment solver is optimal against exhaustive enumeration", { + set.seed(90210L) + for (case in 1:45) { + rows <- sample.int(7L, 1L) + cols <- sample.int(7L, 1L) + score <- matrix(sample(0:6, rows * cols, replace = TRUE), rows, cols) + score[runif(rows * cols) < c(0, 0.3, 0.7)[1L + case %% 3L]] <- Inf + capacity <- sample(0:8, 1L) + pairs <- OpenPVA:::.min_kinship_pairs(score, capacity) + best <- exhaustive_matching(score, capacity) + expect_identical(anyDuplicated(pairs[, 1L]), 0L) + expect_identical(anyDuplicated(pairs[, 2L]), 0L) + expect_true(all(is.finite(score[pairs]))) + expect_identical(as.numeric(nrow(pairs)), best[["pairs"]]) + expect_identical(sum(score[pairs]), best[["cost"]]) + if (rows <= 4L && cols <= 4L) { + expect_identical(enumerated_matching(score, capacity), best) + } + } +}) + +test_that("kinship pairing is the exhaustive optimum on related, inbred pedigrees", { + cases <- data.frame( + seed = c(11:16, 11:16, 11:14), + capacity = c(2, 5, Inf, 2, 5, Inf, Inf, 2, 5, Inf, 3, 1, 4, Inf, 3, 0), + max_kinship = c(0.1, 0.3, Inf, 0.3, Inf, 0.1, 0.3, Inf, 0.1, 0, 0.05, 0.2, 0.15, 0.25, Inf, Inf) + ) + set.seed(4L) + bound <- 0 + for (row in seq_len(nrow(cases))) { + case <- cases[row, ] + pedigree <- random_pedigree(case$seed) + kinship <- tabular_kinship(pedigree) + females <- which(pedigree$sex == "F") + males <- which(pedigree$sex == "M") + females <- sort(females[sample.int(length(females), min(length(females), sample(3:7, 1L)))]) + males <- sort(males[sample.int(length(males), min(length(males), sample(3:7, 1L)))]) + score <- kinship_grid(kinship[females, males, drop = FALSE]) + score[score > kinship_grid(case$max_kinship)] <- Inf + best <- exhaustive_matching(score, case$capacity) + for (limit in c(2000L, 1L, 3L)) { + pairing <- pairing_process(eligible_ids, capacity = case$capacity, priority = "kinship", + max_kinship = case$max_kinship, + params = list(ids = c(females, males))) + out <- execute_processes(pedigree_state(pedigree, limit), list(pairing)) + mate <- out$state$population$mate_id + paired <- females[!is.na(mate[females])] + # Pairs are mutual, within the eligible sets, and admissible. + expect_identical(mate[mate[paired]], paired) + expect_true(all(mate[paired] %in% males)) + expect_true(all(is.na(mate[-c(paired, mate[paired])]))) + cost <- sum(score[cbind(match(paired, females), match(mate[paired], males))]) + expect_true(is.finite(cost)) + expect_identical(as.numeric(length(paired)), best[["pairs"]]) + expect_identical(cost, best[["cost"]]) + expect_identical(out$events$value[out$events$event_type == "pairs_formed"], + best[["pairs"]]) + } + bound <- max(bound, best[["pairs"]]) + } + # The cases include binding limits and unconstrained ones. + expect_gt(bound, 3) + expect_error(pairing_process(always, max_kinship = 0.1), "kinship") + expect_error(pairing_process(always, priority = "kinship", max_kinship = -1), "max_kinship") + expect_error( + execute_processes(pva_state(adult_population(mate_id = NA_integer_)), + list(pairing_process(always, priority = "kinship"))), + "pedigree = TRUE" + ) +}) + +test_that("mate_min_kinship gives every female a least-related admissible male", { + for (seed in 21:24) { + pedigree <- random_pedigree(seed) + kinship <- kinship_grid(tabular_kinship(pedigree)) + females <- which(pedigree$sex == "F") + males <- which(pedigree$sex == "M" & pedigree$id > 2L) + least <- apply(kinship[females, males, drop = FALSE], 1L, min) + for (limit in c(2000L, 1L, 3L)) { + state <- pedigree_state(pedigree, limit) + older <- function(pop, state, context, params) pop$id > 2L + by_id <- mate_min_kinship(older, ties = "id")(state$population, state, NULL, NULL) + expect_true(all(is.na(by_id[-females]))) + expect_identical(kinship[cbind(females, by_id[females])], least) + # Lowest identifier among the tied males. + first <- vapply(seq_along(females), function(i) { + males[which(kinship[females[i], males] == least[i])[1L]] + }, integer(1)) + expect_identical(by_id[females], first) + + set.seed(seed) + random <- mate_min_kinship(older)(state$population, state, NULL, NULL) + after <- .Random.seed + expect_identical(kinship[cbind(females, random[females])], least) + # Exactly one uniform draw per living female, whatever the store. + set.seed(seed) + draws <- runif(length(females)) + expect_identical(.Random.seed, after) + tied <- kinship[females, males, drop = FALSE] == least + expected <- vapply(seq_along(females), function(i) { + males[which(tied[i, ])[floor(draws[i] * sum(tied[i, ])) + 1L]] + }, integer(1)) + expect_identical(random[females], expected) + + limit_score <- sort(least)[ceiling(length(least) / 2)] + strict <- mate_min_kinship(older, max_kinship = limit_score / 2^30, ties = "id")( + state$population, state, NULL, NULL + ) + expect_identical(is.na(strict[females]), least > limit_score) + expect_identical(strict[females][least <= limit_score], by_id[females][least <= limit_score]) + } + } + state <- pedigree_state(random_pedigree(21L)) + nobody <- function(pop, state, context, params) rep(FALSE, length(pop$id)) + expect_true(all(is.na(mate_min_kinship(nobody)(state$population, state, NULL, NULL)))) + expect_error(mate_min_kinship(always)(adult_population(), pva_state(adult_population()), + NULL, NULL), "pedigree = TRUE") + expect_error(mate_min_kinship(always, max_kinship = NA), "max_kinship") +}) + +test_that("dense, traced and mid-run-switched stores make identical mating decisions", { + keep <- c("census", "events", "accounting", "state", "ledger") + dense <- run_scenario(managed_scenario(2000L), keep = keep) + expect_true(all(vapply(dense$states, function(state) is.matrix(state$kinship), NA))) + discrete <- setdiff(names(dense$ledgers[[1L]]), "pedigree_F") + for (limit in c(1L, 3L, 14L)) { + other <- run_scenario(managed_scenario(limit), keep = keep) + expect_false(any(vapply(other$states, function(state) is.matrix(state$kinship), NA))) + expect_identical(other[c("census", "events", "accounting")], + dense[c("census", "events", "accounting")]) + for (run in seq_along(dense$ledgers)) { + expect_identical(other$ledgers[[run]][discrete], dense$ledgers[[run]][discrete]) + expect_lt(max(abs(other$ledgers[[run]]$pedigree_F - dense$ledgers[[run]]$pedigree_F)), 1e-13) + } + } + # The limit of 14 starts dense (10 founders) and switches during the run. + ledger <- dense$ledgers[[1L]] + expect_gt(max(ledger$pedigree_F), 0) + expect_gt(sum(dense$events$value[dense$events$event_type == "pairs_formed"]), 20) + expect_gt(sum(dense$events$value[dense$events$process_name == "floater_births" & + dense$events$event_type == "birth"]), 5) + expect_true(all(summarise_accounting(dense)$reconciled)) +}) + +test_that("within-tolerance asymmetry in supplied founders has one symmetric interpretation", { + midpoint <- 0.03125 + 2^-31 + kin <- diag(0.5, 2L) + kin[1L, 2L] <- midpoint + 2^-48 + kin[2L, 1L] <- midpoint - 2^-48 + for (limit in c(2000L, 1L)) { + state <- pva_state(adult_population(1L, 1L), pedigree = TRUE, kinship = kin, + max_dense_kinship = limit) + expect_identical(as.numeric(kinship_matrix(state, 1L, 2L)), midpoint) + choose <- mate_min_kinship(max_kinship = 0.03125, ties = "id") + expect_identical(choose(state$population, state, NULL, NULL)[1L], 2L) + } +}) + +test_that("non-dyadic founder kinships give the same boundary decisions in every store", { + # Descend separately through each half of the founders until one pair remains. + # The 2 x 2 block flips when traced in one direction. The 4 x 4 block can + # flip after two generations even when traced in both directions. + crosses <- list( + matrix(c(0.00033948436166158119, 0.0011676369323551082, + 0.043618120468006609, 0.079874760100621861), 2L), + matrix(c(0.015419790365267545, 0.054865430046338586, 0.047308773228432986, + 0.010542824941221624, 0.051986096550244838, 0.025514103781897578, + 0.04687268487876281, 0.017705592275597155, 0.027641514544375242, + 0.0064298403053544466, 0.010631600052583963, 0.016188818130176516, + 0.042287033675238492, 0.010781206034589558, 0.023986872979439796, + 0.091837825661059469), 4L) + ) + children <- pva_process("children", function(state, context, params) { + parents <- params$parents + m <- parents[seq.int(1L, length(parents), 2L)] + f <- m + 1L + state <- add_individuals(state, rep(c("F", "M"), length.out = length(m)), 0L, + mother_id = m, father_id = f, mate_id = NA_integer_) + pva_result(state, pva_events("birth", length(m))) + }, creates = c("sex", "age", "mate_id")) + for (cross in crosses) { + n <- 2L * nrow(cross) + for (shift in c(0, 2^-30, 2^-40)) { + threshold <- 0.03125 + if (shift == 2^-30) shift else 0 + founders <- diag(0.5, n) + left <- seq_len(nrow(cross)) + right <- left + nrow(cross) + founders[left, right] <- cross + shift + founders[right, left] <- t(cross + shift) + for (limit in c(2000L, 1L, if (n == 4L) 4L else 12L)) { + state <- pva_state(pva_population(rep(c("F", "M"), n / 2L), 1L, mate_id = NA_integer_), + pedigree = TRUE, kinship = founders, max_dense_kinship = limit) + parents <- seq_len(n) + while (length(parents) > 2L) { + children$params$parents <- parents + state <- execute_processes(state, list(children))$state + parents <- utils::tail(state$population$id, length(parents) / 2L) + } + eligible <- function(pop, state, context, params) pop$id %in% parents + choose <- mate_min_kinship(eligible, max_kinship = threshold, ties = "id") + sire <- choose(state$population, state, NULL, NULL)[parents[1L]] + expect_identical(sire, if (shift == 0) parents[2L] else NA_integer_) + pairing <- pairing_process(eligible, priority = "kinship", max_kinship = threshold) + mates <- execute_processes(state, list(pairing))$state$population$mate_id + expect_identical(mates[parents[1L]], sire) + } + } + } +}) + +test_that("mean kinship selects rare breeders before minimising pair kinship", { + kin <- diag(0.5, 8L) + kin[1:3, 1:3] <- kin[5:7, 5:7] <- 0.25 + diag(kin) <- 0.5 + kin[4L, 8L] <- kin[8L, 4L] <- 0.03125 + pop <- adult_population(4L, 4L, partner = NA_integer_) + for (limit in c(1L, 2000L)) { + state <- pva_state(pop, pedigree = TRUE, kinship = kin, max_dense_kinship = limit) + pair <- function(priority, k = Inf) { + proc <- pairing_process(always, 1, priority, "partner", max_kinship = k) + mate <- execute_processes(state, list(proc))$state$population$partner + f <- which(!is.na(mate) & pop$sex == "F") + c(f, mate[f]) + } + expect_identical(pair("mean_kinship"), c(4L, 8L)) + expect_identical(kin[matrix(pair("kinship"), nrow = 1L)], 0) + allowed <- pair("mean_kinship", 0) + expect_identical(kin[matrix(allowed, nrow = 1L)], 0) + expect_identical(sum(allowed %in% c(4L, 8L)), 1L) + } +}) + +test_that("secondary pair costs break breeder-cost ties over the entire admissible matching", { + set.seed(774L) + for (case in seq_len(30L)) { + nf <- sample(2:6, 1L) + nm <- sample(2:6, 1L) + capacity <- sample.int(min(nf, nm), 1L) + breeder <- outer(2^29 + sample(0:3, nf, TRUE), 2^29 + sample(0:3, nm, TRUE), "+") + score <- matrix(sample(c(0, 2^28, 2^28 + 1, Inf), nf * nm, TRUE), nf) + pairs <- OpenPVA:::.min_kinship_pairs(score, capacity, breeder) + # Centring limits the oracle's integers to 35 bits even at full capacity. + packed <- (breeder - min(breeder)) * (capacity * (2^28 + 1) + 1) + score + best <- exhaustive_matching(packed, capacity) + expect_identical(as.numeric(nrow(pairs)), best[["pairs"]]) + expect_identical(sum(packed[pairs]), best[["cost"]]) + } +}) + +test_that("mate callbacks and monogamous priorities form pairs within their declared patch", { + patches <- c("A", "B", "B", "A", "C", "B") + pop <- pva_population(rep(c("F", "M"), 3L), 2L, patch = patches, partner = NA_integer_) + state <- pva_state(pop, pedigree = TRUE) + choose <- mate_min_kinship(ties = "id", by = "patch") + breed <- reproduction_process(1, litter_categorical(1L, 1), offspring_sex_bernoulli(1), + mate = choose, inherit = c("patch", "partner")) + expect_true("population.patch" %in% breed$requires) + born <- execute_processes(state, list(breed))$state$population + expect_identical(born$mother_id[born$origin == "birth"], c(1L, 3L)) + expect_identical(born$father_id[born$origin == "birth"], c(4L, 2L)) + expect_error(mate_min_kinship(by = c("patch", "sex")), "by") + for (priority in c("id", "lottery", "kinship", "mean_kinship")) { + proc <- pairing_process(always, Inf, priority, "partner", by = "patch") + expect_true("population.patch" %in% proc$requires) + paired <- execute_processes(state, list(proc))$state$population$partner + f <- which(!is.na(paired) & pop$sex == "F") + expect_identical(f, c(1L, 3L)) + expect_identical(patches[f], patches[paired[f]]) + } + state$population$patch[1L] <- NA_character_ + expect_error(execute_processes(state, list(proc)), "non-missing") + expect_error(execute_processes(state, list(breed)), "non-missing") +}) diff --git a/tests/testthat/test-markers.R b/tests/testthat/test-markers.R new file mode 100644 index 0000000..6a6aaff --- /dev/null +++ b/tests/testthat/test-markers.R @@ -0,0 +1,428 @@ +marker_census <- function(state) OpenPVA:::.marker_summary( + OpenPVA:::.marker_living(state), state$markers$n_loci, state$markers$n_native +) + +# Expected heterozygosity of each locus, computed independently of the package. +locus_heterozygosity <- function(alleles, n_loci) { + vapply(seq_len(n_loci), function(locus) { + copies <- c(alleles[, locus], alleles[, n_loci + locus]) + 1 - sum((table(copies) / length(copies))^2) + }, numeric(1)) +} + +test_that("N unrelated founders carry 2N alleles with He = 1 - 1/(2N)", { + for (n in c(2L, 5L, 12L, 49L)) { + state <- pva_state(pva_population(rep(c("F", "M"), length.out = n), 1L), + pedigree = TRUE, n_loci = 3L) + summary <- summarise_markers(state) + expect_identical(summary$n_native_alleles, 2L * n) + expect_identical(summary$allelic_richness, 2 * n) + expect_identical(summary$expected_heterozygosity, 1 - 1 / (2 * n)) + expect_identical(summary$observed_heterozygosity, 1) + expect_identical(summary$allelic_retention, 1) + expect_identical(summary$native_share, 1) + expect_identical(summarise_pedigree(state)$founder_genome_equivalents, as.numeric(n)) + metrics <- genetic_metrics()(state$population, state, NULL, NULL) + expect_identical(metrics[["founder_genome_equivalents"]], as.numeric(n)) + shares <- marker_founder_shares(state) + expect_identical(shares$id, seq_len(n)) + expect_true(all(shares$native)) + expect_identical(shares$share, rep(1 / n, n)) + } + plain <- pva_state(adult_population()) + expect_null(plain$markers) + expect_error(summarise_markers(plain), "not enabled") + expect_error(pva_state(adult_population(), n_loci = -1), "n_loci") +}) + +test_that("two full siblings from AB x CD match all sixteen segregation outcomes", { + # Alleles 1, 3 (dam) and 2, 4 (sire) are the four native alleles; the living + # population is the two offspring. + outcomes <- expand.grid(m1 = c(1L, 3L), p1 = c(2L, 4L), m2 = c(1L, 3L), p2 = c(2L, 4L)) + expect_identical(nrow(outcomes), 16L) + metrics <- vapply(seq_len(16L), function(i) { + alleles <- matrix(as.integer(c(outcomes$m1[i], outcomes$m2[i], + outcomes$p1[i], outcomes$p2[i])), 2L, 2L) + OpenPVA:::.marker_summary(alleles, 1L, 4L) + }, numeric(5)) + expect_identical(mean(metrics["expected_heterozygosity", ]), 5 / 8) + expect_identical(mean(metrics["allelic_retention", ]), 3 / 4) + expect_identical(mean(metrics["observed_heterozygosity", ]), 1) + + # The engine reproduces that distribution locus by locus. The marker stream + # derives from the generator's state, so fix it for a deterministic test. + set.seed(16L) + n_loci <- 4000L + litter <- pva_process("litter", function(state, context, params) { + state <- add_individuals(state, c("F", "M"), 0L, mother_id = 1L, father_id = 2L) + pva_result(state, pva_events("birth", 2L)) + }, creates = c("sex", "age")) + retire <- removal_process(select = function(pop, state, context, params) pop$age > 0L) + state <- pva_state(pva_population(c("F", "M"), 3L), pedigree = TRUE, n_loci = n_loci) + expect_identical(unname(OpenPVA:::.marker_living(state)[, c(1L, n_loci + 1L)]), + matrix(1:4, 2L, 2L)) + siblings <- execute_processes(state, list(litter, retire))$state + expect_identical(siblings$population$id, 3:4) + pedigree <- summarise_pedigree(siblings) + expect_identical(pedigree$founder_genome_equivalents, 4 / 3) + expect_identical(pedigree$mean_kinship, 3 / 8) + alleles <- OpenPVA:::.marker_living(siblings) + maternal <- alleles[, seq_len(n_loci)] + paternal <- alleles[, n_loci + seq_len(n_loci)] + expect_true(all(maternal %in% c(1L, 3L)) && all(paternal %in% c(2L, 4L))) + outcome <- table(factor(paste(maternal[1L, ], paternal[1L, ], maternal[2L, ], paternal[2L, ]), + levels = do.call(paste, outcomes))) + # Sixteen equally likely outcomes: chi-square with 15 df, 99.9 percent point. + expect_lt(sum((outcome - n_loci / 16)^2 / (n_loci / 16)), stats::qchisq(0.999, 15L)) + by_locus <- locus_heterozygosity(alleles, n_loci) + expect_lt(abs(mean(by_locus) - 5 / 8), 4 * stats::sd(by_locus) / sqrt(n_loci)) + summary <- summarise_markers(siblings) + expect_equal(summary$expected_heterozygosity, mean(by_locus), tolerance = 1e-12) + retained <- (colSums(maternal == 1L) > 0) + (colSums(maternal == 3L) > 0) + + (colSums(paternal == 2L) > 0) + (colSums(paternal == 4L) > 0) + expect_equal(summary$allelic_retention, mean(retained) / 4, tolerance = 1e-12) + expect_lt(abs(mean(retained) / 4 - 3 / 4), 4 * stats::sd(retained / 4) / sqrt(n_loci)) + expect_identical(summary$n_native_alleles, 4L) + expect_identical(marker_founder_shares(siblings)$share, c(0.5, 0.5)) +}) + +test_that("expected and observed heterozygosity match 1 - mean K and 1 - mean F on a fixed pedigree", { + n_loci <- 3000L + for (seed in c(41L, 42L)) { + pedigree <- random_pedigree(seed, n = 24L) + state <- pedigree_state(pedigree, n_loci = n_loci) + # Keep the last twelve: a related, inbred sample of the pedigree. + cull <- removal_process(select = function(pop, state, context, params) pop$id <= 12L) + state <- execute_processes(state, list(cull))$state + kinship <- tabular_kinship(pedigree)[13:24, 13:24] + alleles <- OpenPVA:::.marker_living(state) + by_locus <- locus_heterozygosity(alleles, n_loci) + expect_lt(abs(mean(by_locus) - (1 - mean(kinship))), 4 * stats::sd(by_locus) / sqrt(n_loci)) + observed <- colMeans(alleles[, seq_len(n_loci)] != alleles[, n_loci + seq_len(n_loci)]) + expect_lt(abs(mean(observed) - (1 - mean(2 * diag(kinship) - 1))), + 4 * stats::sd(observed) / sqrt(n_loci)) + summary <- summarise_markers(state) + expect_equal(summary$expected_heterozygosity, mean(by_locus), tolerance = 1e-12) + expect_equal(summary$observed_heterozygosity, mean(observed), tolerance = 1e-12) + expect_equal(sum(marker_founder_shares(state)$share), 1, tolerance = 1e-12) + # The comparison has power: the sample is well short of panmixia. + expect_gt(mean(kinship), 0.15) + expect_gt(mean(2 * diag(kinship) - 1), 0.05) + } +}) + +test_that("a sire lost before birth, unknown parents and introductions segregate correctly", { + n_loci <- 40L + loci <- seq_len(n_loci) + state <- pva_state(pva_population(c("F", "M", "M"), 4L, mate_id = c(2L, 1L, NA)), + pedigree = TRUE, n_loci = n_loci) + start <- OpenPVA:::.marker_living(state) + harvest <- removal_process(select = function(pop, state, context, params) pop$id == 2L, + cause = "autumn_harvest") + winter_birth <- reproduction_process( + 1, litter_categorical(3L, 1), offspring_sex_bernoulli(0.5), mate = mate_from_field(), + newborn_fields = function(...) list(mate_id = NA_integer_), newborn_field_names = "mate_id" + ) + out <- execute_processes(state, list(harvest, winter_birth))$state + expect_identical(out$population$father_id[3:5], rep(2L, 3L)) + expect_identical(out$markers$id, out$population$id) + cubs <- OpenPVA:::.marker_living(out)[3:5, ] + for (cub in 1:3) { + expect_true(all(cubs[cub, loci] == start[1L, loci] | cubs[cub, loci] == start[1L, n_loci + loci])) + # The departed sire's two alleles, and nobody else's. + expect_true(all(cubs[cub, n_loci + loci] == start[2L, loci] | + cubs[cub, n_loci + loci] == start[2L, n_loci + loci])) + } + expect_gt(length(unique(cubs[1L, n_loci + loci])), 1L) + + # An unrecorded sire contributes one new allele per newborn, at every locus. + fatherless <- reproduction_process( + function(pop, state, context, params) as.numeric(pop$id == 1L), + litter_categorical(2L, 1), offspring_sex_bernoulli(0.5), + newborn_fields = function(...) list(mate_id = NA_integer_), newborn_field_names = "mate_id" + ) + out <- execute_processes(state, list(fatherless))$state + young <- OpenPVA:::.marker_living(out)[4:5, n_loci + loci] + expect_identical(unname(young), matrix(rep(7:8, n_loci), 2L)) + expect_identical(out$markers$source, c(1:3, 1:3, 4:5)) + expect_identical(out$markers$n_native, 6L) + shares <- marker_founder_shares(out) + expect_identical(shares$native, c(TRUE, TRUE, TRUE, FALSE, FALSE)) + expect_identical(summarise_markers(out)$allelic_retention, 1) + + # A release adds alleles and gene copies but cannot restore a lost native one. + thin <- removal_process(select = function(pop, state, context, params) pop$id == 3L) + release <- introduction_process( + count = 2L, creates = c("sex", "age", "mate_id"), + fields = function(n, state, context, params) { + list(sex = c("F", "M"), age = 1L, mate_id = NA_integer_) + } + ) + thinned <- execute_processes(state, list(thin))$state + released <- execute_processes(thinned, list(release))$state + before <- summarise_markers(thinned) + after <- summarise_markers(released) + expect_identical(before$allelic_retention, 4 / 6) + expect_identical(after$allelic_retention, before$allelic_retention) + expect_identical(after$allelic_richness, before$allelic_richness + 4) + expect_identical(after$native_share, 0.5) + expect_identical(after$n_native_alleles, 6L) + expect_identical(marker_founder_shares(released)$share, c(0.25, 0.25, 0, 0.25, 0.25)) + expect_identical(marker_founder_shares(released)$native, rep(c(TRUE, FALSE), c(3L, 2L))) +}) + +test_that("recorded initial parentage segregates and unexplained founder kinship is refused", { + pedigree <- random_pedigree(7L, n = 10L) + state <- pedigree_state(pedigree, n_loci = 25L) + alleles <- OpenPVA:::.marker_living(state) + loci <- seq_len(25L) + for (child in 5:10) { + dam <- alleles[pedigree$mother_id[child], ] + sire <- alleles[pedigree$father_id[child], ] + expect_true(all(alleles[child, loci] == dam[loci] | alleles[child, loci] == dam[25L + loci])) + expect_true(all(alleles[child, 25L + loci] == sire[loci] | + alleles[child, 25L + loci] == sire[25L + loci])) + } + expect_identical(state$markers$n_native, 8L) + + population <- pva_population(pedigree$sex, 2L, mother_id = pedigree$mother_id, + father_id = pedigree$father_id) + implied <- tabular_kinship(pedigree) + explained <- pva_state(population, pedigree = TRUE, kinship = implied, n_loci = 5L) + expect_identical(explained$markers$n_native, 8L) + related <- implied + related[1L, 2L] <- related[2L, 1L] <- 0.125 + expect_error(pva_state(population, pedigree = TRUE, kinship = related, n_loci = 5L), + "explained by recorded parentage") + expect_s3_class(pva_state(population, pedigree = TRUE, kinship = related), "pva_state") + outside <- pva_population(c("F", "M"), 1L, mother_id = c(NA, 9L)) + expect_error(pva_state(outside, n_loci = 2L), "initial parent ID") +}) + +test_that("neutral loci never perturb demography, and their stream is private", { + keep <- c("census", "events", "accounting", "ledger") + off <- run_scenario(managed_scenario(n_loci = 0L, n_runs = 6L), keep = keep) + on <- run_scenario(managed_scenario(n_loci = 12L, n_runs = 6L), keep = c(keep, "state")) + expect_identical(on[keep], off[keep]) + expect_identical(on$provenance$streams, off$provenance$streams) + expect_gt(sum(off$census$n_alive), 500) + expect_gt(sum(off$events$value[off$events$event_type == "removal"]), 5) + traced <- run_scenario(managed_scenario(limit = 1L, n_loci = 12L, n_runs = 6L), keep = "state") + expect_identical(lapply(traced$states, `[[`, "markers"), lapply(on$states, `[[`, "markers")) + + # Each replicate has a fourth substream for segregation after initialization. + ahead <- function(seed, n) { + for (step in seq_len(n)) seed <- parallel::nextRNGSubStream(seed) + seed + } + probe <- scenario_spec("probe", 3L, 1L, seed = 5L, init_fun = function() { + pva_state(pva_population(c("F", "M"), 1L), n_loci = 1L) + }, processes = list(census_process())) + result <- run_scenario(probe, keep = "state") + for (run in 1:3) { + stream <- result$provenance$streams[[run]] + seed <- result$states[[run]]$markers$seed + expect_identical(seed, ahead(stream, 4L)) + expect_false(any(vapply(result$provenance$streams, identical, NA, seed))) + } + set.seed(21L, kind = "L'Ecuyer-CMRG") + built <- pva_state(pva_population(c("F", "M"), 1L), n_loci = 1L) + expect_identical(built$markers$seed, ahead(.Random.seed, 2L)) + + # One state built beforehand and returned by init_fun still segregates + # independently in every replicate, serially and on workers. + prebuilt <- pva_state(pva_population(c("F", "M"), 3L), pedigree = TRUE, n_loci = 40L) + shared <- scenario_spec( + "prebuilt", 4L, 1L, seed = 8L, init_fun = function() prebuilt, + processes = list(reproduction_process(1, litter_categorical(2L, 1), + offspring_sex_bernoulli(0.5), mate = mate_random(always))) + ) + litters <- lapply(run_scenario(shared, keep = "state")$states, function(state) { + state$markers$alleles[3:4, ] + }) + expect_identical(anyDuplicated(litters), 0L) + parallel_litters <- lapply( + run_scenario(shared, parallel = TRUE, workers = 2L, keep = "state")$states, + function(state) state$markers$alleles[3:4, ] + ) + expect_identical(parallel_litters, litters) + + # Building or advancing a marker state leaves the caller's generator alone. + for (kind in c("Mersenne-Twister", "L'Ecuyer-CMRG")) { + set.seed(11L, kind = kind) + before <- .Random.seed + state <- pva_state(pva_population(c("F", "M"), 3L), n_loci = 6L) + expect_identical(.Random.seed, before) + birth <- reproduction_process(1, litter_categorical(2L, 1), offspring_sex_bernoulli(0.5), + mate = mate_random(always)) + with_loci <- execute_processes(state, list(birth)) + after <- .Random.seed + set.seed(11L, kind = kind) + without <- execute_processes(pva_state(pva_population(c("F", "M"), 3L)), list(birth)) + expect_identical(.Random.seed, after) + expect_identical(with_loci$ledger, without$ledger) + expect_identical(RNGkind()[[1L]], kind) + } + set.seed(1L, kind = "Mersenne-Twister") +}) + +test_that("related ensemble initial states and newborns use distinct marker substreams", { + build <- function(row) { + family <- function() pva_state( + pva_population(c("F", "M", "F"), 2L, mother_id = c(NA, NA, 1L), + father_id = c(NA, NA, 2L)), n_loci = 32L + ) + if (row$prebuilt) { + initial <- family() + init <- function() initial + } else init <- family + birth <- pva_process("birth", function(state, context, params) { + pva_result(add_individuals(state, "F", 0L, mother_id = 1L, father_id = 2L), + pva_events("birth", 1L)) + }, creates = c("sex", "age")) + list(init_fun = init, processes = list(birth), n_steps = 1L, keep = "state") + } + genotypes <- function(result, row) { + code <- function(i) vapply(result$states, function(s) { + paste(s$markers$alleles[i, ], collapse = ",") + }, character(1)) + data.frame(daughter = code(3L), newborn = code(4L)) + } + design <- data.frame(prebuilt = c(TRUE, FALSE)) + serial <- run_pva_ensemble(design, build, 3L, genotypes, seed = 21L) + socket <- run_pva_ensemble(design, build, 3L, genotypes, seed = 21L, + workers = 2L, backend = "psock") + expect_identical(socket, serial) + for (group in split(serial, serial$prebuilt)) { + sisters <- unique(group$daughter) + expect_length(sisters, if (group$prebuilt[1L]) 1L else 3L) + expect_identical(anyDuplicated(c(sisters, group$newborn)), 0L) + } +}) + +test_that("marker uniforms preserve the cached Box-Muller normal and an absent seed", { + old <- .GlobalEnv$.Random.seed + kind <- RNGkind() + on.exit({ + do.call(RNGkind, as.list(kind)) + if (is.null(old)) rm(".Random.seed", envir = .GlobalEnv) else + assign(".Random.seed", old, envir = .GlobalEnv) + }) + family <- pva_population(c("F", "M", "F"), 1L, mother_id = c(NA, NA, 1L), + father_id = c(NA, NA, 2L)) + probe <- function(n_loci, uniform) { + set.seed(432L, uniform, "Box-Muller") + stats::rnorm(1L) + pva_state(family, n_loci = n_loci) + list(seed = .GlobalEnv$.Random.seed, normals = stats::rnorm(3L)) + } + for (uniform in c("Mersenne-Twister", "L'Ecuyer-CMRG")) { + expect_identical(probe(4L, uniform), probe(0L, uniform)) + } + set.seed(1L, "Mersenne-Twister", "Inversion") + borrowed <- pva_state(family, n_loci = 4L)$markers$seed + set.seed(432L, "Mersenne-Twister", "Box-Muller") + normals <- stats::rnorm(2L) + set.seed(432L, "Mersenne-Twister", "Box-Muller") + expect_identical(stats::rnorm(1L), normals[1L]) + OpenPVA:::.marker_uniform(borrowed, 8L) + expect_identical(stats::rnorm(1L), normals[2L]) + rm(".Random.seed", envir = .GlobalEnv) + pva_state(family, n_loci = 4L) + expect_false(exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) +}) + +test_that("markers require sex-consistent parents and parentless introductions", { + for (pedigree in c(TRUE, FALSE)) { + for (sex in c("F", "M")) { + invalid <- pva_population(c(sex, "F"), 1L, mother_id = c(NA, 1L), father_id = c(NA, 1L)) + expect_error(pva_state(invalid, pedigree = pedigree, n_loci = 1L), "non-female mother") + if (pedigree) expect_error(pva_state(invalid, pedigree = TRUE, kinship = diag(0.5, 2L)), + "non-female mother") + } + state <- pva_state(pva_population(c("F", "M"), 1L), pedigree = pedigree, n_loci = 4L) + release <- pva_process("release", function(state, context, params) { + pva_result(add_individuals(state, "M", 0L, mother_id = 1L, father_id = 2L), + pva_events("introduction", 1L)) + }, creates = c("sex", "age")) + expect_error(execute_processes(state, list(release)), "introductions must have NA") + } +}) + +test_that("genotypes are engine-owned and genetic censuses survive extinction", { + state <- pva_state(pva_population(c("F", "M"), 3L), pedigree = TRUE, n_loci = 2L) + tamper <- custom_process(function(state, context, params) { + state$markers$alleles[1L, 1L] <- 99L + pva_result(state) + }) + expect_error(execute_processes(state, list(tamper)), "neutral-locus store") + broken <- state + broken$markers$alleles <- broken$markers$alleles[, 1:2] + expect_error(execute_processes(broken, list(census_process())), "neutral-locus store") + broken <- state + broken$markers$alleles[1L, 1L] <- 99L + expect_error(execute_processes(broken, list(census_process())), "neutral-locus store") + expect_error(marker_founder_shares(broken), "neutral-locus store") + invalid <- list(source = rev(state$markers$source), id = c(1L, 1L), + n_native = 5L, seed = 1:7, seed = c(10407L, 0L, 0L, 0L, 1L, 2L, 3L)) + for (i in seq_along(invalid)) { + broken <- state + broken$markers[[names(invalid)[i]]] <- invalid[[i]] + expect_error(execute_processes(broken, list(census_process())), "neutral-locus store") + } + expect_output(print(state), "neutral loci: 2") + expect_error( + execute_processes(pva_state(adult_population()), list(census_process(genetic_metrics()))), + "pedigree = TRUE" + ) + + doomed <- scenario_spec( + "doomed", n_runs = 30L, n_steps = 6L, seed = 3L, + init_fun = function() pva_state(pva_population(c("F", "M", "F"), 1L), + pedigree = TRUE, n_loci = 4L), + processes = list(survival_process(0.5), census_process(genetic_metrics())), + initial_census = census_process(genetic_metrics()) + ) + run <- run_scenario(doomed) + extinct <- run$census$n_alive == 0 + expect_gt(sum(extinct), 20) + expect_gt(sum(!extinct & run$census$phase == "interval"), 20) + genetic <- c("mean_inbreeding", "mean_kinship", "gene_diversity", "founder_genome_equivalents", + "observed_heterozygosity", "expected_heterozygosity", "allelic_richness", + "allelic_retention", "native_share") + expect_identical(names(run$census)[-(1:6)], genetic) + counts <- c("allelic_richness", "allelic_retention") + expect_true(all(run$census[extinct, counts] == 0)) + expect_true(all(is.na(run$census[extinct, setdiff(genetic, counts)]))) + expect_false(anyNA(run$census[!extinct, genetic])) + # Year zero is observed through the initial census. + initial <- run$census[run$census$phase == "initial", ] + expect_identical(initial$expected_heterozygosity, rep(1 - 1 / 6, 30L)) + expect_identical(initial$founder_genome_equivalents, rep(3, 30L)) + + trajectory <- summarise_trajectory(run, metric = "expected_heterozygosity") + living <- summarise_trajectory(run) + alive <- tapply(!extinct, run$census$time + (run$census$phase == "interval"), sum) + expect_identical(trajectory$n_observed, as.integer(alive)) + expect_identical(trajectory$n_runs, rep(30L, 7L)) + expect_identical(living$n_observed, rep(30L, 7L)) + final <- run$census[run$census$time == 5L & run$census$phase == "interval" & !extinct, ] + expect_equal(trajectory$mean[7L], mean(final$expected_heterozygosity)) + expect_equal(trajectory$median[7L], stats::median(final$expected_heterozygosity)) + expect_error(summarise_pva(run, metric = "expected_heterozygosity"), "finite") + expect_identical(summarise_pva(run)$n_runs, 30L) + + # A year in which every replicate is extinct has no genetic summary at all. + gone <- scenario_spec("gone", 2L, 2L, seed = 1L, init_fun = doomed$init_fun, + processes = list(survival_process(0), census_process(genetic_metrics()))) + extinct_run <- run_scenario(gone) + empty <- summarise_trajectory(extinct_run, metric = "expected_heterozygosity") + expect_identical(empty$n_observed, c(0L, 0L)) + expect_true(all(is.na(empty[c("mean", "mcse", "q05", "median", "q95", "p_below")]))) + retained <- summarise_trajectory(extinct_run, metric = "allelic_retention") + expect_identical(retained$mean, c(0, 0)) + expect_identical(retained$n_extant, c(0L, 0L)) + no_founders <- pva_state(pva_population(character(), integer()), n_loci = 1L) + expect_identical(summarise_markers(no_founders)$allelic_richness, 0) + expect_identical(summarise_markers(no_founders)$allelic_retention, NA_real_) +}) diff --git a/tests/testthat/test-oracle-extinction.R b/tests/testthat/test-oracle-extinction.R index f952b1d..4d64787 100644 --- a/tests/testthat/test-oracle-extinction.R +++ b/tests/testthat/test-oracle-extinction.R @@ -23,7 +23,7 @@ test_that("first-crossing and horizon probabilities match exact enumeration acro n_runs <- 6000L result <- run_scenario( cohort_scenario(design, n_runs = n_runs, seed = 4126L), - validation = "fast", keep = "census" + parallel = TRUE, workers = 2L, validation = "fast", keep = "census" ) summary <- summarise_pva(result, threshold = design$threshold) extinct <- summarise_pva(result, threshold = 1) diff --git a/tests/testthat/test-oracle-matrix.R b/tests/testthat/test-oracle-matrix.R index c6a1ac8..37f02cf 100644 --- a/tests/testthat/test-oracle-matrix.R +++ b/tests/testthat/test-oracle-matrix.R @@ -4,7 +4,7 @@ test_that("multi-year stochastic means match the independent matrix expectation" n_runs <- 1500L result <- run_scenario( oracle_scenario(rates, n_runs = n_runs, n_steps = n_steps, seed = 20261124L), - validation = "fast", keep = "census" + parallel = TRUE, workers = 2L, validation = "fast", keep = "census" ) projection <- oracle_matrix(rates) expected <- matrix(NA_real_, n_steps, 3L, dimnames = list(NULL, c("n_alive", "n_female", "n_male"))) @@ -32,7 +32,8 @@ test_that("the matrix oracle detects a wrong census position", { # Moving the census before reproduction changes what is counted; the oracle # for the declared order must reject it. scenario$processes <- scenario$processes[c(1L, 2L, 4L, 3L)] - result <- run_scenario(scenario, validation = "fast", keep = "census") + result <- run_scenario(scenario, parallel = TRUE, workers = 2L, validation = "fast", + keep = "census") vector <- c(rates$initial$F, rates$initial$M) for (step in 1:4) { vector <- as.vector(oracle_matrix(rates) %*% vector) diff --git a/tests/testthat/test-plots.R b/tests/testthat/test-plots.R new file mode 100644 index 0000000..09b4673 --- /dev/null +++ b/tests/testthat/test-plots.R @@ -0,0 +1,164 @@ +# Render one view on a null device, to a PDF file and, where the build has it, +# to a PNG file. Each device must preserve graphics styling and the RNG. +render <- function(draw) { + set.seed(77L) + seed <- .Random.seed + devices <- list(null = function() grDevices::pdf(NULL)) + pdf_file <- tempfile(fileext = ".pdf") + devices$pdf <- function() grDevices::pdf(pdf_file) + png_file <- tempfile(fileext = ".png") + if (isTRUE(capabilities("png"))) { + devices$png <- function() grDevices::png(png_file, width = 640, height = 480) + } + on.exit(unlink(c(pdf_file, png_file)), add = TRUE) + tables <- list() + coordinates <- c("usr", "xaxp", "yaxp", "xlog", "ylog", "mfg", "page", "plt", "fig", "new", + "cin", "cra", "csi", "cxy", "din", "pin") + for (device in names(devices)) { + devices[[device]]() + graphics::par(mar = c(3.5, 4, 2.5, 1), las = 1L) + before <- graphics::par(no.readonly = TRUE) + visible <- withVisible(draw()) + after <- graphics::par(no.readonly = TRUE) + grDevices::dev.off() + expect_false(visible$visible) + styling <- setdiff(names(before), coordinates) + expect_identical(after[styling], before[styling]) + tables[[device]] <- visible$value + } + expect_identical(.Random.seed, seed) + expect_gt(file.size(pdf_file), 1000) + if (!is.null(devices$png)) expect_gt(file.size(png_file), 1000) + for (table in tables) expect_identical(table, tables[[1L]]) + expect_false(file.exists("Rplots.pdf")) + tables[[1L]] +} + +plot_scenario <- function(n_runs = 12L, n_steps = 6L, survival = 0.8) { + scenario_spec( + "plots", n_runs = n_runs, n_steps = n_steps, seed = 12L, + init_fun = function() pva_state(pva_population(rep(c("F", "M"), 3L), 1L), + pedigree = TRUE, n_loci = 3L), + processes = list( + survival_process(survival), + reproduction_process(0.5, litter_poisson(1), offspring_sex_bernoulli(0.5), + mate = mate_random(always)), + census_process(genetic_metrics()) + ), + initial_census = census_process(genetic_metrics()) + ) +} + +test_that("every run view renders headlessly and returns its summary table", { + run <- run_scenario(plot_scenario()) + expect_identical(render(function() plot(run, threshold = 3)), + summarise_trajectory(run, threshold = 3)) + expect_identical(render(function() plot(run, type = "risk", threshold = 3, main = "Risk")), + summarise_trajectory(run, threshold = 3)) + expect_identical(render(function() plot(run, type = "accounting")), summarise_accounting(run)) + expect_identical(render(function() plot(run, runs = 0L, ylim = c(0, 50), log = "")), + summarise_trajectory(run)) + expect_error(plot(run, type = "pie"), "arg") + expect_error(plot(run, metric = "absent"), "metric") +}) + +test_that("extinct replicates, single runs and single steps still plot", { + # Every replicate dies out, so genetic metrics go missing and then vanish. + doomed <- run_scenario(plot_scenario(survival = 0.3)) + expect_gt(sum(doomed$census$n_alive == 0), 20) + heterozygosity <- render(function() plot(doomed, metric = "expected_heterozygosity")) + expect_identical(heterozygosity, summarise_trajectory(doomed, metric = "expected_heterozygosity")) + expect_true(any(heterozygosity$n_observed == 0L) || anyNA(heterozygosity$median) || + min(heterozygosity$n_observed) < heterozygosity$n_runs[1L]) + expect_identical(render(function() plot(doomed, type = "risk")), summarise_trajectory(doomed)) + expect_identical(render(function() plot(doomed)), summarise_trajectory(doomed)) + + single <- run_scenario(plot_scenario(n_runs = 1L, n_steps = 1L)) + for (type in c("trajectory", "risk")) { + expect_identical(render(function() plot(single, type = type)), summarise_trajectory(single)) + } + expect_identical(render(function() plot(single, type = "accounting")), + summarise_accounting(single)) + bare <- single + bare$scenario$initial_census <- NULL + bare$census <- bare$census[bare$census$phase == "interval", ] + expect_identical(nrow(render(function() plot(bare))), 1L) +}) + +test_that("a broken accounting ledger is plotted and flagged, not hidden", { + run <- run_scenario(plot_scenario()) + broken <- run + broken$accounting$n_after[broken$accounting$time == 2L] <- + broken$accounting$n_after[broken$accounting$time == 2L] + 1L + table <- render(function() plot(broken, type = "accounting")) + expect_identical(table, summarise_accounting(broken)) + expect_false(all(table$reconciled)) + expect_true(all(summarise_accounting(run)$reconciled)) +}) + +test_that("ensembles carry a class and plot their contrasts with intervals", { + design <- expand.grid(survival = c(0.6, 0.9), harvest = c(0, 1)) + build <- function(row) { + list(n_steps = 5L, init_fun = function() adult_population(4L, 4L), + processes = list(survival_process(row$survival), removal_process(count = row$harvest), + census_process())) + } + ensemble <- run_pva_ensemble(design, build, n_runs = 20L, seed = 2L, + summarise = function(result, row) summarise_pva(result, threshold = 3)) + expect_s3_class(ensemble, c("pva_ensemble", "data.frame"), exact = TRUE) + expect_identical(attr(ensemble, "provenance")$design, c("survival", "harvest")) + printed <- utils::capture.output(shown <- withVisible(print(ensemble))) + expect_match(printed[1L], "rows: 4 .*runs/member: 20 .*root seed: 2") + expect_true(any(grepl("survival", printed, fixed = TRUE))) + expect_false(shown$visible) + expect_identical(shown$value, ensemble) + risk <- render(function() plot(ensemble)) + expect_identical(risk$estimate, ensemble$p_ever_below) + expect_identical(risk$lower, ensemble$p_ever_below_lower) + expect_identical(risk$upper, ensemble$p_ever_below_upper) + expect_identical(risk$label, paste(format(design$survival), format(design$harvest), sep = " | ")) + final <- render(function() plot(ensemble, y = "final_mean", by = "survival")) + expect_equal(final$upper - final$estimate, stats::qnorm(0.975) * ensemble$final_mcse) + bare <- render(function() plot(ensemble, y = "final_median", by = "harvest")) + expect_true(all(is.na(bare$lower))) + expect_error(plot(ensemble, y = "absent"), "numeric summary column") + expect_error(plot(ensemble, by = "absent"), "columns of the ensemble") +}) + +test_that("run overlays and ensemble labels use the current panel's data coordinates", { + run <- run_scenario(plot_scenario(n_runs = 2L, n_steps = 3L)) + ensemble <- structure( + data.frame(setting = c("NorthPatch", "SouthPatch"), risk = c(0.25, 0.75)), + class = c("pva_ensemble", "data.frame"), provenance = list(design = "setting") + ) + set.seed(311L) + seed <- .Random.seed + directory <- tempfile() + dir.create(directory) + on.exit(unlink(directory, recursive = TRUE)) + for (xaxt in c("s", "n")) { + filename <- file.path(directory, paste0(xaxt, "-%d.pdf")) + grDevices::pdf(filename, onefile = FALSE, compress = FALSE, useKerning = FALSE, + colormodel = "rgb") + tryCatch({ + graphics::par(mfrow = c(1L, 2L)) + plot(run, xlim = c(-1, 4), ylim = c(0, 16), xaxs = "i", yaxs = "i") + expect_identical(graphics::par("usr"), c(-1, 4, 0, 16)) + graphics::abline(h = 8, col = "magenta") + overlay <- plot(run, add = TRUE, runs = 0L, col = "purple") + expect_identical(overlay, summarise_trajectory(run)) + expect_identical(graphics::par("usr"), c(-1, 4, 0, 16)) + expect_identical(graphics::par("mfg")[1:2], c(1L, 1L)) + plot(ensemble, y = "risk", ylim = c(0, 1), xaxs = "i", yaxs = "i", xaxt = xaxt) + expect_identical(graphics::par("usr"), c(0.5, 2.5, 0, 1)) + expect_identical(graphics::par("mfg")[1:2], c(1L, 2L)) + graphics::abline(h = 0.5, col = "red") + }, finally = grDevices::dev.off()) + pages <- list.files(directory, pattern = paste0("^", xaxt, "-"), full.names = TRUE) + expect_length(pages, 1L) + content <- readLines(pages, warn = FALSE, skipNul = TRUE, encoding = "latin1") + expect_true(any(grepl("1.000 0.000 1.000 RG", content, fixed = TRUE, useBytes = TRUE))) + expect_identical(any(grepl("NorthPatch", content, fixed = TRUE, useBytes = TRUE)), xaxt == "s") + } + expect_identical(.Random.seed, seed) +}) diff --git a/tests/testthat/test-rng-parity.R b/tests/testthat/test-rng-parity.R index 4595a81..fec6d53 100644 --- a/tests/testthat/test-rng-parity.R +++ b/tests/testthat/test-rng-parity.R @@ -98,6 +98,58 @@ test_that("fresh installed-package PSOCK workers receive library paths and callb ) }) +test_that("correlated environments, kinship mating and neutral loci are bit-identical on every backend", { + patches <- c("a", "b", "c") + cor <- matrix(c(1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8, 1), 3L, dimnames = list(patches, patches)) + weather <- environment_process(list( + anomaly = env_ar1(sd = c(0.4, 0.6, 0.4), phi = 0.6, cor = cor), + climate = env_trend(function(time) c(0, 0.1 * time, if (time >= 3L) -1 else 0), + anomaly = "anomaly") + )) + scenario <- managed_scenario(limit = 14L, n_loci = 6L, n_runs = 6L, n_steps = 6L, + census = census_process(genetic_metrics())) + # The environment is drawn first and drives survival through a global. + scenario$processes <- c(list(weather), scenario$processes) + scenario$processes[[8L]] <- survival_process(function(pop, state, context, params) { + shift_logit(c(0.6, 0.8)[1L + (pop$age > 0L)], mean(state$globals$climate)) + }, requires = c("population.age", "globals.climate")) + keep <- c("census", "events", "accounting", "state", "ledger") + serial <- run_scenario(scenario, keep = keep) + expect_identical(comparable(run_scenario(scenario, keep = keep)), comparable(serial)) + if (.Platform$OS.type != "windows") { + forked <- run_scenario(scenario, parallel = TRUE, workers = 2L, backend = "fork", keep = keep) + expect_identical(comparable(forked), comparable(serial)) + } + socket <- run_scenario(scenario, parallel = TRUE, workers = 2L, backend = "psock", keep = keep) + expect_identical(comparable(socket), comparable(serial)) + + # The run exercised what it claims to: red noise, synchrony, loci and kinship. + final <- serial$states[[1L]] + expect_identical(final$globals$anomaly[["a"]], final$globals$anomaly[["c"]]) + expect_false(identical(final$globals$anomaly[["a"]], final$globals$anomaly[["b"]])) + expect_identical(final$globals$climate, c(0, 0.5, -1) + final$globals$anomaly) + expect_identical(final$markers$n_loci, 6L) + expect_false(is.matrix(final$kinship)) + + # No generator state survives from one replicate to the next: in a serial run + # every replicate's first anomaly is the stationary draw from its own stream. + first <- scenario + first$n_steps <- 1L + first$processes <- list(weather) + one_step <- run_scenario(first, keep = "state") + upper <- suppressWarnings(chol(cor, pivot = TRUE)) + loading <- unname(t(upper[seq_len(attr(upper, "rank")), order(attr(upper, "pivot")), drop = FALSE])) + expect_identical(ncol(loading), 2L) + old_seed <- .Random.seed + for (run in seq_len(first$n_runs)) { + assign(".Random.seed", one_step$provenance$streams[[run]], envir = .GlobalEnv) + draws <- rnorm(2L) + expected <- c(0.4, 0.6, 0.4) * (loading[, 1L] * draws[1L] + loading[, 2L] * draws[2L]) + expect_equal(unname(one_step$states[[run]]$globals$anomaly), expected, tolerance = 1e-14) + } + assign(".Random.seed", old_seed, envir = .GlobalEnv) +}) + test_that("fast validation gives bit-identical output to strict validation", { keep <- c("census", "events", "accounting", "state", "ledger") strict <- run_scenario(parity_scenario(), validation = "strict", keep = keep) diff --git a/tests/testthat/test-summaries-ensemble.R b/tests/testthat/test-summaries-ensemble.R index 5e3868e..906d2c6 100644 --- a/tests/testthat/test-summaries-ensemble.R +++ b/tests/testthat/test-summaries-ensemble.R @@ -38,6 +38,45 @@ test_that("viability summaries follow their definitions", { expect_error(summarise_pva(census_fixture()[-3L, ]), "exactly once per interval") }) +test_that("extinct and rescued runs retain their observed threshold crossings", { + census <- expand.grid(run = 1:3, time = 0:3) + census$phase <- "interval" + census$process_name <- "census" + census$n_alive <- c(2, 1, 2, 0, 0, 0, 2, 0, 1, 1, 2, 0) + census$he <- c(0.2, 0.8, 0.6, NA, NA, NA, 0.7, NA, 0.3, 0.8, 0.75, NA) + genetics <- summarise_trajectory(census, "he", 0.5) + expect_identical(genetics$n_extant, c(3L, 0L, 2L, 2L)) + expect_identical(genetics$n_observed, genetics$n_extant) + expect_equal(genetics$p_below, c(1/3, NA, 1/2, 0)) + expect_equal(genetics$p_ever_below, c(1/3, 1/3, 2/3, 2/3)) + expect_equal(c(genetics$q25[3L], genetics$median[3L], genetics$q75[3L]), c(0.4, 0.5, 0.6)) + expect_true(all(is.na(genetics[2L, c("mean", "mcse", "q05", "q25", "median", "q75", "q95")]))) + abundance <- summarise_trajectory(census) + expect_identical(abundance$n_extant, genetics$n_extant) + expect_identical(abundance$n_observed, rep(3L, 4L)) + expect_identical(abundance$p_ever_below, c(0, 1, 1, 1)) + expect_identical(abundance$p_ever_below_lower[1L], 0) + expect_identical(abundance$p_ever_below_upper[2:4], rep(1, 3L)) + expect_equal(abundance$p_ever_below_upper[1L], 0.5614970, tolerance = 1e-6) + bad <- census + bad$he[1L] <- NA_real_ + expect_error(summarise_trajectory(bad, "he"), "n_alive = 0") + for (value in c(Inf, NaN)) { + bad <- census + bad$he[4L] <- value + expect_error(summarise_trajectory(bad, "he"), "finite") + } + bad <- census + bad$n_alive[1L] <- NA_real_ + expect_error(summarise_trajectory(bad), "n_alive must be finite") + expect_error(summarise_trajectory(bad, "he"), "n_alive must be finite") + bad <- census + bad$n_alive <- NULL + expect_error(summarise_trajectory(bad, "he"), "n_alive = 0") + bad$reading <- seq_len(nrow(bad)) + expect_true(all(is.na(summarise_trajectory(bad, "reading")$n_extant))) +}) + test_that("interval accounting reconciles by cohort", { result <- run_scenario(pedigree_scenario(n_runs = 3L, n_steps = 6L, seed = 1L)) accounting <- summarise_accounting(result) @@ -54,6 +93,36 @@ test_that("interval accounting reconciles by cohort", { )), "accounting rows") }) +test_that("balanced interval totals cannot conceal broken process receipts or cohort stocks", { + ledger <- data.frame( + time = 0L, process_index = 1:3, n_before = c(2L, 1L, 2L), + births = c(0L, 1L, 0L), introductions = 0L, deaths_resident = c(1L, 0L, 0L), + deaths_born = 0L, deaths_introduced = 0L, removals_resident = 0L, + removals_born = 0L, removals_introduced = 0L, n_after = c(1L, 2L, 2L) + ) + good <- summarise_accounting(ledger) + expect_true(good$reconciled) + expect_identical(summarise_accounting(ledger[3:1, ]), good) + discontinuous <- ledger + discontinuous$n_before[2L] <- 2L + discontinuous$n_after[2L] <- 3L + receipts <- summarise_accounting(discontinuous) + expect_equal(receipts$residual, 0) + expect_false(receipts$reconciled) + for (cohort in c("born", "introduced")) { + wrong <- ledger + wrong[[paste0("deaths_", cohort)]] <- wrong$deaths_resident + wrong$deaths_resident <- 0L + if (cohort == "introduced") { + wrong$introductions <- wrong$births + wrong$births <- 0L + } + receipts <- summarise_accounting(wrong) + expect_equal(receipts$residual, 0) + expect_false(receipts$reconciled) + } +}) + test_that("initial observations agree across summaries and full runs enforce their design", { s <- scenario_spec( "recovery", 3L, 2L, function() pva_population("F", 1L), diff --git a/vignettes/rosetta.Rmd b/vignettes/rosetta.Rmd new file mode 100644 index 0000000..2d27b49 --- /dev/null +++ b/vignettes/rosetta.Rmd @@ -0,0 +1,363 @@ +--- +title: "A GAPPS, Vortex and Leslie-matrix Rosetta Stone for OpenPVA" +output: + html: + options: + toc: true +--- + + + +`{r} if (!capabilities("png")) invisible(litedown::reactor(dev = "pdf"))` + +```{r setup, include=FALSE} +library(OpenPVA) +litedown::reactor(fig.width = 6.5, fig.height = 4) +``` + +OpenPVA has no fixed annual cycle. A model is an ordered list of processes, and +the order is the biology. This vignette translates idioms from three traditions +into that list: the command scripts of GAPPS, the annual event sequence of +Vortex-style simulators, and the Leslie matrix. Every chunk runs as shown, with +fixed seeds and small ensembles so that the whole document builds in seconds. +The rates are illustrative. + +## Lookup table + +| Idiom | OpenPVA | +|---|---| +| Replicates and years (`RUN`, `YEAR`) | `scenario_spec(n_runs, n_steps)` and `run_scenario()` | +| Starting animals from a table (`READ`) | `pva_population()` from vectors or a data frame | +| Shared algebraic variables (`SET`) | `state$globals`, written by `environment_process()` | +| Survival and ageing (`SURVIVE`, `AGE`) | `survival_process()`, `staged_survival_process()`, `age_process()` | +| Mating and litters (`MATE`, `BREED`, `LITTER`, `BIRTH`) | `pairing_process()`, `mate_random()`, `mate_min_kinship()`, `reproduction_process()` with `litter_*()` | +| Counting (`CENSUS`, `SUMMARY`) | `census_process()`, `summarise_pva()`, `summarise_trajectory()` | +| Environmental variation in rates | `environment_process()` with `env_ar1()`, applied by `shift_logit()` | +| Catastrophes | `catastrophe_process()` | +| Carrying capacity as truncation | `ceiling_process()` | +| Density-dependent rates | `beverton_holt_multiplier()`, `ricker_multiplier()` | +| Harvest and supplementation | `removal_process()`, `introduction_process()` | +| Inbreeding depression (lethal equivalents) | `inbreeding_multiplier()` on `pedigree_F` | +| Genetic management by kinship | `pairing_process(priority = "kinship")`, `mate_min_kinship()` | +| Gene drop, heterozygosity, founder representation | `pva_state(n_loci = )`, `genetic_metrics()`, `summarise_pedigree()` | +| Dispersal among populations | `markov_dispersal_process()`, `dispersal_process()` | +| Leslie projection | the same process list with deterministic expectation $A^t n_0$ | + +The GAPPS command names are those documented in the package's heritage notes +from a surviving 1995 script. Grouping them by role is an inference from the +names and that script, and their argument syntax is not reproduced here, +because no GAPPS manual has been recovered. + +## A Leslie matrix, as a process list + +A post-breeding census with the order survive, age, breed gives a Leslie +matrix whose fertilities are survival times the fecundity of the next age +class. The stochastic model is the same life cycle, one individual at a time. + +```{r leslie} +survival <- c(0.5, 0.8, 0.9) # ages 0, 1 and 2+ +daughters <- c(0, 0.6, 1.1) # per female, by age at breeding +age_class <- function(age) pmin(age, 2L) + 1L + +A <- rbind( + survival * daughters[c(2, 3, 3)], + c(survival[1], 0, 0), + c(0, survival[2], survival[3]) +) +n0 <- c(0, 5, 10) + +females_only <- scenario_spec( + name = "leslie", n_runs = 150, n_steps = 6, seed = 4, + init_fun = function() pva_population(sex = rep("F", sum(n0)), age = rep(0:2, n0)), + processes = list( + survival_process(function(pop, state, context, params) survival[age_class(pop$age)], + requires = "population.age"), + age_process(), + reproduction_process( + breeding_probability = 1, + litter_size = litter_poisson(function(pop, state, context, params) { + daughters[age_class(pop$age)] + }), + offspring_sex = offspring_sex_bernoulli(1), + requires = "population.age" + ), + census_process() + ) +) +run <- run_scenario(females_only, keep = "census") +projected <- vapply(1:6, function(t) { + n <- n0 + for (step in seq_len(t)) n <- as.vector(A %*% n) + sum(n) +}, numeric(1)) +simulated <- summarise_trajectory(run) +round(data.frame(year = 1:6, matrix = projected, simulated = simulated$mean, + mcse = simulated$mcse), 2) +``` + +The simulated mean tracks $A^t n_0$ within Monte Carlo error. Unlike the +matrix, the simulation also gives the distribution around that mean and the +risk of falling below a threshold. + +## A Vortex-style year + +This illustrative Vortex-style cycle applies environmental variation and +catastrophes, then breeding, mortality, ageing, management and a carrying-capacity +limit. The order determines which animals experience each event. + +**Ceiling or density-dependent rates.** `ceiling_process()` truncates +abundance at K. A density multiplier instead lowers a vital rate smoothly. + +```{r vortex} +adult <- function(pop, state, context, params) pop$age >= 1L + +year <- function(limit) { + weather <- environment_process(list( + ev = env_ar1(sd = 0.4) # one shared logit deviate per year + )) + drought <- catastrophe_process(probability = 0.05, mortality = 0.3, name = "drought") + breed <- reproduction_process( + breeding_probability = function(pop, state, context, params) { + crowding <- if (limit == "density") { + beverton_holt_multiplier(length(pop$id), capacity = 60, growth = 1.5) + } else 1 + 0.9 * crowding * (pop$age >= 1L) + }, + litter_size = litter_poisson(1.4), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_random(adult), + requires = "population.age" + ) + die <- survival_process(function(pop, state, context, params) { + shift_logit(c(0.55, 0.85)[1L + (pop$age > 0L)], state$globals$ev) + }, requires = c("population.age", "globals.ev")) + harvest <- removal_process(probability = 0.1, eligible = adult, cause = "harvest", + name = "harvest", requires = "population.age") + release <- introduction_process( + count = function(state, context, params) if (context$time < 5L) 4L else 0L, + fields = function(n, state, context, params) list(sex = rep(c("F", "M"), 2), age = 2L), + name = "release" + ) + c(list(weather, drought, breed, die, age_process(), release, harvest), + if (limit == "ceiling") list(ceiling_process(capacity = 60)), + list(census_process())) +} + +simulate <- function(...) { + run_scenario(scenario_spec( + name = "vortex_style", n_runs = 30, n_steps = 10, seed = 2026, + init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 2L), + processes = year(...), initial_census = census_process() + )) +} +ceiling_run <- simulate("ceiling") +density_run <- simulate("density") +rbind( + ceiling = summarise_pva(ceiling_run, threshold = 10), + density = summarise_pva(density_run, threshold = 10) +)[, c("p_ever_below", "p_ever_below_upper", "final_q05", "final_median", "final_q95")] +``` + +With these rates neither rule lets the population fall below 10 animals in 10 +years, but abundance differs: the ceiling only caps the population at K = 60, +while density-dependent breeding slows growth well before K is reached. + +**Order of harvest and release.** Start with one yearling and one adult. +Release two more yearlings and request a harvest of two, taking the lowest +IDs among eligible yearlings. The receipts show which animals faced harvest. + +```{r order} +initial <- pva_state(pva_population(c("F", "M"), c(1L, 3L))) +harvest <- removal_process(count = 2L, order = "id", requires = "population.age", + eligible = function(pop, ...) pop$age == 1L) +release <- introduction_process(2L, function(...) list(sex = "F", age = 1L), + creates = c("sex", "age")) +compare_order <- function(processes) { + totals <- summarise_accounting(execute_processes(initial, processes)) + totals[c("n_start", "introductions", "removals_resident", "removals_introduced", "n_end")] +} +timing <- rbind(harvest_first = compare_order(list(harvest, release)), + release_first = compare_order(list(release, harvest))) +stopifnot(all(timing$removals_introduced == c(0L, 1L))) +timing +``` + +Harvest first removes the resident yearling alone. Release first exposes the +two newcomers, and the harvest takes the resident and one introduced animal. + +## Kinship-aware mating and gene drop + +`pva_state(pedigree = TRUE)` tracks exact kinship, and `n_loci` drops neutral +loci through the same pedigree. Compare random mating with a rule that gives +each female the least related eligible male, in a population held near 16 +animals. + +```{r genetics} +captive <- function(mate) { + scenario_spec( + name = "captive", n_runs = 24, n_steps = 12, seed = 1989, + init_fun = function() { + pva_state(pva_population(sex = rep(c("F", "M"), 4), age = 2L), + pedigree = TRUE, n_loci = 20L) + }, + processes = list( + survival_process(0.8), + age_process(), + reproduction_process( + breeding_probability = function(pop, state, context, params) { + 0.8 * (pop$age >= 2L) + }, + litter_size = litter_poisson(1.2), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate, requires = "population.age" + ), + ceiling_process(capacity = 16), + census_process(genetic_metrics()) + ), + initial_census = census_process(genetic_metrics()) + ) +} +random <- run_scenario(captive(mate_random(adult)), keep = "census") +managed <- run_scenario(captive(mate_min_kinship(adult)), keep = "census") +final <- function(run, metric) { + row <- summarise_trajectory(run, metric = metric)[13, ] + sprintf("%.3f (%d extant)", row$mean, row$n_extant) +} +metrics <- c("mean_inbreeding", "founder_genome_equivalents", + "expected_heterozygosity", "allelic_retention") +data.frame( + metric = metrics, + random = vapply(metrics, function(m) final(random, m), ""), + min_kinship = vapply(metrics, function(m) final(managed, m), ""), + row.names = NULL +) +``` + +Mean inbreeding, founder genome equivalents and heterozygosity are defined +for extant populations. Allelic retention includes extinct replicates at zero +when founders contributed alleles. Demographic draws use their own stream. + +For monogamous species, `pairing_process(priority = "kinship")` forms the set +of pairs with the lowest total kinship, here refusing pairs as related as +half-siblings or closer. + +```{r pairing} +family <- pva_state( + pva_population(sex = c("F", "M", "F", "M", "F", "M"), age = c(5, 5, 1, 1, 2, 2), + mother_id = c(NA, NA, 1, 1, NA, NA), father_id = c(NA, NA, 2, 2, NA, NA), + mate_id = NA_integer_), + pedigree = TRUE +) +pairs <- pairing_process(adult, priority = "kinship", max_kinship = 0.1, + requires = "population.age") +execute_processes(family, list(pairs))$state$population$mate_id +``` + +Parents 1 and 2 are not paired with their offspring 3 and 4, and the full +siblings are not paired with each other. + +## Two correlated patches + +`env_ar1()` generates anomalies that are autocorrelated in time and correlated +among patches, and `env_trend()` adds a deterministic trend or regime shift +without lagging it through the autoregression. Here two patches share +red-noise survival conditions (correlation 0.7) and patch B degrades from +interval 10. Females choose sires within their current patch before dispersal. + +```{r patches} +patches <- c("A", "B") +synchrony <- spatial_correlation(patches, rho = 0.7) +climate <- environment_process(list( + anomaly = env_ar1(sd = 0.5, phi = 0.6, cor = synchrony), + 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)) +two_patch <- scenario_spec( + name = "two_patch", n_runs = 40, n_steps = 20, seed = 77, + init_fun = function() { + pva_state(pva_population(sex = rep(c("F", "M"), 20), age = 2L, + patch_id = rep(patches, each = 20)), pedigree = TRUE) + }, + processes = list( + climate, + survival_process(function(pop, state, context, params) { + shift_logit(0.8, 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 = 30, 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") + ), + markov_dispersal_process(moves, eligible = function(pop, state, context, params) { + pop$age == 1L + }, requires = "population.age"), + census_process(function(pop, state, context, params) { + c(n_alive = length(pop$id), patch_counts(pop, patches)) + }) + ) +) +patch_run <- run_scenario(two_patch) +by_patch <- cbind(A = summarise_trajectory(patch_run, metric = "A")$median, + B = summarise_trajectory(patch_run, metric = "B")$median) +by_patch[c(10, 20), ] +``` + +## Diagnostic plots + +`plot()` on a run draws a trajectory fan, a cumulative risk curve or the +accounting view, and returns the table behind the figure. + +```{r fan, fig.alt = "Trajectory fan for the two-patch model"} +plot(patch_run, threshold = 20) +``` + +```{r risk, fig.alt = "Cumulative risk of falling below 20 animals"} +risk <- plot(patch_run, type = "risk", threshold = 20) +round(risk[c(10, 20), c("year", "p_ever_below", "p_ever_below_lower", + "p_ever_below_upper")], 3) +``` + +```{r accounting, fig.alt = "Mean entries and losses per year"} +invisible(plot(ceiling_run, type = "accounting")) +``` + +An ensemble separates the design from the replicates, and `plot()` contrasts +its members with their Monte Carlo intervals. + +```{r ensemble, fig.alt = "Risk by harvest rate"} +design <- data.frame(harvest = c(0, 0.15, 0.3)) +build <- function(row) { + list( + n_steps = 10, + init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 2L), + processes = list( + reproduction_process( + breeding_probability = function(pop, state, context, params) 0.6 * (pop$age >= 1L), + litter_size = litter_poisson(1.4), offspring_sex = offspring_sex_bernoulli(0.5), + requires = "population.age" + ), + survival_process(0.75), + age_process(), + removal_process(probability = row$harvest, cause = "harvest"), + ceiling_process(capacity = 60), + census_process() + ) + ) +} +ensemble <- run_pva_ensemble(design, build, n_runs = 30, seed = 3, + summarise = function(result, row) { + summarise_pva(result, threshold = 10) + }) +plot(ensemble, ylim = c(0, 1)) +``` From 56c18192abd2b4416f7f348092b8d40e6d12e974 Mon Sep 17 00:00:00 2001 From: "Barry W. Brook" Date: Mon, 30 Nov 2026 11:40:13 +1100 Subject: [PATCH 2/4] Tests & CI: self-contain PSOCK oracle fixtures for Windows and add libcurl4-openssl-dev for Linux V8 --- .github/workflows/ci-fast.yaml | 2 +- tests/testthat/helper-fixtures.R | 16 ++++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci-fast.yaml b/.github/workflows/ci-fast.yaml index 5ee1c5a..013346d 100644 --- a/.github/workflows/ci-fast.yaml +++ b/.github/workflows/ci-fast.yaml @@ -40,7 +40,7 @@ jobs: - name: Install HTML validators for the Linux release check if: matrix.manual run: | - sudo apt-get install -y --no-install-recommends tidy libnode-dev + sudo apt-get install -y --no-install-recommends tidy libnode-dev libcurl4-openssl-dev Rscript --vanilla -e 'install.packages("V8", repos = "https://cloud.r-project.org"); stopifnot(requireNamespace("V8", quietly = TRUE))' - name: Install LaTeX packages for the PDF manual if: matrix.manual diff --git a/tests/testthat/helper-fixtures.R b/tests/testthat/helper-fixtures.R index 73a6a1a..c91f5bc 100644 --- a/tests/testthat/helper-fixtures.R +++ b/tests/testthat/helper-fixtures.R @@ -48,6 +48,7 @@ oracle_matrix <- function(rates) { } oracle_scenario <- function(rates, n_runs, n_steps, seed) { + age_class <- function(age) pmin(age, 2L) + 1L scenario_spec( name = "matrix_oracle", n_runs = n_runs, @@ -63,17 +64,17 @@ oracle_scenario <- function(rates, n_runs, n_steps, seed) { survival_process(function(pop, state, context, params) { ifelse( pop$sex == "F", - rates$survival$F[oracle_class(pop$age)], - rates$survival$M[oracle_class(pop$age)] + rates$survival$F[age_class(pop$age)], + rates$survival$M[age_class(pop$age)] ) }, requires = "population.age"), age_process(), reproduction_process( breeding_probability = function(pop, state, context, params) { - rates$breeding[oracle_class(pop$age)] + rates$breeding[age_class(pop$age)] }, litter_size = litter_poisson(function(pop, state, context, params) { - rates$litter[oracle_class(pop$age)] + rates$litter[age_class(pop$age)] }), offspring_sex = offspring_sex_bernoulli(rates$female_probability), requires = "population.age" @@ -176,12 +177,15 @@ exact_cohort_chain <- function(design) { } cohort_scenario <- function(design, n_runs, seed) { + all_eligible <- function(pop, state, context, params) rep(TRUE, length(pop$id)) scenario_spec( name = "cohort_oracle", n_runs = n_runs, n_steps = design$years, seed = seed, - init_fun = function() adult_population(design$f0, design$m0), + init_fun = function() { + pva_population(sex = c(rep("F", design$f0), rep("M", design$m0)), age = 2L) + }, processes = list( survival_process(function(pop, state, context, params) { ifelse(pop$sex == "F", design$s_f, design$s_m) @@ -205,7 +209,7 @@ cohort_scenario <- function(design, n_runs, seed) { }, litter_size = litter_categorical(1:2, c(1 - design$p_two, design$p_two)), offspring_sex = offspring_sex_bernoulli(design$female_probability), - mate = mate_random(always), + mate = mate_random(all_eligible), require_mate = TRUE ), census_process() From 85cc1bba3d82715036cee61a0bd4c992ee11f06c Mon Sep 17 00:00:00 2001 From: "Barry W. Brook" Date: Mon, 30 Nov 2026 11:47:07 +1100 Subject: [PATCH 3/4] ci: install pandoc for Linux release top-level Markdown checks --- .github/workflows/ci-fast.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-fast.yaml b/.github/workflows/ci-fast.yaml index 013346d..63e9348 100644 --- a/.github/workflows/ci-fast.yaml +++ b/.github/workflows/ci-fast.yaml @@ -37,10 +37,10 @@ jobs: - name: Install a LaTeX distribution for the PDF manual if: matrix.manual uses: r-lib/actions/setup-tinytex@v2 - - name: Install HTML validators for the Linux release check + - name: Install HTML and Markdown validators for the Linux release check if: matrix.manual run: | - sudo apt-get install -y --no-install-recommends tidy libnode-dev libcurl4-openssl-dev + sudo apt-get install -y --no-install-recommends tidy pandoc libnode-dev libcurl4-openssl-dev Rscript --vanilla -e 'install.packages("V8", repos = "https://cloud.r-project.org"); stopifnot(requireNamespace("V8", quietly = TRUE))' - name: Install LaTeX packages for the PDF manual if: matrix.manual From 4de47bd4a1cecd80740ef4cfd26d7fba450c7909 Mon Sep 17 00:00:00 2001 From: "Barry W. Brook" Date: Mon, 30 Nov 2026 12:01:00 +1100 Subject: [PATCH 4/4] ci: set 20-minute job timeout on Package check --- .github/workflows/ci-fast.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci-fast.yaml b/.github/workflows/ci-fast.yaml index 63e9348..2cf3b0f 100644 --- a/.github/workflows/ci-fast.yaml +++ b/.github/workflows/ci-fast.yaml @@ -10,6 +10,7 @@ jobs: check: name: ${{ matrix.os }} / R ${{ matrix.r }} runs-on: ${{ matrix.os }} + timeout-minutes: 20 strategy: fail-fast: false matrix: