OpenPVA has no fixed annual cycle. A model is an ordered list of processes, and the order is the biology. This vignette translates idioms from three traditions into that list: the command scripts of GAPPS, the annual event sequence of Vortex-style simulators, and the Leslie matrix. Every chunk runs as shown, with fixed seeds and small ensembles so that the whole document builds in seconds. The rates are illustrative.
Lookup table
| Idiom | OpenPVA |
|---|---|
Replicates and years (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) |
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() |
| Carrying capacity as truncation | ceiling_process() |
| Density-dependent rates | beverton_holt_multiplier(), ricker_multiplier() |
| Harvest and supplementation | removal_process(), introduction_process() |
| Inbreeding depression (lethal equivalents) | inbreeding_multiplier() on pedigree_F |
| Genetic management by kinship | pairing_process(priority = "kinship"), mate_min_kinship() |
| Gene drop, heterozygosity, founder representation | pva_state(n_loci = ), genetic_metrics(), summarise_pedigree() |
| Dispersal among populations | markov_dispersal_process(), dispersal_process() |
| Leslie projection | the same process list with deterministic expectation \(A^t n_0\) |
The 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
A post-breeding census with the order survive, age, breed gives a Leslie matrix whose fertilities are survival times the fecundity of the next age class. The stochastic model is the same life cycle, one individual at a time.
survival <- c(0.5, 0.8, 0.9) # ages 0, 1 and 2+
daughters <- c(0, 0.6, 1.1) # per female, by age at breeding
age_class <- function(age) pmin(age, 2L) + 1L
A <- rbind(
survival * daughters[c(2, 3, 3)],
c(survival[1], 0, 0),
c(0, survival[2], survival[3])
)
n0 <- c(0, 5, 10)
females_only <- scenario_spec(
name = "leslie", n_runs = 150, n_steps = 6, seed = 4,
init_fun = function() pva_population(sex = rep("F", sum(n0)), age = rep(0:2, n0)),
processes = list(
survival_process(function(pop, state, context, params) survival[age_class(pop$age)],
requires = "population.age"),
age_process(),
reproduction_process(
breeding_probability = 1,
litter_size = litter_poisson(function(pop, state, context, params) {
daughters[age_class(pop$age)]
}),
offspring_sex = offspring_sex_bernoulli(1),
requires = "population.age"
),
census_process()
)
)
run <- run_scenario(females_only, keep = "census")
projected <- vapply(1:6, function(t) {
n <- n0
for (step in seq_len(t)) n <- as.vector(A %*% n)
sum(n)
}, numeric(1))
simulated <- summarise_trajectory(run)
round(data.frame(year = 1:6, matrix = projected, simulated = simulated$mean,
mcse = simulated$mcse), 2)
| year | matrix | simulated | mcse |
|---|---|---|---|
| 1 | 27.30 | 27.32 | 0.36 |
| 2 | 36.01 | 36.12 | 0.60 |
| 3 | 47.85 | 48.03 | 0.83 |
| 4 | 63.55 | 64.04 | 1.27 |
| 5 | 84.39 | 85.27 | 1.79 |
| 6 | 112.07 | 112.86 | 2.44 |
The simulated mean tracks \(A^t n_0\) within Monte Carlo error. Unlike the matrix, the simulation also gives the distribution around that mean and the risk of falling below a threshold.
A Vortex-style year
This illustrative Vortex-style cycle applies environmental variation and catastrophes, then breeding, mortality, ageing, management and a carrying-capacity limit. The order determines which animals experience each event.
Ceiling or density-dependent rates. ceiling_process() truncates
abundance at K. A density multiplier instead lowers a vital rate smoothly.
adult <- function(pop, state, context, params) pop$age >= 1L
year <- function(limit) {
weather <- environment_process(list(
ev = env_ar1(sd = 0.4) # one shared logit deviate per year
))
drought <- catastrophe_process(probability = 0.05, mortality = 0.3, name = "drought")
breed <- reproduction_process(
breeding_probability = function(pop, state, context, params) {
crowding <- if (limit == "density") {
beverton_holt_multiplier(length(pop$id), capacity = 60, growth = 1.5)
} else 1
0.9 * crowding * (pop$age >= 1L)
},
litter_size = litter_poisson(1.4),
offspring_sex = offspring_sex_bernoulli(0.5),
mate = mate_random(adult),
requires = "population.age"
)
die <- survival_process(function(pop, state, context, params) {
shift_logit(c(0.55, 0.85)[1L + (pop$age > 0L)], state$globals$ev)
}, requires = c("population.age", "globals.ev"))
harvest <- removal_process(probability = 0.1, eligible = adult, cause = "harvest",
name = "harvest", requires = "population.age")
release <- introduction_process(
count = function(state, context, params) if (context$time < 5L) 4L else 0L,
fields = function(n, state, context, params) list(sex = rep(c("F", "M"), 2), age = 2L),
name = "release"
)
c(list(weather, drought, breed, die, age_process(), release, harvest),
if (limit == "ceiling") list(ceiling_process(capacity = 60)),
list(census_process()))
}
simulate <- function(...) {
run_scenario(scenario_spec(
name = "vortex_style", n_runs = 30, n_steps = 10, seed = 2026,
init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 2L),
processes = year(...), initial_census = census_process()
))
}
ceiling_run <- simulate("ceiling")
density_run <- simulate("density")
rbind(
ceiling = summarise_pva(ceiling_run, threshold = 10),
density = summarise_pva(density_run, threshold = 10)
)[, c("p_ever_below", "p_ever_below_upper", "final_q05", "final_median", "final_q95")]
| p_ever_below | p_ever_below_upper | final_q05 | final_median | final_q95 | |
|---|---|---|---|---|---|
| ceiling | 0 | 0.114 | 26.45 | 56 | 60.0 |
| density | 0 | 0.114 | 21.35 | 33 | 55.2 |
With these rates neither rule lets the population fall below 10 animals in 10 years, but abundance differs: the ceiling only caps the population at K = 60, while density-dependent breeding slows growth well before K is reached.
Order of harvest and release. Start with one yearling and one adult. Release two more yearlings and request a harvest of two, taking the lowest IDs among eligible yearlings. The receipts show which animals faced harvest.
initial <- pva_state(pva_population(c("F", "M"), c(1L, 3L)))
harvest <- removal_process(count = 2L, order = "id", requires = "population.age",
eligible = function(pop, ...) pop$age == 1L)
release <- introduction_process(2L, function(...) list(sex = "F", age = 1L),
creates = c("sex", "age"))
compare_order <- function(processes) {
totals <- summarise_accounting(execute_processes(initial, processes))
totals[c("n_start", "introductions", "removals_resident", "removals_introduced", "n_end")]
}
timing <- rbind(harvest_first = compare_order(list(harvest, release)),
release_first = compare_order(list(release, harvest)))
stopifnot(all(timing$removals_introduced == c(0L, 1L)))
timing
| n_start | introductions | removals_resident | removals_introduced | n_end | |
|---|---|---|---|---|---|
| harvest_first | 2 | 2 | 1 | 0 | 3 |
| release_first | 2 | 2 | 1 | 1 | 2 |
Harvest first removes the resident yearling alone. Release first exposes the two newcomers, and the harvest takes the resident and one introduced animal.
Kinship-aware mating and gene drop
pva_state(pedigree = TRUE) tracks exact kinship, and n_loci drops neutral
loci through the same pedigree. Compare random mating with a rule that gives
each female the least related eligible male, in a population held near 16
animals.
captive <- function(mate) {
scenario_spec(
name = "captive", n_runs = 24, n_steps = 12, seed = 1989,
init_fun = function() {
pva_state(pva_population(sex = rep(c("F", "M"), 4), age = 2L),
pedigree = TRUE, n_loci = 20L)
},
processes = list(
survival_process(0.8),
age_process(),
reproduction_process(
breeding_probability = function(pop, state, context, params) {
0.8 * (pop$age >= 2L)
},
litter_size = litter_poisson(1.2),
offspring_sex = offspring_sex_bernoulli(0.5),
mate = mate, requires = "population.age"
),
ceiling_process(capacity = 16),
census_process(genetic_metrics())
),
initial_census = census_process(genetic_metrics())
)
}
random <- run_scenario(captive(mate_random(adult)), keep = "census")
managed <- run_scenario(captive(mate_min_kinship(adult)), keep = "census")
final <- function(run, metric) {
row <- summarise_trajectory(run, metric = metric)[13, ]
sprintf("%.3f (%d extant)", row$mean, row$n_extant)
}
metrics <- c("mean_inbreeding", "founder_genome_equivalents",
"expected_heterozygosity", "allelic_retention")
data.frame(
metric = metrics,
random = vapply(metrics, function(m) final(random, m), ""),
min_kinship = vapply(metrics, function(m) final(managed, m), ""),
row.names = NULL
)
| metric | random | min_kinship |
|---|---|---|
| mean_inbreeding | 0.163 (21 extant) | 0.112 (21 extant) |
| founder_genome_equivalents | 1.649 (21 extant) | 1.839 (21 extant) |
| expected_heterozygosity | 0.657 (21 extant) | 0.699 (21 extant) |
| allelic_retention | 0.245 (21 extant) | 0.265 (21 extant) |
Mean inbreeding, founder genome equivalents and heterozygosity are defined for extant populations. Allelic retention includes extinct replicates at zero when founders contributed alleles. Demographic draws use their own stream.
For monogamous species, pairing_process(priority = "kinship") forms the set
of pairs with the lowest total kinship, here refusing pairs as related as
half-siblings or closer.
family <- pva_state(
pva_population(sex = c("F", "M", "F", "M", "F", "M"), age = c(5, 5, 1, 1, 2, 2),
mother_id = c(NA, NA, 1, 1, NA, NA), father_id = c(NA, NA, 2, 2, NA, NA),
mate_id = NA_integer_),
pedigree = TRUE
)
pairs <- pairing_process(adult, priority = "kinship", max_kinship = 0.1,
requires = "population.age")
execute_processes(family, list(pairs))$state$population$mate_id
#> [1] 2 1 6 5 4 3
Parents 1 and 2 are not paired with their offspring 3 and 4, and the full siblings are not paired with each other.
Two correlated patches
env_ar1() generates anomalies that are autocorrelated in time and correlated
among patches, and env_trend() adds a deterministic trend or regime shift
without lagging it through the autoregression. Here two patches share
red-noise survival conditions (correlation 0.7) and patch B degrades from
interval 10. Females choose sires within their current patch before dispersal.
patches <- c("A", "B")
synchrony <- spatial_correlation(patches, rho = 0.7)
climate <- environment_process(list(
anomaly = env_ar1(sd = 0.5, phi = 0.6, cor = synchrony),
climate = env_trend(function(time) c(A = 0, B = if (time >= 10) -0.8 else 0),
anomaly = "anomaly")
))
moves <- matrix(c(0.9, 0.1, 0.1, 0.9), 2, byrow = TRUE, dimnames = list(patches, patches))
two_patch <- scenario_spec(
name = "two_patch", n_runs = 40, n_steps = 20, seed = 77,
init_fun = function() {
pva_state(pva_population(sex = rep(c("F", "M"), 20), age = 2L,
patch_id = rep(patches, each = 20)), pedigree = TRUE)
},
processes = list(
climate,
survival_process(function(pop, state, context, params) {
shift_logit(0.8, state$globals$climate[pop$patch_id])
}, requires = c("population.patch_id", "globals.climate")),
age_process(),
reproduction_process(
breeding_probability = function(pop, state, context, params) {
local <- patch_counts(pop, patches)[pop$patch_id]
0.9 * (pop$age >= 1L) * beverton_holt_multiplier(local, capacity = 30, growth = 2)
},
litter_size = litter_poisson(1.3),
offspring_sex = offspring_sex_bernoulli(0.5),
mate = mate_min_kinship(adult, by = "patch_id"),
inherit = "patch_id", requires = c("population.age", "population.patch_id")
),
markov_dispersal_process(moves, eligible = function(pop, state, context, params) {
pop$age == 1L
}, requires = "population.age"),
census_process(function(pop, state, context, params) {
c(n_alive = length(pop$id), patch_counts(pop, patches))
})
)
)
patch_run <- run_scenario(two_patch)
by_patch <- cbind(A = summarise_trajectory(patch_run, metric = "A")$median,
B = summarise_trajectory(patch_run, metric = "B")$median)
by_patch[c(10, 20), ]
| A | B |
|---|---|
| 32.0 | 32.0 |
| 32.0 | 7.5 |
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.
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),
requires = "population.sex"
)
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",
requires = c("population.sex", "population.age")
)
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.
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)
}, requires = c("population.age", "population.treated_until")
)
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),
requires = "population.sex"),
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)
#> fawns earlier_sire_loss
#> 468 80
summarise_pva(herd_run)[, c("final_median", "ema", "ema_mcse")]
| final_median | ema | ema_mcse |
|---|---|---|
| 26.5 | 21.417 | 1.19 |
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
accounting view, and returns the table behind the figure.
plot(patch_run, threshold = 20)
risk <- plot(patch_run, type = "risk", threshold = 20)
round(risk[c(10, 20), c("year", "p_ever_below", "p_ever_below_lower",
"p_ever_below_upper")], 3)
| year | p_ever_below | p_ever_below_lower | p_ever_below_upper |
|---|---|---|---|
| 10 | 0.1 | 0.040 | 0.231 |
| 20 | 0.3 | 0.181 | 0.454 |
invisible(plot(ceiling_run, type = "accounting"))
An ensemble separates the design from the replicates, and plot() contrasts
its members with their Monte Carlo intervals.
design <- data.frame(harvest = c(0, 0.15, 0.3))
build <- function(row) {
list(
n_steps = 10,
init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 2L),
processes = list(
reproduction_process(
breeding_probability = function(pop, state, context, params) 0.6 * (pop$age >= 1L),
litter_size = litter_poisson(1.4), offspring_sex = offspring_sex_bernoulli(0.5),
requires = "population.age"
),
survival_process(0.75),
age_process(),
removal_process(probability = row$harvest, cause = "harvest"),
ceiling_process(capacity = 60),
census_process()
)
)
}
ensemble <- run_pva_ensemble(design, build, n_runs = 30, seed = 3,
summarise = function(result, row) {
summarise_pva(result, threshold = 10)
})
plot(ensemble, ylim = c(0, 1))