Inspecting, Checking, and Comparing PVAs in OpenPVA

An individual-based Population Viability Analysis (PVA) is only as trustworthy as its biological assumptions, accounting identities, and sensitivity comparisons. This walkthrough demonstrates the standard OpenPVA workflow on a small island population facing environmental variability, cyclones, and inbreeding depression:

  1. Assemble and visually inspect the lifecycle before simulating.
  2. Check the deterministic baseline with life_table_metrics().
  3. Run and audit stochastic trajectories with cohort accounting and diagnostic plots.
  4. Compare management options and genetic retention in a paired ensemble.

Every chunk uses small replicate counts and fixed seeds so the vignette builds in seconds; real assessments should scale n_runs to achieve the desired Monte Carlo precision.

1. Assemble and inspect the lifecycle

We define a helper that builds our island population (N0 = 36, exact pedigree tracking, and 8 neutral microsatellite-like loci) under three management options: status quo, biennial imperfect surveys (p = 0.70) triggering adaptive releases, and a fixed 12-year release schedule.

build_island <- function(name, strategy = c("status_quo", "adaptive", "fixed"),
                         n_runs = 20L, seed = 2026L) {
  strategy <- match.arg(strategy)

  init_fun <- function() {
    pva_state(
      pva_population(
        sex = rep(c("F", "M"), each = 18L),
        age = rep(1:6, times = 6L)
      ),
      pedigree = TRUE,
      n_loci = 8L
    )
  }

  env_proc <- environment_process(list(env = env_ar1(sd = 0.42, phi = 0.45)))
  cyclone <- catastrophe_process(probability = 0.06, mortality = 0.28, name = "cyclone")

  surv_proc <- survival_process(
    probability = function(pop, state, context, params) {
      base <- ifelse(pop$age == 0L, 0.56, 0.84)
      dens <- ceiling_density_multiplier(length(pop$id), capacity = 95)
      inb <- inbreeding_multiplier(pop$pedigree_F, lethal_equivalents = 3.14)
      shift_logit(base, state$globals$env) * dens * inb
    },
    requires = c("population.age", "population.pedigree_F", "globals.env")
  )

  breed_proc <- reproduction_process(
    breeding_probability = function(pop, state, context, params) {
      as.numeric(pop$age >= 2L) * 0.78
    },
    litter_size = litter_poisson(1.15),
    offspring_sex = offspring_sex_bernoulli(0.5),
    mate = mate_min_kinship(
      eligible = function(pop, state, context, params) pop$age >= 2L,
      max_kinship = 0.25
    ),
    requires = "population.age"
  )

  release_fields <- function(n, state, context, params) {
    list(sex = rep(c("F", "M"), length.out = n), age = rep(2L, n))
  }

  mgmt <- switch(
    strategy,
    status_quo = list(),
    adaptive = list(
      survey_process(detection = 0.70, when = seq.int(0L, 29L, by = 2L), field = "obs"),
      introduction_process(
        count = survey_quota(
          rule = function(obs, state, context, params) if (obs$count < 26L) 6L else 0L,
          field = "obs",
          on_skip = 0L
        ),
        fields = release_fields,
        name = "adaptive_release"
      )
    ),
    fixed = list(
      introduction_process(
        count = function(state, context, params) if (context$time < 12L) 4L else 0L,
        fields = release_fields,
        name = "fixed_release"
      )
    )
  )

  census <- census_process(genetic_metrics())

  scenario_spec(
    name = name,
    n_runs = n_runs,
    n_steps = 30L,
    init_fun = init_fun,
    processes = c(
      list(env_proc, cyclone, surv_proc, age_process(), breed_proc),
      mgmt,
      list(census)
    ),
    initial_census = census,
    seed = seed
  )
}

sc_adaptive <- build_island("Island adaptive management", "adaptive")

Before running a single replicate, describe_lifecycle() audits process order, ecological roles, declared field effects, and inter-process data flows—without advancing the RNG:

lc <- describe_lifecycle(sc_adaptive, state = sc_adaptive$init_fun())
lc[, c("step", "phase", "name", "role", "writes", "creates")]
step phase name role writes creates
0 initial census census
1 interval environment environment globals.env
2 interval cyclone environment globals.cyclone, population.alive
3 interval survival demography population.alive
4 interval age demography population.age
5 interval reproduction demography sex, age, mother_id, father_id
6 interval survey survey globals.obs
7 interval adaptive_release management sex, age
8 interval census census

