diff --git a/AGENTS.md b/AGENTS.md index fe016ca..dd22fa4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`, @@ -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 diff --git a/DESCRIPTION b/DESCRIPTION index 825f420..aa89b25 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -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")) @@ -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. diff --git a/NAMESPACE b/NAMESPACE index 8b0e12a..49af906 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -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) @@ -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) @@ -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) @@ -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) @@ -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) diff --git a/NEWS.md b/NEWS.md index 8b8f221..140828d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 diff --git a/R/ancestry.R b/R/ancestry.R index bb97b55..a24caae 100644 --- a/R/ancestry.R +++ b/R/ancestry.R @@ -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) { @@ -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 } @@ -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 } diff --git a/R/ensemble.R b/R/ensemble.R index 5689980..57145e9 100644 --- a/R/ensemble.R +++ b/R/ensemble.R @@ -107,6 +107,7 @@ summarise_pva <- function( horizon <- census$years[[length(census$years)]] below <- values < threshold final <- values[, ncol(values)] + minima <- apply(values, 1L, min) ever <- rowSums(below) > 0 first <- ifelse(ever, census$years[max.col(below, ties.method = "first")], NA_integer_) restricted <- ifelse(ever, first, horizon) @@ -134,7 +135,9 @@ summarise_pva <- function( final_q25 = quantiles[[2L]], final_median = quantiles[[3L]], final_q75 = quantiles[[4L]], - final_q95 = quantiles[[5L]] + final_q95 = quantiles[[5L]], + ema = mean(minima), + ema_mcse = mcse(minima) ) ), stringsAsFactors = FALSE) } @@ -298,18 +301,20 @@ run_pva_ensemble <- function( seed <- .as_count(seed, "seed") version <- as.character(utils::packageVersion("OpenPVA")) .with_rng_restored({ - RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection") - set.seed(seed) + .set_pva_seed(seed) + rng_kind <- RNGkind() + rng_header <- .GlobalEnv$.Random.seed[1L] block_seeds <- sample.int(.Machine$integer.max, max(block)) member_seeds <- block_seeds[block] revision <- if (!is.null(cache_dir)) { list(validation = validation, package_version = version, r_version = R.version.string, + rng_kind = rng_kind, callbacks = .callback_bindings(list(build, summarise), fingerprint = TRUE), cache_key = cache_key) } payload <- list( design = design, build = build, summarise = summarise, n_runs = n_runs, - seeds = member_seeds, validation = validation, cache_dir = cache_dir, + seeds = member_seeds, rng_header = rng_header, validation = validation, cache_dir = cache_dir, revision = revision ) summaries <- .dispatch( @@ -331,6 +336,7 @@ run_pva_ensemble <- function( class(out) <- c("pva_ensemble", "data.frame") attr(out, "provenance") <- list( root_seed = seed, + rng_kind = rng_kind, n_runs = n_runs, design = names(design), seed_by = seed_by, @@ -357,7 +363,7 @@ run_pva_ensemble <- function( } } summary <- .with_rng_restored({ - set.seed(seed, kind = "L'Ecuyer-CMRG", normal.kind = "Inversion", sample.kind = "Rejection") + .set_pva_seed(seed, payload$rng_header) assign(".Random.seed", parallel::nextRNGSubStream(.GlobalEnv$.Random.seed), envir = .GlobalEnv) components <- payload$build(as.list(row)) if (!is.list(components) || diff --git a/R/life_table.R b/R/life_table.R new file mode 100644 index 0000000..7978116 --- /dev/null +++ b/R/life_table.R @@ -0,0 +1,83 @@ +life_table_metrics <- function(survival, fecundity, timing = c("post_breeding", "pre_breeding"), + plus_group = TRUE) { + timing <- match.arg(timing) + n <- length(survival) + if (!is.numeric(survival) || !is.null(dim(survival)) || !n || + any(!is.finite(survival)) || any(survival < 0 | survival > 1)) { + .stop("survival must give one finite probability per age class") + } + if (!is.numeric(fecundity) || !is.null(dim(fecundity)) || length(fecundity) != n || + any(!is.finite(fecundity)) || any(fecundity < 0)) { + .stop("fecundity must give finite non-negative daughters per female in each age class") + } + if (n > 1L && fecundity[[1L]] > 0) .stop("fecundity at age 0 must be zero") + if (!.is_flag(plus_group)) .stop("plus_group must be TRUE or FALSE") + terminal <- if (plus_group) survival[[n]] else 0 + if (terminal == 1) .stop("terminal survival must be below one for a finite cohort life table") + + classes <- seq_len(n) + next_class <- pmin(classes + 1L, n) + projection <- matrix(0, n, n) + transitions <- survival + transitions[n] <- terminal + projection[cbind(next_class, classes)] <- transitions + ages <- classes - 1L + if (timing == "post_breeding") { + to_breeding <- if (n == 1L) survival else transitions + projection[1L, ] <- projection[1L, ] + to_breeding * fecundity[next_class] + } else { + first <- next_class[1L] + projection[first, ] <- projection[first, ] + survival[1L] * fecundity + present <- seq.int(first, n) + projection <- projection[present, present, drop = FALSE] + ages <- pmax(1L, ages[present]) + } + labels <- as.character(ages) + if (terminal > 0) labels[length(ages)] <- paste0(ages[length(ages)], "+") + dimnames(projection) <- list(labels, labels) + + # At stable growth, mothers of age x contribute their cohort daughters + # discounted by lambda^x. Repeated terminal pulses form a geometric tail. + breeding_age <- seq_len(max(1L, n - 1L)) + daughters <- cumprod(survival[breeding_age]) * fecundity[next_class[breeding_age]] + maternity <- function(growth) { + count <- daughters + age <- breeding_age + if (growth != 1) { + producing <- count > 0 + count[producing] <- exp(log(count[producing]) - age[producing] * log(growth)) + } + last <- length(age) + if (daughters[last] > 0 && terminal > 0) { + if (growth <= terminal) return(c(Inf, NA_real_)) + extra <- terminal / (growth - terminal) + count[last] <- count[last] * (1 + extra) + age[last] <- age[last] + extra + } + total <- sum(count) + c(total, if (total > 0 && is.finite(total)) sum(age * (count / total)) else NA_real_) + } + cohort <- maternity(1) + + right <- eigen(projection) + index <- which.max(Re(right$values)) + lambda <- Re(right$values[index]) + stable <- value <- rep(NA_real_, nrow(projection)) + generation_time <- NA_real_ + tolerance <- 16 * .Machine$double.eps * length(stable) * lambda + if (lambda > 0 && sum(Mod(right$values - lambda) <= tolerance) == 1L) { + stable <- abs(Re(right$vectors[, index])) + stable <- stable / sum(stable) + left <- eigen(t(projection)) + value <- abs(Re(left$vectors[, which.max(Re(left$values))])) + value <- value / sum(value * stable) + if (cohort[1L] > 0) { + mothers <- maternity(lambda) + if (mothers[1L] >= 1 - 1e-9) generation_time <- mothers[2L] + } + } + names(stable) <- names(value) <- labels + list(matrix = projection, lambda = lambda, r = log(lambda), R0 = cohort[1L], + generation_time = generation_time, cohort_generation_time = cohort[2L], + stable_age = stable, reproductive_value = value) +} diff --git a/R/markers.R b/R/markers.R index 90149fe..4709fda 100644 --- a/R/markers.R +++ b/R/markers.R @@ -1,7 +1,7 @@ # 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); +# earlier in the interval and any retained sires; # 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; @@ -12,34 +12,12 @@ # # 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 -} +# in a builder, 4 subsequent segregation and 5 surveys in each replicate. .marker_seed <- function() { seed <- .GlobalEnv$.Random.seed - if (!is.null(seed) && seed[1L] %% 100L == 7L) return(.marker_stream(seed, 2L)) - .with_marker_rng({ + if (!is.null(seed) && seed[1L] %% 100L == 7L) return(.rng_substream(seed, 2L)) + .with_rng_restored({ # 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) @@ -47,7 +25,7 @@ } .marker_uniform <- function(seed, n) { - .with_marker_rng({ + .with_rng_restored({ # 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] @@ -96,7 +74,7 @@ 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") + .stop("a parent has no stored genotype") } value <- rep(NA_integer_, n * n_loci) if (!all(unknown)) { @@ -147,12 +125,13 @@ all(first < 4294967087) && all(last < 4294944443) && any(first > 0) && any(last > 0) } -.validate_markers <- function(markers, population, next_id, at_entry) { +.validate_markers <- function(markers, population, next_id, at_entry, retained = NULL) { ids <- population$id + expected <- if (length(retained)) sort.int(c(ids, retained)) else ids 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.unsorted(markers$id, strictly = TRUE) || anyNA(match(expected, markers$id)) || + (at_entry && !identical(expected, 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)) || diff --git a/R/mating_process.R b/R/mating_process.R new file mode 100644 index 0000000..78116db --- /dev/null +++ b/R/mating_process.R @@ -0,0 +1,118 @@ +.is_male_capacity <- function(x) { + is.numeric(x) && is.null(dim(x)) && length(x) == 1L && !is.na(x) && + (x == Inf || .is_count(x)) +} + +.draw_sires <- function(males, n, capacity, weights) { + w <- if (!is.null(weights)) weights[males] + if (capacity >= n) { + if (!is.null(w)) w <- w / max(w) + return(males[sample.int(length(males), n, replace = TRUE, prob = w)]) + } + if (capacity == 1L) { + if (is.null(w)) return(males[sample.int(length(males), n)]) + # Here draw order determines which female receives each sire. + return(males[.weighted_order(w)[seq_len(n)]]) + } + slots <- as.double(length(males)) * capacity + if (slots <= 65536L) { + # Each sire runs one Poisson clock until his last mating. Ranking + # cumulative unit-rate waits avoids overflow from division by tiny rates. + arrivals <- matrix(stats::rexp(slots), nrow = capacity) + if (capacity <= length(males)) { + for (k in 2:capacity) arrivals[k, ] <- arrivals[k, ] + arrivals[k - 1L, ] + } else { + for (j in seq_along(males)) arrivals[, j] <- cumsum(arrivals[, j]) + } + if (!is.null(w)) arrivals <- log(arrivals) - rep(log(w), each = capacity) + first <- order(arrivals)[seq_len(n)] + return(males[(first - 1L) %/% capacity + 1L]) + } + remaining <- rep(capacity, length(males)) + drawn <- integer(n) + prob <- if (!is.null(w)) w / max(w) + for (i in seq_len(n)) { + j <- sample.int(length(males), 1L, prob = prob) + drawn[i] <- males[j] + remaining[j] <- remaining[j] - 1L + if (remaining[j] == 0L) { + males <- males[-j] + remaining <- remaining[-j] + if (!is.null(w) && length(males)) { + w <- w[-j] + prob <- w / max(w) + } + } + } + drawn +} + +mating_process <- function( + eligible = NULL, + male_capacity = Inf, + weights = NULL, + by = NULL, + field = "mate_id", + name = "mating", + requires = character(), + params = list(), + when = TRUE, + clear = TRUE) { + .check_optional_function(eligible, "eligible") + .check_optional_function(weights, "weights") + if (!.is_flag(clear)) .stop("clear must be TRUE or FALSE") + if (!is.function(male_capacity) && !.is_male_capacity(male_capacity)) { + .stop("male_capacity must be a non-negative whole number, Inf or a count callback") + } + capacity <- .count_function(male_capacity, "male_capacity") + visit <- .when_function(when) + group_path <- .mating_group_requirement(by) + if (!.is_name(field) || field %in% .reserved_fields) { + .stop("field must be a user-defined population field for mate IDs") + } + path <- paste0("population.", field) + pva_process( + name = name, + run = function(state, context, params) { + user <- params$user + if (!params$when(state, context, user)) { + return(pva_result(state, pva_events(c("mated_females", "unmated_females"), c(0L, 0L)))) + } + pop <- state$population + mate <- pop[[params$field]] + if (!is.numeric(mate)) .stop("mate field must hold numeric individual IDs") + rows <- .eligible_rows(params$eligible, pop, state, context, user) + females <- rows[pop$sex[rows] == "F"] + males <- rows[pop$sex[rows] == "M"] + if (params$clear) mate[] <- NA else mate[females] <- NA + w <- .individual_weights(params$weights, pop, state, context, user) + if (!is.null(w)) males <- males[w[males] > 0] + capacity <- params$capacity(state, context, user) + if (!.is_male_capacity(capacity)) { + .stop("male_capacity must evaluate to a non-negative whole number or Inf") + } + group <- if (is.null(params$by)) rep.int(1L, length(mate)) else pop[[params$by]] + if (anyNA(group)) .stop("population field ", params$by, " must be non-missing") + if (capacity > 0 && length(females) && length(males)) { + group_index <- match(group, unique(group)) + dams <- split(females, group_index[females]) + sires <- split(males, group_index[males]) + for (g in intersect(names(dams), names(sires))) { + f <- dams[[g]] + m <- sires[[g]] + n <- min(length(f), as.double(capacity) * length(m)) + if (capacity < length(f)) f <- f[sample.int(length(f), n)] + mate[f] <- pop$id[.draw_sires(m, n, capacity, w)] + } + } + state$population[[params$field]] <- mate + mated <- sum(!is.na(mate[females])) + pva_result(state, pva_events(c("mated_females", "unmated_females"), + c(mated, length(females) - mated))) + }, + params = list(eligible = eligible, capacity = capacity, weights = weights, by = by, + field = field, when = visit, clear = clear, user = params), + requires = unique(c("population.sex", path, group_path, requires)), writes = path, + description = "Record seasonal sires subject to relative male weights, capacity and mating groups." + ) +} diff --git a/R/pedigree.R b/R/pedigree.R index 8b997a9..f29ab21 100644 --- a/R/pedigree.R +++ b/R/pedigree.R @@ -57,8 +57,68 @@ store } -# Known parents are living, or were lost earlier in the same interval. -.check_parents <- function(pop, n_before, context, dead_females) { +.sire_references <- function(pop, field, next_id = Inf) { + if (!.is_name(field) || field %in% .reserved_fields || !is.numeric(pop[[field]])) { + .stop("mate_field must name a numeric model field containing sire IDs") + } + ids <- pop[[field]][pop$sex == "F"] + if (any(is.nan(ids)) || any(ids < 1 | ids > .Machine$integer.max | + ids != floor(ids), na.rm = TRUE)) { + .stop("mate_field must contain positive integer IDs or NA") + } + if (any(ids >= next_id, na.rm = TRUE)) .stop("mate_field contains an unallocated sire ID") + unique(ids[!is.na(ids)]) +} + +.validate_sires <- function(state) { + sires <- state$sires + if (!identical(names(sires), c("field", "records"))) .stop("invalid retained sire store") + pop <- state$population + refs <- .sire_references(pop, sires$field, state$next_id) + records <- sires$records + if (is.null(records)) return(invisible(TRUE)) + if (!is.list(records) || + !identical(names(records), names(pop)) || + !identical(vapply(records, typeof, ""), vapply(pop, typeof, "")) || + any(vapply(records, function(column) !is.null(attributes(column)), logical(1)))) { + .stop("invalid retained sire records") + } + .validate_population(records, pedigree = !is.null(state$kinship)) + if (any(records$sex != "M" | records$alive | records$id >= state$next_id) || + any(records$id %in% pop$id) || !all(records$id %in% refs)) { + .stop("invalid retained sire records") + } + if (!is.null(state$kinship)) { + store <- state$kinship + slots <- if (is.list(store)) { + if (is.null(store$values)) store$id else store$ids + } + if (!all(records$id %in% slots)) { + .stop("retained sire is missing from the pedigree store") + } + } + invisible(TRUE) +} + +# Loss snapshots use the population at exit (including changes in that process). +# Materialise only sires needed for a litter or referenced at the boundary. +.sire_records <- function(wanted, retained, losses) { + pieces <- list() + if (length(retained$id)) { + rows <- which(retained$id %in% wanted) + if (length(rows)) pieces[[1L]] <- lapply(retained, `[`, rows) + } + for (loss in losses) { + rows <- which(loss$id %in% wanted) + if (length(rows)) pieces[[length(pieces) + 1L]] <- lapply(loss, `[`, rows) + } + if (!length(pieces)) return(NULL) + records <- Reduce(function(x, y) Map(c, x, y), pieces) + if (is.unsorted(records$id)) records <- lapply(records, `[`, order(records$id)) + records +} + +.check_parents <- function(pop, n_before, context, dead_females, retained) { new <- seq.int(n_before + 1L, length(pop$id)) m <- pop$mother_id[new] f <- pop$father_id[new] @@ -66,7 +126,7 @@ females <- pop$sex[existing] == "F" ids <- pop$id[existing] if (any(!is.na(m) & !m %in% c(ids[females], dead_females)) || - any(!is.na(f) & !f %in% c(ids[!females], context$departed_males))) { + any(!is.na(f) & !f %in% c(ids[!females], context$departed_males, retained))) { .stop("process '", context$process_name, "' supplied an unknown parent ID, non-female mother or non-male father in this interval") } @@ -126,7 +186,8 @@ } .close_kinship <- function(state) { - if (is.list(state$kinship) && !is.null(state$kinship$values)) { + if (is.list(state$kinship) && !is.null(state$kinship$values) && + !length(state$sires$records$id)) { state$kinship <- kinship_matrix(state) } state diff --git a/R/process.R b/R/process.R index dc18208..7ea0319 100644 --- a/R/process.R +++ b/R/process.R @@ -138,6 +138,32 @@ validate_processes <- function(processes, state = NULL) { processes <- lapply(processes, .validate_process) names_in_order <- vapply(processes, `[[`, character(1), "name") occurrence <- stats::ave(seq_along(names_in_order), names_in_order, FUN = seq_along) + survey <- vapply(processes, function(p) { + # Serialisation can replace nested source-reference environments on workers. + identical(environment(p$run), environment(.run_survey)) && + (identical(p$run, .run_survey) || + identical(utils::removeSource(p$run), utils::removeSource(.run_survey))) + }, logical(1)) + sire_lookup <- vapply(processes, function(p) { + !is.null(p$params$mate_field) && is.function(p$params$newborn_fields) + }, logical(1)) + snapshot_sires <- logical(length(processes)) + for (lookup in which(sire_lookup)) { + field <- processes[[lookup]]$params$mate_field + path <- paste0("population.", field) + prior <- seq_len(lookup - 1L) + writers <- which(vapply(processes[prior], function(p) { + path %in% p$writes || field %in% p$creates + }, logical(1))) + # A subsequent custom write can designate a male that has already died. + # Only a final, unconditional pairing with living males rules that out. + if (length(writers)) { + last <- writers[[length(writers)]] + if (isTRUE(attr(processes[[last]]$run, "resets_mate_field", exact = TRUE)) && + identical(processes[[last]]$params$field, field)) prior <- prior[prior > last] + } + snapshot_sires[prior] <- TRUE + } strip <- function(paths, prefix) { sub(prefix, "", paths[startsWith(paths, prefix)], fixed = TRUE) } @@ -145,6 +171,10 @@ validate_processes <- function(processes, state = NULL) { processes = processes, names = names_in_order, occurrence = as.integer(occurrence), + has_survey = any(survey), + survey = survey, + sire_lookup = sire_lookup, + snapshot_sires = snapshot_sires, closed_proxy = any(vapply(processes, function(p) { identical(p$run, .update_inbreeding_proxy) && is.null(p$params$migration) }, logical(1))), @@ -249,9 +279,11 @@ validate_processes <- function(processes, state = NULL) { population_writes, checked_writes, global_writes, + has_optional, + is_survey, totals, - n_lost) { - label <- paste0("process '", process$name, "'") + n_lost, + label = paste0("process '", process$name, "'")) { if (!inherits(after, "pva_state") || !identical(names(after), names(before))) { .stop(label, " must return a pva_state inside pva_result()") } @@ -307,6 +339,12 @@ validate_processes <- function(processes, state = NULL) { if (!identical(after$markers, before$markers)) { .stop(label, " changed the engine-owned neutral-locus store") } + if (has_optional) { + if (!identical(after$sires, before$sires)) .stop(label, " changed engine-owned sire records") + if (!identical(after$survey_seed, before$survey_seed) && !is_survey) { + .stop(label, " changed the engine-owned survey substream") + } + } if (n_new) { if (is.null(process$creates)) { .stop(label, " created individuals without a creates declaration") @@ -396,6 +434,9 @@ validate_processes <- function(processes, state = NULL) { markers <- !is.null(state$markers) parentage <- pedigree || markers dead_males <- dead_females <- integer() + remember <- !is.null(state$sires) + has_optional <- remember || !is.null(state$survey_seed) + losses <- list() for (index in seq_len(n_processes)) { process <- processes[[index]] @@ -410,6 +451,7 @@ validate_processes <- function(processes, state = NULL) { occurrence = execution$occurrence[[index]], departed_males = dead_males ) + if (length(losses) && execution$sire_lookup[[index]]) context$sire_losses <- losses result <- process$run(state, context, process$params) if (!inherits(result, "pva_result")) { .stop("process '", process$name, "' must return pva_result()") @@ -430,6 +472,8 @@ validate_processes <- function(processes, state = NULL) { population_writes = execution$population_writes[[index]], checked_writes = execution$checked_writes[[index]], global_writes = execution$global_writes[[index]], + has_optional = has_optional, + is_survey = execution$survey[[index]], totals = totals, n_lost = n_lost ) @@ -444,7 +488,8 @@ 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 (parentage) .check_parents(population, n_before, context, dead_females, + state$sires$records$id) if (pedigree) { births <- .kinship_births( after$kinship, population, n_before, state$max_dense_kinship @@ -480,6 +525,9 @@ validate_processes <- function(processes, state = NULL) { ledger[[index]] <- chunk } male <- population$sex[lost] == "M" + if ((remember || execution$snapshot_sires[[index]]) && any(male)) { + losses[[length(losses) + 1L]] <- lapply(population, `[`, lost[male]) + } dead_males <- c(dead_males, population$id[lost[male]]) if (parentage) dead_females <- c(dead_females, population$id[lost[!male]]) keep <- population$alive @@ -487,6 +535,20 @@ validate_processes <- function(processes, state = NULL) { } accounting[index, 12L] <- length(population$id) after$population <- population + if (remember) refs <- .sire_references(population, after$sires$field, after$next_id) + if (remember && length(after$sires$records$id)) { + expired <- setdiff(after$sires$records$id, refs) + if (length(expired)) { + after$sires["records"] <- list(.sire_records(refs, after$sires$records, NULL)) + if (pedigree && !is.null(after$kinship$values)) { + after$kinship <- .dense_materialise(.kinship_release(after$kinship, expired)) + } + if (markers) { + ids <- after$markers$id + after$markers <- .marker_release(after$markers, ids[!ids %in% expired]) + } + } + } state <- after if (keep_events && !is.null(result$events)) { events[[index]] <- result$events @@ -495,11 +557,22 @@ validate_processes <- function(processes, state = NULL) { census[[index]] <- result$census } } + dead <- c(dead_males, dead_females) + marker_ids <- state$population$id + if (remember) { + records <- .sire_records(refs, state$sires$records, losses) + state$sires["records"] <- list(records) + if (length(records$id)) { + dead <- dead[!dead %in% records$id] + if (markers) marker_ids <- sort.int(c(marker_ids, records$id)) + } + } if (pedigree) { - state$kinship <- .kinship_release(state$kinship, c(dead_males, dead_females)) + state$kinship <- .kinship_release(state$kinship, dead) + if (remember && !is.null(state$kinship$values)) state$kinship <- .dense_materialise(state$kinship) } if (markers) { - state$markers <- .marker_release(state$markers, state$population$id) + state$markers <- .marker_release(state$markers, marker_ids) } if (execution$closed_proxy && any(accounting[, 5L] > 0L)) { msg <- "introductions with an inbreeding proxy require an explicit migration function" @@ -631,9 +704,12 @@ execute_processes <- function( dt = 1, validation = c("strict", "fast")) { validation <- match.arg(validation) - state <- .validate_state(state, at_entry = TRUE) + state <- .invalidate_survey_records(.validate_state(state, at_entry = TRUE)) execution <- .prepare_execution(validate_processes(processes)) .validate_field_plan(execution$processes, state) + if (execution$has_survey && is.null(state$survey_seed)) { + state$survey_seed <- .standalone_survey_seed() + } time <- .as_count(time, "time") state <- .open_kinship(state) result <- .run_processes( diff --git a/R/processes_demography.R b/R/processes_demography.R index 959281f..514c2ab 100644 --- a/R/processes_demography.R +++ b/R/processes_demography.R @@ -143,18 +143,53 @@ litter_categorical <- function(sizes, probabilities) { any(sizes != floor(sizes)) || anyDuplicated(sizes)) { .stop("sizes must be unique non-negative whole numbers") } - if (!is.numeric(probabilities) || length(probabilities) != length(sizes) || - anyNA(probabilities) || any(probabilities < 0) || - abs(sum(probabilities) - 1) > 1e-12) { - .stop("probabilities must be non-negative, match sizes and sum to 1") - } sizes <- as.integer(sizes) + check <- function(p, n = NULL) { + shared <- is.null(n) || is.null(dim(p)) + valid_shape <- if (shared) { + length(p) == length(sizes) + } else { + is.matrix(p) && nrow(p) == n && ncol(p) == length(sizes) + } + if (!valid_shape || !is.numeric(p) || any(!is.finite(p)) || any(p < 0)) { + .stop("probabilities must be finite, non-negative and match sizes and population rows") + } + totals <- if (shared) sum(p) else rowSums(p) + if (any(abs(totals - 1) > 1e-12)) .stop("litter probabilities must sum to 1") + totals + } + if (!is.function(probabilities)) { + check(probabilities) + return(function(mothers, pop, state, context, params) { + sizes[sample.int(length(sizes), length(mothers), replace = TRUE, prob = probabilities)] + }) + } function(mothers, pop, state, context, params) { - sizes[sample.int(length(sizes), length(mothers), replace = TRUE, prob = probabilities)] + p <- probabilities(pop, state, context, params) + totals <- check(p, length(pop$id)) + if (!is.matrix(p)) { + return(sizes[sample.int(length(sizes), length(mothers), replace = TRUE, prob = p)]) + } + draw <- stats::runif(length(mothers)) * totals[mothers] + cumulative <- numeric(length(mothers)) + category <- rep.int(1L, length(mothers)) + for (j in seq_len(length(sizes) - 1L)) { + cumulative <- cumulative + p[mothers, j] + category <- category + (draw >= cumulative) + } + sizes[category] } } offspring_sex_bernoulli <- function(female_probability = 0.5) { + if (is.function(female_probability)) { + return(function(mothers, pop, state, context, params) { + p <- female_probability(pop, state, context, params) + if (!is.null(dim(p))) .stop("female_probability must return a scalar or vector") + p <- .per_individual(p, length(pop$id), "female_probability", 0, 1) + ifelse(stats::runif(length(mothers)) < p[mothers], "F", "M") + }) + } if (!is.numeric(female_probability) || length(female_probability) != 1L || is.na(female_probability) || female_probability < 0 || female_probability > 1) { .stop("female_probability must be one number in [0, 1]") @@ -194,8 +229,9 @@ mate_from_field <- function(field = "mate_id", stale = c("error", "unpaired")) { rows <- match(ids, pop$id) if (stale == "error") { absent <- pop$sex == "F" & is.na(rows) & !is.na(ids) - if (any(absent) && !all(ids[absent] %in% context$departed_males)) { - .stop("recorded sire must be a living male or one lost earlier in this interval") + retained <- if (identical(field, state$sires$field)) state$sires$records$id + if (any(absent) && !all(ids[absent] %in% c(context$departed_males, retained))) { + .stop("recorded sire must be a living male, a male lost this interval or a retained sire") } } rows @@ -268,9 +304,13 @@ reproduction_process <- function( .stop("mate returned a row that is not male for a female") } father_id <- pop$id[as.integer(father)] - if (!is.null(params$mate_field) && length(context$departed_males)) { + departed_ids <- context$departed_males + if (!is.null(state$sires) && identical(params$mate_field, state$sires$field)) { + departed_ids <- c(departed_ids, state$sires$records$id) + } + if (!is.null(params$mate_field) && length(departed_ids)) { recorded <- pop[[params$mate_field]] - departed <- female & recorded %in% context$departed_males + departed <- female & recorded %in% departed_ids father_id[departed] <- recorded[departed] } candidates <- which(female & probability > 0) @@ -295,7 +335,15 @@ reproduction_process <- function( extra <- if (is.null(params$newborn_fields)) { list() } else { - params$newborn_fields(mothers, fathers, pop, state, context, user) + parents <- pop + missing <- which(is.na(fathers) & !is.na(father_id[mothers])) + if (length(missing)) { + ids <- father_id[mothers[missing]] + sires <- .sire_records(ids, state$sires$records, context$sire_losses) + parents <- Map(c, pop, sires) + fathers[missing] <- n + match(ids, sires$id) + } + params$newborn_fields(mothers, fathers, parents, state, context, user) } if (!setequal(names(extra), params$newborn_field_names)) { .stop("newborn_fields must return exactly the declared newborn_field_names") diff --git a/R/processes_environment.R b/R/processes_environment.R index fa1dd22..5054006 100644 --- a/R/processes_environment.R +++ b/R/processes_environment.R @@ -291,11 +291,39 @@ beta_shapes <- function(mean, sd) { any(mean <= 0 | mean >= 1) || any(sd <= 0)) { .stop("mean must lie in (0, 1) and sd must be positive") } - scale <- mean * (1 - mean) / sd^2 - 1 - if (any(scale <= 0)) { + max_variance <- mean * (1 - mean) + variance <- sd^2 + if (any(max_variance - variance <= 8 * .Machine$double.eps * max_variance)) { .stop("sd is too large for a beta distribution with this mean") } - list(shape1 = mean * scale, shape2 = (1 - mean) * scale) + scale <- max_variance / variance - 1 + shape1 <- mean * scale + shape2 <- (1 - mean) * scale + if (any(!is.finite(shape1) | !is.finite(shape2) | shape1 <= 0 | shape2 <= 0)) { + .stop("beta shapes exceed the finite numeric range") + } + list(shape1 = shape1, shape2 = shape2) +} + +qbeta_norm <- function(z, mean, sd) { + if (!is.numeric(z) || anyNA(z)) .stop("z must contain non-missing normal deviates") + sizes <- c(length(z), length(mean), length(sd)) + if (!length(mean) || !length(sd) || any(!sizes[sizes > 0L] %in% c(1L, max(sizes)))) { + .stop("z, mean and sd must have compatible lengths (scalar or common length)") + } + shapes <- beta_shapes(mean, sd) + if (!length(z)) return(numeric()) + n <- max(sizes) + result <- if (length(z) == n) z else shapes$shape1 + z <- rep_len(z, n) + a <- rep_len(shapes$shape1, n) + b <- rep_len(shapes$shape2, n) + upper <- z > 0 + result[upper] <- stats::qbeta(stats::pnorm(z[upper], lower.tail = FALSE, log.p = TRUE), + a[upper], b[upper], lower.tail = FALSE, log.p = TRUE) + result[!upper] <- stats::qbeta(stats::pnorm(z[!upper], log.p = TRUE), + a[!upper], b[!upper], log.p = TRUE) + result } shift_logit <- function(probability, deviation) { diff --git a/R/processes_management.R b/R/processes_management.R index e1a4507..8e1d88c 100644 --- a/R/processes_management.R +++ b/R/processes_management.R @@ -9,100 +9,126 @@ function(state, context, params) value } -.pick_rows <- function(rows, n, order) { - if (n >= length(rows)) { - return(rows) +.when_function <- function(when) { + if (is.function(when)) { + return(function(state, context, params) { + visit <- when(state, context, params) + if (!.is_flag(visit)) .stop("when must return one non-missing logical value") + visit + }) } - if (n <= 0) { - return(integer()) + if (.is_flag(when)) return(function(state, context, params) when) + if (!is.numeric(when) || !is.null(dim(when)) || any(!is.finite(when)) || + any(when < 0 | when != floor(when) | when > .Machine$integer.max)) { + .stop("when must be a logical flag, non-negative interval indices or a function") } + function(state, context, params) context$time %in% when +} + +.individual_weights <- function(callback, pop, state, context, params) { + if (is.null(callback)) return(NULL) + w <- callback(pop, state, context, params) + n <- length(pop$id) + if (!is.numeric(w) || !is.null(dim(w)) || !(length(w) %in% c(1L, n)) || + any(!is.finite(w)) || any(w < 0)) { + .stop("weights must return finite non-negative values, scalar or one per individual") + } + rep_len(w, n) +} + +.weighted_order <- function(weights) { + # Independent exponential waiting times give successive draws proportional + # to remaining weights. Log times accommodate the full finite weight range. + order(log(stats::rexp(length(weights))) - log(weights)) +} + +.pick_rows <- function(rows, n, order, weights = NULL) { + if (!is.null(weights)) { + rows <- rows[weights[rows] > 0] + if (n <= 0 || !length(rows)) return(integer()) + if (length(rows) > 1L) rows <- rows[.weighted_order(weights[rows])] + return(rows[seq_len(min(n, length(rows)))]) + } + if (n >= length(rows)) return(rows) + if (n <= 0) return(integer()) if (order == "id") rows[seq_len(n)] else rows[sample.int(length(rows), n)] } -.loss_process <- function( - name, - loss, - cause, - count, - probability, - select, - eligible, - order, - requires, - params, - description) { - supplied <- c(!is.null(count), !is.null(probability), !is.null(select)) - if (sum(supplied) != 1L) { +.selection_parameters <- function(count, probability, select, eligible, order, weights, params) { + if (sum(c(!is.null(count), !is.null(probability), !is.null(select))) != 1L) { .stop("supply exactly one of count, probability or select") } - if (!is.null(count)) { - count <- .count_function(count, "count") - } - if (!is.null(probability)) { - probability <- .rate_function(probability, "probability") + if (!is.null(weights) && (is.null(count) || order != "random")) { + .stop("weights require count selection with random order") } .check_optional_function(select, "select") .check_optional_function(eligible, "eligible") - if (!.is_name(cause)) { - .stop("cause must be one non-empty character value") + .check_optional_function(weights, "weights") + list(count = if (!is.null(count)) .count_function(count, "count"), + probability = if (!is.null(probability)) .rate_function(probability, "probability"), + select = select, eligible = eligible, order = order, weights = weights, user = params) +} + +.select_individuals <- function(state, context, params) { + pop <- state$population + user <- params$user + rows <- .eligible_rows(params$eligible, pop, state, context, user) + requested <- NULL + if (!is.null(params$capacity) || !is.null(params$count)) { + if (!is.null(params$capacity)) { + limit <- params$capacity(state, context, user) + if (!is.numeric(limit) || length(limit) != 1L || is.na(limit) || limit < 0) { + .stop("capacity must evaluate to one non-negative number") + } + eligible_n <- length(rows) + # Legacy ceilings evaluated a supplied eligibility callback twice. + if (is.null(params$weights) && !is.null(params$eligible)) { + eligible_n <- length(.eligible_rows(params$eligible, pop, state, context, user)) + } + requested <- max(0, eligible_n - floor(limit)) + } else { + requested <- params$count(state, context, user) + if (!.is_count(requested)) .stop("count must evaluate to one non-negative whole number") + } + w <- .individual_weights(params$weights, pop, state, context, user) + taken <- .pick_rows(rows, requested, params$order, w) + } else if (!is.null(params$probability)) { + chance <- .per_individual(params$probability(pop, state, context, user), + length(pop$id), "selection probability", 0, 1) + taken <- rows[stats::runif(length(rows)) < chance[rows]] + } else { + taken <- params$select(pop, state, context, user) + if (is.logical(taken)) { + if (length(taken) != length(pop$id) || anyNA(taken)) { + .stop("logical select must return one non-missing value per living individual") + } + taken <- which(taken) + } + if ((!is.null(taken) && (!is.numeric(taken) || !is.null(dim(taken)))) || + anyNA(taken) || anyDuplicated(taken) || !all(taken %in% rows)) { + .stop("select must return distinct eligible rows") + } } + list(rows = taken, requested = requested) +} + +.selection_events <- function(type, n, requested, label) { + if (is.null(requested)) return(pva_events(type, n, label)) + pva_events(c(type, paste0(type, "_shortfall")), c(n, requested - n), label) +} + +.loss_process <- function(name, loss, cause, selection, requires, description) { + if (!.is_name(cause)) .stop("cause must be one non-empty character value") pva_process( name = name, run = function(state, context, params) { - pop <- state$population - user <- params$user - rows <- .eligible_rows(params$eligible, pop, state, context, user) - shortfall <- 0 - if (!is.null(params$count)) { - requested <- params$count(state, context, user) - if (!.is_count(requested)) { - .stop("count must evaluate to one non-negative whole number") - } - taken <- .pick_rows(rows, requested, params$order) - shortfall <- requested - length(taken) - } else if (!is.null(params$probability)) { - chance <- .per_individual( - params$probability(pop, state, context, user), - length(pop$id), paste(params$loss, "probability"), 0, 1 - ) - taken <- rows[stats::runif(length(rows)) < chance[rows]] - } else { - taken <- params$select(pop, state, context, user) - if (is.logical(taken)) { - if (length(taken) != length(pop$id) || anyNA(taken)) { - .stop("logical select must return one non-missing value per living individual") - } - taken <- which(taken) - } - if (anyNA(taken) || anyDuplicated(taken) || !all(taken %in% rows)) { - .stop("select must return distinct eligible rows") - } - } - if (length(taken)) { - state$population$alive[taken] <- FALSE - } - events <- if (is.null(params$count)) { - pva_events(params$loss, length(taken), params$cause) - } else { - pva_events( - c(params$loss, paste0(params$loss, "_shortfall")), - c(length(taken), shortfall), - params$cause - ) - } + pick <- .select_individuals(state, context, params) + if (length(pick$rows)) state$population$alive[pick$rows] <- FALSE + events <- .selection_events(params$loss, length(pick$rows), pick$requested, params$cause) pva_result(state, events) }, - params = list( - loss = loss, - cause = cause, - count = count, - probability = probability, - select = select, - eligible = eligible, - order = order, - user = params - ), - requires = unique(c("population.alive", requires)), + params = c(list(loss = loss, cause = cause), selection), + requires = unique(c("population.alive", attr(selection$count, "requires", exact = TRUE), requires)), writes = "population.alive", description = description ) @@ -117,20 +143,12 @@ removal_process <- function( cause = "removal", name = "removal", requires = character(), - params = list()) { - .loss_process( - name = name, - loss = "removal", - cause = cause, - count = count, - probability = probability, - select = select, - eligible = eligible, - order = match.arg(order), - requires = requires, - params = params, - description = "Harvest, cull or capture living individuals as accounted removals." - ) + params = list(), + weights = NULL) { + selection <- .selection_parameters(count, probability, select, eligible, match.arg(order), + weights, params) + .loss_process(name, "removal", cause, selection, requires, + "Harvest, cull or capture living individuals as accounted removals.") } ceiling_process <- function( @@ -139,37 +157,78 @@ ceiling_process <- function( cause = "ceiling", name = "ceiling", requires = character(), - params = list()) { - capacity <- .count_function(capacity, "capacity") + params = list(), + weights = NULL) { .check_optional_function(eligible, "eligible") - excess <- function(state, context, params) { - limit <- params$capacity(state, context, params$user) - if (!is.numeric(limit) || length(limit) != 1L || is.na(limit) || limit < 0) { - .stop("capacity must evaluate to one non-negative number") - } - rows <- .eligible_rows( - params$eligible, state$population, state, context, params$user - ) - max(0, length(rows) - floor(limit)) + .check_optional_function(weights, "weights") + selection <- list(capacity = .count_function(capacity, "capacity"), eligible = eligible, + order = "random", weights = weights, user = params) + .loss_process(name, "death", cause, selection, requires, + "Apply accounted deaths above the eligible population ceiling.") +} + +.field_values <- function(value, column, n, field) { + if (!is.atomic(value) || is.null(value) || is.object(value) || !is.null(dim(value)) || + !(length(value) %in% c(1L, n))) { + .stop("value must supply one plain value or one per selected row for population.", field) } - .loss_process( - name = name, - loss = "death", - cause = cause, - count = excess, + untyped <- is.logical(value) && all(is.na(value)) + if (is.integer(column) && (is.numeric(value) || untyped)) { + value <- .whole_field(value, paste0("values for integer field population.", field)) + } else if (is.double(column) && (is.numeric(value) || untyped)) { + value <- as.double(value) + } else if (untyped && !is.raw(column)) { + storage.mode(value) <- typeof(column) + } + if (!identical(typeof(value), typeof(column))) { + .stop("value must match the field type for population.", field) + } + value +} + +assign_process <- function( + field, + value, + count = NULL, probability = NULL, select = NULL, - eligible = if (is.null(eligible)) { - NULL - } else { - function(pop, state, context, params) { - params$eligible(pop, state, context, params$user) + eligible = NULL, + order = c("random", "id"), + name = "assign", + requires = character(), + params = list(), + weights = NULL, + event = "assigned") { + if (!.is_name(field) || field %in% .reserved_fields) { + .stop("field must be an existing user-defined population field") + } + if (!.is_name(event) || event %in% .accounting_events) { + .stop("event must be a non-empty name other than an accounting event") + } + if (!is.function(value) && (!is.atomic(value) || length(value) != 1L || + !is.null(dim(value)) || is.object(value))) { + .stop("value must be a typed scalar or a function of (rows, pop, state, context, params)") + } + selection <- .selection_parameters(count, probability, select, eligible, match.arg(order), + weights, params) + path <- paste0("population.", field) + pva_process( + name = name, + run = function(state, context, params) { + pick <- .select_individuals(state, context, params) + rows <- pick$rows + if (length(rows)) { + pop <- state$population + v <- params$value + if (is.function(v)) v <- v(rows, pop, state, context, params$user) + state$population[[params$field]][rows] <- + .field_values(v, pop[[params$field]], length(rows), params$field) } + pva_result(state, .selection_events(params$event, length(rows), pick$requested, params$field)) }, - order = "random", - requires = requires, - params = list(capacity = capacity, eligible = eligible, user = params), - description = "Hard ceiling: random deaths bring eligible abundance down to capacity." + params = c(list(field = field, value = value, event = event), selection), + requires = unique(c(path, attr(count, "requires", exact = TRUE), requires)), writes = path, + description = "Assign a treatment or state value to selected living individuals." ) } @@ -207,7 +266,7 @@ introduction_process <- function( pva_result(state, pva_events("introduction", n, params$source)) }, params = list(count = count, fields = fields, source = source, user = params), - requires = requires, + requires = unique(c(attr(count, "requires", exact = TRUE), requires)), creates = unique(c("sex", "age", creates)), description = "Scheduled supplementation, release or immigration with engine-allocated ids." ) @@ -239,7 +298,7 @@ pairing_process <- function( } pva_process( name = name, - run = function(state, context, params) { + run = structure(function(state, context, params) { pop <- state$population rows <- .eligible_rows(params$eligible, pop, state, context, params$user) females <- rows[pop$sex[rows] == "F"] @@ -294,7 +353,7 @@ pairing_process <- function( c(n_pairs, length(rows) - 2L * n_pairs) ) ) - }, + }, resets_mate_field = TRUE), params = list( eligible = eligible, capacity = capacity, diff --git a/R/scenario.R b/R/scenario.R index 6e18b2f..e11d052 100644 --- a/R/scenario.R +++ b/R/scenario.R @@ -80,8 +80,8 @@ run_scenario <- function( root_seed <- sample.int(.Machine$integer.max, 1L) } .with_rng_restored({ - RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection") - set.seed(root_seed) + .set_pva_seed(root_seed) + rng_kind <- RNGkind() streams <- .make_replicate_streams(scenario$n_runs) payload <- list( scenario = scenario, @@ -116,8 +116,10 @@ run_scenario <- function( ledgers = if ("ledger" %in% keep) lapply(runs, `[[`, "ledger") else NULL, provenance = list( root_seed = as.integer(root_seed), - rng_kind = c("L'Ecuyer-CMRG", "Inversion", "Rejection"), + rng_kind = rng_kind, streams = streams, + substreams = c(demography = 0L, ensemble_builder = 1L, initial_markers = 2L, + builder_markers = 3L, segregation = 4L, survey = 5L), validation = validation, process_plan = payload$execution$plan, package_version = as.character(utils::packageVersion("OpenPVA")), @@ -253,7 +255,6 @@ print.pva_run <- function(x, ...) { .replicate_worker <- function(run_id, payload) { .with_rng_restored({ - RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection") assign(".Random.seed", payload$streams[[run_id]], envir = .GlobalEnv) .run_replicate( scenario = payload$scenario, @@ -281,9 +282,11 @@ print.pva_run <- function(x, ...) { } else { pva_state(initial) } + state <- .invalidate_survey_records(state) if (!is.null(state$markers)) { - state$markers$seed <- .marker_stream(stream, 4L) + state$markers$seed <- .rng_substream(stream, 4L) } + if (execution$has_survey) state$survey_seed <- .rng_substream(stream, 5L) .validate_field_plan(execution$processes, state) state <- .open_kinship(state) keep_events <- "events" %in% keep @@ -379,19 +382,47 @@ print.pva_run <- function(x, ...) { streams } +.pva_rng_header <- function(header) { + # CMRG, Inversion and Rejection. Preserve additional kind digits on R-devel. + as.integer(header %/% 100000L * 100000L + 10407L) +} + +.set_pva_seed <- function(seed, header = .pva_rng_header(.GlobalEnv$.Random.seed[1L])) { + # R's CMRG initialisation in RNG.c. Public set.seed()/RNGkind() discard a + # caller's cached Box-Muller deviate, which is absent from .Random.seed. + # Each LCG product is an exact integer smaller than 2^49. + word <- as.double(seed) + for (i in seq_len(50L)) word <- (69069 * word + 1) %% 2^32 + words <- numeric(6L) + for (i in seq_along(words)) { + repeat { + word <- (69069 * word + 1) %% 2^32 + if (word < 4294944443) break + } + words[i] <- if (word >= 2^31) word - 2^32 else word + } + words[words == -2^31] <- NA_real_ + assign(".Random.seed", c(header, as.integer(words)), envir = .GlobalEnv) +} + +.rng_substream <- function(seed, ahead) { + for (step in seq_len(ahead)) seed <- parallel::nextRNGSubStream(seed) + seed +} + .with_rng_restored <- function(expr) { - old_kind <- RNGkind() - had_seed <- exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE) - if (had_seed) { - old_seed <- get(".Random.seed", envir = .GlobalEnv, inherits = FALSE) - } - on.exit({ - do.call(RNGkind, as.list(old_kind)) - if (had_seed) { - assign(".Random.seed", old_seed, envir = .GlobalEnv) - } else if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) { + 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) - } - }, add = TRUE) + }) + } else { + on.exit(assign(".Random.seed", old, envir = .GlobalEnv)) + } expr } diff --git a/R/spatial.R b/R/spatial.R index 62cee09..8543797 100644 --- a/R/spatial.R +++ b/R/spatial.R @@ -21,11 +21,16 @@ dispersal_process <- function( field = "patch_id", name = "dispersal", requires = character(), - params = list()) { + params = list(), + count = NULL, + weights = NULL) { if (!is.function(destination)) { .stop("destination must be a function of (rows, pop, state, context, params)") } .check_optional_function(eligible, "eligible") + .check_optional_function(weights, "weights") + if (!is.null(weights) && is.null(count)) .stop("weights require count-targeted dispersal") + if (!is.null(count)) count <- .count_function(count, "count") if (!length(patches) || anyNA(patches) || anyDuplicated(patches)) { .stop("patches must be unique non-missing patch identifiers") } @@ -36,8 +41,15 @@ dispersal_process <- function( name = name, run = function(state, context, params) { pop <- state$population - rows <- .eligible_rows(params$eligible, pop, state, context, params$user) - events <- pva_events("dispersal", 0L) + requested <- NULL + if (is.null(params$count)) { + rows <- .eligible_rows(params$eligible, pop, state, context, params$user) + } else { + pick <- .select_individuals(state, context, params) + rows <- pick$rows + requested <- pick$requested + } + events <- .selection_events("dispersal", 0L, requested, NA_character_) if (length(rows)) { origin <- pop[[params$field]][rows] from <- match(origin, params$patches) @@ -50,11 +62,13 @@ dispersal_process <- function( route <- paste(from, match(target, params$patches)) first <- !duplicated(route) counts <- tabulate(match(route, route[first])) + totals <- .selection_events("dispersal", sum(target != origin), requested, NA_character_) + no_patch <- rep(NA_character_, length(totals$value)) events <- pva_events( - c("dispersal", rep("patch_transition", length(counts))), - c(sum(target != origin), counts), - origin_patch_id = c(NA_character_, as.character(origin[first])), - destination_patch_id = c(NA_character_, as.character(target[first])) + c(totals$event_type, rep("patch_transition", length(counts))), + c(totals$value, counts), + origin_patch_id = c(no_patch, as.character(origin[first])), + destination_patch_id = c(no_patch, as.character(target[first])) ) state$population[[params$field]][rows] <- target } @@ -65,9 +79,12 @@ dispersal_process <- function( patches = patches, eligible = eligible, field = field, + count = count, + order = "random", + weights = weights, user = params ), - requires = unique(c(paste0("population.", field), requires)), + requires = unique(c(paste0("population.", field), attr(count, "requires", exact = TRUE), requires)), writes = paste0("population.", field), description = "Move eligible individuals among discrete patches." ) diff --git a/R/state.R b/R/state.R index 1a89fda..df8f638 100644 --- a/R/state.R +++ b/R/state.R @@ -80,6 +80,12 @@ pva_population <- function( .stop("additional population fields must be named") } recycle <- function(value, label) { + if (!is.null(names(value))) { + value <- unname(value) + } + if (!is.atomic(value) || is.null(value) || !is.null(attributes(value))) { + .stop("population field ", label, " must be a plain atomic vector without attributes") + } if (length(value) == 1L) { return(rep(value, n)) } @@ -142,8 +148,8 @@ pva_population <- function( n <- length(population$id) for (field in fields) { column <- population[[field]] - if (!is.atomic(column) || is.null(column) || !is.null(dim(column))) { - .stop("population field ", field, " must be an atomic vector") + if (!is.atomic(column) || is.null(column) || !is.null(attributes(column))) { + .stop("population field ", field, " must be a plain atomic vector without attributes") } if (length(column) != n) { .stop("population field ", field, " has length ", length(column), ", expected ", n) @@ -199,7 +205,8 @@ pva_state <- function( pedigree = FALSE, kinship = NULL, max_dense_kinship = 2000L, - n_loci = 0L) { + n_loci = 0L, + mate_field = NULL) { if (inherits(population, "pva_state")) { .stop("population is already a pva_state") } @@ -218,6 +225,12 @@ pva_state <- function( if (!all(population$alive)) { .stop("the initial population can contain living individuals only") } + if (!is.null(mate_field)) { + refs <- .sire_references(population, mate_field) + if (!all(refs %in% population$id[population$sex == "M"])) { + .stop("initial female mate_field values must identify living initial males") + } + } if (pedigree || n_loci > 0L) { sex <- population$sex if (any(sex[match(population$mother_id, population$id, 0L)] != "F") || @@ -262,6 +275,9 @@ pva_state <- function( state$population$pedigree_F <- ancestry$F[match(population$id, ancestry$id)] } } + if (!is.null(mate_field)) { + state$sires <- list(field = mate_field, records = NULL) + } class(state) <- "pva_state" state } @@ -289,24 +305,40 @@ pva_state <- function( } .validate_state <- function(state, at_entry = FALSE) { - if (!inherits(state, "pva_state") || - !identical(names(state), .state_fields)) { + fields <- names(state) + optional <- fields[!fields %in% .state_fields] + if (!inherits(state, "pva_state") || anyDuplicated(fields) || + !identical(fields, c(.state_fields, optional)) || + any(!optional %in% c("sires", "survey_seed"))) { .stop("state must be created by pva_state()") } pedigree <- !is.null(state$kinship) .validate_population(state$population, pedigree = pedigree) n <- length(state$population$id) if (!is.integer(state$next_id) || length(state$next_id) != 1L || - is.na(state$next_id) || (n && state$next_id <= max(state$population$id))) { + is.na(state$next_id) || state$next_id < 1L || (n && state$next_id <= max(state$population$id))) { .stop("state next_id must exceed every allocated id") } if (is.matrix(state$kinship)) { .validate_kinship(state$kinship, n) } else if (pedigree && !is.list(state$kinship)) { .stop("invalid pedigree store") + } else if (at_entry && !is.null(state$kinship$values)) { + store <- .dense_materialise(state$kinship) + slots <- store$ids[!is.na(store$ids)] + expected <- c(state$population$id, state$sires$records$id) + if (!is.integer(store$ids) || anyDuplicated(slots) || !setequal(slots, expected)) { + .stop("occupied dense kinship slots must equal living and retained sire IDs") + } + .validate_kinship(store$values, length(store$ids)) + } + if ("sires" %in% optional) .validate_sires(state) + if ("survey_seed" %in% optional && !.valid_marker_seed(state$survey_seed)) { + .stop("invalid survey substream") } if (!is.null(state$markers)) { - .validate_markers(state$markers, state$population, state$next_id, at_entry) + .validate_markers(state$markers, state$population, state$next_id, at_entry, + state$sires$records$id) } state } @@ -352,6 +384,12 @@ add_individuals <- function( .stop("the id allocator would overflow") } recycle <- function(value, label) { + if (!is.null(names(value))) { + value <- unname(value) + } + if (!is.atomic(value) || is.null(value) || !is.null(attributes(value))) { + .stop("new field ", label, " must be a plain atomic vector without attributes") + } if (length(value) == 1L) { return(rep(value, n)) } diff --git a/R/survey.R b/R/survey.R new file mode 100644 index 0000000..d2230f5 --- /dev/null +++ b/R/survey.R @@ -0,0 +1,98 @@ +.standalone_survey_seed <- function() { + .with_rng_restored({ + seed <- .GlobalEnv$.Random.seed + if (seed[1L] %% 100L != 7L) { + seed <- c(seed[1L], as.integer(stats::runif(6L, 1, .Machine$integer.max))) + } + seed[1L] <- .pva_rng_header(seed[1L]) + .rng_substream(seed, 5L) + }) +} + +.invalidate_survey_records <- function(state) { + # A new execution can reuse the run and interval indices of an input state. + for (field in names(state$globals)) { + if (inherits(state$globals[[field]], "pva_survey_observation")) { + state$globals[[field]]$run <- NA_integer_ + } + } + state +} + +.run_survey <- function(state, context, params) { + observation <- .with_rng_restored({ + seed <- state$survey_seed + header <- seed[1L] + seed[1L] <- .pva_rng_header(.GlobalEnv$.Random.seed[1L]) + assign(".Random.seed", seed, envir = .GlobalEnv) + visited <- params$when(state, context, params$user) + count <- NA_integer_ + ids <- integer() + if (visited) { + pop <- state$population + rows <- .eligible_rows(params$eligible, pop, state, context, params$user) + chance <- .per_individual(params$detection(pop, state, context, params$user), + length(pop$id), "detection probability", 0, 1) + ids <- pop$id[rows[stats::runif(length(rows)) < chance[rows]]] + count <- length(ids) + } + state$survey_seed <- .GlobalEnv$.Random.seed + state$survey_seed[1L] <- header + structure(list(run = context$run, time = context$time, dt = context$dt, + phase = context$phase, visited = visited, count = count, ids = ids), + class = "pva_survey_observation") + }) + state$globals[[params$field]] <- observation + events <- if (observation$visited) { + pva_events(c("survey_visit", "survey_detection"), c(1L, observation$count), params$field) + } else { + pva_events("survey_skip", 1L, params$field) + } + pva_result(state, events) +} + +survey_process <- function(detection, eligible = NULL, when = TRUE, field = "survey", + name = "survey", requires = character(), params = list()) { + if (!.is_name(field)) .stop("field must be one non-empty global name") + if (!is.function(detection)) .per_individual(detection, 1L, "detection probability", 0, 1) + detection <- .rate_function(detection, "detection") + .check_optional_function(eligible, "eligible") + pva_process( + name, .run_survey, + params = list(detection = detection, eligible = eligible, when = .when_function(when), + field = field, user = params), + requires = requires, writes = paste0("globals.", field), + description = "Count independent individual detections on scheduled visits." + ) +} + +survey_quota <- function(rule, field = "survey", on_skip = "error") { + if (!.is_name(field)) .stop("field must be one non-empty global name") + if (!is.function(rule)) .stop("rule must be a function of (obs, state, context, params)") + if (!.is_count(on_skip) && !identical(on_skip, "error") && !is.function(on_skip)) { + .stop("on_skip must be a non-negative whole count, a function, or 'error'") + } + quota <- function(state, context, params) { + obs <- state$globals[[field]] + if (!inherits(obs, "pva_survey_observation") || !.is_flag(obs$visited) || + !(if (obs$visited) .is_count(obs$count) else identical(obs$count, NA_integer_))) { + .stop("missing or invalid survey record in globals.", field) + } + if (!identical(obs$run, context$run) || !identical(obs$time, context$time) || + !isTRUE(obs$dt == context$dt) || !identical(obs$phase, context$phase)) { + .stop("stale survey record in globals.", field) + } + if (obs$visited) { + value <- rule(obs, state, context, params) + } else if (is.function(on_skip)) { + value <- on_skip(obs, state, context, params) + } else if (identical(on_skip, "error")) { + .stop("survey skipped in globals.", field) + } else { + value <- on_skip + } + .as_count(value, "survey quota") + } + attr(quota, "requires") <- paste0("globals.", field) + quota +} diff --git a/README.md b/README.md index 955d6eb..d8bf483 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # OpenPVA -OpenPVA 2.1.1 is a modular, individual-based engine for population viability +OpenPVA 2.2.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 @@ -18,7 +18,7 @@ recommended R packages and supports R 4.1.0 and later. declared writes, field types, engine-owned fields, and accounting reconciled separately for existing and newly created individuals, by cohort. - Exact pedigree inbreeding from recorded parentage, including a known sire - lost after mating. Above the dense slot limit the engine traces ancestors of + lost after mating. A declared mate field can retain a sire across seasons. Above the dense slot limit the engine traces ancestors of the breeders, retaining any specified starting kinships. - One preassigned L'Ecuyer-CMRG stream per replicate: results are bit-identical on one core, on fork workers and on a PSOCK cluster. @@ -28,7 +28,9 @@ recommended R packages and supports R 4.1.0 and later. `removal_process()`, `ceiling_process()`, `introduction_process()`, `environment_process()`, `catastrophe_process()`, `inbreeding_proxy_process()`, dispersal among patches, and `census_process()`. -- Helpers: age-by-sex rate tables, Beverton–Holt, Ricker and ceiling density +- Imperfect surveys on a separate random stream, with observation-based quotas + for removals, releases and treatment. +- Helpers: analytical life tables, 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 diff --git a/docs/design/lifecycle_process_contract.md b/docs/design/lifecycle_process_contract.md index b7f0d21..feee1b6 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.1.0. It describes what a +This is the active engine contract for OpenPVA 2.2.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,8 +24,10 @@ 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). +- `markers` holds genotypes when `n_loci > 0`, including any retained sires. +- With a declared `mate_field`, `sires` holds the field name and exit records + of referenced departed males. A state running a survey also carries its + private `survey_seed`. Strict validation protects both additions. Core population fields are `id`, `sex`, `age`, `alive`, `mother_id`, `father_id`, `origin` and `entry_time`. Any other field is the modeller's, with @@ -105,9 +107,12 @@ through the ordered list against the initial state: caught even though net abundance is unchanged. A process reports one loss type and one entry type per execution. -Fast validation skips the structural comparison. Parentage and individual -accounting counts are checked in both modes, which give identical biological -results for valid inputs. +Both modes validate the process plan, check parent IDs when genetics is active, +require non-negative whole accounting event values and construct cohort counts +from the actual changes to the population. Strict mode calls +`.validate_transition()` to reconcile event totals with entries and losses +and check declared writes, column types and engine-owned fields. Fast mode +skips that function. Valid processes produce identical biological results. ## Accounting ledger @@ -130,13 +135,20 @@ Initial parent IDs may refer to later rows. The engine evaluates them in pedigree order. Supply an aligned matrix when starting animals have known kinship outside the recorded ancestry. Each missing parent represents an independent, unrelated contribution. Either known parent may die after -pairing and before birth in the same interval. +pairing and before birth in the same interval. With +`pva_state(mate_field = "mate_id")`, a female may retain a sire across +intervals. A departed sire's records expire when his last living female +reference disappears. A subsequent birth cannot use his historical ancestor +row. For `newborn_fields(mothers, fathers, pop, state, context, params)`, +index `pop` with the supplied row indices. When required, the engine appends +sire attributes at exit to this callback's living rows. An unknown sire has +an `NA` row. `state$population` always holds the living population. Small populations use reusable dense slots with deferred offspring rows. Callbacks receive R values with copy-on-modify semantics, so they cannot silently change another process's kinship. Above the dense limit the engine tracks parent indices and inbreeding in a compact ledger. It traces the -ancestors of each distinct breeding pair, preserving the covariance of any +ancestors of batches of distinct breeding pairs, preserving the covariance of any related starting animals. The ledger grows with recorded ancestry. Starting animals with nonzero mutual kinship retain a dense covariance block. Request selected living pairs with `kinship_matrix(state, ids)`. Population-wide mean kinship uses a weighted @@ -150,19 +162,25 @@ 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 +earlier in the interval still transmits. At the boundary it keeps genotypes +for the living and any referenced departed sire. Genetic summaries describe +the living population. 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. +Each replicate has the following L'Ecuyer-CMRG substreams, numbered from zero. + +| Offset | Draws | +|---|---| +| 0 | Demographic processes | +| 1 | Ensemble member builder | +| 2 | Initial marker gene drop inside a replicate's initializer | +| 3 | Initial marker gene drop within a member builder (two jumps from substream 1) | +| 4 | Subsequent segregation in the replicate | +| 5 | Visit schedules, detection and other callbacks inside surveys | + +A seeded scenario records the allocation in `provenance$substreams`. A prebuilt +family can share initial genotypes across replicates. Each replicate starts +its subsequent segregation and survey draws in its own stream. 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 @@ -174,7 +192,8 @@ makes them rank and admit the same mates. work is dispatched. A replicate consumes its stream in declared process order, so results are bit-identical for a given seed whether replicates run serially, on fork workers or on a PSOCK cluster. An unseeded call first draws one root seed from the caller. The remaining -simulation restores the caller's RNG on exit, including on error. Processes may draw random numbers but +simulation restores the caller's RNG on exit, including on error and when a +Box–Muller normal is pending. Processes may draw random numbers but never call `set.seed()`. Reordering a lifecycle is a model change and changes the draws. @@ -186,6 +205,14 @@ A census is an ordinary non-mutating process, and its position defines what it observes. An optional initial census describes the state at year 0; `summarise_pva()` labels the census of interval `t` as year `t + 1`. +A survey writes an observation to a global in process order. Each record +includes run, phase, interval index, duration, visit status, count and detected +IDs. Skipping writes a fresh record with a missing count and an empty ID vector. +A `survey_quota()` callback +requires an observation from this execution and interval, then applies its +rule or explicit skip policy. The management action can affect subsequent +demography. Observation alone advances only the survey substream. + ## Retention `run_scenario(keep = ...)` chooses what a run returns: `census`, `events`, diff --git a/docs/gapps_heritage.md b/docs/gapps_heritage.md index e65c05d..c7ad119 100644 --- a/docs/gapps_heritage.md +++ b/docs/gapps_heritage.md @@ -18,14 +18,17 @@ and what OpenPVA chooses to inherit. Detailed provenance is in - A commercial Applied Biomathematics generation, GAPPS II 1.2/1.3, was in use by 1993–1996 [@appliedbiomathematics1993; @seagle_close1996; @mills_etal1996]. -- The strongest accessible script evidence is Appendix II of Brook's January - 1995 woodhen manuscript [@brook1995woodhen]: - run/year loops, DBF input, censuses, algebraic shared variables, explicit - lifecycle commands, summaries and purging. It demonstrates - commands including `SETUP`, `RUN`, `YEAR`, `READ`, `CENSUS`, `SET`, `BREED`, - `MATE`, `LITTER`, `AGE`, `BIRTH`, `SURVIVE`, `WEAN`, `SUMMARY`, and `PURGE`. - The later journal article supplies the published ecological analysis - [@brook_etal1997], but is not the source cited for the exact script. +- The recovered spatial edition of GAPPS II 1.3 credits Randall Downer + of Applied Biomathematics for spatial modelling. Its 16-bit MS-DOS executable + was built with Borland C++. The dispatch table contains 27 commands. + `BEGIN(RUN(n))` and `BEGIN(YEAR(y))` open nested blocks. `ALLELES` + initialises one diploid locus. The version-specific evidence is recorded in + `GAPPS-II-1.3-FOSSIL-SYNTHESIS.md`, the supplied examples and DBF schemas. +- Twenty recovered Brook et al. (2000) scripts now complement Appendix II + of the 1995 woodhen manuscript [@brook1995woodhen]. In `G_r1_rd1.in` one + deviate drives 33 survival symbols (17 male and 16 female). In + `G_r1_rd2.in` ageing precedes birth. These details determine which animals + share environmental variation and which age newborns reach at census. - Direct applications modelled bear harvest and genetics, deer and horse contraception, grizzly survival/management scenarios, and comparative or retrospective PVAs across diverse vertebrates [@harris_allendorf1989; @@ -46,15 +49,15 @@ GAPPS was: - able to target management actions such as harvest or contraception at individuals or classes. -The evidence does **not** establish native metapopulation support. Spatial/map -attributes in the Assateague work came from a modified GAPPS version. Exact -syntax for `ALLELES`, `INBREED`, immigration, harvest and reseeding is not -verified because neither the 1986 nor 1993 manual was recovered. Capability -evidence must not be promoted into invented syntax. - -The available sources also do not establish that GAPPS was closed source, a -binary-only product, or specifically DOS-based. Those claims are omitted until -primary documentation is retrieved. +The spatial edition exposes coordinates, social groups and map inputs. Its +command table and examples document weighted hunting and contraception, +immigration, reseeding and single-locus inheritance. All 15 Brook et al. scripts +that call `HUNT` use it to remove the excess over a population ceiling. The +exact weighted cumulative-distribution sampling algorithm remains unrecovered. +Evidence for population +movement between explicit patches must come from a model that defines those +patches and transitions. The software licence and source distribution remain +unresolved. ## 3. Lessons from actual use diff --git a/docs/literature/gapps_evidence_review.md b/docs/literature/gapps_evidence_review.md index ed966b4..aba757d 100644 --- a/docs/literature/gapps_evidence_review.md +++ b/docs/literature/gapps_evidence_review.md @@ -32,11 +32,30 @@ The BibTeX keys below refer to `../../references/gapps.bib`. |---|---|---| | Origin in grizzly population/harvest modelling | Harris thesis [@harris1984]; 1986 manual citation [@harris_metzgar_bevins1986] | Strong origin evidence; manual full text inaccessible | | Harris was not sole documented author | 1986 manual citation; Alaska report names Bevins as programmer [@miller_miller1990] | Strong; respective intellectual/programming contributions are not fully documented | -| Explicit ordered script and DBF tables | Woodhen manuscript Appendix II [@brook1995woodhen] | Strong accessible script evidence; one application, not the manual | +| Explicit ordered script and DBF tables | Woodhen manuscript Appendix II [@brook1995woodhen] | The fossil archive adds 20 species scripts and the v1.3 command inventory | | Individual demographic and genetic integration | Harris & Allendorf [@harris_allendorf1989] | Strong substantive use | | Explicit management interventions | Assateague [@kirkpatrick1995]; deer contraception [@seagle_close1996]; GYE survival scenarios [@harris_etal2006] | Strong; Assateague later moved to VORTEX modelling | | Density/stochastic implementation changed results | Mills et al. [@mills_etal1996]; Brook et al. [@brook_etal1999; @brook_burgman_frankham2000] | Strong comparative evidence | -| Native metapopulation support | No substantive evidence found | Do not claim; modified Assateague version added space | +| Spatial modelling in v1.3 | Executable credits, map and group fields, spatial-edition command table | Coordinates and social groups are documented. The Brook scripts supply no model of a patch network. | + +## Recovered GAPPS II 1.3 evidence + +The recovered spatial edition credits Randall Downer of Applied Biomathematics. +The 16-bit MS-DOS executable was built with Borland C++. Its 27 commands include +`BEGIN` for nested `BEGIN(RUN(n))` and `BEGIN(YEAR(y))` blocks, and `ALLELES` +for a single diploid locus. The dispatch-table inventory, two example scripts +and DBF field summaries identify the implemented commands. The 20 recovered +Brook et al. (2000) species scripts show which commands those models used. +All 15 scripts using `HUNT` implement ceilings. Twelve request +`max(0, N - K)` directly. The other three multiply the excess proportion by +abundance to obtain the same target. The executable mentions cumulative +distribution buffers for weighted draws. Its exact sampling algorithm +remains unrecovered. +Counting the assignments in `G_r1_rd1.in` gives 33 survival symbols driven by +one environmental deviate (17 male, 16 female). `G_r1_rd2.in` executes +`AGE()` before `BIRTH()`. Both details matter for reconstructing the stochastic +life cycle. Source inventory: `GAPPS-II-1.3-FOSSIL-SYNTHESIS.md` and +`brook2000-scripts/`. ## Precursor and origin evidence @@ -148,8 +167,9 @@ landscape. - Repeated claims of other large-mammal applications cite Dixon et al. (1991) and Dobson et al. (1992), but those primary applications were not reliably resolved. -- The 1986 and 1993 manuals were not recovered. Exact genetics, immigration, - harvest and reseeding syntax remains unverified. +- The 1986 and 1993 manuals were not recovered. The v1.3 command inventory and scripts now establish genetics, immigration, + harvest and reseeding syntax for that edition. The manuals could establish + how those semantics changed between releases. ## Synthesis for OpenPVA diff --git a/docs/reference/public_api.md b/docs/reference/public_api.md index b171a5e..690bdbb 100644 --- a/docs/reference/public_api.md +++ b/docs/reference/public_api.md @@ -1,4 +1,4 @@ -# Public API (OpenPVA 2.1.0) +# Public API (OpenPVA 2.2.0) The help pages under `man/` are the reference; this page is the map. Every entry is exported. @@ -9,12 +9,13 @@ entry is exported. | 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()`, `mate_min_kinship()` | -| Management and limits | `removal_process()`, `ceiling_process()`, `introduction_process()`, `pairing_process()` | -| Environment | `environment_process()`, `env_ar1()`, `env_trend()`, `spatial_correlation()`, `catastrophe_process()`, `beta_shapes()`, `shift_logit()` | +| Management and limits | `removal_process()`, `ceiling_process()`, `introduction_process()`, `assign_process()`, `mating_process()`, `pairing_process()` | +| Survey and adaptive management | `survey_process()`, `survey_quota()` | +| Environment | `environment_process()`, `env_ar1()`, `env_trend()`, `spatial_correlation()`, `catastrophe_process()`, `beta_shapes()`, `qbeta_norm()`, `shift_logit()` | | Density feedback | `ceiling_density_multiplier()`, `beverton_holt_multiplier()`, `ricker_multiplier()` | | 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()` | +| Rates and life tables | `validate_age_sex_table()`, `age_sex_rate()`, `life_table_metrics()` | | 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()` | @@ -42,14 +43,54 @@ The default retains census, events and accounting. Include `"state"` for final s ## Event vocabulary `death`, `removal`, `birth` and `introduction` are accounting events: their -values must equal the state change. Built-in processes also emit -`breeding_females`, `removal_shortfall`, `death_shortfall` (from a ceiling, -always zero), `pairs_formed`, `unpaired_eligible`, `catastrophe` and -`dispersal`. The latter counts movers. Each `patch_transition` row records an origin, destination and count, including stays among eligible individuals. Other event rows have missing patch IDs. +values must equal the state change. Additional counts include `breeding_females`, `mated_females`, +`pairs_formed`, `unpaired_eligible`, `catastrophe`, `assigned` and +`dispersal` (actual moves). Count targets report unmet demand in +`removal_shortfall`, `death_shortfall`, `assigned_shortfall` or +`dispersal_shortfall`. Each `patch_transition` records its selected origin, +destination and count, including stays. `survey_visit` and `survey_detection` +record a visit and the number detected. A missed visit emits `survey_skip`. ## Composing a species model -Use `mate_random()` for fresh two-sex mating or `mate_from_field()` for a recorded sire. Mating can precede a mortality process in the same interval. Use `mate_from_field(stale = "unpaired")` to treat 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 `mate_random()` for fresh two-sex mating or `mate_from_field()` for a recorded sire. Mating can precede a mortality process in the same interval. Use `mate_from_field(stale = "unpaired")` to treat an absent, unretained sire as unavailable for breeding. With `mate = NULL`, fecundity is female-dominant. A one-sex rate table requires `missing_sex = "zero"` to assign zero when the omitted sex is present. Environment variables evaluate in their listed order, so a shared weather draw can affect several rates. + +For seasonal or patch-local weighted polygyny, use `mating_process()` before +mortality. Set `pva_state(mate_field = "mate_id")` to retain a departed sire +across intervals until the last living female releases his ID. Use +`clear = FALSE` for staggered mating when other pregnant females must keep +their recorded sire. In +`newborn_fields`, index the supplied `pop` with `mothers` and `fathers` to +read parental attributes. The appended records for departed sires carry +`alive = FALSE`. Sex ratios and +categorical litters can depend on the current mother's age or annual environment. + +`assign_process()` records a treatment expiry or other typed individual field. +Its `event` argument names the count of treated animals. +Its count, removal and translocation targets and a ceiling can use susceptibility +weights. At each draw, selection is proportional to remaining positive weights. +Final inclusion probabilities generally differ from strict PPS. Assignment and +destination callbacks receive the weighted draw order even when all positive-weight +animals are selected. A selected +animal whose destination is its current patch contributes to the movement +shortfall. + +`survey_process()` writes a timestamped count and the detected IDs in a named +global. A skipped visit clears the IDs and writes a missing count. +`survey_quota(rule, field, on_skip)` applies the rule to a current visit. +Its default `on_skip = "error"` requires an explicit policy to act on skipped +visits. Surveys draw from +replicate substream 5. Enabling observation alone preserves ecological and +genetic histories. + +`qbeta_norm()` maps a standard normal environmental deviate to a beta rate +with specified mean and SD. `life_table_metrics()` returns the Leslie matrix, +growth factor and log growth, cohort reproduction, stable age distribution +and reproductive values at either breeding census. Use `plus_group = FALSE` +for a finite terminal age. The drift proxy takes `generation_time`, the +stable-population mean maternal age. `cohort_generation_time` averages maternal +ages within a newborn cohort. `summarise_pva()` appends `ema` and `ema_mcse` over the selected census +schedule and metric. 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. diff --git a/inst/examples/grizzly/model.R b/inst/examples/grizzly/model.R index 12bb129..b3b1a48 100644 --- a/inst/examples/grizzly/model.R +++ b/inst/examples/grizzly/model.R @@ -18,22 +18,12 @@ grizzly_initial_state <- function() { } grizzly_summer_mating <- function(parameters) { - OpenPVA::pva_process( + OpenPVA::mating_process( name = "summer_mating", params = parameters, - requires = c("population.age", "population.sex", "population.mother_id"), - writes = "population.mate_id", - run = function(state, context, params) { - pop <- state$population + requires = c("population.age", "population.mother_id"), + eligible = function(pop, state, context, params) { carers <- pop$mother_id[pop$age < params$weaning_age] - mature <- pop$age >= params$maturity_age - females <- which(mature & pop$sex == "F" & !(pop$id %in% carers)) - males <- which(mature & pop$sex == "M") - sire <- rep(NA_integer_, length(pop$id)) - if (length(females) && length(males)) { - sire[females] <- pop$id[males[sample.int(length(males), length(females), replace = TRUE)]] - } - state$population$mate_id <- sire - OpenPVA::pva_result(state, OpenPVA::pva_events("mated_females", sum(!is.na(sire)))) + pop$age >= params$maturity_age & (pop$sex == "M" | !(pop$id %in% carers)) } ) } diff --git a/man/demography_processes.Rd b/man/demography_processes.Rd index 43c98a3..4c0ef64 100644 --- a/man/demography_processes.Rd +++ b/man/demography_processes.Rd @@ -67,7 +67,7 @@ census_process( \item{offspring_sex}{Function of \code{(mothers, pop, state, context, params)} returning \code{"F"} or \code{"M"} for each newborn; \code{mothers} holds one row index per newborn. Required: the engine supplies no default sex ratio.} \item{mate}{Optional function of \code{(pop, state, context, params)} returning, for each living individual, the row of its mate (the father of its offspring) or \code{NA}. See \code{\link{mate_random}()} and \code{\link{mate_from_field}()}.} \item{require_mate}{Whether a recorded mate is required. Supplying a mate function enables this by default. With mate = NULL, reproduction is female-dominant.} -\item{newborn_fields}{Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the non-core fields of the newborns. The arguments hold current living row indices. A sire lost since mating has an \code{NA} row and retains his recorded ID in the offspring.} +\item{newborn_fields}{Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the newborns' non-core fields. Index the supplied \code{pop} with \code{mothers} and \code{fathers}. Departed sires needed by the litter appear after the living rows, with their attributes at exit and \code{alive = FALSE}. \code{state$population} contains the living population. An unknown sire has an \code{NA} index.} \item{newborn_field_names}{Names of the fields \code{newborn_fields} returns.} \item{inherit}{Non-core fields copied from each mother to her offspring.} \item{metrics}{Optional function of \code{(pop, state, context, params)} returning a named numeric vector. The default reports \code{n_alive}, \code{n_female} and \code{n_male}.} diff --git a/man/environment_processes.Rd b/man/environment_processes.Rd index 2f7199e..1371a79 100644 --- a/man/environment_processes.Rd +++ b/man/environment_processes.Rd @@ -7,6 +7,7 @@ \alias{spatial_correlation} \alias{catastrophe_process} \alias{beta_shapes} +\alias{qbeta_norm} \alias{shift_logit} \title{Environmental variation and catastrophes} \usage{ @@ -35,6 +36,8 @@ catastrophe_process( beta_shapes(mean, sd) +qbeta_norm(z, mean, sd) + shift_logit(probability, deviation) } \arguments{ @@ -42,7 +45,7 @@ shift_logit(probability, deviation) \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{sd}{For \code{beta_shapes()} and \code{qbeta_norm()}, positive beta standard deviation with variance below mean times one minus mean. Values within eight machine epsilons of that limit, relative to the limit, are rejected. 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.} @@ -56,11 +59,12 @@ shift_logit(probability, deviation) \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{mean}{Mean of the beta distribution in (0, 1).} +\item{z}{Standard normal deviates for \code{qbeta_norm()}. Arguments may be scalar or have a common vector length.} \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{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. +\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{qbeta_norm()} maps a standard normal through its CDF and the beta quantile function, preserving a chosen beta mean and standard deviation. \code{beta_shapes()} converts moments 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. diff --git a/man/inbreeding.Rd b/man/inbreeding.Rd index 63eea55..681ed9c 100644 --- a/man/inbreeding.Rd +++ b/man/inbreeding.Rd @@ -36,7 +36,7 @@ sex_ratio_effective_size(n_females, n_males) \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.} -\item{generation_time}{Generation time in model intervals. Required for the effective-size approximation.} +\item{generation_time}{Stable-population mean maternal age in model intervals for the effective-size approximation, as returned by \code{\link{life_table_metrics}()}.} \item{migration}{Optional function of \code{(pop, state, context, params)} returning the fraction of the gene pool replaced by unrelated immigrants this interval.} \item{name}{Process name used in events, accounting and error messages.} \item{global}{Name of the numeric global holding the aggregate inbreeding coefficient.} diff --git a/man/life_table_metrics.Rd b/man/life_table_metrics.Rd new file mode 100644 index 0000000..186c439 --- /dev/null +++ b/man/life_table_metrics.Rd @@ -0,0 +1,30 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{life_table_metrics} +\alias{life_table_metrics} +\title{Female life-table projection and generation time} +\usage{ +life_table_metrics( + survival, + fecundity, + timing = c("post_breeding", "pre_breeding"), + plus_group = TRUE +) +} +\arguments{ +\item{survival}{Survival over one model interval, indexed by physical age from zero.} +\item{fecundity}{Expected daughters per female at the breeding pulse, in the same age order as survival. Age-zero fecundity must be zero in a multi-age table.} +\item{timing}{\code{"post_breeding"} for survival, ageing and breeding, with newborns in the census. \code{"pre_breeding"} for breeding, survival and ageing, with first-year survivors in the census.} +\item{plus_group}{Whether survivors can breed repeatedly in the terminal class. With \code{TRUE}, terminal survival must be below one. With \code{FALSE}, individuals leave after the last breeding age.} +} +\description{ +Construct the deterministic projection for a female population with a birth pulse once per model interval and a common terminal age class. +} +\details{ +Post-breeding fertility multiplies maternal survival by fecundity at her next age. Pre-breeding recruitment multiplies fecundity at her current age by newborn survival. A single aggregate class first breeds after one interval. Both generation times are in model intervals. For age \eqn{x}, survivorship \eqn{l_x} and daughters per mother \eqn{m_x}, the cohort weights are \eqn{l_x m_x}. Stable-population weights are \eqn{\lambda^{-x} l_x m_x}. They give the same mean maternal age at replacement. Use the stable-population \code{generation_time} for \code{\link{inbreeding_proxy_process}()}. +} +\value{ +A list with the projection \code{matrix}, dominant growth factor \code{lambda}, its logarithm \code{r}, lifetime daughters per newborn \code{R0}, stable mean maternal age \code{generation_time}, newborn-cohort mean maternal age \code{cohort_generation_time}, \code{stable_age} (sum one) and \code{reproductive_value} (inner product one with stable age). A cohort producing no daughters has undefined mean maternal age. Stable generation time is also \code{NA} when a non-breeding terminal class determines population growth. A zero or repeated dominant root gives undefined eigenvectors. +} +\examples{ +life_table_metrics(c(0.6, 0.8, 0.7), c(0, 0.5, 1.2))$generation_time +} diff --git a/man/management_processes.Rd b/man/management_processes.Rd index 9ba4c7e..ab55e7e 100644 --- a/man/management_processes.Rd +++ b/man/management_processes.Rd @@ -4,8 +4,10 @@ \alias{removal_process} \alias{ceiling_process} \alias{introduction_process} +\alias{assign_process} \alias{pairing_process} -\title{Removal, ceiling, introduction and pairing processes} +\alias{mating_process} +\title{Targeted management and seasonal mating} \usage{ removal_process( count = NULL, @@ -16,7 +18,8 @@ removal_process( cause = "removal", name = "removal", requires = character(), - params = list() + params = list(), + weights = NULL ) ceiling_process( @@ -25,7 +28,8 @@ ceiling_process( cause = "ceiling", name = "ceiling", requires = character(), - params = list() + params = list(), + weights = NULL ) introduction_process( @@ -38,6 +42,21 @@ introduction_process( params = list() ) +assign_process( + field, + value, + count = NULL, + probability = NULL, + select = NULL, + eligible = NULL, + order = c("random", "id"), + name = "assign", + requires = character(), + params = list(), + weights = NULL, + event = "assigned" +) + pairing_process( eligible, capacity = Inf, @@ -49,30 +68,53 @@ pairing_process( max_kinship = Inf, by = NULL ) + +mating_process( + eligible = NULL, + male_capacity = Inf, + weights = NULL, + by = NULL, + field = "mate_id", + name = "mating", + requires = character(), + params = list(), + when = TRUE, + clear = TRUE +) } \arguments{ -\item{count}{Number of individuals to remove or introduce in an interval: one number, or a function of \code{(state, context, params)}. A removal takes at most the eligible number and reports any shortfall.} -\item{probability}{Per-capita removal probability: one number, or a function of \code{(pop, state, context, params)}.} -\item{select}{Function of \code{(pop, state, context, params)} returning the rows (or a logical vector) of the individuals to remove.} +\item{count}{Number to assign, remove or introduce per interval, supplied as one number, or a function of \code{(state, context, params)}. A removal takes at most the eligible number and reports any shortfall.} +\item{probability}{Per-capita assignment or removal probability, given as one number, or a function of \code{(pop, state, context, params)}.} +\item{select}{Function of \code{(pop, state, context, params)} returning the rows (or a logical vector) of the individuals to assign or remove.} \item{eligible}{Function of \code{(pop, state, context, params)} returning one logical value per living individual. Optional (\code{NULL} means everyone) except for \code{pairing_process()}.} -\item{order}{How a \code{count} removal chooses individuals: at random, or lowest identifiers first.} +\item{order}{Choose individuals at random or by ascending ID for count removals and assignments. Weights require random order.} \item{cause}{Label stored with the accounting event, for example \code{"natural"} or \code{"harvest"}.} \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{weights}{Optional function of \code{(pop, state, context, params)} returning a finite non-negative weight for each living individual, or a scalar. Zero excludes an individual.} \item{capacity}{Capacity: one number, or a function of \code{(state, context, params)}. For \code{ceiling_process()} the maximum number of eligible individuals; for \code{pairing_process()} the maximum number of pairs (territories).} \item{fields}{Function of \code{(n, state, context, params)} returning a named list with \code{sex}, \code{age} and every non-core field of the \code{n} introduced individuals. Optional \code{mother_id} and \code{father_id} must both be missing when neutral loci are enabled.} \item{creates}{Fields that \code{fields} initialises.} \item{source}{Label stored with the introduction event.} +\item{field}{Existing model field to assign, or the numeric field receiving mate identifiers.} +\item{value}{Scalar to assign, or a function of \code{(rows, pop, state, context, params)} returning one value or one per selected row. Integer fields accept whole, representable doubles. An untyped \code{NA} takes the field's type on fields that support missing values.} +\item{event}{Name of the assignment count event. Count selection also emits this name with the suffix \code{_shortfall}. The four demographic accounting event names are reserved.} \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.} +\item{male_capacity}{Maximum matings per eligible positive-weight male per event. Supply a non-negative integer, \code{Inf}, or a function of \code{(state, context, params)} returning either.} +\item{when}{Run in every interval (\code{TRUE}), on the specified zero-based integer intervals, or when a function of \code{(state, context, params)} returns true.} +\item{clear}{On a scheduled mating, clear all existing mate records before the draw. With \code{FALSE} only eligible females have their records replaced, so other dams can keep a sire until birth.} } \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{ +Count removals, ceilings and assignments choose among eligible positive-weight individuals without replacement, in proportion to the remaining weights at each draw. Marginal inclusion probabilities generally differ from strict probability-proportional-to-size sampling. Assignment and destination callbacks receive the weighted draw order even when every positive-weight animal is selected. Unweighted selection preserves the original draws. The number taken plus its shortfall equals the request, including when all weights are zero. A weighted ceiling can leave the population above capacity. The default assignment events are \code{assigned} and, for counts, \code{assigned_shortfall}. + +On scheduled occasions \code{mating_process()} writes a sire ID to each mated female. With the default \code{clear = TRUE} it first clears the entire mate field. Positive male weights govern draws among sires with remaining capacity. With unlimited capacity, draws are independent with replacement. A finite limit bounds each male's matings, and partners must share their group when \code{by} is set. Skipping an occasion preserves the field. The events \code{mated_females} and \code{unmated_females} count eligible females with and without a new mate. Both counts are zero on a skipped occasion. Use \code{mate_from_field()} at birth. + \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{ diff --git a/man/markers.Rd b/man/markers.Rd index 55f34d1..5ddc18d 100644 --- a/man/markers.Rd +++ b/man/markers.Rd @@ -19,7 +19,7 @@ genetic_metrics() \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. +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 or a sire retained through \code{pva_state(mate_field = )} 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. diff --git a/man/pva_state.Rd b/man/pva_state.Rd index 2d3be1b..ffc3e93 100644 --- a/man/pva_state.Rd +++ b/man/pva_state.Rd @@ -13,7 +13,8 @@ pva_state( pedigree = FALSE, kinship = NULL, max_dense_kinship = 2000L, - n_loci = 0L + n_loci = 0L, + mate_field = NULL ) add_individuals( @@ -37,6 +38,7 @@ add_individuals( \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{mate_field}{Optional numeric field in which females record sire IDs. In the initial population each recorded sire must be a living male. Later references must be allocated IDs. A departed sire's genetic material and attributes are retained until his last living mate releases the reference.} \item{state}{A \code{pva_state}.} } \description{ @@ -45,10 +47,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. -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. +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. A known parent may die earlier in the interval. With \code{mate_field}, a recorded sire can father offspring in later intervals. The traced pedigree preserves historical ancestry after a mate reference expires. 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}, \code{max_dense_kinship} and \code{markers}. \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}. With sire retention, \code{sires$records} holds referenced departed males at the interval boundary. Surveys add a private \code{survey_seed}. \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 825119a..6bd45cb 100644 --- a/man/reproduction_helpers.Rd +++ b/man/reproduction_helpers.Rd @@ -34,11 +34,11 @@ mate_min_kinship( \item{size}{Maximum litter size of the bounded binomial distribution.} \item{min_size}{Minimum litter size conditional on breeding. The mean must lie between the two bounds.} \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{probabilities}{Probabilities of \code{sizes}, summing to one. A function of \code{(pop, state, context, params)} can return a shared vector or a matrix with one distribution per living individual (rows) in the order of \code{sizes} (columns).} +\item{female_probability}{Probability that a newborn is female, or a function of \code{(pop, state, context, params)} giving one probability or one per living individual. Each newborn uses its mother's probability.} \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{stale}{How to handle a female's recorded sire ID when the sire is absent from both the current interval and the retained sire records. 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.} @@ -47,7 +47,7 @@ mate_min_kinship( 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_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. A sire recorded in the state's designated \code{mate_field} can also father offspring in later intervals. The offspring inherit his ID and \code{newborn_fields} can read his attributes at exit. 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. } diff --git a/man/run_pva_ensemble.Rd b/man/run_pva_ensemble.Rd index e8eb8a9..bf1818f 100644 --- a/man/run_pva_ensemble.Rd +++ b/man/run_pva_ensemble.Rd @@ -36,7 +36,7 @@ run_pva_ensemble( 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{ -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. +The builder and summary draw on a reproducible member substream. Cache entries record callback code and statically referenced inputs, package and R versions, the row, member seed, full RNG specification (including the binomial generator when available), replicate count, validation mode and cache key. Member seeds are a deterministic function of \code{seed} and the design order, so the ensemble is reproducible and independent of the number of workers and of the backend. } \value{ A data frame of class \code{pva_ensemble}: the design rows, \code{member}, \code{member_seed} and the summary columns. Provenance is attached as an attribute. \code{\link[=plot.pva_ensemble]{plot()}} contrasts the members. diff --git a/man/scenario.Rd b/man/scenario.Rd index 76b7616..0f0869b 100644 --- a/man/scenario.Rd +++ b/man/scenario.Rd @@ -47,7 +47,7 @@ run_scenario( \code{scenario_spec()} bundles an initial state, an ordered lifecycle and a replicate design. \code{run_scenario()} executes it serially or in parallel. } \details{ -Each replicate receives its own L'Ecuyer-CMRG stream, assigned before any work is dispatched, so results are bit-identical for a given seed whether replicates run serially, on fork workers or on a PSOCK cluster. After the optional root draw the caller's RNG kind and seed are restored, including on error. +Each replicate receives its own L'Ecuyer-CMRG stream, assigned before any work is dispatched, so results are bit-identical for a given seed whether replicates run serially, on fork workers or on a PSOCK cluster. After the optional root draw the caller's RNG is restored, including a cached Box--Muller normal and on error. Provenance records substreams 0 (demography), 1 (ensemble builder), 2 and 3 (initial markers in a replicate and builder respectively), 4 (offspring segregation) and 5 (surveys). Managed socket workers start with \code{--vanilla}. Both runners propagate the parent library paths and export statically referenced callback helpers and data. A supplied cluster can initialise resources resolved dynamically by the model. } diff --git a/man/spatial.Rd b/man/spatial.Rd index e31ca97..878819e 100644 --- a/man/spatial.Rd +++ b/man/spatial.Rd @@ -15,7 +15,9 @@ dispersal_process( field = "patch_id", name = "dispersal", requires = character(), - params = list() + params = list(), + count = NULL, + weights = NULL ) markov_dispersal_process( @@ -30,15 +32,17 @@ markov_dispersal_process( \item{pop}{A columnar population.} \item{patches}{Vector of the declared patch identifiers.} \item{field}{Population field holding each individual's patch.} -\item{destination}{Function of \code{(rows, pop, state, context, params)} returning one declared patch per eligible individual.} +\item{destination}{Function of \code{(rows, pop, state, context, params)} returning one declared patch per selected individual.} \item{eligible}{Optional function of \code{(pop, state, context, params)} returning one logical value per living individual. \code{NULL} means every living individual.} \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{count}{Optional target number to move or a count function of \code{(state, context, params)}. Positive weights govern successive selection without replacement.} +\item{weights}{Optional function of \code{(pop, state, context, params)} returning a finite non-negative weight for each living individual, or a scalar. Zero excludes an individual.} \item{transition}{Square row-stochastic matrix whose row and column names are the patch identifiers.} } \description{ -\code{dispersal_process()} moves eligible individuals to modeller-chosen patches; \code{markov_dispersal_process()} draws each destination from a transition matrix. The \code{dispersal} event counts movers. Each \code{patch_transition} row reports one realised origin, destination and count, including eligible individuals who stayed. \code{patch_counts()} tabulates abundance by patch for patch-specific density feedback. +\code{dispersal_process()} moves eligible individuals to modeller-chosen patches; \code{markov_dispersal_process()} draws each destination from a transition matrix. The \code{dispersal} event counts movers. Each \code{patch_transition} row reports one realised origin, destination and count, including selected individuals assigned their original patch. For a count target, \code{dispersal + dispersal_shortfall} equals the requested count. A selected animal assigned its current patch contributes one to the shortfall. Unselected animals stay in place. \code{patch_counts()} tabulates abundance by patch for patch-specific density feedback. } \value{ The constructors return a \code{pva_process}; \code{patch_counts()} returns a named integer vector. diff --git a/man/summaries.Rd b/man/summaries.Rd index ba4196d..34f6853 100644 --- a/man/summaries.Rd +++ b/man/summaries.Rd @@ -42,7 +42,7 @@ Proportions carry a binomial Monte Carlo standard error and a 95 percent Wilson \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. +\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. For the selected metric, \code{ema} is the mean of replicate minima across the evaluated censuses. The final two columns are \code{ema} and \code{ema_mcse}. The latter is the sample standard deviation of the minima divided by the square root of the replicate count (undefined for a single replicate). } \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}. diff --git a/man/survey_processes.Rd b/man/survey_processes.Rd new file mode 100644 index 0000000..cda2520 --- /dev/null +++ b/man/survey_processes.Rd @@ -0,0 +1,48 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{survey_processes} +\alias{survey_processes} +\alias{survey_process} +\alias{survey_quota} +\title{Imperfect surveys and observation-based management} +\usage{ +survey_process( + detection, + eligible = NULL, + when = TRUE, + field = "survey", + name = "survey", + requires = character(), + params = list() +) + +survey_quota(rule, field = "survey", on_skip = "error") +} +\arguments{ +\item{detection}{Independent individual detection probability on a visit. Supply a scalar or a function of \code{(pop, state, context, params)} returning a scalar or one probability per living individual.} +\item{eligible}{Optional function of \code{(pop, state, context, params)} returning one logical value per living individual. \code{NULL} means every living individual.} +\item{when}{Run in every interval (\code{TRUE}), on the specified zero-based integer intervals, or when a function of \code{(state, context, params)} returns true.} +\item{field}{Name of the observation record in the state globals.} +\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{rule}{Function of \code{(obs, state, context, params)} returning a non-negative whole quota. The observation's \code{count} can be zero on a completed visit.} +\item{on_skip}{Policy for a skipped visit. The default \code{"error"} signals the skipped visit. Supply a non-negative whole count or a function with the same arguments as \code{rule} to take an action.} +} +\description{ +Use an imperfect scheduled count to trigger an ordered management action. The survey draws from replicate substream 5 independently of demography and neutral loci. +} +\details{ +Each visit writes \code{run}, \code{time}, \code{dt}, \code{phase}, \code{visited}, \code{count} and the vector of detected individual IDs (\code{ids}) into \code{state$globals[[field]]}. Its events are \code{survey_visit} and \code{survey_detection}. A skipped visit writes \code{NA_integer_} for the count, clears the IDs to \code{integer(0)} and emits \code{survey_skip}. Surveys within a replicate use the same advancing cursor in execution order. In direct \code{execute_processes()} calls, keep the returned state to continue its survey sequence. Repeated calls on the same initial state and caller RNG position derive the same survey stream and return identical detections. A quota checks the observation's timestamp before invoking the rule or skip policy. A missing or stale record is an error. +} +\value{ +\code{survey_process()} returns a \code{pva_process}. \code{survey_quota()} returns a count callback for a subsequent removal, introduction, assignment or count-targeted movement. +} +\examples{ +visit <- survey_process(0.6, when = c(0L, 2L)) +quota <- survey_quota(rule = function(obs, state, context, params) as.integer(obs$count == 0L)) +release <- introduction_process(quota, fields = function(n, state, context, params) { + list(sex = rep("F", n), age = 1L) +}) +state <- pva_state(pva_population("F", 1L)) +execute_processes(state, list(visit, release))$events +} diff --git a/scripts/benchmark_panmictic_pedigree.R b/scripts/benchmark_panmictic_pedigree.R new file mode 100644 index 0000000..37bf6a0 --- /dev/null +++ b/scripts/benchmark_panmictic_pedigree.R @@ -0,0 +1,55 @@ +# Run against either installed package. Pass "oracle" for the independent +# cohort-tabular check; omit it for the timed process-tree measurement. +library(OpenPVA) +oracle <- "oracle" %in% commandArgs(trailingOnly = TRUE) +n <- 2000L +generations <- 12L +pairs <- n %/% 2L +dam <- seq.int(1L, n, by = 2L) +set.seed(20261130L) +sires <- replicate(generations, 2L * sample.int(pairs)) +birth <- pva_process("birth", function(state, context, params) { + ids <- state$population$id + fathers <- params$sires[, context$time + 1L] + state <- add_individuals(state, rep(c("F", "M"), length(fathers)), 0L, + mother_id = rep(ids[params$dam], each = 2L), + father_id = rep(ids[fathers], each = 2L)) + pva_result(state, pva_events("birth", length(ids))) +}, params = list(dam = dam, sires = sires), creates = c("age", "sex")) +life <- list(birth, removal_process(select = function(pop, state, context, params) pop$age > 0L), + age_process()) +state <- pva_state(pva_population(rep(c("F", "M"), pairs), 1L), pedigree = TRUE) +stopifnot(is.matrix(state$kinship), state$max_dense_kinship == n) +F_by_generation <- matrix(0, n, generations) +elapsed <- system.time({ + for (g in seq_len(generations)) { + state <- execute_processes(state, life, time = g - 1L)$state + stopifnot(length(state$population$id) == n, is.null(state$kinship$values)) + F_by_generation[, g] <- state$population$pedigree_F + } +})[["elapsed"]] +ids <- state$population$id +probe <- unique(round(seq(1, n, length.out = 24L))) +K_probe <- kinship_matrix(state, ids[probe]) +F_error <- K_error <- NA_real_ +if (oracle) { + # Separate generations allow the exact tabular recursion to discard adults. + K <- diag(0.5, n) + family <- rep(seq_len(pairs), each = 2L) + F_error <- 0 + for (g in seq_len(generations)) { + sire <- sires[, g] + F <- K[cbind(dam, sire)][family] + F_error <- max(F_error, abs(F - F_by_generation[, g])) + sib <- 0.25 * (K[dam, dam] + K[dam, sire] + K[sire, dam] + K[sire, sire]) + K <- sib[family, family] + diag(K) <- 0.5 * (1 + F) + } + K_error <- max(abs(K_probe - K[probe, probe])) + stopifnot(F_error <= 1e-13, K_error <= 1e-13) +} +write.table(data.frame(version = as.character(packageVersion("OpenPVA")), n = n, + peak_living = 2L*n, generations = generations, + engine_s = elapsed, max_F = max(F_by_generation), + F_error = F_error, kinship_error = K_error), + file = "", sep = ",", quote = FALSE, row.names = FALSE) diff --git a/scripts/benchmark_pedigree.sh b/scripts/benchmark_pedigree.sh new file mode 100755 index 0000000..bd9c76b --- /dev/null +++ b/scripts/benchmark_pedigree.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Usage: bash scripts/benchmark_pedigree.sh output/prefix scripts/benchmark_NAME.R [oracle] +# The prefix receives the R output (.log) and elapsed time / summed tree RSS (.csv). +set -euo pipefail +prefix=$1 +shift +mkdir -p "$(dirname "$prefix")" +start=$(date +%s.%N) +Rscript --vanilla "$@" > "$prefix.log" & +pid=$! +peak=0 +while kill -0 "$pid" 2>/dev/null; do + rss=$(ps -e -o pid=,ppid=,rss= | awk -v root="$pid" ' + { parent[$1] = $2; mem[$1] = $3 } + END { + for (p in parent) { + q = p + while (q && q != 1 && q != root) q = parent[q] + if (q == root) total += mem[p] + } + print total + 0 + }') + if (( rss > peak )); then peak=$rss; fi + sleep 0.2 +done +wait "$pid" +end=$(date +%s.%N) +awk -v start="$start" -v end="$end" -v peak="$peak" 'BEGIN { + print "wall_s,peak_tree_rss_mb" + printf "%.2f,%.2f\n", end-start, peak/1024 +}' > "$prefix.csv" diff --git a/scripts/check_r_floor.R b/scripts/check_r_floor.R index ecfd464..844bdc1 100644 --- a/scripts/check_r_floor.R +++ b/scripts/check_r_floor.R @@ -1,11 +1,16 @@ #!/usr/bin/env Rscript -# Run with R 4.1.0: Rscript --vanilla scripts/check_r_floor.R +# Rscript --vanilla scripts/check_r_floor.R [binom.kind] args <- commandArgs(trailingOnly = TRUE) -stopifnot(getRversion() == "4.1.0", length(args) == 1L) +stopifnot(getRversion() >= "4.1.0", length(args) %in% 1:2) +if (length(args) == 2L) { + if (length(RNGkind()) < 4L) stop("this R interpreter has no binom.kind") + suppressWarnings(do.call(RNGkind, list(binom.kind = args[[2L]]))) +} private_lib <- normalizePath(args[[1L]], mustWork = TRUE) .libPaths(c(private_lib, .libPaths())) library(OpenPVA, lib.loc = private_lib) cat(R.version.string, "\nOpenPVA", as.character(packageVersion("OpenPVA")), "\n") +cat("Caller RNG:", paste(RNGkind(), collapse = ", "), "\n") floor_population <- function() pva_state( pva_population(rep(c("F", "M"), 4L), 2L, mate_id = NA_integer_, @@ -27,7 +32,7 @@ floor_components <- function(row) { }, 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), + reproduction_process(0.5, litter_binomial(4L, 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"), @@ -38,6 +43,69 @@ design <- data.frame(p = c(0.7, 0.9)) scenario <- do.call(scenario_spec, c(list(name = "floor", n_runs = 4L, seed = 23L), floor_components(design[1L, , drop = FALSE]))) +herd <- scenario_spec( + "seasonal-herd", n_runs = 2L, n_steps = 2L, dt = 0.5, seed = 19L, + init_fun = function() pva_state( + pva_population(rep(c("F", "M"), c(4L, 3L)), 2L, patch_id = "north", + mate_id = NA_integer_, sterile_until = 0L), + pedigree = TRUE, max_dense_kinship = 1L, n_loci = 2L, mate_field = "mate_id" + ), + processes = list( + survey_process(1, when = 0L), + dispersal_process(function(rows, pop, ...) ifelse(pop$id[rows] == 1L, "south", "north"), + c("north", "south"), count = 2L, weights = function(pop, ...) 1 * (pop$id <= 2L)), + assign_process("sterile_until", 2, count = 1L, weights = function(pop, ...) 1 * (pop$id == 4L), + event = "contraception"), + mating_process(function(pop, state, context, ...) pop$sterile_until <= context$time, + male_capacity = 2L, weights = function(pop, ...) 1 * (pop$id == 5L), + when = 0L, clear = FALSE), + removal_process(survey_quota(function(obs, ...) { + stopifnot(identical(obs$ids, 1:7), obs$count == 7L) + 1L + }, on_skip = function(obs, ...) { + stopifnot(identical(obs$ids, integer()), is.na(obs$count)) + 0L + }), weights = function(pop, ...) 1 * (pop$id == 5L)), + ceiling_process(5L, weights = function(pop, ...) 1 * (pop$id == 7L)), + reproduction_process( + function(pop, state, context, ...) as.numeric(context$time == 1L & pop$sterile_until == 0L), + litter_categorical(c(0L, 1L), function(pop, ...) cbind(1 * (pop$age == 0), 1 * (pop$age > 0))), + offspring_sex_bernoulli(function(pop, ...) as.numeric(pop$age > 0)), + mate = mate_from_field(), inherit = "patch_id", + newborn_fields = function(mothers, fathers, pop, ...) { + stopifnot(all(pop$id[fathers] == 5L), all(!pop$alive[fathers])) + list(mate_id = NA_integer_, sterile_until = 0L) + }, newborn_field_names = c("mate_id", "sterile_until") + ), + assign_process("mate_id", NA, select = function(pop, state, context, ...) { + context$time == 1L & pop$sex == "F" + }, name = "clear_sires"), + census_process() + ) +) +keep <- c("state", "events", "census", "accounting") +season <- run_scenario(herd, keep = keep) +events <- function(type) season$events$value[season$events$event_type == type] +stopifnot(identical(events("dispersal"), rep(c(1, 0), 2L)), + identical(events("dispersal_shortfall"), rep(c(1, 2), 2L)), + identical(events("mated_females"), rep(c(2, 0), 2L)), + identical(events("unmated_females"), rep(c(1, 0), 2L)), + all(events("contraception") == 1), all(summarise_accounting(season)$reconciled)) +for (state in season$states) { + pop <- state$population + newborn <- pop$origin == "birth" + stopifnot(identical(pop$father_id[newborn], c(5L, 5L)), all(pop$sex[newborn] == "F"), + !4L %in% pop$mother_id[newborn], is.null(state$sires$records)) +} +minimum <- summarise_pva(season) +life <- life_table_metrics(c(1, 0.5), c(0, 1)) +terminal <- life_table_metrics(c(1, 0.5), c(0, 1), "pre_breeding", plus_group = FALSE) +stopifnot(minimum$ema == 5, minimum$ema_mcse == 0, + abs(life$generation_time - 1.5) < 1e-12, life$cohort_generation_time == 2, + terminal$generation_time == 1, terminal$cohort_generation_time == 1, + abs(qbeta_norm(40, 0.5, 0.01) - 0.8438410024) < 1e-9) +cat("Two half-year intervals verified survey decisions, management, retained paternity and EMA.\n") + Sys.unsetenv(c("R_LIBS", "R_LIBS_USER", "R_LIBS_SITE")) cl <- parallel::makePSOCKcluster(2L, rscript_args = "--vanilla") tryCatch({ @@ -47,27 +115,35 @@ tryCatch({ loaded = "OpenPVA" %in% loadedNamespaces(), found = nzchar(system.file(package = "OpenPVA"))) }) for (worker in workers) { - stopifnot(identical(worker$version, "4.1.0"), identical(worker$paths, .Library), + stopifnot(identical(worker$version, as.character(getRversion())), identical(worker$paths, .Library), !worker$loaded, !worker$found) } - cat("Both --vanilla R 4.1.0 workers have only the base library and cannot find OpenPVA.\n") + cat("Both --vanilla workers match the caller's R version and start with only the base library.\n") set.seed(521L) before <- .Random.seed serial <- run_scenario(scenario) socket <- run_scenario(scenario, parallel = TRUE, cluster = cl) + socket_season <- run_scenario(herd, parallel = TRUE, cluster = cl, keep = keep) loaded <- parallel::clusterCall(cl, function() getNamespaceInfo(asNamespace("OpenPVA"), "path")) - stopifnot(identical(serial, socket), identical(before, .Random.seed), + stopifnot(identical(serial, socket), identical(season, socket_season), identical(before, .Random.seed), all(unlist(loaded) == find.package("OpenPVA", lib.loc = private_lib))) cat("Scenario results match serial and both workers loaded the private installation.\n") }, finally = parallel::stopCluster(cl)) -serial_design <- run_pva_ensemble(design, floor_components, 3L, seed = 37L) -socket_design <- run_pva_ensemble(design, floor_components, 3L, seed = 37L, +floor_summary <- function(result, row) { + summary <- summarise_pva(result) + summary$member_rng <- paste(result$provenance$rng_kind, collapse = "/") + summary +} +serial_design <- run_pva_ensemble(design, floor_components, 3L, floor_summary, seed = 37L) +socket_design <- run_pva_ensemble(design, floor_components, 3L, floor_summary, seed = 37L, workers = 2L, backend = "psock") -stopifnot(identical(serial_design, socket_design), identical(before, .Random.seed)) +stopifnot(identical(serial_design, socket_design), identical(before, .Random.seed), + all(serial_design$member_rng == paste(serial$provenance$rng_kind, collapse = "/"))) cat("Ensemble results match serial on a second, internally created PSOCK cluster.\n") if (.Platform$OS.type != "windows") { forked <- run_scenario(scenario, parallel = TRUE, workers = 2L, backend = "fork") - stopifnot(identical(forked, serial), identical(before, .Random.seed)) + fork_season <- run_scenario(herd, parallel = TRUE, workers = 2L, backend = "fork", keep = keep) + stopifnot(identical(forked, serial), identical(season, fork_season), identical(before, .Random.seed)) cat("Forked and serial scenarios also agree.\n") } cat("All seeded calls restored the caller's RNG.\n") diff --git a/scripts/rd_topics.R b/scripts/rd_topics.R index 36a881c..e21fe9b 100644 --- a/scripts/rd_topics.R +++ b/scripts/rd_topics.R @@ -3,6 +3,8 @@ callback <- r"(\code{(pop, state, context, params)})" common_arguments <- list( + weights = r"(Optional function of \code{(pop, state, context, params)} returning a finite non-negative weight for each living individual, or a scalar. Zero excludes an individual.)", + when = r"(Run in every interval (\code{TRUE}), on the specified zero-based integer intervals, or when a function of \code{(state, context, params)} returns true.)", name = "Process name used in events, accounting and error messages.", requires = r"(Additional state paths (\code{population.} or \code{globals.}) read by the supplied functions; checked before a run starts.)", params = r"(Named list of modeller parameters, passed unchanged to every supplied function as \code{params}.)", @@ -43,13 +45,14 @@ topics <- list( 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.", + mate_field = "Optional numeric field in which females record sire IDs. In the initial population each recorded sire must be a living male. Later references must be allocated IDs. A departed sire's genetic material and attributes are retained until his last living mate releases the reference.", 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. -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.)", +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. A known parent may die earlier in the interval. With \code{mate_field}, a recorded sire can father offspring in later intervals. The traced pedigree preserves historical ancestry after a mate reference expires. 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}. With sire retention, \code{sires$records} holds referenced departed males at the interval boundary. Surveys add a private \code{survey_seed}. \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 @@ -127,7 +130,7 @@ out$accounting)" r"( returning, for each living individual, the row of its mate (the father of its offspring) or \code{NA}. See \code{\link{mate_random}()} and \code{\link{mate_from_field}()}.)" ), require_mate = "Whether a recorded mate is required. Supplying a mate function enables this by default. With mate = NULL, reproduction is female-dominant.", - newborn_fields = r"(Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the non-core fields of the newborns. The arguments hold current living row indices. A sire lost since mating has an \code{NA} row and retains his recorded ID in the offspring.)", + newborn_fields = r"(Optional function of \code{(mothers, fathers, pop, state, context, params)} returning a named list of the newborns' non-core fields. Index the supplied \code{pop} with \code{mothers} and \code{fathers}. Departed sires needed by the litter appear after the living rows, with their attributes at exit and \code{alive = FALSE}. \code{state$population} contains the living population. An unknown sire has an \code{NA} index.)", newborn_field_names = r"(Names of the fields \code{newborn_fields} returns.)", inherit = "Non-core fields copied from each mother to her offspring.", metrics = paste0( @@ -175,10 +178,10 @@ summarise_pva(run_scenario(scenario), threshold = 10))" size = "Maximum litter size of the bounded binomial distribution.", min_size = "Minimum litter size conditional on breeding. The mean must lie between the two bounds.", sizes = "Distinct litter sizes of the categorical distribution.", - probabilities = r"(Probabilities of \code{sizes}; they must sum to one.)", - female_probability = "Probability that a newborn is female.", + probabilities = r"(Probabilities of \code{sizes}, summing to one. A function of \code{(pop, state, context, params)} can return a shared vector or a matrix with one distribution per living individual (rows) in the order of \code{sizes} (columns).)", + female_probability = r"(Probability that a newborn is female, or a function of \code{(pop, state, context, params)} giving one probability or one per living individual. Each newborn uses its mother's probability.)", field = r"(Name of the population field holding recorded mate IDs. Initialise unpaired individuals with \code{NA_integer_}.)", - 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.)", + stale = r"(How to handle a female's recorded sire ID when the sire is absent from both the current interval and the retained sire records. 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. For mate_min_kinship(), NULL makes every living male eligible." @@ -187,7 +190,7 @@ summarise_pva(run_scenario(scenario), threshold = 10))" 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. A sire recorded in the state's designated \code{mate_field} can also father offspring in later intervals. The offspring inherit his ID and \code{newborn_fields} can read his attributes at exit. 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}()}.)", @@ -197,21 +200,21 @@ set.seed(1) cubs(mothers = 1:2, pop = pop, state = NULL, context = NULL, params = NULL))" ), management_processes = list( - title = "Removal, ceiling, introduction and pairing processes", + title = "Targeted management and seasonal mating", functions = c( - "removal_process", "ceiling_process", "introduction_process", - "pairing_process" + "removal_process", "ceiling_process", "introduction_process", "assign_process", + "pairing_process", "mating_process" ), arguments = list( - count = r"(Number of individuals to remove or introduce in an interval: one number, or a function of \code{(state, context, params)}. A removal takes at most the eligible number and reports any shortfall.)", + count = r"(Number to assign, remove or introduce per interval, supplied as one number, or a function of \code{(state, context, params)}. A removal takes at most the eligible number and reports any shortfall.)", probability = paste0( - "Per-capita removal probability: one number, or a function of ", callback, "." + "Per-capita assignment or removal probability, given as one number, or a function of ", callback, "." ), select = paste0( "Function of ", callback, - " returning the rows (or a logical vector) of the individuals to remove." + " returning the rows (or a logical vector) of the individuals to assign or remove." ), - order = r"(How a \code{count} removal chooses individuals: at random, or lowest identifiers first.)", + order = r"(Choose individuals at random or by ascending ID for count removals and assignments. Weights require random order.)", capacity = r"(Capacity: one number, or a function of \code{(state, context, params)}. For \code{ceiling_process()} the maximum number of eligible individuals; for \code{pairing_process()} the maximum number of pairs (territories).)", fields = r"(Function of \code{(n, state, context, params)} returning a named list with \code{sex}, \code{age} and every non-core field of the \code{n} introduced individuals. Optional \code{mother_id} and \code{father_id} must both be missing when neutral loci are enabled.)", creates = r"(Fields that \code{fields} initialises.)", @@ -222,10 +225,18 @@ cubs(mothers = 1:2, pop = pop, state = NULL, context = NULL, params = NULL))" "Function of ", callback, r"( returning one logical value per living individual. Optional (\code{NULL} means everyone) except for \code{pairing_process()}.)" ), - field = "Integer population field that receives each paired individual's mate identifier." + value = r"(Scalar to assign, or a function of \code{(rows, pop, state, context, params)} returning one value or one per selected row. Integer fields accept whole, representable doubles. An untyped \code{NA} takes the field's type on fields that support missing values.)", + event = r"(Name of the assignment count event. Count selection also emits this name with the suffix \code{_shortfall}. The four demographic accounting event names are reserved.)", + clear = r"(On a scheduled mating, clear all existing mate records before the draw. With \code{FALSE} only eligible females have their records replaced, so other dams can keep a sire until birth.)", + male_capacity = r"(Maximum matings per eligible positive-weight male per event. Supply a non-negative integer, \code{Inf}, or a function of \code{(state, context, params)} returning either.)", + field = "Existing model field to assign, or the numeric field receiving mate identifiers." ), 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.)", + details = r"(Count removals, ceilings and assignments choose among eligible positive-weight individuals without replacement, in proportion to the remaining weights at each draw. Marginal inclusion probabilities generally differ from strict probability-proportional-to-size sampling. Assignment and destination callbacks receive the weighted draw order even when every positive-weight animal is selected. Unweighted selection preserves the original draws. The number taken plus its shortfall equals the request, including when all weights are zero. A weighted ceiling can leave the population above capacity. The default assignment events are \code{assigned} and, for counts, \code{assigned_shortfall}. + +On scheduled occasions \code{mating_process()} writes a sire ID to each mated female. With the default \code{clear = TRUE} it first clears the entire mate field. Positive male weights govern draws among sires with remaining capacity. With unlimited capacity, draws are independent with replacement. A finite limit bounds each male's matings, and partners must share their group when \code{by} is set. Skipping an occasion preserves the field. The events \code{mated_females} and \code{unmated_females} count eligible females with and without a new mate. Both counts are zero on a skipped occasion. Use \code{mate_from_field()} at birth. + +\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_ @@ -246,11 +257,45 @@ set.seed(1) out <- execute_processes(state, list(territories, cull, release, census_process())) out$events[, c("process_name", "event_type", "value")])" ), + survey_processes = list( + title = "Imperfect surveys and observation-based management", + functions = c("survey_process", "survey_quota"), + arguments = list( + detection = r"(Independent individual detection probability on a visit. Supply a scalar or a function of \code{(pop, state, context, params)} returning a scalar or one probability per living individual.)", + field = "Name of the observation record in the state globals.", + rule = r"(Function of \code{(obs, state, context, params)} returning a non-negative whole quota. The observation's \code{count} can be zero on a completed visit.)", + on_skip = r"(Policy for a skipped visit. The default \code{"error"} signals the skipped visit. Supply a non-negative whole count or a function with the same arguments as \code{rule} to take an action.)" + ), + description = "Use an imperfect scheduled count to trigger an ordered management action. The survey draws from replicate substream 5 independently of demography and neutral loci.", + details = r"(Each visit writes \code{run}, \code{time}, \code{dt}, \code{phase}, \code{visited}, \code{count} and the vector of detected individual IDs (\code{ids}) into \code{state$globals[[field]]}. Its events are \code{survey_visit} and \code{survey_detection}. A skipped visit writes \code{NA_integer_} for the count, clears the IDs to \code{integer(0)} and emits \code{survey_skip}. Surveys within a replicate use the same advancing cursor in execution order. In direct \code{execute_processes()} calls, keep the returned state to continue its survey sequence. Repeated calls on the same initial state and caller RNG position derive the same survey stream and return identical detections. A quota checks the observation's timestamp before invoking the rule or skip policy. A missing or stale record is an error.)", + value = r"(\code{survey_process()} returns a \code{pva_process}. \code{survey_quota()} returns a count callback for a subsequent removal, introduction, assignment or count-targeted movement.)", + examples = r"(visit <- survey_process(0.6, when = c(0L, 2L)) +quota <- survey_quota(rule = function(obs, state, context, params) as.integer(obs$count == 0L)) +release <- introduction_process(quota, fields = function(n, state, context, params) { + list(sex = rep("F", n), age = 1L) +}) +state <- pva_state(pva_population("F", 1L)) +execute_processes(state, list(visit, release))$events)" + ), + life_table_metrics = list( + title = "Female life-table projection and generation time", + functions = "life_table_metrics", + arguments = list( + survival = "Survival over one model interval, indexed by physical age from zero.", + fecundity = "Expected daughters per female at the breeding pulse, in the same age order as survival. Age-zero fecundity must be zero in a multi-age table.", + timing = r"(\code{"post_breeding"} for survival, ageing and breeding, with newborns in the census. \code{"pre_breeding"} for breeding, survival and ageing, with first-year survivors in the census.)", + plus_group = r"(Whether survivors can breed repeatedly in the terminal class. With \code{TRUE}, terminal survival must be below one. With \code{FALSE}, individuals leave after the last breeding age.)" + ), + description = "Construct the deterministic projection for a female population with a birth pulse once per model interval and a common terminal age class.", + details = r"(Post-breeding fertility multiplies maternal survival by fecundity at her next age. Pre-breeding recruitment multiplies fecundity at her current age by newborn survival. A single aggregate class first breeds after one interval. Both generation times are in model intervals. For age \eqn{x}, survivorship \eqn{l_x} and daughters per mother \eqn{m_x}, the cohort weights are \eqn{l_x m_x}. Stable-population weights are \eqn{\lambda^{-x} l_x m_x}. They give the same mean maternal age at replacement. Use the stable-population \code{generation_time} for \code{\link{inbreeding_proxy_process}()}.)", + value = r"(A list with the projection \code{matrix}, dominant growth factor \code{lambda}, its logarithm \code{r}, lifetime daughters per newborn \code{R0}, stable mean maternal age \code{generation_time}, newborn-cohort mean maternal age \code{cohort_generation_time}, \code{stable_age} (sum one) and \code{reproductive_value} (inner product one with stable age). A cohort producing no daughters has undefined mean maternal age. Stable generation time is also \code{NA} when a non-breeding terminal class determines population growth. A zero or repeated dominant root gives undefined eigenvectors.)", + examples = r"(life_table_metrics(c(0.6, 0.8, 0.7), c(0, 0.5, 1.2))$generation_time)" + ), environment_processes = list( title = "Environmental variation and catastrophes", functions = c( "environment_process", "env_ar1", "env_trend", "spatial_correlation", "catastrophe_process", - "beta_shapes", "shift_logit" + "beta_shapes", "qbeta_norm", "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. The variable's own name is supplied as \code{context$variable}.)", @@ -269,11 +314,12 @@ out$events[, c("process_name", "event_type", "value")])" callback, "." ), global = "Name of the logical global that records whether the catastrophe occurred this interval.", - mean = "Mean of the beta distribution, in (0, 1).", - 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).)", + z = r"(Standard normal deviates for \code{qbeta_norm()}. Arguments may be scalar or have a common vector length.)", + mean = "Mean of the beta distribution in (0, 1).", + sd = r"(For \code{beta_shapes()} and \code{qbeta_norm()}, positive beta standard deviation with variance below mean times one minus mean. Values within eight machine epsilons of that limit, relative to the limit, are rejected. 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. \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.)", + 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{qbeta_norm()} maps a standard normal through its CDF and the beta quantile function, preserving a chosen beta mean and standard deviation. \code{beta_shapes()} converts moments 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. @@ -332,7 +378,7 @@ ceiling_density_multiplier(n, capacity = 100))" arguments = list( 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.", + generation_time = r"(Stable-population mean maternal age in model intervals for the effective-size approximation, as returned by \code{\link{life_table_metrics}()}.)", inbreeding = "Inbreeding coefficients in [0, 1].", lethal_equivalents = r"(Slope \code{B} of the log-linear cost \code{exp(-B * F)}.)", effective_size = paste0( @@ -386,7 +432,7 @@ summarise_pedigree(run_scenario(scenario, keep = "state")$states[[1]]))" keep = r"(Which outputs to retain: any of \code{"census"}, \code{"events"}, \code{"accounting"}, \code{"state"} (final states) and \code{"ledger"} (every individual that ever lived, with its fate). The default retains census, events and accounting. Request final states or ledgers explicitly.)" ), description = r"(\code{scenario_spec()} bundles an initial state, an ordered lifecycle and a replicate design. \code{run_scenario()} executes it serially or in parallel.)", - details = r"(Each replicate receives its own L'Ecuyer-CMRG stream, assigned before any work is dispatched, so results are bit-identical for a given seed whether replicates run serially, on fork workers or on a PSOCK cluster. After the optional root draw the caller's RNG kind and seed are restored, including on error. + details = r"(Each replicate receives its own L'Ecuyer-CMRG stream, assigned before any work is dispatched, so results are bit-identical for a given seed whether replicates run serially, on fork workers or on a PSOCK cluster. After the optional root draw the caller's RNG is restored, including a cached Box--Muller normal and on error. Provenance records substreams 0 (demography), 1 (ensemble builder), 2 and 3 (initial markers in a replicate and builder respectively), 4 (offspring segregation) and 5 (surveys). Managed socket workers start with \code{--vanilla}. Both runners propagate the parent library paths and export statically referenced callback helpers and data. A supplied cluster can initialise resources resolved dynamically by the model.)", value = r"(\code{scenario_spec()} returns a \code{pva_scenario}. \code{run_scenario()} returns a \code{pva_run}: a list with the scenario, data frames \code{census}, \code{events} and \code{accounting}, lists \code{states} and \code{ledgers}, and \code{provenance} (root seed, streams, validation mode, process plan and versions).)", @@ -411,7 +457,7 @@ all(summarise_accounting(run)$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.)", +\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. For the selected metric, \code{ema} is the mean of replicate minima across the evaluated censuses. The final two columns are \code{ema} and \code{ema_mcse}. The latter is the sample standard deviation of the minima divided by the square root of the replicate count (undefined for a single replicate).)", 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, @@ -448,7 +494,7 @@ all(summarise_accounting(run)$reconciled))" cache_key = "Optional revision string for model inputs read from external files or resolved dynamically." ), description = "Separates the outer design (structure, parameters, management) from the inner Monte Carlo replicates. Each member is built, run and reduced to its summary inside a worker, so memory use does not grow with the size of the design.", - details = r"(The builder and summary draw on a reproducible member substream. Cache entries record callback code and statically referenced inputs, package and R versions, the row, member seed, 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.)", + details = r"(The builder and summary draw on a reproducible member substream. Cache entries record callback code and statically referenced inputs, package and R versions, the row, member seed, full RNG specification (including the binomial generator when available), replicate count, validation mode and cache key. Member seeds are a deterministic function of \code{seed} and the design order, so the ensemble is reproducible and independent of the number of workers and of the backend.)", 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) { @@ -492,11 +538,12 @@ survival(pva_population(sex = c("F", "F", "M"), age = c(0, 5, 2)), NULL, NULL, N arguments = list( pop = "A columnar population.", patches = "Vector of the declared patch identifiers.", - destination = r"(Function of \code{(rows, pop, state, context, params)} returning one declared patch per eligible individual.)", + destination = r"(Function of \code{(rows, pop, state, context, params)} returning one declared patch per selected individual.)", + count = r"(Optional target number to move or a count function of \code{(state, context, params)}. Positive weights govern successive selection without replacement.)", transition = "Square row-stochastic matrix whose row and column names are the patch identifiers.", field = "Population field holding each individual's patch." ), - description = r"(\code{dispersal_process()} moves eligible individuals to modeller-chosen patches; \code{markov_dispersal_process()} draws each destination from a transition matrix. The \code{dispersal} event counts movers. Each \code{patch_transition} row reports one realised origin, destination and count, including eligible individuals who stayed. \code{patch_counts()} tabulates abundance by patch for patch-specific density feedback.)", + description = r"(\code{dispersal_process()} moves eligible individuals to modeller-chosen patches; \code{markov_dispersal_process()} draws each destination from a transition matrix. The \code{dispersal} event counts movers. Each \code{patch_transition} row reports one realised origin, destination and count, including selected individuals assigned their original patch. For a count target, \code{dispersal + dispersal_shortfall} equals the requested count. A selected animal assigned its current patch contributes one to the shortfall. Unselected animals stay in place. \code{patch_counts()} tabulates abundance by patch for patch-specific density feedback.)", value = r"(The constructors return a \code{pva_process}; \code{patch_counts()} returns a named integer vector.)", examples = r"(transition <- matrix(c(0.9, 0.1, 0.2, 0.8), 2, byrow = TRUE, dimnames = list(c("north", "south"), c("north", "south"))) @@ -510,7 +557,7 @@ patch_counts(moved$state$population, c("north", "south")))" 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. + 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 or a sire retained through \code{pva_state(mate_field = )} 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. diff --git a/tests/testthat/test-ancestry-propagation.R b/tests/testthat/test-ancestry-propagation.R new file mode 100644 index 0000000..75b40e0 --- /dev/null +++ b/tests/testthat/test-ancestry-propagation.R @@ -0,0 +1,42 @@ +test_that("depthless traced kinship agrees with tabular recursion across source blocks", { + founders <- diag(c(0.625, 0.5, 0.5, 0.5)) + founders[1L, 4L] <- founders[4L, 1L] <- 0.125 + state <- pva_state(pva_population(c("F", "M", "F", "M"), 2L), pedigree = TRUE, + kinship = founders, max_dense_kinship = 2L) + dams <- seq.int(5L, by = 2L, length.out = 70L) + sires <- dams + 1L + cohorts <- list( + cbind(rep(c(1L, 3L), 70L), rep(c(4L, 2L, NA_integer_, 4L), 35L)), + cbind(rev(dams), sires[c(2:70, 1L)]), + cbind(c(145L, 145L, 3L, NA_integer_), c(4L, 6L, 146L, 146L)) + ) + for (parents in cohorts) { + litter <- pva_process("litter", function(state, context, params) { + parents <- params$parents + state <- add_individuals(state, rep(c("F", "M"), length.out = nrow(parents)), 0L, + mother_id = parents[, 1L], father_id = parents[, 2L]) + pva_result(state, pva_events("birth", nrow(parents))) + }, params = list(parents = parents), creates = c("age", "sex")) + state <- execute_processes(state, list(litter))$state + } + expect_null(state$kinship[["depth"]]) + parents <- do.call(rbind, cohorts) + parents[is.na(parents)] <- 0L + n <- length(state$population$id) + # Row 1 is an unrecorded parent, unrelated to every animal. + K <- matrix(0, n + 1L, n + 1L) + K[2:5, 2:5] <- founders + for (j in seq_len(nrow(parents))) { + child <- 5L + j + prior <- seq_len(child - 1L) + m <- parents[j, 1L] + 1L + f <- parents[j, 2L] + 1L + K[child, prior] <- K[prior, child] <- (K[m, prior] + K[f, prior]) / 2 + K[child, child] <- (1 + K[m, f]) / 2 + } + K <- K[-1L, -1L] + expect_lt(max(abs(state$population$pedigree_F - (2 * diag(K) - 1))), 1e-13) + expect_lt(max(abs(kinship_matrix(state, rev(sires), dams) - K[rev(sires), dams])), 1e-13) + expect_lt(max(abs(kinship_matrix(state) - K)), 1e-13) + expect_lt(max(abs(mean_kinship(state) - rowMeans(K))), 1e-13) +}) diff --git a/tests/testthat/test-markers.R b/tests/testthat/test-markers.R index f718f04..b4240b3 100644 --- a/tests/testthat/test-markers.R +++ b/tests/testthat/test-markers.R @@ -304,7 +304,7 @@ test_that("marker uniforms preserve the cached Box-Muller normal and an absent s old <- .GlobalEnv$.Random.seed kind <- RNGkind() on.exit({ - do.call(RNGkind, as.list(kind)) + suppressWarnings(do.call(RNGkind, as.list(kind))) if (is.null(old)) rm(".Random.seed", envir = .GlobalEnv) else assign(".Random.seed", old, envir = .GlobalEnv) }) diff --git a/tests/testthat/test-sire-retention.R b/tests/testthat/test-sire-retention.R new file mode 100644 index 0000000..fe21e94 --- /dev/null +++ b/tests/testthat/test-sire-retention.R @@ -0,0 +1,202 @@ +sire_fixture <- function(limit, retain = TRUE) { + pva_state(pva_population( + c("F", "M", "F", "M", "M"), 4L, mate_id = NA_integer_, + coat = c("A", "B", "C", "red", "black"), + mother_id = c(NA, NA, 1L, 1L, NA), father_id = c(NA, NA, 2L, 2L, NA) + ), pedigree = TRUE, n_loci = 12L, max_dense_kinship = limit, + mate_field = if (retain) "mate_id") +} + +sire_lifecycle <- function() { + list( + mating_process(eligible = function(pop, state, context, params) pop$id %in% 3:4, + when = 0L), + removal_process(select = function(pop, state, context, params) { + context$time == 0L & pop$id %in% c(1L, 2L, 4L, 5L) + }), + reproduction_process( + function(pop, state, context, params) as.numeric(pop$id == 3L & context$time == 1L), + litter_categorical(2L, 1), offspring_sex_bernoulli(1), mate = mate_from_field(), + newborn_fields = function(mothers, fathers, pop, state, context, params) { + stopifnot(all(pop$sex[fathers] == "M"), all(!pop$alive[fathers]), + all(pop$id[fathers] == 4L), all(pop$alive[mothers]), + all(state$population$alive)) + list(coat = pop$coat[fathers], mate_id = NA_integer_) + }, newborn_field_names = c("mate_id", "coat") + ) + ) +} + +test_that("referenced sires transmit across censuses and expire with the last reference", { + set.seed(4201) + K <- tabular_kinship(data.frame( + id = 1:7, mother_id = c(NA, NA, 1L, 1L, NA, 3L, 3L), + father_id = c(NA, NA, 2L, 2L, NA, 4L, 4L) + )) + life <- sire_lifecycle() + clear <- assign_process("mate_id", NA_integer_, + select = function(pop, state, context, params) pop$id == 3L) + for (limit in c(50L, 1L)) for (dt in c(1, 0.25)) { + initial <- sire_fixture(limit) + father <- initial$markers$alleles[4L, ] + state <- execute_processes(initial, life, time = 0L, dt = dt)$state + expect_identical(state$population$id, 3L) + expect_identical(state$sires$records$id, 4L) + expect_identical(state$markers$id, 3:4) + if (limit == 50L) { + slots <- state$kinship$ids + expect_identical(slots[!is.na(slots)], 3:4) + } + expect_equal(summarise_markers(state)$n_living, 1L) + born <- execute_processes(state, life, time = 1L, dt = dt)$state + ids <- born$population$id + expect_identical(ids, c(3L, 6L, 7L)) + expect_identical(born$population$father_id[-1L], c(4L, 4L)) + expect_identical(born$population$coat[-1L], c("red", "red")) + expect_identical(born$population$pedigree_F[-1L], c(0.25, 0.25)) + expect_lt(max(abs(kinship_matrix(born) - K[ids, ids])), 1e-13) + loci <- seq_len(initial$markers$n_loci) + for (id in 6:7) { + inherited <- born$markers$alleles[match(id, born$markers$id), length(loci) + loci] + expect_true(all(inherited == father[loci] | inherited == father[length(loci) + loci])) + } + + for (end in list(clear, removal_process(select = function(pop, state, context, params) pop$id == 3L))) { + inspect <- pva_process("inspect", function(state, context, params) { + stopifnot(is.null(state$sires$records), !4L %in% state$markers$id) + if (!is.null(state$kinship$values)) stopifnot(!4L %in% state$kinship$ids) + pva_result(state) + }) + final <- execute_processes(born, list(end, inspect), time = 2L, dt = dt)$state + expect_identical(final$markers$id, final$population$id) + living <- final$population$id + expect_lt(max(abs(kinship_matrix(final) - K[living, living])), 1e-13) + illegal <- pva_process("late", function(state, context, params) { + pva_result(add_individuals(state, "F", 0, father_id = 4L, mate_id = NA_integer_, + coat = "red"), pva_events("birth", 1)) + }, creates = c("age", "sex", "mate_id", "coat")) + expect_error(execute_processes(final, list(illegal)), "unknown parent ID") + } + spec <- scenario_spec("seasonal", 2L, 2L, function() initial, life, dt = dt, seed = 29L) + result <- run_scenario(spec, keep = c("state", "accounting")) + expect_true(all(summarise_accounting(result)$reconciled)) + expect_identical(result$states[[2L]]$population, born$population) + } +}) + +test_that("sire attributes are available within an interval without persistent retention", { + state <- sire_fixture(20L, retain = FALSE) + life <- sire_lifecycle() + life[[3L]]$params$breeding_probability <- function(pop, state, context, params) as.numeric(pop$id == 3L) + out <- execute_processes(state, life) + expect_identical(out$state$population$coat, c("C", "red", "red")) + expect_identical(out$state$markers$id, out$state$population$id) + expect_null(out$state$sires) + expect_error(execute_processes(out$state, life, time = 1L), "recorded sire") +}) + +test_that("strict validation protects sire records and the declared sire field", { + state <- sire_fixture(50L) + edit <- pva_process("edit", function(state, context, params) { + state$sires$field <- "coat" + pva_result(state) + }) + expect_error(execute_processes(state, list(edit)), "engine-owned sire") + expect_error(pva_state(state$population[c("sex", "age")], mate_field = "unknown"), "mate_field") +}) + +test_that("declared mate IDs cannot anticipate a future allocation", { + pop <- pva_population(c("F", "M"), 2L, mate_id = c(2L, NA_integer_)) + initial <- pva_state(pop, mate_field = "mate_id") + for (bad in c(1L, 3L)) { + pop$mate_id[1L] <- bad + expect_error(pva_state(pop, mate_field = "mate_id"), "living initial males") + } + female <- function(pop, ...) pop$sex == "F" + future <- assign_process("mate_id", 3L, select = female) + release <- introduction_process(1L, function(...) list(sex = "M", age = 2L, mate_id = NA_integer_), + creates = "mate_id") + for (mode in c("strict", "fast")) { + expect_error(execute_processes(initial, list(future, release), validation = mode), "unallocated") + } + stale <- execute_processes(initial, list(assign_process("mate_id", NA_integer_, select = female), + removal_process(select = function(pop, ...) pop$sex == "M")))$state + observed <- execute_processes(stale, list(assign_process("mate_id", 2L, select = female)))$state + mate <- mate_from_field(stale = "unpaired") + expect_identical(mate(observed$population, observed, list(), list()), NA_integer_) + expect_null(observed$sires$records) +}) + +test_that("entry reconciles both directions of the dense slots and retained sire records", { + retained <- execute_processes(sire_fixture(50L), sire_lifecycle(), time = 0L)$state + check <- function(state) validate_processes(list(census_process()), state) + expect_silent(check(retained)) + x <- retained + x["markers"] <- list(NULL) + x$sires["records"] <- list(NULL) + expect_error(check(x), "occupied dense kinship slots") + x <- retained + x$kinship$ids[x$kinship$ids %in% 3L] <- NA_integer_ + expect_error(check(x), "occupied dense kinship slots") + x <- retained + x$kinship$values[3L, 4L] <- 0.01 + expect_error(check(x), "symmetric") + x$kinship$values[3L, 4L] <- x$kinship$values[4L, 3L] <- 1.1 + expect_error(check(x), "in \\[0, 1\\]") + x <- retained + x$sires$records$age <- -1L + expect_error(check(x), "age") + x <- retained + x$sires$records$coat <- 5L + expect_error(check(x), "sire records") + x <- retained + x$sires$records$coat <- structure("red", class = "label") + expect_error(check(x), "sire records") + x <- retained + x$sires$records$id <- x$next_id + expect_error(check(x), "slot|sire records") + x <- retained + x$markers <- OpenPVA:::.marker_release(x$markers, x$population$id) + expect_error(check(x), "neutral-locus store") + legacy <- pva_state(pva_population("F", 1L), pedigree = TRUE) + expect_length(legacy, 6L) + expect_silent(check(legacy)) +}) + +test_that("late mate designation can recover attributes after an intervening pairing", { + initial <- sire_fixture(20L, retain = FALSE) + litter <- sire_lifecycle()[[3L]] + lose <- removal_process(select = function(pop, ...) pop$id != 3L) + pair <- pairing_process(function(pop, ...) rep(TRUE, length(pop$id))) + routine <- list(lose, pair, litter) + expect_false(any(OpenPVA:::.prepare_execution(routine)$snapshot_sires[1:2])) + late <- assign_process("mate_id", 4L, select = function(pop, ...) pop$sex == "F") + life <- list(lose, pair, late, litter) + expect_true(OpenPVA:::.prepare_execution(life)$snapshot_sires[1L]) + out <- execute_processes(initial, life, time = 1L)$state + expect_identical(out$population$father_id[-1L], c(4L, 4L)) + expect_identical(out$population$coat, c("C", "red", "red")) + expect_identical(out$population$pedigree_F[-1L], c(0.25, 0.25)) +}) + +test_that("two dams share one retained genotype through a dense-to-traced conversion", { + initial <- pva_state(pva_population(c("F", "F", "M"), 3L, mate_id = NA_integer_), + pedigree = TRUE, n_loci = 3L, max_dense_kinship = 3L, mate_field = "mate_id") + stored <- execute_processes(initial, list(mating_process(), + removal_process(select = function(pop, ...) pop$sex == "M")))$state + expect_identical(stored$sires$records$id, 3L) + clear_one <- assign_process("mate_id", NA_integer_, select = function(pop, ...) pop$id == 1L) + births <- reproduction_process(1, litter_categorical(2L, 1), offspring_sex_bernoulli(1), + mate = mate_from_field(), newborn_fields = function(...) list(mate_id = NA_integer_), + newborn_field_names = "mate_id") + born <- execute_processes(stored, list(clear_one, births), time = 1L)$state + expect_null(born$kinship$values) + expect_identical(born$population$father_id, c(NA_integer_, NA_integer_, 3L, 3L)) + expect_identical(born$sires$records$id, 3L) + expect_identical(born$markers$id, 1:5) + expect_identical(kinship_matrix(born, 4L, 5L)[1L, 1L], 0.25) + final <- execute_processes(born, list(removal_process(select = function(pop, ...) pop$id == 2L)), + time = 2L)$state + expect_null(final$sires$records) + expect_identical(final$markers$id, c(1L, 4L, 5L)) +}) diff --git a/tests/testthat/test-state.R b/tests/testthat/test-state.R index 4493286..d5adc95 100644 --- a/tests/testthat/test-state.R +++ b/tests/testthat/test-state.R @@ -58,3 +58,58 @@ test_that("add_individuals allocates ids and demands complete initialisation", { ) expect_error(add_individuals(state, sex = "F", age = 0L, patch = 1L), "has type") }) + +test_that("population constructors strip vector names and reject other attributes", { + pop <- pva_population( + sex = c(f1 = "F", m1 = "M"), + age = c(f1 = 2L, m1 = 3L), + patch = c(north = "a"), + trait = c(f1 = 1.5, m1 = 2.5), + mate_id = c(f1 = 2L, m1 = NA_integer_) + ) + expect_null(attributes(pop$age)) + expect_null(attributes(pop$patch)) + expect_null(attributes(pop$trait)) + expect_null(attributes(pop$mate_id)) + + expect_error( + pva_population(sex = "F", age = 1L, stage = factor("adult")), + "without attributes" + ) + expect_error( + pva_population(sex = "F", age = 1L, trait = structure(1, tag = "x")), + "without attributes" + ) + + state <- pva_state(pop, mate_field = "mate_id") + grown <- add_individuals( + state, + sex = c(f2 = "F"), + age = c(f2 = 1L), + patch = c(p = "b"), + trait = c(t = 3.5), + mate_id = c(m = NA_integer_) + ) + expect_null(attributes(grown$population$trait)) + expect_error( + add_individuals( + state, + sex = "F", + age = 1L, + patch = "b", + trait = structure(3.5, tag = "x"), + mate_id = NA_integer_ + ), + "without attributes" + ) + + kill_males <- survival_process(function(pop, state, context, params) { + ifelse(pop$sex == "M", 0, 1) + }) + for (mode in c("strict", "fast")) { + step1 <- execute_processes(state, list(kill_males), validation = mode) + expect_identical(step1$state$sires$records$id, 2L) + step2 <- execute_processes(step1$state, list(census_process()), validation = mode) + expect_identical(step2$state$sires$records$id, 2L) + } +}) diff --git a/tests/testthat/test-statistical-oracles.R b/tests/testthat/test-statistical-oracles.R new file mode 100644 index 0000000..00927a3 --- /dev/null +++ b/tests/testthat/test-statistical-oracles.R @@ -0,0 +1,194 @@ +test_that("categorical litters and newborn sex preserve constant draws and follow maternal rates", { + pop <- pva_population(c("F", "M", "F"), age = c(1L, 3L, 4L)) + mothers <- rep(c(3L, 1L, 1L), 20L) + sizes <- c(0L, 2L, 4L) + probability <- c(0.2, 0.3, 0.5) + set.seed(450L) + expected <- sizes[sample.int(3L, length(mothers), replace = TRUE, prob = probability)] + expected_sex <- ifelse(stats::runif(length(mothers)) < 0.42, "F", "M") + after <- .Random.seed + for (p in list(probability, function(...) probability)) { + set.seed(450L) + expect_identical(litter_categorical(sizes, p)(mothers, pop, NULL, NULL, NULL), expected) + expect_identical(offspring_sex_bernoulli(0.42)(mothers, pop, NULL, NULL, NULL), expected_sex) + expect_identical(.Random.seed, after) + } + + state <- pva_state(pop, globals = list(female = 0.65)) + conditional <- function(pop, state, context, params) { + cbind(as.numeric(pop$age == 1L), as.numeric(pop$age == 3L), as.numeric(pop$age == 4L)) + } + expect_identical(litter_categorical(sizes, conditional)(mothers, pop, state, NULL, NULL), + c(4L, 0L, 0L)[rep(1:3, 20L)]) + sex <- offspring_sex_bernoulli(function(pop, state, context, params) { + ifelse(pop$age == context$age, state$globals$female, params$other) + }) + set.seed(81L) + reference <- ifelse(stats::runif(length(mothers)) < c(0.1, 0, 0.65)[mothers], "F", "M") + set.seed(81L) + expect_identical(sex(mothers, pop, state, list(age = 4L), list(other = 0.1)), reference) + expect_error(litter_categorical(sizes, function(...) matrix(1, 2, 3))( + mothers, pop, state, NULL, NULL), "match") + expect_error(litter_categorical(sizes, function(...) matrix(0, 3, 3))( + mothers, pop, state, NULL, NULL), "sum to 1") + expect_error(offspring_sex_bernoulli(function(...) NaN)(mothers, pop, state, NULL, NULL), + "female_probability") +}) + +test_that("normal-to-beta transform preserves both moments and Gaussian copula ranks", { + sigma <- 0.07 + for (mu in c(0.05, 0.5, 0.95)) { + rate <- function(z) qbeta_norm(z, mu, sigma) + moment <- stats::integrate(function(z) stats::dnorm(z) * rate(z), + -Inf, Inf, rel.tol = 1e-12)$value + variance <- stats::integrate(function(z) stats::dnorm(z) * (rate(z) - mu)^2, + -Inf, Inf, rel.tol = 1e-12)$value + expect_lt(abs(moment - mu), 1e-10) + expect_lt(abs(sqrt(variance) - sigma), 1e-10) + expect_error(qbeta_norm(0, mu, sqrt(mu * (1 - mu))), "too large") + } + expect_error(qbeta_norm(1, 0.9, 0.4), "too large") + expect_error(qbeta_norm(c(-1, 0, 1), c(0.2, 0.5), 0.01), "length") + expect_identical(qbeta_norm(c(-Inf, Inf), 0.5, 0.1), c(0, 1)) + boundary <- sqrt(0.95 * 0.05) + expect_error(beta_shapes(0.95, boundary), "too large") + expect_error(qbeta_norm(1, 0.95, boundary), "too large") + expect_gt(beta_shapes(0.95, boundary * (1 - 1e-10))$shape2, 0) + expect_equal(qbeta_norm(c(-40, 40), 0.5, 0.01), + c(1 - 0.8438410024043705, 0.8438410024043705), tolerance = 1e-12) + expect_equal(qbeta_norm(40, c(0.5, 0.9), 0.01), + c(qbeta_norm(40, 0.5, 0.01), qbeta_norm(40, 0.9, 0.01))) + + rho <- 0.6 + draw <- env_ar1(cor = matrix(c(1, rho, rho, 1), 2L)) + set.seed(20261130L) + normals <- replicate(12000L, draw(list(globals = list()), list(variable = "weather"), NULL)) + x <- qbeta_norm(normals[1L, ], 0.05, sigma) + y <- qbeta_norm(normals[2L, ], 0.95, sigma) + theoretical <- 6 / pi * asin(rho / 2) + batches <- split(seq_along(x), rep(seq_len(40L), each = 300L)) + correlations <- vapply(batches, function(i) stats::cor(x[i], y[i], method = "spearman"), + numeric(1)) + mcse <- stats::sd(correlations) / sqrt(length(batches)) + expect_lt(abs(stats::cor(x, y, method = "spearman") - theoretical), mcse) +}) + +test_that("both census matrices satisfy cohort renewal, replacement and eigenvector identities", { + s <- c(0.5, 0.8, 0.75, 0) + b <- c(0, 0.3, 1.4, 2.2) + births <- c(0.5 * 0.3, 0.4 * 1.4, 0.3 * 2.2) + post <- rbind(c(0.15, 1.12, 1.65, 0), c(0.5, 0, 0, 0), + c(0, 0.8, 0, 0), c(0, 0, 0.75, 0)) + pre <- rbind(c(0.15, 0.7, 1.1), c(0.8, 0, 0), c(0, 0.75, 0)) + for (timing in c("post_breeding", "pre_breeding")) { + life <- life_table_metrics(s, b, timing) + expect_equal(unname(life$matrix), if (timing == "post_breeding") post else pre) + expect_lt(abs(sum(births / life$lambda^(1:3)) - 1), 1e-12) + expect_equal(life$R0, sum(births)) + expect_equal(life$generation_time, sum(1:3 * births / life$lambda^(1:3))) + expect_equal(life$cohort_generation_time, sum(1:3 * births) / sum(births)) + expect_equal(life$r, log(life$lambda)) + expect_equal(sum(life$stable_age), 1) + expect_equal(sum(life$stable_age * life$reproductive_value), 1) + expect_lt(max(abs(drop(life$matrix %*% life$stable_age) - life$lambda * life$stable_age)), + 1e-12) + expect_lt(max(abs(drop(life$reproductive_value %*% life$matrix) - + life$lambda * life$reproductive_value)), 1e-12) + for (scale in c(0.7, 1, 1.3)) { + replacement <- life_table_metrics(s, b * scale / sum(births), timing) + expect_lt(abs(replacement$R0 - scale), 1e-12) + if (scale == 1) { + expect_lt(abs(replacement$lambda - 1), 1e-12) + expect_equal(replacement$generation_time, replacement$cohort_generation_time) + } else { + expect_equal(sign(replacement$lambda - 1), sign(scale - 1)) + } + } + + plus <- life_table_metrics(s[1:3], b[1:3], timing) + terminal <- births[2L] / (1 - 0.75) + expect_equal(plus$R0, births[1L] + terminal) + expect_equal(plus$cohort_generation_time, + (births[1L] + (2 + 0.75 / 0.25) * terminal) / plus$R0) + ages <- 1:200 + cohort_births <- c(births[1L], births[2L] * 0.75^(ages[-1L] - 2L)) + expect_equal(plus$generation_time, sum(ages * cohort_births / plus$lambda^ages)) + expect_lt(abs(births[1L] / plus$lambda + + births[2L] / plus$lambda^2 / (1 - 0.75 / plus$lambda) - 1), 1e-12) + single <- life_table_metrics(0.8, 0.4, timing) + expect_equal(c(single$lambda, single$R0, single$generation_time, single$cohort_generation_time), + c(1.12, 1.6, 3.5, 5)) + semelparous <- life_table_metrics(0.8, 0.4, timing, plus_group = FALSE) + expect_equal(c(semelparous$lambda, semelparous$R0, semelparous$generation_time), + c(0.32, 0.32, 1)) + finite <- life_table_metrics(c(s[1:3], 1), b, timing, plus_group = FALSE) + expect_equal(finite, life) + senescent <- life_table_metrics(c(0.5, 0.6, 0.95), c(0, 1, 0), timing) + expect_equal(c(senescent$lambda, senescent$cohort_generation_time), c(0.95, 1)) + expect_identical(senescent$generation_time, NA_real_) + } + infertile <- life_table_metrics(c(0.7, 0), c(0, 0)) + expect_identical(c(infertile$lambda, infertile$r, infertile$R0), c(0, -Inf, 0)) + expect_true(is.na(infertile$generation_time) && all(is.na(infertile$stable_age))) + expect_error(life_table_metrics(c(0.7, 1), c(0, 1)), "terminal survival") + expect_error(life_table_metrics(c(0.7, 0), c(0.01, 1)), "age 0") + expect_error(life_table_metrics(c(0.7, 0), c(0, 1), plus_group = NA), "plus_group") +}) + +test_that("female cohort projections match stochastic pre- and post-breeding censuses", { + survival <- c(0.5, 0.8, 0.75, 0) + fecundity <- c(0, 0.3, 1.4, 2.2) + survive <- survival_process(function(pop, state, context, params) survival[pop$age + 1L]) + breed <- reproduction_process(1, litter_poisson(function(pop, state, context, params) { + fecundity[pop$age + 1L] + }), offspring_sex_bernoulli(1)) + for (timing in c("post_breeding", "pre_breeding")) { + life <- life_table_metrics(survival, fecundity, timing) + post <- timing == "post_breeding" + processes <- if (post) list(survive, age_process(), breed) else list(breed, survive, age_process()) + ages <- if (post) 0:3 else 1:3 + n <- c(13L, 19L, 11L, 7L)[ages + 1L] + initial <- pva_population(rep("F", sum(n)), rep(ages, n)) + spec <- scenario_spec(timing, 240L, 3L, function() initial, + c(processes, list(census_process())), seed = 20261130L) + result <- run_scenario(spec, keep = "census") + observed <- summarise_trajectory(result) + expected <- numeric(3L) + for (i in seq_along(expected)) { + n <- life$matrix %*% n + expected[i] <- sum(n) + } + expect_lt(max(abs(observed$mean - expected) / observed$mcse), 3) + } +}) + +test_that("EMA uses the minimum of each selected path including absorbing extinction", { + n <- rbind(c(1, 5, 2, 7), c(7, 3, 0, 0), c(3, 6, 4, 5)) + census <- data.frame(run = rep(1:3, each = 4L), time = rep(c(0L, 0:2), 3L), + phase = rep(c("initial", rep("interval", 3L)), 3L), + process_name = "counts", n_alive = as.vector(t(n))) + for (initial in c(FALSE, TRUE)) { + out <- summarise_pva(census, include_initial = initial) + minima <- if (initial) c(1, 0, 3) else c(2, 0, 4) + expect_equal(out$ema, mean(minima)) + expect_equal(out$ema_mcse, stats::sd(minima) / sqrt(3)) + } + single <- summarise_pva(census[census$run == 1L, ]) + expect_identical(single$ema, 1) + expect_true(is.na(single$ema_mcse)) + + spec <- scenario_spec("absorbing", 80L, 4L, function() pva_population(c("F", "F"), 1L), + list(survival_process(0.6), + reproduction_process(1, litter_poisson(0.65), offspring_sex_bernoulli(1)), + census_process()), seed = 17L) + run <- run_scenario(spec, keep = "census") + paths <- split(run$census$n_alive, run$census$run) + minima <- vapply(paths, min, numeric(1)) + expect_true(any(minima == 0)) + expect_true(all(vapply(paths[minima == 0], function(z) all(z[match(0, z):length(z)] == 0), + logical(1)))) + expect_true(any(minima < vapply(paths, function(z) z[length(z)], numeric(1)))) + out <- summarise_pva(run) + expect_equal(out$ema, mean(minima)) + expect_equal(out$ema_mcse, stats::sd(minima) / sqrt(length(minima))) +}) diff --git a/tests/testthat/test-summaries-ensemble.R b/tests/testthat/test-summaries-ensemble.R index 906d2c6..f662edf 100644 --- a/tests/testthat/test-summaries-ensemble.R +++ b/tests/testthat/test-summaries-ensemble.R @@ -11,6 +11,9 @@ census_fixture <- function() { test_that("viability summaries follow their definitions", { summary <- summarise_pva(census_fixture(), threshold = 2) + expect_identical(tail(names(summary), 7L), + c("final_q05", "final_q25", "final_median", "final_q75", "final_q95", + "ema", "ema_mcse")) expect_identical(summary$n_runs, 4L) expect_identical(summary$horizon, 4L) expect_equal(summary$p_below_at_horizon, 0.25) @@ -241,6 +244,36 @@ test_that("cache receipts include callbacks, their captured inputs and run revis expect_identical(key$revision$validation, "fast") }) +test_that("ensemble members, socket workers and cache receipts share the full RNG kind", { + build <- function(row) { + draw <- stats::rbinom(1L, 1000L, 0.4) + list(n_steps = 1L, init_fun = function() pva_state(pva_population("F", draw)), + processes = list(census_process())) + } + summary <- function(result, row) { + data.frame(builder = result$scenario$init_fun()$population$age, + header = result$provenance$streams[[1L]][1L], + kind = paste(result$provenance$rng_kind, collapse = "/")) + } + design <- data.frame(x = 1:2) + cache <- tempfile() + kinds <- RNGkind() + on.exit(suppressWarnings(do.call(RNGkind, as.list(kinds)))) + methods <- if (length(kinds) == 4L) c("Buggy BTPE", "BTPE") else "default" + for (method in methods) { + if (length(kinds) == 4L) suppressWarnings(do.call(RNGkind, list(binom.kind = method))) + serial <- run_pva_ensemble(design, build, 1L, summary, seed = 11L, cache_dir = cache) + socket <- run_pva_ensemble(design, build, 1L, summary, seed = 11L, workers = 2L, + backend = "psock") + expect_identical(socket, serial) + effective <- c("L'Ecuyer-CMRG", "Inversion", "Rejection", if (length(kinds) == 4L) method) + expect_identical(unique(serial$kind), paste(effective, collapse = "/")) + expect_identical(attr(serial, "provenance")$rng_kind, effective) + expect_identical(readRDS(file.path(cache, "member-000001.rds"))$key$revision$rng_kind, + effective) + } +}) + test_that("stochastic builders and summaries use a reproducible member substream", { build <- function(row) { individuals <- sample.int(100L, 1L) diff --git a/tests/testthat/test-survey.R b/tests/testthat/test-survey.R new file mode 100644 index 0000000..1597d32 --- /dev/null +++ b/tests/testthat/test-survey.R @@ -0,0 +1,241 @@ +test_that("two-animal detections and zero-triggered releases match their exact distribution", { + n <- 2048L + monitor <- survey_process(function(pop, state, context, params) c(1, 3) / 4) + quota <- survey_quota(rule = function(obs, state, context, params) as.integer(obs$count == 0)) + release <- introduction_process(quota, function(n, state, context, params) list(sex = "F", age = 1L)) + spec <- scenario_spec("two animals", n, 1L, function() pva_population(c("F", "M"), 1L), + list(monitor, release, census_process()), seed = 217L) + result <- run_scenario(spec) + detections <- result$events$value[result$events$event_type == "survey_detection"] + observed <- tabulate(detections + 1L, 3L) / n + expected <- c(3, 10, 3) / 16 + expect_length(detections, n) + expect_true(all(abs(observed - expected) < 3 * sqrt(expected * (1 - expected) / n))) + expect_equal(result$census$n_alive, 2L + (detections == 0L)) + expect_lt(abs(mean(result$census$n_alive) - (2 + 3/16)), 3 * sqrt((3/16) * (13/16) / n)) + expect_identical(unique(result$events$event_type), + c("survey_visit", "survey_detection", "introduction")) + expect_true(all(result$accounting$n_after == result$accounting$n_before + + result$accounting$introductions)) +}) + +test_that("survey records distinguish an observed zero, a skip, and a stale observation", { + state <- pva_state(pva_population(c("F", "M"), 1L)) + called <- survey_process(1, eligible = function(pop, ...) pop$sex == "F", when = c(0L, 2L)) + rule <- function(obs, state, context, params) params$quota + obs$count + quota <- survey_quota(rule = rule, on_skip = 0L) + release <- introduction_process(quota, function(n, ...) list(sex = "F", age = 0L), + params = list(quota = 2L)) + first <- execute_processes(state, list(called, release), dt = 0.25) + expect_identical(unclass(first$state$globals$survey), + list(run = 1L, time = 0L, dt = 0.25, phase = "interval", + visited = TRUE, count = 1L, ids = 1L)) + expect_identical(first$events$value, c(1, 1, 3)) + expect_error(execute_processes(state, list(release), dt = 0.25), "requires|missing") + expect_error(execute_processes(first$state, list(release), time = 1, dt = 0.25), "stale") + expect_error(execute_processes(first$state, list(release), run = 2L, dt = 0.25), "stale") + expect_error(execute_processes(first$state, list(release), dt = 1), "stale") + expect_error(execute_processes(first$state, list(release), dt = 0.25), "stale") + reused <- scenario_spec("another scenario", 1L, 1L, function() first$state, + list(release), seed = 3L, dt = 0.25) + expect_error(run_scenario(reused), "stale") + second <- execute_processes(first$state, list(called, release), time = 1, dt = 0.25) + expect_identical(unclass(second$state$globals$survey), + list(run = 1L, time = 1L, dt = 0.25, phase = "interval", + visited = FALSE, count = NA_integer_, ids = integer())) + expect_identical(second$state$survey_seed, first$state$survey_seed) + expect_identical(second$events$event_type, c("survey_skip", "introduction")) + expect_identical(second$events$value, c(1, 0)) + context <- list(run = 1L, time = 1L, dt = 0.25, phase = "interval") + skip_rule <- function(obs, state, context, params) if (is.na(obs$count)) params$n + expect_identical(survey_quota(rule = rule, on_skip = skip_rule)( + second$state, context, list(n = 4)), 4L) + expect_error(survey_quota(rule)(second$state, context, list()), "skipped") + expect_error(survey_quota(rule = rule, on_skip = -1), "on_skip") + expect_error(survey_process(2), "detection") + expect_error(execute_processes(state, list(survey_process(1, when = function(...) NA))), "when") + no_animals <- pva_state(pva_population(character(), integer())) + zero <- execute_processes(no_animals, list(survey_process(1)))$state$globals$survey + expect_identical(zero$count, 0L) + expect_identical(zero$ids, integer()) + expect_true(zero$visited) +}) + +test_that("standalone surveys advance foreign CMRG words and preserve caller normals", { + OpenPVA:::.with_rng_restored({ + initial <- pva_state(pva_population(rep("F", 12L), 1L)) + OpenPVA:::.set_pva_seed(74L) + native <- .GlobalEnv$.Random.seed + detected <- which(stats::runif(12L) < 0.5) + advanced <- .GlobalEnv$.Random.seed + next_normal <- function() { + set.seed(18L, "Mersenne-Twister", "Box-Muller") + stats::rnorm(1L) + .GlobalEnv$.Random.seed + } + next_normal() + expected <- stats::rnorm(1L) + for (header in c(10407L, 110407L)) { + initial$survey_seed <- native + initial$survey_seed[1L] <- header + before <- next_normal() + state <- expect_no_warning(execute_processes(initial, list(survey_process(0.5))))$state + expect_identical(.GlobalEnv$.Random.seed, before) + expect_identical(stats::rnorm(1L), expected) + expect_identical(state$globals$survey$ids, detected) + expect_identical(state$survey_seed, c(header, advanced[-1L])) + before <- next_normal() + broken <- survey_process(function(...) { stats::rnorm(3L); stop("callback failed") }) + expect_error(execute_processes(initial, list(broken)), "callback failed") + expect_identical(.GlobalEnv$.Random.seed, before) + expect_identical(stats::rnorm(1L), expected) + expect_identical(initial$survey_seed, c(header, native[-1L])) + } + }) +}) + +test_that("saved surveys with source references retain their private stream on workers", { + monitor <- survey_process(0.5) + callback <- monitor$run + body(callback) <- parse(text = deparse(body(callback)), keep.source = TRUE)[[1L]] + monitor$run <- unserialize(serialize(callback, NULL)) + model <- scenario_spec("saved survey", 2L, 2L, function() pva_population(c("F", "M"), 1L), + list(monitor), seed = 23L) + serial <- run_scenario(model, keep = "state") + socket <- run_scenario(model, parallel = TRUE, workers = 2L, backend = "psock", keep = "state") + expect_identical(serial$states, socket$states) + expect_length(serial$states[[1L]]$survey_seed, 7L) + edit <- pva_process("survey", function(state, context, params) { + state$survey_seed <- parallel::nextRNGSubStream(state$survey_seed) + pva_result(state) + }) + expect_error(execute_processes(serial$states[[1L]], list(edit)), "engine-owned survey") +}) + +test_that("all surveys consume replicate substream five in process and interval order", { + init <- function() { + stats::runif(5L) + pva_population(c("F", "M", "F"), 1L) + } + two_fields <- list(survey_process(0.4, field = "north"), + survey_process(0.8, field = "south", when = c(0L, 2L))) + run <- run_scenario(scenario_spec("two surveys", 3L, 3L, init, two_fields, seed = 197L), + keep = c("state", "events")) + expect_identical(run$provenance$substreams[["survey"]], 5L) + for (i in seq_along(run$states)) { + cursor <- run$provenance$streams[[i]] + for (j in seq_len(5L)) cursor <- parallel::nextRNGSubStream(cursor) + reference <- OpenPVA:::.with_rng_restored({ + assign(".Random.seed", cursor, envir = .GlobalEnv) + counts <- vapply(c(0.4, 0.8, 0.4, 0.4, 0.8), function(p) sum(stats::runif(3L) < p), + integer(1)) + list(counts = counts, cursor = .GlobalEnv$.Random.seed) + }) + rows <- run$events$run == i & run$events$event_type == "survey_detection" + expect_equal(run$events$value[rows], reference$counts) + expect_identical(run$states[[i]]$survey_seed, reference$cursor) + expect_identical(run$events$label[rows], c("north", "south", "north", "north", "south")) + } +}) + +test_that("observation alone leaves demographic histories, genotypes and pedigree identical on all backends", { + base <- managed_scenario(limit = 14L, n_loci = 8L, n_runs = 4L, n_steps = 5L, seed = 31L) + view <- survey_process( + function(pop, state, context, params) stats::pnorm(stats::rnorm(length(pop$id))), + when = function(state, context, params) stats::runif(1L) < 0.8, name = "monitor") + observed <- base + observed$processes <- c(observed$processes, list(view)) + keep <- c("census", "events", "accounting", "ledger", "state") + truth <- run_scenario(base, keep = keep) + serial <- run_scenario(observed, keep = keep) + for (backend in c("psock", if (.Platform$OS.type != "windows") "fork")) { + other <- run_scenario(observed, parallel = TRUE, backend = backend, workers = 2L, keep = keep) + compare <- c("states", "events", "census", "accounting", "ledgers", "provenance") + expect_identical(other[compare], serial[compare]) + } + expect_identical(serial$census, truth$census) + expect_identical(serial$ledgers, truth$ledgers) + demographic_events <- serial$events[serial$events$process_name != "monitor", , drop = FALSE] + rownames(demographic_events) <- NULL + expect_identical(demographic_events, truth$events) + accounts <- serial$accounting[serial$accounting$process_index <= length(base$processes), ] + rownames(accounts) <- NULL + expect_identical(accounts, truth$accounting) + for (i in seq_along(truth$states)) { + expect_identical(serial$states[[i]]$population, truth$states[[i]]$population) + expect_identical(serial$states[[i]]$kinship, truth$states[[i]]$kinship) + expect_identical(serial$states[[i]]$markers, truth$states[[i]]$markers) + } +}) + +test_that("survey evaluation and seeded runners preserve the caller's pending Box-Muller deviate", { + old <- .GlobalEnv$.Random.seed + kind <- RNGkind() + on.exit({ + suppressWarnings(do.call(RNGkind, as.list(kind))) + if (is.null(old)) rm(".Random.seed", envir = .GlobalEnv) else + assign(".Random.seed", old, envir = .GlobalEnv) + }) + survey <- survey_process(function(pop, ...) stats::pnorm(stats::rnorm(length(pop$id))), + when = function(...) { stats::rnorm(1L); TRUE }) + broken <- survey_process(function(...) { stats::rnorm(1L); stop("detection failed") }) + init <- function() pva_population(c("F", "M"), 1L) + state <- pva_state(init()) + build <- function(row) list(n_steps = 1L, init_fun = init, processes = list(survey, census_process())) + spec <- scenario_spec("observed", 2L, 1L, init, list(survey), seed = 1L) + probe <- function(action, uniform) { + set.seed(276L, uniform, "Box-Muller") + stats::rnorm(1L) + action() + list(seed = .GlobalEnv$.Random.seed, kind = RNGkind(), normals = stats::rnorm(3L)) + } + actions <- list(function() execute_processes(state, list(survey)), + function() expect_error(execute_processes(state, list(broken)), "detection failed"), + function() run_scenario(spec), + function() run_scenario(spec, parallel = TRUE, backend = "psock"), + function() run_pva_ensemble(data.frame(x = 1L), build, n_runs = 2L, seed = 1L), + function() { + spec$processes <- list(broken) + expect_error(run_scenario(spec), "detection failed") + }) + if (.Platform$OS.type != "windows") { + actions <- c(actions, list(function() run_scenario(spec, parallel = TRUE, backend = "fork"))) + } + for (uniform in c("Mersenne-Twister", "L'Ecuyer-CMRG")) { + expected <- probe(function() NULL, uniform) + for (action in actions) expect_identical(probe(action, uniform), expected) + } + rm(".Random.seed", envir = .GlobalEnv) + invisible(execute_processes(state, list(survey))) + expect_false(exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) + invisible(run_scenario(spec)) + expect_false(exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) +}) + +test_that("CMRG roots equal base R including rejected and signed-NA generator words", { + seeds <- c(0L, 1L, 217L, .Machine$integer.max, 1741922965L, 75348296L, 1303866489L) + OpenPVA:::.with_rng_restored({ + for (seed in seeds) { + set.seed(seed, "L'Ecuyer-CMRG", "Inversion", "Rejection") + reference <- .GlobalEnv$.Random.seed + OpenPVA:::.set_pva_seed(seed) + expect_identical(.GlobalEnv$.Random.seed, reference) + } + }) + expect_identical(OpenPVA:::.pva_rng_header(100203L), 110407L) + expect_identical(OpenPVA:::.pva_rng_header(1000203L), 1010407L) + if ("binom.kind" %in% names(formals(RNGkind))) { + for (method in c("Buggy BTPE", "BTPE")) { + OpenPVA:::.with_rng_restored({ + suppressWarnings(do.call(set.seed, list(seed = 23L, kind = "L'Ecuyer-CMRG", + normal.kind = "Inversion", sample.kind = "Rejection", binom.kind = method))) + base_seed <- .GlobalEnv$.Random.seed + probe <- scenario_spec("root", 1L, 1L, function() pva_population("F", 1L), + list(survey_process(0.5)), seed = 23L) + result <- run_scenario(probe, keep = "state") + expect_identical(result$provenance$streams[[1L]], base_seed) + expect_identical(result$states[[1L]]$survey_seed[1L], base_seed[1L]) + }) + } + } +}) diff --git a/tests/testthat/test-targeted-management.R b/tests/testthat/test-targeted-management.R new file mode 100644 index 0000000..a94dbb1 --- /dev/null +++ b/tests/testthat/test-targeted-management.R @@ -0,0 +1,328 @@ +test_that("all four weighted count constructors use the exact successive urn", { + urn <- function(w, k) { + flags <- 2^(seq_along(w) - 1L) + mass <- c(1, numeric(2^length(w) - 1L)) + for (step in seq_len(k)) { + next_mass <- numeric(length(mass)) + for (i in which(mass > 0)) { + free <- bitwAnd(i - 1L, flags) == 0L & w > 0 + dest <- i + flags[free] + next_mass[dest] <- next_mass[dest] + mass[i] * w[free] / sum(w[free]) + } + mass <- next_mass + } + mass + } + trials <- 20000L + w <- c(0, 1, 2, 3, 5, 8) + flags <- 2^(seq_along(w) - 1L) + pick <- OpenPVA:::.pick_rows + state <- pva_state(adult_population(3L, 3L, w = w, patch_id = "a", treated = FALSE)) + weights <- function(pop, ...) pop$w + for (k in 2:3) { + set.seed(700L + k) + masks <- replicate(trials, sum(flags[pick(seq_along(w), k, "random", w)])) + model <- urn(w, k) + counts <- tabulate(masks + 1L, nbins = length(model)) + possible <- model > 0 + expect_equal(sum(model), 1) + expect_true(all(counts[!possible] == 0L)) + chisq <- sum((counts[possible] - trials * model[possible])^2 / (trials * model[possible])) + expect_gt(stats::pchisq(chisq, sum(possible) - 1L, lower.tail = FALSE), 0.001) + included <- outer(seq_along(model) - 1L, flags, bitwAnd) != 0 + pi <- as.vector(crossprod(model, included)) + inclusion <- as.vector(crossprod(counts / trials, included)) + expect_true(all(abs(inclusion - pi) <= 3 * sqrt(pi * (1 - pi) / trials))) + + # Replay enough of the same stream through each constructor to see + # every reachable subset. The 20,000-draw oracle above uses the picker directly. + prefix <- seq_len(max(match(which(possible) - 1L, masks))) + lost <- function(pop) !pop$alive + cases <- list( + list(removal_process(k, weights = weights), lost), + list(ceiling_process(length(w) - k, weights = weights), lost), + list(dispersal_process(function(rows, ...) rep("b", length(rows)), + c("a", "b"), count = k, weights = weights), + function(pop) pop$patch_id == "b"), + list(assign_process("treated", TRUE, count = k, weights = weights), function(pop) pop$treated) + ) + for (case in cases) { + set.seed(700L + k) + observed <- vapply(prefix, function(i) { + out <- case[[1L]]$run(state, list(), case[[1L]]$params) + sum(flags[case[[2L]](out$state$population)]) + }, numeric(1)) + expect_identical(observed, masks[prefix]) + } + } + + set.seed(20261201L) + marked <- replicate(trials, sum(pick(1:6, 3L, "random", rep(1, 6L)) <= 2L)) + expected <- stats::dhyper(0:2, 2, 4, 3) + frequency <- tabulate(marked + 1L, nbins = 3L) / trials + expect_true(all(abs(frequency - expected) <= 3 * sqrt(expected * (1 - expected) / trials))) +}) + +test_that("a quota exhausting the urn still gives callbacks the weighted draw order", { + state <- pva_state(pva_population(rep("F", 3), 1L, capture_order = 0L)) + mark <- assign_process("capture_order", function(rows, ...) seq_along(rows), count = 3L, + weights = function(...) c(1, 0, 3)) + set.seed(905L) + first <- replicate(4000L, OpenPVA:::.pick_rows(1:3, 3L, "random", c(1, 0, 3))[1L]) + expect_lt(abs(mean(first == 3L) - 0.75), 3 * sqrt(0.75 * 0.25 / length(first))) + set.seed(501L) + expected <- OpenPVA:::.pick_rows(1:3, 3L, "random", c(1, 0, 3)) + set.seed(501L) + out <- execute_processes(state, list(mark)) + expect_identical(out$state$population$capture_order[expected], 1:2) + expect_equal(out$events$value, c(2, 1)) +}) + +test_that("weighted counts reconcile and the original uniform draws are preserved", { + state <- pva_state(adult_population(3L, 3L)) + chosen <- function(process) execute_processes(state, list(process)) + w <- function(pop, state, context, params) params$w + params <- list(w = c(0, 1, 0, 2, 0, 0)) + loss <- chosen(removal_process(5L, weights = w, params = params)) + expect_identical(loss$state$population$id, c(1L, 3L, 5L, 6L)) + expect_identical(loss$events$value, c(2, 3)) + cap <- chosen(ceiling_process(1L, weights = w, params = params)) + expect_identical(cap$state$population$id, loss$state$population$id) + expect_identical(cap$events$value, c(2, 3)) + expect_identical(chosen(ceiling_process(0, weights = function(...) 0))$events$value, c(0, 6)) + expect_identical(chosen(removal_process(2, weights = function(...) 0))$events$value, c(0, 2)) + for (bad in list(-1, Inf, NA_real_, NaN, c(1, 2))) { + expect_error(chosen(removal_process(1L, weights = function(...) bad)), "weights") + } + dominant <- c(1e-300, 1e300, 1, 1, 1, 1) + set.seed(719L) + weighted <- chosen(removal_process(1L, weights = function(...) dominant)) + expect_identical(weighted$state$population$id, (1:6)[-2L]) + expect_error(removal_process(probability = 1, weights = w), "count") + expect_error(removal_process(1, order = "id", weights = w), "random order") + + for (p in list(removal_process(2L, weights = NULL), ceiling_process(4L, weights = NULL))) { + set.seed(731L) + expected <- (1:6)[-sample.int(6L, 2L)] + seed_after <- .Random.seed + set.seed(731L) + expect_identical(chosen(p)$state$population$id, expected) + expect_identical(.Random.seed, seed_after) + } +}) + +test_that("assignments preserve column types, shortfalls and individual accounting", { + state <- pva_state(adult_population(3L, 2L, expires = NA_integer_, origin_tag = "local")) + process <- assign_process("expires", function(rows, pop, state, context, params) { + pop$age[rows] + params$duration + }, count = 3L, weights = function(pop, ...) as.numeric(pop$id %in% c(2L, 5L)), + params = list(duration = 4L)) + out <- execute_processes(state, list(process)) + expect_identical(out$state$population$expires, c(NA, 6L, NA, NA, 6L)) + expect_identical(out$events$event_type, c("assigned", "assigned_shortfall")) + expect_identical(out$events$label, c("expires", "expires")) + expect_identical(out$events$value, c(2, 1)) + expect_identical(out$accounting$n_before, out$accounting$n_after) + + mark <- assign_process("origin_tag", "release", select = function(pop, ...) pop$sex == "M") + out <- execute_processes(out$state, list(mark)) + expect_identical(out$state$population$origin_tag, c(rep("local", 3L), rep("release", 2L))) + expect_equal(out$events$value, 2) + for (field in OpenPVA:::.reserved_fields) { + expect_error(assign_process(field, NA, count = 1), "user-defined") + } + mark <- assign_process("expires", 1, count = 7L, event = "contraception") + marked <- execute_processes(state, list(mark)) + expect_identical(marked$state$population$expires, rep(1L, 5L)) + expect_identical(marked$events$event_type, c("contraception", "contraception_shortfall")) + expect_identical(marked$events$value, c(5, 2)) + clear <- assign_process("expires", NA, select = function(pop, ...) pop$sex == "M") + expect_identical(execute_processes(marked$state, list(clear))$state$population$expires, + c(1L, 1L, 1L, NA, NA)) + for (invalid in list(2.5, Inf, NaN, 2^31)) { + expect_error(execute_processes(state, list(assign_process("expires", invalid, count = 1))), + "whole numbers") + } + expect_error(assign_process("expires", NA, count = 1, event = "birth"), "accounting") +}) + +test_that("contraception multiplies the deterministic birth expectation by the untreated fraction", { + female <- c(12L, 8L) + breeding <- c(0.55, 0.85) + litter <- c(1L, 2L) + treated <- 7L + init <- function() pva_population(rep("F", sum(female)), rep(1:2, female), sterile = FALSE) + processes <- list( + assign_process("sterile", TRUE, count = treated, eligible = function(pop, ...) pop$sex == "F"), + reproduction_process(function(pop, ...) (!pop$sterile) * breeding[pop$age], + function(mothers, pop, ...) litter[pop$age[mothers]], + offspring_sex_bernoulli(1), inherit = "sterile", + requires = c("population.sterile", "population.age")) + ) + result <- run_scenario(scenario_spec("contraception", 500L, 1L, init, processes, seed = 1832L), + keep = "events") + obs <- result$events$value[result$events$event_type == "birth"] + leslie <- rbind(breeding * litter, c(1, 1)) + expected <- (1 - treated / sum(female)) * (leslie %*% female)[1L] + expect_lt(abs(mean(obs) - expected), 3 * stats::sd(obs) / sqrt(length(obs))) + mark <- assign_process("sterile", TRUE, probability = function(pop, ...) as.numeric(pop$age == 2L)) + expect_identical(execute_processes(pva_state(init()), list(mark))$state$population$sterile, + rep(c(FALSE, TRUE), female)) +}) + +test_that("count translocation reconstructs every patch stock and every directed flow", { + patches <- c("a", "b", "c") + origin <- rep(patches, c(3L, 3L, 2L)) + state <- pva_state(adult_population(4L, 4L, patch_id = origin)) + dest <- c("b", "a", "c", "b", "a", "b", "c", "c") + move <- dispersal_process(function(rows, ...) dest[rows], patches, count = 6L, + weights = function(pop, ...) as.numeric(pop$id %% 2L == 1L)) + result <- execute_processes(state, list(move)) + pop <- result$state$population + expect_identical(pop$id, state$population$id) + expect_identical(pop$patch_id, dest) + e <- result$events + expect_identical(e$value[match(c("dispersal", "dispersal_shortfall"), e$event_type)], c(3, 3)) + flow <- e[e$event_type == "patch_transition", ] + observed <- matrix(0, 3L, 3L, dimnames = list(patches, patches)) + observed[cbind(match(flow$origin_patch_id, patches), match(flow$destination_patch_id, patches))] <- + flow$value + selected <- c(1L, 3L, 5L, 7L) + expected <- table(factor(origin[selected], levels = patches), factor(dest[selected], levels = patches)) + expect_equal(as.numeric(observed), as.numeric(expected)) + expect_equal(as.numeric(patch_counts(state$population, patches) + colSums(observed) - rowSums(observed)), + as.numeric(patch_counts(pop, patches))) + expect_identical(result$accounting$n_after, result$accounting$n_before) + none <- dispersal_process(function(...) stop("no destinations expected"), patches, + count = 3L, weights = function(...) 0) + expect_equal(execute_processes(state, list(none))$events$value, c(0, 3)) +}) + +test_that("unlimited weighted mating has multinomial sire counts", { + dams <- 6000L + state <- pva_state(adult_population(dams, 4L, mate_id = NA_integer_)) + w <- c(0, 1, 2, 4) + mating <- mating_process(weights = function(pop, ...) c(numeric(dams), w)) + set.seed(260612L) + result <- execute_processes(state, list(mating)) + ids <- result$state$population$mate_id + observed <- tabulate(ids[seq_len(dams)] - dams, nbins = 4L) + expected <- dams * w[-1L] / sum(w) + expect_identical(observed[1L], 0L) + expect_identical(sum(observed), dams) + expect_true(all(is.na(tail(ids, 4L)))) + chisq <- sum((observed[-1L] - expected)^2 / expected) + expect_lt(chisq, stats::qchisq(0.9973, 2)) + expect_equal(result$events$value, c(dams, 0)) +}) + +test_that("finite male capacity, groups and seasonal schedules constrain stored mate IDs", { + state <- pva_state(adult_population(12L, 5L, mate_id = NA_integer_, + patch_id = c(rep(1:2, c(8L, 4L)), rep(1:2, c(2L, 3L))))) + pop <- state$population + mating <- mating_process(male_capacity = 2L, by = "patch_id", when = 0L) + set.seed(201L) + out <- execute_processes(state, list(mating)) + mates <- out$state$population$mate_id + paired <- which(!is.na(mates)) + expect_true(all(pop$sex[paired] == "F" & pop$sex[mates[paired]] == "M")) + expect_identical(pop$patch_id[paired], pop$patch_id[mates[paired]]) + expect_lte(max(tabulate(mates[paired], length(mates))), 2L) + expect_identical(tabulate(pop$patch_id[paired], nbins = 2L), c(4L, 4L)) + expect_identical(out$events$event_type, c("mated_females", "unmated_females")) + expect_equal(out$events$value, c(8, 4)) + skipped <- execute_processes(out$state, list(mating), time = 1L) + expect_identical(skipped$state$population$mate_id, mates) + expect_equal(skipped$events$value, c(0, 0)) + clear <- mating_process(male_capacity = function(...) 0L, when = function(...) TRUE) + expect_true(all(is.na(execute_processes(skipped$state, list(clear))$state$population$mate_id))) + weighted <- mating_process(male_capacity = 2L, by = "patch_id", + weights = function(pop, ...) as.numeric(pop$id %% 2L == 0L)) + limited <- execute_processes(state, list(weighted))$state$population$mate_id + positive <- pop$id[pop$sex == "M" & pop$id %% 2L == 0L] + expect_equal(tabulate(match(limited, positive), length(positive)), c(2L, 2L)) + expect_true(all(stats::na.omit(limited) %in% positive)) + expect_error(mating_process(male_capacity = 0.5), "male_capacity") + expect_error(execute_processes(state, list(mating_process(weights = function(...) Inf))), "weights") +}) + +test_that("finite-capacity matings follow the exact successive sire probabilities", { + weights <- c(1, 2, 5) + males <- seq_along(weights) + draw <- OpenPVA:::.draw_sires + trials <- 8000L + set.seed(4L) + for (capacity in 1:2) { + n <- capacity + 1L + sequences <- as.matrix(expand.grid(rep(list(males), n))) + law <- apply(sequences, 1L, function(sires) { + remaining <- rep.int(capacity, length(males)) + p <- 1 + for (sire in sires) { + if (!remaining[sire]) return(0) + p <- p * weights[sire] / sum(weights[remaining > 0]) + remaining[sire] <- remaining[sire] - 1L + } + p + }) + expect_equal(sum(law), 1) + counts <- replicate(trials, draw(males, n, capacity, weights)) + keys <- 1L + colSums((counts - 1L) * length(males)^(seq_len(n) - 1L)) + observed <- tabulate(keys, length(law)) + possible <- law > 0 + expect_true(all(observed[!possible] == 0L)) + chi <- sum((observed[possible] - trials * law[possible])^2 / (trials * law[possible])) + expect_gt(stats::pchisq(chi, sum(possible) - 1L, lower.tail = FALSE), 0.001) + for (i in males) { + sired <- colSums(counts == i) + expected <- sum(law * rowSums(sequences == i)) + expect_lt(abs(mean(sired) - expected), 3 * stats::sd(sired) / sqrt(trials)) + } + } +}) + +test_that("capped sire races handle extreme weights and bound the arrival allocation", { + draw <- OpenPVA:::.draw_sires + for (weights in list(c(1, 2, 5), c(1, 2, 5) * 1e-310, c(1, 2, 5) * 2e307)) { + set.seed(460L) + observed <- replicate(40L, draw(1:3, 3L, 2L, weights)) + set.seed(460L) + expect_identical(observed, replicate(40L, draw(1:3, 3L, 2L, c(1, 2, 5)))) + } + set.seed(101L) + mixed <- replicate(1500L, draw(1:3, 3L, 2L, c(1e308, 1e-310, 9e-310))) + expect_true(all(mixed[1:2, ] == 1L)) + expect_lt(abs(mean(mixed[3L, ] == 3L) - 0.9), 3 * sqrt(0.9 * 0.1 / ncol(mixed))) + + # One million possible arrivals exceed the 65,536-slot bound. Compare the + # actual draws and final RNG state with sequential rescaling after saturation. + males <- seq_len(10000L) + weights <- c(1e308, rep(1e-310, length(males) - 2L), 1e-306) + set.seed(824L) + observed <- draw(males, 101L, 100L, weights) + after <- .Random.seed + set.seed(824L) + dominant <- replicate(100L, sample.int(length(males), 1L, prob = weights / max(weights))) + remaining <- weights[-1L] + last <- males[-1L][sample.int(length(remaining), 1L, prob = remaining / max(remaining))] + expect_identical(observed, c(dominant, last)) + expect_identical(after, .Random.seed) +}) + +test_that("staggered matings preserve ineligible dams and count only this occasion", { + state <- pva_state(adult_population(3L, 2L, mate_id = c(4L, 5L, 4L, NA, NA))) + eligible <- function(pop, ...) pop$id %in% c(1L, 2L, 5L) + retain <- mating_process(eligible, male_capacity = 1L, clear = FALSE) + set.seed(503L) + out <- execute_processes(state, list(retain)) + expect_identical(out$state$population$mate_id[3L], 4L) + expect_equal(sum(out$state$population$mate_id[1:2] == 5L, na.rm = TRUE), 1L) + expect_equal(sum(is.na(out$state$population$mate_id[1:2])), 1L) + expect_identical(out$events$value, c(1, 1)) + clear <- mating_process(eligible, male_capacity = 1L) + expect_true(is.na(execute_processes(state, list(clear))$state$population$mate_id[3L])) + expect_error(mating_process(clear = NA), "clear") + expect_error(execute_processes(state, list(mating_process(male_capacity = function(...) 1.5))), + "male_capacity") + for (field in OpenPVA:::.reserved_fields) expect_error(mating_process(field = field), "user-defined") +}) diff --git a/vignettes/rosetta.Rmd b/vignettes/rosetta.Rmd index 2d27b49..5c17202 100644 --- a/vignettes/rosetta.Rmd +++ b/vignettes/rosetta.Rmd @@ -30,11 +30,11 @@ The rates are illustrative. | Idiom | OpenPVA | |---|---| -| Replicates and years (`RUN`, `YEAR`) | `scenario_spec(n_runs, n_steps)` and `run_scenario()` | +| Replicates and years (`BEGIN(RUN(n))`, `BEGIN(YEAR(y))`) | `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_*()` | +| Mating and litters (`MATE`, `BREED`, `LITTER`, `BIRTH`) | `mating_process()`, `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()` | @@ -47,10 +47,15 @@ The rates are illustrative. | 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. +The recovered spatial edition of GAPPS II 1.3 credits Randall Downer of +Applied Biomathematics. Its 16-bit MS-DOS executable, built with Borland C++, +has 27 commands. `ALLELES` initialises one diploid locus. In +`G_r1_rd1.in`, a single annual deviate drives 33 survival symbols across age +and sex. In `G_r1_rd2.in`, ageing precedes birth. The analogous choices in R +are which rates share an environmental draw and where ageing sits in the +process list. All 15 Brook et al. scripts that call `HUNT` apply a population +ceiling. They establish the intended quota, while the original weighted +cumulative-distribution sampling algorithm remains unrecovered. ## A Leslie matrix, as a process list @@ -313,6 +318,79 @@ by_patch <- cbind(A = summarise_trajectory(patch_run, metric = "A")$median, by_patch[c(10, 20), ] ``` +## Seasonal management of a surveyed herd + +In this example a step is half a year. Each autumn a survey detects animals +with probability 0.7. Managers divide the count by 0.7, round it, and cull the +estimated surplus above 30. Males have three times the culling weight of +females. Among mature females still eligible for treatment, up to three +receive contraception for two years. + +```{r herd-management} +autumn <- function(state, context, params) context$time %% 2L == 0L +survey <- survey_process(0.7, when = autumn) +cull <- removal_process( + count = survey_quota(function(obs, state, context, params) { + max(0L, round(obs$count / 0.7) - 30L) + }, on_skip = 0L), + weights = function(pop, ...) ifelse(pop$sex == "M", 3, 1) +) +untreated <- function(pop, state, context, params) { + pop$sex == "F" & pop$age >= 4L & pop$treated_until <= context$time +} +dart <- assign_process( + "treated_until", function(rows, pop, state, context, params) context$time + 4L, + count = function(state, context, params) 3L * autumn(state, context, params), + eligible = untreated, event = "contracepted" +) +``` + +In the autumn rut, older males receive more weight and each can mate with at +most five females. Mortality occurs in both seasons. A dam keeps her recorded +sire until spring fawning, even if he dies in autumn. + +```{r herd-fawning} +rut <- mating_process( + when = autumn, male_capacity = 5L, weights = function(pop, ...) pop$age, + eligible = function(pop, state, context, params) { + (pop$sex == "M" & pop$age >= 4L) | untreated(pop, state, context, params) + } +) +fawn <- reproduction_process( + function(pop, state, context, params) 0.9 * !autumn(state, context, params), + litter_poisson(1.2), offspring_sex_bernoulli(0.5), mate = mate_from_field(), + newborn_fields = function(...) list(mate_id = NA_integer_, treated_until = -1L), + newborn_field_names = c("mate_id", "treated_until") +) +clear_sires <- assign_process("mate_id", NA, select = function(pop, state, context, params) { + !autumn(state, context, params) & !is.na(pop$mate_id) +}) +herd <- scenario_spec( + "seasonal herd", n_runs = 12L, n_steps = 8L, dt = 0.5, seed = 1993L, + init_fun = function() pva_state( + pva_population(rep(c("F", "M"), c(22L, 8L)), rep(c(4L, 8L, 12L), 10L), + mate_id = NA_integer_, treated_until = -1L), + pedigree = TRUE, mate_field = "mate_id" + ), + processes = list(survey, cull, dart, rut, + survival_process(function(pop, ...) ifelse(pop$sex == "M", 0.85, 0.93)), + fawn, clear_sires, age_process(), census_process()), + initial_census = census_process() +) +herd_run <- run_scenario(herd, keep = c("census", "ledger")) +fawning <- vapply(herd_run$ledgers, function(animals) { + young <- animals[animals$origin == "birth", ] + sire_exit <- animals$exit_time[match(young$father_id, animals$id)] + c(fawns = nrow(young), earlier_sire_loss = sum(sire_exit < young$entry_time, na.rm = TRUE)) +}, numeric(2)) +rowSums(fawning) +summarise_pva(herd_run)[, c("final_median", "ema", "ema_mcse")] +``` + +The ledger counts fawns whose sire died in an earlier half-year. Expected +minimum abundance (`ema`) averages each replicate's lowest count across +the initial census and the eight end-of-season censuses. + ## Diagnostic plots `plot()` on a run draws a trajectory fan, a cumulative risk curve or the