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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 39 additions & 5 deletions .github/workflows/ci-fast.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ jobs:
check:
name: ${{ matrix.os }} / R ${{ matrix.r }}
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
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:
Expand All @@ -31,13 +35,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 and Markdown validators for the Linux release check
if: matrix.manual
run: |
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
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: |
Expand Down
20 changes: 11 additions & 9 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

Expand All @@ -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
```
Expand Down
22 changes: 15 additions & 7 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
11 changes: 11 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -12,18 +15,24 @@ 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)
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)
Expand All @@ -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)
Expand Down
51 changes: 51 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
51 changes: 41 additions & 10 deletions R/ancestry.R
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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) {
Expand All @@ -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)
Expand Down
Loading
Loading