Calling plot() on a scenario (or pva_lifecycle) translates that declared contract into a pure-base-R lifecycle flow diagram. Dashed arcs highlight inter-process state and global couplings (env, age, obs), while the outer loop closes the annual step:

plot(lc)

For manuscripts, reports, or GitHub READMEs, format_lifecycle() exports the exact same structure as Mermaid or Graphviz DOT:

cat(format_lifecycle(lc, "mermaid"), "\n")
#> flowchart LR
#>   S0["0. census (t = 0)"]:::census
#>   S1["1. environment (writes: env)"]:::environment
#>   S2["2. cyclone (writes: cyclone, alive)"]:::environment
#>   S3["3. survival (writes: alive)"]:::demography
#>   S4["4. age (writes: age)"]:::demography
#>   S5["5. reproduction (creates: sex, age, mother_id, father_id)"]:::demography
#>   S6["6. survey (writes: obs)"]:::survey
#>   S7["7. adaptive_release (creates: sex, age)"]:::management
#>   S8["8. census"]:::census
#>   S0 --> S1
#>   S1 ==> S2
#>   S2 ==> S3
#>   S3 ==> S4
#>   S4 ==> S5
#>   S5 ==> S6
#>   S6 ==> S7
#>   S7 ==> S8
#>   S8 -. "t + 1" .-> S1
#>   S4 -. "age (carryover)" .-> S3
#>   S1 -. "env" .-> S3
#>   S4 -. "age" .-> S5
#>   S6 -. "obs" .-> S7
#>   classDef census fill:#EEF3F5,stroke:#4D646E,color:#25343A,stroke-width:2px
#>   classDef environment fill:#ECF4FA,stroke:#2E6F9E,color:#173D59,stroke-width:2px
#>   classDef demography fill:#E7F4F6,stroke:#1B6B78,color:#0F3D45,stroke-width:2px
#>   classDef survey fill:#F3EFF9,stroke:#72559B,color:#3D2A57,stroke-width:2px
#>   classDef management fill:#FDF3E6,stroke:#C97A24,color:#6E3F0C,stroke-width:2px 

2. Check the deterministic baseline

Before interpreting stochastic risk, compare the baseline mean vital rates against an analytical female projection using life_table_metrics(). Here our post-breeding census counts newborns at age 0, females survive with baseline rates 0.56 (age 0) and 0.84 (ages 1+), and produce an expected 0.78 * 1.15 * 0.5 = 0.4485 daughters per year from age 2 onward:

lt <- life_table_metrics(
  survival = c(0.56, 0.84, 0.84),
  fecundity = c(0, 0, 0.78 * 1.15 * 0.5),
  timing = "post_breeding",
  plus_group = TRUE
)
round(c(
  lambda = lt$lambda,
  r = lt$r,
  R0 = lt$R0,
  generation_time = lt$generation_time,
  cohort_generation_time = lt$cohort_generation_time
), 3)
#>                 lambda                      r                     R0 
#>                  1.042                  0.042                  1.319 
#>        generation_time cohort_generation_time 
#>                  6.150                  7.250 

Without cyclones, environmental autocorrelation, density caps, or inbreeding depression, the baseline demography grows gently (λ = 1.04, stable generation time = 6.2 years, cohort generation time = 7.2 years). Stochasticity, cyclones, and inbreeding depression in a small founder pool of 36 animals are therefore what drive quasi-extinction risk below.

3. Run, audit accounting, and visualise trajectories

Let us run the status-quo and survey-triggered scenarios on the same seed and verify strict cohort accounting first:

sc_sq <- build_island("Status quo", "status_quo")
run_sq <- run_scenario(sc_sq)
run_ar <- run_scenario(sc_adaptive)

c(
  status_quo_reconciled = all(summarise_accounting(run_sq)$reconciled),
  adaptive_reconciled = all(summarise_accounting(run_ar)$reconciled)
)
#> status_quo_reconciled   adaptive_reconciled 
#>                  TRUE                  TRUE 

plot(run, type = "accounting") inspects mean annual births, introductions, deaths, and net population change across replicates (flagging any unreconciled interval with a red cross):

