A Model-Building Cookbook: PVAs from Tables and Ordered Steps

This cookbook builds population viability analyses without writing a single R function. A model has two parts that you keep apart:

Wherever a step needs a rate or a rule you write a short formula such as ~ rate("p_surv") or ~ age >= maturity. OpenPVA checks every name in it, then compiles the model into the same process objects a hand-written model uses, so every tool in the package works on the result. The recipes use small replicate counts so the page builds in seconds; raise n_runs for real work.

1. Three tables, one lifecycle

The inputs

The tables are typed inline here; read.csv("parameters.csv") reads the same thing from a file. One parameter table serves the whole cookbook, so each model below uses only some of its rows.

parameters <- read.csv(strip.white = TRUE, text = "
parameter,          value, unit,        source
female_share,       0.5,   proportion,  assumed even sex ratio at birth
maturity,           2,     years,       field notes 2019-2024
capacity,           60,    animals,     habitat survey
env_sd,             0.35,  logit SD,    variation in annual survival
env_phi,            0.3,   correlation, between successive years
cyclone_p,          0.05,  per year,    regional cyclone record
cyclone_kill,       0.3,   proportion,  counts after the 2011 cyclone
lethal_equivalents, 3.14,  per genome,  published mammal and bird average
area,               6,     ratio,       source study area / island area
releases,           FALSE, flag,        management option
detect,             0.7,   probability, double-observer trial
trigger,            25,    animals,     recovery plan
release_size,       4,     animals,     captive stock available
")

rates <- read.csv(strip.white = TRUE, text = "
age, sex, p_surv, p_breed, litter
0,   All, 0.50,   0,       0
1,   All, 0.75,   0.30,    1.2
2+,  All, 0.86,   0.70,    1.4
")

cohorts <- read.csv(strip.white = TRUE, text = "
age, females, males
0,   6,       6
1,   4,       4
2,   8,       7
")

Age classes can be written 0, 1-2 or 2+, and sex = All shares a row between the sexes. The cohort table could equally have the columns age, sex, n.

The lifecycle

basic <- pva_model(parameters, rates, cohorts, n_steps = 15, name = "island") |>
  step_survival(~ rate("p_surv")) |>
  step_age() |>
  step_reproduction(
    breeding_probability = ~ rate("p_breed"),
    litter_size = litter_poisson(~ rate("litter")),
    offspring_sex = offspring_sex_bernoulli(~ female_share)
  ) |>
  step_census()
basic
#> <pva_model 'island' | 4 steps over 15 intervals (dt = 1) | N0 = 35 | 13 parameters>
#>    1. survival [survival]  probability = ~rate("p_surv")
#>    2. age [age]
#>    3. reproduction [reproduction]  breeding_probability = ~rate("p_breed"), litter_size = litter_poisson(mean = ~rate("litter")), offspring_sex = offspring_sex_bernoulli(female_probability = ~female_share)
#>    4. census [census]

Order is biology. Survival before ageing is mortality over the year just lived; breeding before the census makes this a post-breeding count that includes newborns.

Audit before you run

plot() draws the compiled lifecycle and describe_model() reports what the model will build: the cohorts, each step’s formula with the values bound into it, and where every parameter goes. Neither draws a random number.

plot(basic)

audit <- describe_model(basic, life_table = list(
  survival = ~ rate("p_surv"),
  fecundity = ~ rate("p_breed") * rate("litter") * female_share
))
audit$steps[, c("step", "name", "equations", "parameters")]
step name equations parameters
1 survival probability = ~rate(“p_surv”)
2 age
3 reproduction breeding_probability = ~rate(“p_breed”); litter_size = litter_poisson(mean = ~rate(“litter”)); offspring_sex = offspring_sex_bernoulli(female_probability = ~female_share) female_share = 0.5
4 census
audit$parameters[1:4, c("parameter", "value", "status", "used_by", "unit", "source")]
parameter value status used_by unit source
female_share 0.5 active reproduction proportion assumed even sex ratio at birth
maturity 2 unused years field notes 2019-2024
capacity 60 unused animals habitat survey
env_sd 0.35 unused logit SD variation in annual survival
audit$unused
#>  [1] "maturity"           "capacity"           "env_sd"            
#>  [4] "env_phi"            "cyclone_p"          "cyclone_kill"      
#>  [7] "lethal_equivalents" "area"               "releases"          
#> [10] "detect"             "trigger"            "release_size"      

Only female_share is active so far; the other rows are flagged as unused until a later recipe gives them a job. Unused inputs are reported, not hidden.

The life_table argument evaluates the authored rates for females of each age and passes them to life_table_metrics(), the deterministic projection of the same life cycle. We can first check its growth rate against the rates entered directly.

by_hand <- life_table_metrics(
  survival = c(0.50, 0.75, 0.86),
  fecundity = c(0, 0.30 * 1.2 * 0.5, 0.70 * 1.4 * 0.5)
)
c(authored = audit$life_table$lambda, by_hand = by_hand$lambda,
  generation_time = audit$life_table$generation_time)
#>        authored         by_hand generation_time 
#>        1.051173        1.051173        6.027771 

For a check in animals per year, start with the six newborn, four yearling and eight adult females in the cohort table. Surviving newborns breed at the yearling rate. The older survivors breed at the adult rate. Multiplying each group by its breeding probability, mean litter and female share gives the expected number of daughters at the first census.

daughters <- 6 * 0.50 * 0.30 * 1.2 * 0.5 +
  (4 * 0.75 + 8 * 0.86) * 0.70 * 1.4 * 0.5
projected <- sum(audit$life_table$matrix[1, ] * cohorts$females)
stopifnot(isTRUE(all.equal(daughters, projected)))
c(hand = daughters, life_table = projected)
#>       hand life_table 
#>     5.3812     5.3812 

Run it

compile_scenario() produces an ordinary scenario for run_scenario().

run <- basic |> compile_scenario(n_runs = 20, seed = 1) |> run_scenario()
all(summarise_accounting(run)$reconciled)
#> [1] TRUE
summarise_pva(run, threshold = 10)[c("p_ever_below", "p_ever_below_lower",
                                    "p_ever_below_upper", "final_mean", "final_mcse")]
p_ever_below p_ever_below_lower p_ever_below_upper final_mean final_mcse
0.05 0.009 0.236 67.9 7.336

With 20 replicates, one extra crossing changes the estimated risk by five percentage points. Use the reported 95% interval for risk and the Monte Carlo standard error for mean abundance to choose the precision your decision needs. Quadrupling the replicate count roughly halves the Monte Carlo standard error.

2. Bad years, cyclones, crowding and inbreeding

The next model keeps the same three tables and adds steps. core stops before the census so that later recipes can extend it; a model is a plain value, and adding a step returns a new model without changing the old one.

core <- pva_model(parameters, rates, cohorts, n_steps = 15, pedigree = TRUE,
                  name = "island, ceiling") |>
  step_environment(weather = env_ar1(sd = ~ env_sd, phi = ~ env_phi)) |>
  step_catastrophe(~ cyclone_p, mortality = ~ cyclone_kill, name = "cyclone") |>
  step_survival(
    ~ shift_logit(rate("p_surv"), weather) *
      inbreeding_multiplier(pedigree_F, lethal_equivalents)
  ) |>
  step_age() |>
  step_reproduction(
    ~ rate("p_breed"), litter_poisson(~ rate("litter")),
    offspring_sex_bernoulli(~ female_share),
    mate = mate_min_kinship(~ age >= maturity)
  ) |>
  step_ceiling(~ capacity)

ceiling_model <- core |> step_census()

A ceiling is the bluntest density dependence. Brook et al. (2000) fitted smoother curves in which each class’s survival falls with the number of females counted at the start of the year. Their GAPPS script G_R1_SS.IN reads, for young females,

census (sexes(females) var(fempop))
set (rsurv = 1 - nrand(1,1))
set (f0surv = ((0.9824 / (1 + ((0.00530 * fempop)^9.6625))) + (0.0280 * rsurv)))

The same three lines as steps, with the four classes’ coefficients in a second rate table:

density_rates <- read.csv(strip.white = TRUE, text = "
age, sex, s_max,  crowd,   shape,   s_sd
0,   F,   0.9824, 0.00530, 9.6625,  0.0280
1+,  F,   0.9411, 0.00373, 6.8658,  0.0480
0,   M,   0.9843, 0.00619, 7.3205,  0.1253
1+,  M,   0.8237, 0.00487, 13.5832, 0.0373
")

smooth_model <- pva_model(parameters, list(vital = rates, density = density_rates),
                          cohorts, n_steps = 15, pedigree = TRUE,
                          name = "island, smooth density") |>
  step_environment(
    females = ~ sum(sex == "F"),       # census (sexes(females) var(fempop))
    year = env_ar1(sd = 1)             # set (rsurv = 1 - nrand(1,1))
  ) |>
  step_survival(
    ~ pmin(1, pmax(0, rate("s_max") / (1 + (rate("crowd") * area * females)^rate("shape")) +
                      rate("s_sd") * year)) *
      inbreeding_multiplier(pedigree_F, lethal_equivalents)
  ) |>
  step_age() |>
  step_reproduction(
    ~ rate("p_breed"), litter_poisson(~ rate("litter")),
    offspring_sex_bernoulli(~ female_share),
    mate = mate_min_kinship(~ age >= maturity)
  ) |>
  step_census()

females is a filtered census held for the rest of the year, exactly what CENSUS ... VAR(fempop) did, and area rescales the published crowding coefficients to this smaller island. The curve is ordinary arithmetic on table columns, so no function was needed.

run_ceiling <- ceiling_model |> compile_scenario(n_runs = 16, seed = 2) |> run_scenario()
run_smooth <- smooth_model |> compile_scenario(n_runs = 16, seed = 2) |> run_scenario()
op <- par(mar = c(4.2, 4.4, 2.2, 1), las = 1, bty = "l")
plot(run_ceiling, threshold = 10, runs = 0L, col = "#1B6B78", ylim = c(0, 90),
     main = "Ceiling (teal) and smooth female density (orange)")
plot(run_smooth, threshold = 10, runs = 0L, col = "#C97A24", add = TRUE)
par(op)

3. Seasons, dependent young and two patches

A seasonal lifecycle with maternal care

In this grizzly-style year, bears age in spring, mate in summer, are hunted in autumn and give birth in winter. A female with cubs under three does not mate, and a cub that loses its mother dies. Both rules are conditions on the individual records; mate_id is a custom field with a declared default.

bears <- data.frame(
  sex = c(rep("F", 6), rep("M", 4), "F", "M"), age = c(rep(6, 10), 0, 0),
  mother_id = c(rep(NA, 10), 1, 1), father_id = c(rep(NA, 10), 7, 7)
)

grizzly <- pva_model(
  params = list(weaning_age = 3, maturity_age = 5, s_cub = 0.78, s_adult = 0.93,
                breeding = 0.7, litter = 2, harvest_f = 0.10, harvest_m = 0.20),
  init = bears, fields = list(mate_id = NA_integer_), pedigree = TRUE,
  n_steps = 12, name = "grizzly"
) |>
  step_age(name = "spring_ageing") |>
  step_survival(~ ifelse(age < weaning_age, s_cub, s_adult), name = "natural_survival") |>
  step_mating(
    eligible = ~ age >= maturity_age &
      (sex == "M" | !(id %in% mother_id[age < weaning_age])),
    name = "summer_mating"
  ) |>
  step_survival(~ 1 - ifelse(sex == "F", harvest_f, harvest_m),
                eligible = ~ age >= maturity_age, cause = "harvest", name = "autumn_harvest") |>
  step_survival(0, eligible = ~ age < weaning_age & !(mother_id %in% id),
                cause = "loss_of_mother", name = "orphan_loss") |>
  step_reproduction(~ breeding, litter_binomial(3, ~ litter, min_size = 1),
                    offspring_sex_bernoulli(0.5), mate = mate_from_field(),
                    name = "winter_birth") |>
  step_census(list(n_alive = ~ N, dependent = ~ age < weaning_age,
                   adult_females = ~ sex == "F" & age >= maturity_age))

bear_run <- grizzly |> compile_scenario(n_runs = 15, seed = 1987) |> run_scenario()
losses <- bear_run$events[bear_run$events$event_type == "death", ]
round(tapply(losses$value, losses$label, sum) / 15, 1)   # deaths per replicate, by cause
#>        harvest loss_of_mother        natural 
#>            8.3            4.9           15.7 

The founder table has one row per animal because two cubs start with a known mother and father. A mother shot in autumn leaves orphans in the next step, and a sire shot after mating still fathers the winter litter: the engine keeps him because mate_from_field() reads the recorded mate.

Two patches

Space is one more field. Here patch_id comes from the cohort table, rate(..., by = "patch_id") looks survival up by patch, newborns inherit their mother’s patch, and yearlings move by a transition matrix. The two patches share correlated bad years.

patch_rates <- read.csv(strip.white = TRUE, text = "
age, sex, patch_id, p_surv
0+,  All, north,    0.84
0+,  All, south,    0.74
")
patches <- c("north", "south")
moves <- matrix(c(0.9, 0.1, 0.2, 0.8), 2, byrow = TRUE, dimnames = list(patches, patches))

two_patch <- pva_model(
  params = list(patches = patches, moves = moves, rho = 0.7, local_capacity = 25),
  rates = patch_rates,
  init = data.frame(age = 2, sex = rep(c("F", "M"), 2), n = 8,
                    patch_id = rep(patches, each = 2)),
  n_steps = 12, pedigree = TRUE, name = "two patches"
) |>
  step_environment(
    weather = env_ar1(sd = 0.4, phi = 0.5, cor = spatial_correlation(~ patches, rho = ~ rho))
  ) |>
  step_survival(~ shift_logit(rate("p_surv", by = "patch_id"), weather[patch_id])) |>
  step_age() |>
  step_reproduction(
    ~ 0.9 * (age >= 1) *
      beverton_holt_multiplier(patch_counts(patches)[patch_id], local_capacity, growth = 2),
    litter_poisson(1.3), offspring_sex_bernoulli(0.5),
    mate = mate_min_kinship(~ age >= 1, by = "patch_id"), inherit = "patch_id"
  ) |>
  step_dispersal(transition = ~ moves, eligible = ~ age == 1) |>
  step_census(~ c(n_alive = N, patch_counts(patches)))

patch_run <- two_patch |> compile_scenario(n_runs = 12, seed = 77) |> run_scenario()
sapply(c("north", "south"), function(patch) {
  summarise_trajectory(patch_run, metric = patch)$median[c(1, 7, 13)]
})
north south
16.0 16.0
23.0 11.0
29.5 10.0

4. Imperfect surveys and paired comparisons

Managers rarely know the true count. step_survey() detects each animal with probability detect and stores the count; survey_quota() turns that count (called observed) into a number of animals to release. Both steps are switched by the flag parameter releases, which is FALSE in the table.

managed <- core |>
  step_survey(~ detect, when = ~ time %% 2 == 0, field = "count", enabled = ~ releases) |>
  step_introduce(
    count = survey_quota(~ if (observed < trigger) release_size else 0,
                         field = "count", on_skip = 0),
    fields = list(sex = c("F", "M"), age = 2L), name = "release", enabled = ~ releases
  ) |>
  step_census()

run_pva_ensemble() takes the model directly. Each design column that names a parameter overrides it for that row. Here label names the strategies, and seed_by = TRUE runs every row on the same replicate seeds.

design <- data.frame(
  label = c("No action", "Release 4", "Release 8"),
  releases = c(FALSE, TRUE, TRUE),
  release_size = c(NA, 4, 8)
)
options <- run_pva_ensemble(
  design, managed, n_runs = 16, seed = 2026, seed_by = TRUE,
  summarise = function(run, row) summarise_pva(run, threshold = 15)
)
options[, c("label", "p_ever_below", "p_ever_below_mcse", "ema", "final_mean")]
label p_ever_below p_ever_below_mcse ema final_mean
No action 0.125 0.083 27.875 49.062
Release 4 0.000 0.000 31.125 51.062
Release 8 0.000 0.000 31.438 49.875

release_size is NA in the first row because that row has no release step to use it. Overriding a parameter that cannot matter is an error, not a silent no-op (see the last section).

The same call compares model structures. Give a named list of models and a model column:

structures <- data.frame(model = c("ceiling", "smooth"),
                         label = c("Hard ceiling", "Smooth female density"))
compared <- run_pva_ensemble(
  structures, list(ceiling = ceiling_model, smooth = smooth_model),
  n_runs = 16, seed = 2026, seed_by = TRUE,
  summarise = function(run, row) summarise_pva(run, threshold = 15)
)
compared[, c("label", "p_ever_below", "ema", "final_mean")]
label p_ever_below ema final_mean
Hard ceiling 0.125 27.875 49.062
Smooth female density 0.438 17.375 23.188
op <- par(mfrow = c(1, 2), mar = c(4.2, 4.4, 2.2, 1), las = 1, bty = "l")
plot(options, y = "ema", by = "label", xlab = "", ylab = "Expected minimum abundance",
     cex.axis = 0.75, main = "Management options")
plot(compared, y = "ema", by = "label", xlab = "", ylab = "Expected minimum abundance",
     cex.axis = 0.75, main = "Model structure")
par(op)

What pairing does and does not do. seed_by = TRUE gives every row the same starting random-number stream for replicate 1, replicate 2 and so on, which removes seed-to-seed noise from the contrast. It does not freeze the weather: environmental draws and demographic draws come from the same stream, so once two rows’ populations differ they use that stream differently and their environmental sequences drift apart. Read paired contrasts as “same seeds”, not “same years”. Survey detections and neutral-marker inheritance use their own separate streams, which is why adding a survey that nobody acts on leaves a population’s history unchanged.

5. When a formula is not enough

A formula must be a pure expression. Anything else is an ordinary OpenPVA process, and step_process() places it at an exact position in the pipeline. This one removes the oldest animal each year, between survival and ageing:

harvest_oldest <- pva_process(
  name = "harvest_oldest",
  run = function(state, context, params) {
    if (!length(state$population$id)) return(pva_result(state))
    oldest <- which.max(state$population$age)
    state$population$alive[oldest] <- FALSE
    pva_result(state, pva_events("removal", length(oldest), "trophy"))
  },
  requires = "population.age", writes = "population.alive", role = "management"
)

hunted <- pva_model(parameters, rates, cohorts, n_steps = 15, name = "island, hunted") |>
  step_survival(~ rate("p_surv")) |>
  step_process(harvest_oldest) |>
  step_age() |>
  step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")),
                    offspring_sex_bernoulli(~ female_share)) |>
  step_census()

describe_lifecycle(hunted)[, c("step", "name", "role", "writes")]
step name role writes
0 census census
1 survival demography population.alive
2 harvest_oldest management population.alive
3 age demography population.age
4 reproduction demography
5 census census
hunted_run <- hunted |> compile_scenario(n_runs = 20, seed = 1) |> run_scenario()
all(summarise_accounting(hunted_run)$reconciled)
#> [1] TRUE

The custom step is checked like any other: had it forgotten its removal event, strict validation would stop the run and name the process. A step also accepts an R function wherever it accepts a formula, and step_process() accepts any native constructor, such as inbreeding_proxy_process().

Mistakes are caught before anything runs

Every name in a formula, every override and every table is checked when the model is compiled. The message names the step and the problem.

compile_scenario(basic |> step_ceiling(~ capcity))
#> Error: step 5 'ceiling' (capacity): unknown symbol 'capcity' in a formula (did you mean 'capacity'?). Formulas may use declared parameters, population fields, globals written by a step, time, dt, n_steps, N and rate("<column>")
compile_scenario(managed, overrides = list(release_size = 8))
#> Error: override 'release_size' has no effect: it is used only by the disabled step 8 'release'; drop the override or enable the step
late_survey <- core |>
  step_introduce(survey_quota(~ if (observed < trigger) release_size else 0, field = "count"),
                 fields = list(sex = "F", age = 2L)) |>
  step_survey(~ detect, field = "count")
compile_scenario(late_survey)
#> Error: step 7 'introduction' reads the survey record 'count' before step 8 'survey' writes it; a survey_quota() must come after its step_survey()

The misspelled parameter, the override of a release that is switched off and the quota placed before its survey are all refused at once, before a single random number is drawn.

Where to go next