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
16 changes: 9 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ 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.1.0)
## Core architecture (OpenPVA 2.2.0)

- **One unified, pure-base-R engine:** `NeedsCompilation: no`, `Depends: R (>= 4.1.0)`,
and runtime `Imports` restricted to base/recommended packages (`codetools`,
Expand All @@ -25,15 +25,17 @@ inspectable, individual-based Population Viability Analyses in ordinary R.
`pva_process()` objects declaring `requires`, `writes`, and `creates`. Community
processes compose through the exact same public contract without controller edits.
- **Columnar living state:** `pva_population()` / `pva_state()` hold living
individuals as equal-length vectors; dead/removed records move to an optional
life-history ledger. Callbacks are vectorised over the living population and see
a shared pre-process state.
individuals as plain equal-length atomic vectors; dead/removed records move to an
optional life-history ledger (and departed sires referenced by living females
under a declared `mate_field` are retained by the engine until no longer needed).
Callbacks are vectorised over the living population and see 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` 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), and optional
preserved; substream 5 reserved for `survey_process()`), cohort-by-origin
accounting, exact conditional pedigree inbreeding (value-semantic dense kinship
store up to `max_dense_kinship`, switching cleanly to level-batched 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 Down
5 changes: 3 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: OpenPVA
Title: Composable Individual-Based Population Viability Analysis
Version: 2.1.1
Version: 2.2.0
Authors@R:
person("Barry W.", "Brook", email = "barry.brook@utas.edu.au",
role = c("aut", "cre", "cph"))
Expand All @@ -12,7 +12,8 @@ Description: An execution engine for individual-based population viability
inbreeding coefficients and provenance. Reusable processes cover
survival, reproduction with several litter-size distributions, pairing
and territory limits, kinship-aware mate choice, removals,
introductions, temporally and spatially correlated environmental
introductions, imperfect surveys and observation-based management,
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.
Expand Down
8 changes: 7 additions & 1 deletion NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ S3method(print,pva_state)
export(add_individuals)
export(age_process)
export(age_sex_rate)
export(assign_process)
export(beta_shapes)
export(beverton_holt_multiplier)
export(catastrophe_process)
Expand All @@ -24,6 +25,7 @@ export(inbreeding_multiplier)
export(inbreeding_proxy_process)
export(introduction_process)
export(kinship_matrix)
export(life_table_metrics)
export(litter_binomial)
export(litter_categorical)
export(litter_poisson)
Expand All @@ -32,6 +34,7 @@ export(markov_dispersal_process)
export(mate_from_field)
export(mate_min_kinship)
export(mate_random)
export(mating_process)
export(mean_kinship)
export(offspring_sex_bernoulli)
export(pairing_process)
Expand All @@ -41,6 +44,7 @@ export(pva_population)
export(pva_process)
export(pva_result)
export(pva_state)
export(qbeta_norm)
export(removal_process)
export(reproduction_process)
export(ricker_multiplier)
Expand All @@ -50,12 +54,14 @@ export(scenario_spec)
export(sex_ratio_effective_size)
export(shift_logit)
export(spatial_correlation)
export(staged_survival_process)
export(summarise_accounting)
export(summarise_markers)
export(summarise_pedigree)
export(summarise_pva)
export(summarise_trajectory)
export(staged_survival_process)
export(survey_process)
export(survey_quota)
export(survival_process)
export(validate_age_sex_table)
export(validate_processes)
38 changes: 38 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,43 @@
# OpenPVA news

## OpenPVA 2.2.0

- Target removals, ceilings, translocations and individual treatments with
successive weighted draws. Count events report unmet demand. `assign_process()`
writes a typed treatment, dependency, or group field and accepts a custom
event name.
- `mating_process()` records seasonal sires with male reproductive skew,
capacities and local mating. A state with a declared `mate_field` retains
a departed sire's attributes, kinship and alleles while a living female
references him. In `newborn_fields`, the supplied population appends any
departed sires needed by the litter with their attributes at exit and
`alive = FALSE`. Staggered mating can preserve other dams' sire records with
`clear = FALSE`. The grizzly example uses the new mating process.
- `survey_process()` records imperfect counts and detected IDs on scheduled visits using
replicate substream 5. `survey_quota()` applies a decision rule to the
current observation and handles missed visits explicitly. Seeded runs also
preserve a caller's pending Box–Muller normal.
- Litter distributions and offspring sex ratios accept individual rate
callbacks. `qbeta_norm()` maps Gaussian environmental variation to beta
rates. `life_table_metrics()` projects either breeding census convention
with a finite or repeating terminal age, and reports mean maternal age in
the stable population and in a newborn cohort.
`summarise_pva()` reports expected minimum abundance and its Monte Carlo
standard error.
- Traced pedigrees batch parental kinship queries. The documentation and
Rosetta Stone vignette incorporate the recovered spatial GAPPS II 1.3
command and species scripts.
- *Development provenance:* Developed under Barry W. Brook's direction using
independent multi-model sessions coordinated through `BWBrook/research-advisor`:
2.2.0 backbone implementation, B4 hardening, harvest integration, and
R 4.1.0 / R-devel verification by OpenAI Codex (`gpt-6.2-astra`); B1/B3
cross-critique by Anthropic Claude Opus 5.5, with level-batched traced
pedigree propagation, half-year herd vignette, assignment coercion design,
and final B5 diff audit by Anthropic Claude Fable 5.2; B1–B3 gap analysis,
`qbeta_norm()` upper-tail guard, and initial `mate_field` founder checks
from Google Gemini 4 Carbon (High); GAPPS II 1.3 archive synthesis,
independent verification, and adjudication by Google Gemini 4 Neon.

## OpenPVA 2.1.1

- Accept R-devel (`R >= 4.7.0`) `.Random.seed` headers incorporating
Expand Down
164 changes: 108 additions & 56 deletions R/ancestry.R
Original file line number Diff line number Diff line change
Expand Up @@ -15,44 +15,97 @@
}

.ancestor_graph <- function(ped, rows) {
active <- frontier <- unique(rows)
# Index 1 marks the unrecorded parent. Visit each ancestor once, then
# reuse the visited indices to map parent rows into this subgraph.
index <- integer(length(ped$id) + 1L)
index[1L] <- -1L
frontier <- unique(rows)
index[frontier + 1L] <- 1L
while (length(frontier)) {
parents <- unique(c(ped$mother[frontier], ped$father[frontier]))
frontier <- setdiff(parents[parents != 0L], active)
active <- c(active, frontier)
parents <- c(ped$mother[frontier], ped$father[frontier]) + 1L
unseen <- unique(parents[index[parents] == 0L])
index[unseen] <- 1L
frontier <- unseen - 1L
}
active <- sort.int(active)
active <- which(index == 1L) - 1L
nil <- length(active) + 1L
mother <- match(ped$mother[active], active, nil)
father <- match(ped$father[active], active, nil)
index[1L] <- nil
index[active + 1L] <- seq_along(active)
mother <- index[ped$mother[active] + 1L]
father <- index[ped$father[active] + 1L]
remaining <- which(mother != nil | father != nil)
ready <- rep.int(TRUE, nil)
ready[remaining] <- FALSE
levels <- list()
while (length(remaining)) {
resolved <- ready[mother[remaining]] & ready[father[remaining]]
level <- remaining[resolved]
if (!length(level)) .stop("cyclic ancestry in traced pedigree")
levels[[length(levels) + 1L]] <- level
ready[level] <- TRUE
remaining <- remaining[!resolved]
}
index <- match(active, ped$related, 0L)
base <- which(index > 0L)
list(rows = active, mother = mother, father = father,
children = which(mother != nil | father != nil), d = ped$d[active],
levels = levels, d = ped$d[active],
base = base, base_K = ped$base[index[base], index[base], drop = FALSE])
}

# K = T D T'. Trace the source's inherited contributions back through T',
# apply the founder covariance and Mendelian sampling variances D, then
# propagate covariance forward through T. Only ancestors of the query occur.
.graph_covariance <- function(graph, source, target) {
n <- length(graph$rows)
weight <- numeric(n + 1L)
weight[source] <- 1
for (i in rev(graph$children)) {
half <- 0.5 * weight[i]
m <- graph$mother[i]
f <- graph$father[i]
weight[m] <- weight[m] + half
weight[f] <- weight[f] + half
# K = T D T'. No node has a parent on its own level. Sum
# contributions to shared parents in the backward pass, then propagate the
# founder covariances and Mendelian sampling variances forward level by level.
.graph_propagate <- function(graph, source, target, summed = FALSE) {
weight <- matrix(0, length(graph$rows) + 1L, if (summed) 1L else length(source))
if (summed) {
weight[source, 1L] <- 1
} else {
weight[cbind(source, seq_along(source))] <- 1
}
populated <- needed <- logical(nrow(weight))
populated[source] <- TRUE
needed[target] <- TRUE
forward <- graph$levels
for (i in rev(seq_along(graph$levels))) {
level <- graph$levels[[i]]
nodes <- level[needed[level]]
forward[[i]] <- nodes
needed[c(graph$mother[nodes], graph$father[nodes])] <- TRUE
nodes <- level[populated[level]]
if (!length(nodes)) next
m <- graph$mother[nodes]
f <- graph$father[nodes]
half <- 0.5 * weight[nodes, , drop = FALSE]
# Full siblings transmit their summed contributions to the same parents.
first <- c(TRUE, diff(m) != 0L | diff(f) != 0L)
if (!all(first)) {
half <- rowsum(half, cumsum(first), reorder = FALSE)
m <- m[first]
f <- f[first]
}
for (parents in list(m, f)) {
to <- unique(parents)
delta <- half
if (length(to) < length(parents)) delta <- rowsum(half, parents, reorder = FALSE)
if (any(populated[to])) delta <- delta + weight[to, , drop = FALSE]
weight[to, ] <- delta
populated[to] <- TRUE
}
}
value <- c(graph$d * weight[seq_len(n)], 0)
b <- graph$base
if (length(b)) value[b] <- graph$base_K %*% weight[b]
for (i in graph$children) {
value[i] <- value[i] + 0.5 * (value[graph$mother[i]] + value[graph$father[i]])
if (length(b)) founder <- graph$base_K %*% weight[b, , drop = FALSE]
weight <- weight * c(graph$d, 0)
if (length(b)) weight[b, ] <- founder
for (nodes in forward) {
weight[nodes, ] <- weight[nodes, , drop = FALSE] +
0.5 * (weight[graph$mother[nodes], , drop = FALSE] + weight[graph$father[nodes], , drop = FALSE])
}
value[target]
weight
}

# Linearity gives the sum against all living sources in a single column.
.graph_covariance <- function(graph, source, target) {
.graph_propagate(graph, source, target, summed = TRUE)[target, 1L]
}

.ancestry_pairs <- function(ped, mother, father) {
Expand All @@ -71,12 +124,20 @@
same <- m == f
out[known[same]] <- 0.5 * (1 + ped$F[m[same]])
query <- known[!same & !(root[m] & root[f])]
for (group in split(query, mother[query])) {
dam <- mother[group[1L]]
sires <- unique(father[group])
graph <- .ancestor_graph(ped, c(dam, sires))
kin <- .graph_covariance(graph, match(dam, graph$rows), match(sires, graph$rows))
out[group] <- kin[match(father[group], sires)]
if (!length(query)) return(out)
a <- mother[query]
b <- father[query]
if (length(unique(b)) < length(unique(a))) {
a <- father[query]
b <- mother[query]
}
# Nearby parents often share ancestors. Bound the union of their pedigrees
# by grouping distinct sources in pedigree order, regardless of litter order.
group <- (match(a, sort.int(unique(a))) - 1L) %/% 64L
for (pairs in split(seq_along(query), group)) {
graph <- .ancestor_graph(ped, c(a[pairs], b[pairs]))
out[query[pairs]] <- .graph_block(graph, match(a[pairs], graph$rows),
match(b[pairs], graph$rows), paired = TRUE)
}
out
}
Expand All @@ -92,31 +153,22 @@
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]])
# A repeated source needs only one column, even when queried with many mates.
# Reduce the block size for large graphs to budget a million entries per matrix.
.graph_block <- function(graph, source, target, paired = FALSE) {
out <- if (paired) numeric(length(source)) else matrix(0, length(source), length(target))
sources <- sort.int(unique(source))
index <- match(source, sources)
size <- max(1L, min(64L, 1e6 %/% (length(graph$rows) + 1L)))
for (rows in split(seq_along(source), (index - 1L) %/% size)) {
block <- seq.int(min(index[rows]), max(index[rows]))
value <- .graph_propagate(graph, sources[block], if (paired) target[rows] else target)
columns <- index[rows] - block[1L] + 1L
if (paired) {
out[rows] <- value[cbind(target[rows], columns)]
} else {
out[rows, ] <- t(value[target, columns, drop = FALSE])
}
out[block, ] <- value[, target, drop = FALSE]
}
out
}
Expand Down
Loading
Loading