op <- par(mar = c(4.2, 4.4, 2.6, 1.0), las = 1, bty = "l")
plot(run_ar, type = "accounting", main = "Survey-triggered release: cohort accounting")
par(op)

Next, overlay the two strategies’ abundance ribbons and cumulative quasi-extinction risk curves (N < 15) using add = TRUE:

col_sq <- "#B84A39"
col_ar <- "#1B6B78"

op <- par(mfrow = c(1L, 2L), mar = c(4.2, 4.4, 2.8, 1.0), las = 1, bty = "l")
plot(run_sq, type = "trajectory", threshold = 15, runs = 0L, col = col_sq,
     ylim = c(0, 120), ylab = "Living individuals (N)",
     main = "Trajectories (50% & 90% bands)")
plot(run_ar, type = "trajectory", threshold = 15, runs = 0L, col = col_ar, add = TRUE)
legend("topleft", c("Survey-triggered", "Status quo"),
       col = c(col_ar, col_sq), lwd = 2.4, bty = "n", cex = 0.85)

plot(run_sq, type = "risk", threshold = 15, col = col_sq, ylim = c(0, 0.9),
     ylab = "P(N < 15 by year t)", main = "Cumulative risk (95% Wilson CI)")
plot(run_ar, type = "risk", threshold = 15, col = col_ar, add = TRUE)
legend("topleft", c("Status quo", "Survey-triggered"),
       col = c(col_sq, col_ar), lwd = 2.4, bty = "n", cex = 0.85)
par(op)

4. Paired management ensemble and genetic retention

run_pva_ensemble() separates the experimental design from the inner Monte Carlo replicates. Supplying a shared grouping column in seed_by (here a constant column pair = 1L) pairs all three strategies on the exact same replicate streams (seed_by = NULL gives each row an independent seed). Subsetting the returned pva_ensemble data frame keeps its provenance header intact:

design <- data.frame(
  strategy = c("status_quo", "adaptive", "fixed"),
  label = c("Status quo", "Adaptive", "Fixed 12-yr"),
  pair = 1L,
  stringsAsFactors = FALSE
)

ens <- run_pva_ensemble(
  design = design,
  build = function(row) build_island(row$label, row$strategy),
  n_runs = 20L,
  summarise = function(run, row) summarise_pva(run, threshold = 15),
  seed = 2026L,
  seed_by = "pair"
)

stopifnot(length(unique(ens$member_seed)) == 1L)
ens[, c("label", "p_ever_below", "p_ever_below_lower", "p_ever_below_upper", "ema", "final_mean")]
label p_ever_below p_ever_below_lower p_ever_below_upper ema final_mean
Status quo 0.35 0.181 0.567 20.05 37.40
Adaptive 0.00 0.000 0.161 30.45 65.40
Fixed 12-yr 0.05 0.009 0.236 33.25 75.35

Finally, contrast the three management options alongside neutral genetic diversity (expected_heterozygosity tracked on isolated marker substreams via n_loci = 8L and census_process(genetic_metrics())):

cols <- c(col_sq, col_ar, "#C88A2B")

op <- par(mfrow = c(1L, 2L), mar = c(4.2, 4.4, 2.8, 1.0), las = 1, bty = "l")
plot(ens, y = "p_ever_below", by = "label", col = cols, ylim = c(0, 0.95),
     cex.axis = 0.78, xlab = "", ylab = "30-yr quasi-extinction risk (N < 15)",
     main = "Ensemble risk contrast")

plot(run_sq, type = "trajectory", metric = "expected_heterozygosity",
     threshold = 0, runs = 0L, col = col_sq, ylim = c(0.65, 1.0),
     ylab = "Expected heterozygosity (He)",
     main = "Neutral genetic retention (8 loci)")
plot(run_ar, type = "trajectory", metric = "expected_heterozygosity",
     threshold = 0, runs = 0L, col = col_ar, add = TRUE)
legend("bottomleft", c("Survey-triggered", "Status quo"),
       col = c(col_ar, col_sq), lwd = 2.4, bty = "n", cex = 0.85)
par(op)

Each strategy has 20 replicates, so one additional run below 15 animals changes its estimated 30-year risk by five percentage points. The table gives the 95% Wilson interval for each risk estimate. The genetic trajectories show median heterozygosity among surviving populations. More replicates would be needed to estimate the size of a management effect with precision.