Function reference

All 82 exported functions and S3 methods grouped by ecological role

Model Authoring & Audit

Separated parameter, vital-rate and cohort inputs, ordered lifecycle steps written as formulas, compilation to standard scenarios, and parameter-provenance audits.

lifecycle_steps step_environment() step_catastrophe() step_survival() step_age() step_pairing() step_mating() step_reproduction() step_dispersal() step_survey() step_remove() step_ceiling() step_introduce() step_assign() step_census() step_process() model_audit describe_model() describe_parameters() pva_model() cohort_population() compile_scenario()

State & Process Contract

Living-state constructors, individual allocation, and the ordered process execution contract.

pva_process() pva_result() pva_events() validate_processes() execute_processes() pva_state() pva_population() add_individuals()

Demography, Life Tables & Mating

Core vital-rate processes, litter and sex helpers, age-sex rate tables, and deterministic life-table projections.

age_sex_rate() validate_age_sex_table() demography_processes age_process() survival_process() staged_survival_process() reproduction_process() census_process() life_table_metrics() reproduction_helpers litter_poisson() litter_binomial() litter_categorical() offspring_sex_bernoulli() mate_random() mate_from_field() mate_min_kinship()

Environment, Density & Space

Correlated environmental anomalies, catastrophes, density multipliers, and discrete-patch dispersal.

density_multipliers ceiling_density_multiplier() beverton_holt_multiplier() ricker_multiplier() environment_processes environment_process() env_ar1() env_trend() spatial_correlation() catastrophe_process() beta_shapes() qbeta_norm() shift_logit() spatial patch_counts() dispersal_process() markov_dispersal_process()

Management, Surveys & Adaptive Control

Targeted removals, ceilings, introductions, individual assignments, seasonal mating, and substream-5 imperfect surveys.

management_processes removal_process() ceiling_process() introduction_process() assign_process() pairing_process() mating_process() survey_processes survey_process() survey_quota()

Genetics, Pedigree & Neutral Markers

Exact conditional pedigree kinship, inbreeding depression, and non-perturbing neutral-locus gene drop.

inbreeding summarise_pedigree() kinship_matrix() mean_kinship() inbreeding_multiplier() inbreeding_proxy_process() sex_ratio_effective_size() markers summarise_markers() marker_founder_shares() genetic_metrics()

Execution, Ensembles & Summaries

Replicated scenarios, paired and structural ensembles, resumable member summaries, viability risk, EMA, and cohort accounting.

run_pva_ensemble() scenario scenario_spec() run_scenario() summaries summarise_pva() summarise_trajectory() summarise_accounting()

Visualisation & Printing

Base-graphics trajectory, risk, accounting, ensemble and lifecycle flow diagrams, Mermaid/DOT export, plus print and subset methods.

lifecycle describe_lifecycle() format_lifecycle() plot.pva_scenario() plot.pva_model() plot.pva_lifecycle() plot.pva_run() plot.pva_ensemble() print.pva_state() print.pva_process() print.pva_scenario() print.pva_lifecycle() print.pva_run() print.pva_ensemble() print.pva_model() print.pva_model_audit() print.pva_formula() print.pva_deferred() [.pva_ensemble() [.pva_lifecycle()

Lifecycle steps for an authored model

Description

Each step_*() adds one step to the end of a pva_model() and returns the new model, so a lifecycle reads top to bottom in a pipe. Order is biology: survival before ageing is pre-ageing mortality, and a census observes whatever precedes it. Every step compiles to the OpenPVA constructor of the same purpose, and step_process() inserts any hand-written or native process at that exact position.

Usage

step_environment(
  model,
  ...,
  name = "environment",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_catastrophe(
  model,
  probability,
  mortality = NULL,
  eligible = NULL,
  name = "catastrophe",
  global = name,
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_survival(
  model,
  probability,
  eligible = NULL,
  cause = "natural",
  stage = NULL,
  post_share = NULL,
  field = "survival_draw",
  name = if (is.null(stage)) "survival" else paste0("survival_", stage),
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_age(
  model,
  increment = 1L,
  name = "age",
  when = TRUE,
  enabled = TRUE,
  uses = NULL
)

step_pairing(
  model,
  eligible,
  capacity = Inf,
  priority = "id",
  max_kinship = Inf,
  by = NULL,
  field = "mate_id",
  name = "pairing",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_mating(
  model,
  eligible = NULL,
  male_capacity = Inf,
  weights = NULL,
  by = NULL,
  field = "mate_id",
  clear = TRUE,
  name = "mating",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_reproduction(
  model,
  breeding_probability,
  litter_size,
  offspring_sex,
  mate = NULL,
  require_mate = !is.null(mate),
  newborn_fields = NULL,
  inherit = character(),
  name = "reproduction",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_dispersal(
  model,
  transition = NULL,
  destination = NULL,
  patches = NULL,
  eligible = NULL,
  count = NULL,
  weights = NULL,
  field = "patch_id",
  name = "dispersal",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_survey(
  model,
  detection,
  eligible = NULL,
  field = "survey",
  name = "survey",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_remove(
  model,
  count = NULL,
  probability = NULL,
  select = NULL,
  eligible = NULL,
  weights = NULL,
  order = "random",
  cause = "removal",
  name = "removal",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_ceiling(
  model,
  capacity,
  eligible = NULL,
  weights = NULL,
  cause = "ceiling",
  name = "ceiling",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_introduce(
  model,
  count,
  fields,
  source = "introduction",
  name = "introduction",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_assign(
  model,
  field,
  value,
  count = NULL,
  probability = NULL,
  select = NULL,
  eligible = NULL,
  weights = NULL,
  order = "random",
  event = "assigned",
  name = "assign",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_census(
  model,
  metrics = NULL,
  name = "census",
  when = TRUE,
  enabled = TRUE,
  requires = character(),
  uses = NULL
)

step_process(model, process, enabled = TRUE, when = TRUE, uses = NULL)

Arguments

Details

Values, formulas or functions. Wherever a step takes a rate, condition, count or value you can give a constant, a one-sided formula, or an R function with the signature the underlying constructor documents. A formula is the closure-free form: ~ ifelse(age == 0, s_juvenile, s_adult) instead of function(pop, state, context, params) ifelse(pop$age == 0, params$s_juvenile, params$s_adult).

What a formula may contain.

Names must be unambiguous, so a parameter cannot share a name with a field, a global or one of the reserved words. Assignment, function definitions, random draws and anything with a side effect are rejected: write those as an R function or a step_process().

Functions in the allowlist may be namespace-qualified, for example stats::plogis() and OpenPVA::shift_logit(). A per-individual formula is evaluated once per step for the whole living population. Logical probabilities contribute 0 or 1. A formula that reads only parameters is evaluated when the model is compiled and passed on as a constant.

Helpers inside steps. env_ar1(), env_trend(), spatial_correlation(), the litter, offspring-sex and mate helpers and survey_quota() accept formulas for their own arguments when used in a step, for example env_ar1(sd = ~ env_sd), litter_poisson(~ rate("litter")) or mate_random(~ age >= maturity). They are then bound to the scenario's parameters at compile time. Inside survey_quota(), observed and obs$count give the survey count. The current observation also exposes obs$visited, obs$ids and obs$time.

Fields of new individuals. Newborns and released animals receive the model's fields defaults for every custom field a step does not set or inherit. A custom field with no default and no value on the step is reported when the model is compiled.

Scheduling and switching. when restricts a step to some intervals; enabled decides at compile time whether the step exists in a scenario at all. A step disabled through a flag parameter draws no random numbers and leaves no rows in the event or accounting tables.

Value

The pva_model with the step appended.

See Also

pva_model(), compile_scenario() and describe_model(); the constructors each step compiles to, survival_process(), reproduction_process(), removal_process(), environment_process(), dispersal_process() and survey_process().

Examples

model <- pva_model(
  params = list(s_juvenile = 0.5, s_adult = 0.85, env_sd = 0.3, maturity = 2,
                detect = 0.7, trigger = 12, release = 4),
  init = data.frame(age = c(1, 3), sex = c("F", "M"), n = 8),
  n_steps = 10, pedigree = TRUE
) |>
  step_environment(weather = env_ar1(sd = ~ env_sd, phi = 0.4)) |>
  step_survival(~ shift_logit(ifelse(age == 0, s_juvenile, s_adult), weather) *
                  inbreeding_multiplier(pedigree_F, 3.14)) |>
  step_age() |>
  step_reproduction(~ 0.8 * (age >= maturity), litter_poisson(1.3),
                    offspring_sex_bernoulli(0.5),
                    mate = mate_min_kinship(~ age >= maturity)) |>
  step_survey(~ detect, when = ~ time %% 2 == 0, field = "count") |>
  step_introduce(
    survey_quota(~ if (observed < trigger) release else 0, field = "count", on_skip = 0),
    fields = list(sex = c("F", "M"), age = 2L), name = "release"
  ) |>
  step_process(pva_process(
    "tag_oldest", function(state, context, params) pva_result(state),
    requires = "population.age"
  )) |>
  step_census(list(n_alive = ~ N, breeders = ~ age >= maturity))

describe_lifecycle(model)
#> <pva_lifecycle 'model' | 8 interval processes + initial census | N = 16, pedigree: on>
#>  step phase    name         role       
#>  0    initial  census       census     
#>  1    interval environment  environment
#>  2    interval survival     demography 
#>  3    interval age          demography 
#>  4    interval reproduction demography 
#>  5    interval survey       survey     
#>  6    interval release      management 
#>  7    interval tag_oldest   custom     
#>  8    interval census       census     
#>  requires                                                                
#>  population.sex, population.alive, population.age                        
#>  -                                                                       
#>  population.alive, population.age, globals.weather, population.pedigree_F
#>  population.age                                                          
#>  population.sex, population.alive, population.age                        
#>  -                                                                       
#>  globals.count                                                           
#>  population.age                                                          
#>  population.sex, population.alive, population.age                        
#>  writes           creates                       
#>  -                -                             
#>  globals.weather  -                             
#>  population.alive -                             
#>  population.age   -                             
#>  -                sex, age, mother_id, father_id
#>  globals.count    -                             
#>  -                sex, age                      
#>  -                -                             
#>  -                -                             
#> Data flows (6): age -> survival (population.age) [next interval]; environment -> survival (globals.weather); age -> reproduction (population.age); survey -> release (globals.count); age -> tag_oldest (population.age); age -> census (population.age)
#> Authored steps:
#>   1. environment: weather = env_ar1(sd = ~env_sd, phi = 0.4, cor = NULL, names = NULL)
#>        with env_sd = 0.3
#>   2. survival: probability = ~shift_logit(ifelse(age == 0, s_juvenile, s_adult), weather) * inbreeding_multiplier(pedigree_F, 3.14)
#>        with s_juvenile = 0.5; s_adult = 0.85
#>   4. reproduction: breeding_probability = ~0.8 * (age >= maturity); litter_size = litter_poisson(1.3); offspring_sex = offspring_sex_bernoulli(0.5); mate = mate_min_kinship(eligible = ~age >= maturity, max_kinship = Inf, ties = c("random", "id"), by = NULL)
#>        with maturity = 2
#>   5. survey: detection = ~detect; field = "count" {when = ~time%%2 == 0}
#>        with detect = 0.7
#>   6. release: count = survey_quota(rule = ~if (observed < trigger) release else 0, field = "count", on_skip = 0); fields$sex = c("F", "M"); fields$age = 2L
#>        with trigger = 12; release = 4
#>   7. tag_oldest: process = <native pva_process>
#>   8. census: n_alive = ~N; breeders = ~age >= maturity
#>        with maturity = 2
run <- run_scenario(compile_scenario(model, n_runs = 10, seed = 3))
all(summarise_accounting(run)$reconciled)
#> [1] TRUE

Audit an authored model and its parameters

Description

describe_model() reports what a model will build before anything runs: the initial cohorts, custom fields, each step with its formulas and the parameter values bound into them, and the parameter table. describe_parameters() returns that table alone. Neither draws a random number.

Usage

describe_model(model, overrides = list(), life_table = NULL)

describe_parameters(model, overrides = list())

Arguments

Details

The parameter table has one row per declared parameter: its base value, the effective value once overrides are applied, whether it is overridden, the steps that use it (used_by), a status, and the evidence columns of the parameter table the model was built from. The status is "active" when an enabled step or a step switch uses the parameter, "inactive" when only disabled steps do, and "unused" when nothing does. For indirect parameter reads in a callback or factory, supply the names in the step's uses argument. The base and value columns are lists. Use [[i]] to extract row i in its original type, including matrix dimensions and dimnames. Evidence columns that share a name with an audit column receive the prefix evidence..

Unused base parameters are reported, not rejected, because a disabled step may legitimately leave a parameter idle. An override of such a parameter is an error.

Value

describe_parameters() returns a data frame. describe_model() returns a list of class pva_model_audit with name, settings, n_initial, initial (counts by sex and age), fields, globals, steps (one row per step, including disabled ones), parameters, unused and, when requested, life_table; printing it gives a readable report.

See Also

describe_lifecycle() and plot() for the process-level view of the same model.

Examples

rates <- data.frame(age = c("0", "1", "2+"), sex = "All",
                    p_surv = c(0.5, 0.8, 0.9), p_breed = c(0, 0.6, 1), litter = c(0, 1.2, 2))
model <- pva_model(
  params = data.frame(parameter = c("capacity", "female_share", "spare"),
                      value = c(80, 0.5, 1), unit = c("animals", "proportion", "-")),
  rates = rates, init = data.frame(age = 0:2, females = c(4, 3, 6), males = c(4, 3, 5)),
  n_steps = 20
) |>
  step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, capacity)) |>
  step_age() |>
  step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")),
                    offspring_sex_bernoulli(~ female_share)) |>
  step_census()

describe_parameters(model, overrides = list(capacity = 60))
#>      parameter base value overridden status      used_by       unit
#> 1     capacity   80    60       TRUE active     survival    animals
#> 2 female_share  0.5   0.5      FALSE active reproduction proportion
#> 3        spare    1     1      FALSE unused                       -
describe_model(model, life_table = list(
  survival = ~ rate("p_surv"),
  fecundity = ~ rate("p_breed") * rate("litter") * female_share
))
#> <pva_model audit 'model' | 20 intervals (dt = 1) | N0 = 25 | pedigree: off>
#> Initial population: 13 F, 12 M; ages 0-2
#> 
#> Steps:
#>    1. survival [survival]
#>         probability = ~rate("p_surv") * ceiling_density_multiplier(N, capacity)
#>         with capacity = 80
#>    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)
#>         with female_share = 0.5
#>    4. census [census]
#> 
#> Parameters:
#>  parameter    base value overridden status used_by      unit      
#>  capacity     80   80    FALSE      active survival     animals   
#>  female_share 0.5  0.5   FALSE      active reproduction proportion
#>  spare        1    1     FALSE      unused              -         
#> 
#> Declared but unused: spare
#> 
#> Female life table from the authored rates: lambda = 1.2677, R0 = 4.180, generation time = 3.96

Author a model from separated inputs

Description

pva_model() holds a model's inputs apart from its lifecycle: parameters, vital-rate tables, the initial population and the custom individual fields. Steps are then added in order with the step_*() functions, usually in a pipe. compile_scenario() turns the model into an ordinary pva_scenario, built from the same constructors a hand-written model uses, for run_scenario().

Usage

pva_model(
  params = list(),
  rates = NULL,
  init,
  n_steps,
  fields = list(),
  globals = list(),
  name = "model",
  dt = 1,
  pedigree = FALSE,
  n_loci = 0L,
  mate_field = NULL,
  initial_census = TRUE
)

cohort_population(counts, ...)

compile_scenario(
  model,
  overrides = list(),
  n_runs = 100L,
  seed = NULL,
  name = NULL,
  validation = c("strict", "fast")
)

Arguments

Details

A pva_model is a plain value. Adding a step returns a new model; nothing is registered or stored elsewhere, and a stored formula keeps only its expression, never the environment it was written in.

Compilation resolves every formula once against the model's parameters, population fields, globals, the context values time, dt, n_steps and N, and its rate() tables, and rewrites it into an ordinary closure with the parameter values written in (see lifecycle_steps). The closure is bound to the package namespace or a locked child environment holding its rate lookups, so it runs as fast as the hand-written equivalent and travels unchanged to fork and socket workers. The required fields of every process are derived from what its formulas read.

Compilation fails, before any random number is drawn, on: a symbol that is not in the vocabulary; a name used for two things (say a parameter and a population field); a function outside the pure-function list, an assignment or a random draw in a formula; a rate table with overlapping or missing age classes in a sex or stratum, no open terminal age class for a sex and its fixed strata when ageing is enabled, or a probability outside [0, 1]; a step that reads a global written only by a disabled step, or a survey quota placed before its survey; an unknown override; and an override that cannot affect the scenario because only disabled steps use that parameter. The message names the step and the offending symbol or value. A base parameter that no step uses is not an error; describe_parameters() lists it as unused.

cohort_population() is the population builder pva_model() applies to a cohort table; use it directly with pva_state() in hand-written models.

Value

pva_model() returns a pva_model. cohort_population() returns a population as pva_population() does. compile_scenario() returns a pva_scenario whose authoring element records each step's formulas and bound parameter values for describe_lifecycle().

See Also

lifecycle_steps for the steps and the formula vocabulary, describe_model() for the audit, and run_pva_ensemble(), which accepts a model directly.

Examples

parameters <- data.frame(
  parameter = c("capacity", "female_share", "releases", "release_size"),
  value = c("60", "0.5", "FALSE", "4"),
  source = c("habitat map", "assumed", "scenario", "scenario")
)
rates <- data.frame(
  age = c("0", "1", "2+"), sex = "All",
  p_surv = c(0.55, 0.80, 0.88), p_breed = c(0, 0.5, 0.9), litter = c(0, 1.2, 1.6)
)
cohorts <- data.frame(age = 0:2, females = c(6, 4, 8), males = c(6, 4, 7))

model <- pva_model(parameters, rates, cohorts, n_steps = 15, name = "island") |>
  step_survival(~ rate("p_surv") * ceiling_density_multiplier(N, capacity)) |>
  step_age() |>
  step_reproduction(~ rate("p_breed"), litter_poisson(~ rate("litter")),
                    offspring_sex_bernoulli(~ female_share),
                    mate = mate_random(~ age >= 1)) |>
  step_introduce(~ release_size, fields = list(sex = c("F", "M"), age = 1L),
                 name = "release", when = 0:4, enabled = ~ releases) |>
  step_census()
model
#> <pva_model 'island' | 5 steps over 15 intervals (dt = 1) | N0 = 35 | 4 parameters>
#>    1. survival [survival]  probability = ~rate("p_surv") * ceiling_density_multiplier(N, capacity)
#>    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), mate = mate_random(eligible = ~age >= 1)
#>    4. release [introduction]  count = ~release_size, fields = list(sex = c("F", "M"), age = 1L)  {when = 0:4, enabled = ~releases}
#>    5. census [census]
result <- run_scenario(compile_scenario(model, n_runs = 20, seed = 1))
summarise_pva(result, threshold = 10)[c("p_ever_below", "final_mean")]
#>   p_ever_below final_mean
#> 1            0       69.1
# the same model with the release step switched on, paired on one seed
run_pva_ensemble(data.frame(releases = c(FALSE, TRUE)), model, n_runs = 20,
                 seed = 1, seed_by = TRUE)[c("releases", "final_mean", "ema")]
#> <pva_ensemble | rows: 2 | runs/member: 20 | root seed: 1>
#>   releases final_mean  ema
#> 1    FALSE      64.80 34.8
#> 2     TRUE      74.95 35.0

Lifecycle processes and their execution contract

Description

A lifecycle is a direct ordered list of ordinary R process objects. Each wraps a function and declares the state fields it requires, writes and creates. The engine calls the processes in order and owns time, identifiers, random-number streams, accounting and provenance.

Usage

pva_process(
  name,
  run,
  params = list(),
  requires = character(),
  writes = character(),
  creates = NULL,
  description = NULL,
  role = NULL
)

pva_result(state, events = NULL, census = NULL)

pva_events(
  event_type,
  value = 1,
  label = NA_character_,
  origin_patch_id = NULL,
  destination_patch_id = NULL
)

validate_processes(processes, state = NULL)

execute_processes(
  state,
  processes,
  time = 0L,
  run = 1L,
  dt = 1,
  validation = c("strict", "fast")
)

Arguments

Details

The context passed to run is a read-only list with run, time, dt, phase, n_steps, process_index, process_name, occurrence and departed_males (IDs of males lost in earlier processes of this interval).

Under strict validation the engine checks after every process that only declared fields changed, that field types and lengths are intact, that existing records were neither deleted nor reordered, that new records came from add_individuals(), and that the accounting events equal the state change for each cohort separately: existing individuals that stopped living must equal the reported deaths or removals, and created individuals must equal the reported births or introductions. A process may report one loss type and one entry type per execution, and individuals it creates must be alive when it returns. Compensating errors that leave the net count unchanged are therefore still detected.

The engine records, for every process and interval, losses split into residents, individuals born in that interval and individuals introduced in that interval; see summarise_accounting.

Value

pva_process() returns a validated pva_process; pva_result() a pva_result; pva_events() an event list. validate_processes() returns the validated list invisibly and, given a state, also checks the field plan. execute_processes() runs one interval with the caller's random-number stream and returns the new state with events, census, accounting and ledger data frames.

Examples

harvest <- pva_process(
  name = "harvest_oldest",
  run = function(state, context, params) {
    oldest <- which.max(state$population$age)
    state$population$alive[oldest] <- FALSE
    pva_result(state, pva_events("removal", length(oldest), "harvest"))
  },
  requires = "population.age",
  writes = "population.alive"
)
state <- pva_state(pva_population(sex = c("F", "M", "F"), age = c(2, 9, 4)))
out <- execute_processes(state, list(harvest, census_process()))
out$census
#>   run time    phase process_name occurrence n_alive n_female n_male
#> 1   1    0 interval       census          1       2        2      0
out$accounting
#>   time process_index n_before births introductions deaths_resident deaths_born
#> 1    0             1        3      0             0               0           0
#> 2    0             2        2      0             0               0           0
#>   deaths_introduced removals_resident removals_born removals_introduced n_after
#> 1                 0                 1             0                   0       2
#> 2                 0                 0             0                   0       2

Population state

Description

The population is columnar: a named list of equal-length vectors with one element per living individual. pva_population() builds it, pva_state() wraps it with shared globals and the identifier allocator, and add_individuals() is the only way for a process to create individuals.

Usage

pva_population(sex, age, ..., mother_id = NA_integer_, father_id = NA_integer_)

pva_state(
  population,
  globals = list(),
  pedigree = FALSE,
  kinship = NULL,
  max_dense_kinship = 2000L,
  n_loci = 0L,
  mate_field = NULL
)

add_individuals(
  state,
  sex,
  age,
  ...,
  mother_id = NA_integer_,
  father_id = NA_integer_
)

Arguments

Details

Core fields are id, sex, age, alive, mother_id, father_id, origin and entry_time. The engine owns id, origin ("initial", "birth" or "introduction"), entry_time (the interval of entry, -1 for the initial population) and pedigree_F; processes cannot write them. A process records mortality by setting alive to 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. A known parent may die earlier in the interval. With mate_field, a recorded sire can father offspring in later intervals. The traced pedigree preserves historical ancestry after a mate reference expires. Use kinship_matrix for living pairs in either storage mode.

Value

pva_population() returns the columnar population. pva_state() returns a pva_state with elements population, globals, next_id, kinship, max_dense_kinship and markers. With sire retention, sires$records holds referenced departed males at the interval boundary. Surveys add a private survey_seed. add_individuals() returns the state with the new records appended and next_id advanced.

Examples

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
#> <pva_state | living: 3 | fields: id, sex, age, alive, mother_id, father_id, origin, entry_time, patch_id, pedigree_F | globals: 1 | pedigree: exact>
state <- add_individuals(state, sex = "F", age = 0L, patch_id = 1L,
                         mother_id = 1L, father_id = 3L)
length(state$population$id)
#> [1] 4

Vital rates from age-by-sex tables

Description

age_sex_rate() compiles a table into a vectorised rate function for survival_process() or reproduction_process(). An uncovered age for a represented sex raises an error in either mode.

Usage

validate_age_sex_table(table, value, by = NULL)

age_sex_rate(table, value, missing_sex = c("error", "zero"), by = NULL)

Arguments

Details

Age classes must not overlap within a sex (and stratum). A gap between classes is found when an individual of that age is looked up; a pva_model() that uses the table through rate() rejects gaps, a missing sex and uncovered starting or newborn ages when it is compiled, before any replicate runs.

Value

validate_age_sex_table() returns the table invisibly. age_sex_rate() returns a function of (pop, state, context, params).

Examples

rates <- data.frame(
  age_min = c(0, 1, 0), age_max = c(0, Inf, Inf),
  sex = c("F", "F", "M"), p_surv = c(0.5, 0.9, 0.8)
)
survival <- age_sex_rate(rates, "p_surv")
survival(pva_population(sex = c("F", "F", "M"), age = c(0, 5, 2)), NULL, NULL, NULL)
#> [1] 0.5 0.9 0.8
# the same idea in the shorthand an ecologist would type into a spreadsheet
shorthand <- data.frame(age = c("0", "1-2", "3+"), sex = "All", p_surv = c(0.5, 0.8, 0.9))
age_sex_rate(shorthand, "p_surv")(pva_population(sex = c("F", "M"), age = c(2, 7)),
                                  NULL, NULL, NULL)
#> [1] 0.8 0.9

Ageing, survival, reproduction and census processes

Description

Reusable demographic processes. All rate functions are vectorised over the living population.

Usage

age_process(name = "age", increment = 1L)

survival_process(
  probability,
  eligible = NULL,
  cause = "natural",
  name = "survival",
  requires = character(),
  params = list()
)

staged_survival_process(
  probability,
  post_share,
  stage = c("pre", "post"),
  field = "survival_draw",
  cause = "natural",
  name = paste0("survival_", stage),
  requires = character(),
  params = list()
)

reproduction_process(
  breeding_probability,
  litter_size,
  offspring_sex,
  mate = NULL,
  require_mate = !is.null(mate),
  newborn_fields = NULL,
  newborn_field_names = character(),
  inherit = character(),
  name = "reproduction",
  requires = character(),
  params = list()
)

census_process(
  metrics = NULL,
  name = "census",
  requires = character(),
  params = list()
)

Arguments

Details

Every function supplied to one process sees the same pre-process population, so survival of one individual cannot depend on a death drawn earlier in the same process, and breeding cannot see newborns of the same process. Random draws are taken in population (identifier) order.

staged_survival_process() splits mortality around events such as a release. Write \(q\) for post_share. An original resident passes the pre stage when its uniform draw is below \(a = s_{pre}^{1-q}\). Survivors carry the draw divided by \(a\) into the post stage, where the threshold is \(s_{post}^q\). With fixed stage-specific rates the joint survival probability is their product. If rates are unchanged the final decision matches a single draw against the annual rate exactly. Entrants between stages draw afresh. A zero post share spares all individuals at the post stage.

A census is an ordinary non-mutating process: its position in the lifecycle defines whether it observes the population before or after breeding, mortality or management.

Value

A pva_process.

Examples

survival <- survival_process(
  probability = function(pop, state, context, params) ifelse(pop$age == 0, 0.5, 0.9)
)
breeding <- reproduction_process(
  breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2),
  litter_size = litter_poisson(1.2),
  offspring_sex = offspring_sex_bernoulli(0.5),
  mate = mate_random(function(pop, state, context, params) pop$age >= 2)
)
scenario <- scenario_spec(
  name = "minimal",
  n_runs = 20, n_steps = 10, seed = 1,
  init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 3),
  processes = list(survival, age_process(), breeding, census_process())
)
summarise_pva(run_scenario(scenario), threshold = 10)
#>    metric census_process census_occurrence threshold n_runs horizon
#> 1 n_alive         census                 1        10     20      10
#>   p_below_at_horizon p_below_at_horizon_mcse p_below_at_horizon_lower
#> 1                  0                       0                        0
#>   p_below_at_horizon_upper p_ever_below p_ever_below_mcse p_ever_below_lower
#> 1                0.1611252            0                 0                  0
#>   p_ever_below_upper time_to_threshold_mean time_to_threshold_median
#> 1          0.1611252                     NA                       NA
#>   time_to_threshold_restricted_mean time_to_threshold_restricted_mcse
#> 1                                10                                 0
#>   final_mean final_mcse final_q05 final_q25 final_median final_q75 final_q95
#> 1       92.6   6.700511      43.2     81.25         95.5    107.75     140.6
#>     ema  ema_mcse
#> 1 28.85 0.9740718

Female life-table projection and generation time

Description

Construct the deterministic projection for a female population with a birth pulse once per model interval and a common terminal age class.

Usage

life_table_metrics(
  survival,
  fecundity,
  timing = c("post_breeding", "pre_breeding"),
  plus_group = TRUE
)

Arguments

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 \(x\), survivorship \(l_x\) and daughters per mother \(m_x\), the cohort weights are \(l_x m_x\). Stable-population weights are \(\lambda^{-x} l_x m_x\). They give the same mean maternal age at replacement. Use the stable-population generation_time for inbreeding_proxy_process().

Value

A list with the projection matrix, dominant growth factor lambda, its logarithm r, lifetime daughters per newborn R0, stable mean maternal age generation_time, newborn-cohort mean maternal age cohort_generation_time, stable_age (sum one) and reproductive_value (inner product one with stable age). A cohort producing no daughters has undefined mean maternal age. Stable generation time is also 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
#> [1] 2.683928

Litter-size, offspring-sex and mating helpers

Description

Building blocks for reproduction_process(). Litter size can be Poisson, bounded binomial (under-dispersed, with a maximum) or an explicit categorical distribution. 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 min_size to a binomial draw with size - min_size trials, giving the specified conditional mean.

Usage

litter_poisson(mean)

litter_binomial(size, mean, min_size = 0L)

litter_categorical(sizes, probabilities)

offspring_sex_bernoulli(female_probability = 0.5)

mate_random(eligible)

mate_from_field(field = "mate_id", stale = c("error", "unpaired"))

mate_min_kinship(
  eligible = NULL,
  max_kinship = Inf,
  ties = c("random", "id"),
  by = NULL
)

Arguments

Details

mate_from_field() reads a vector of positive integer IDs or 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 mate_field can also father offspring in later intervals. The offspring inherit his ID and newborn_fields can read his attributes at exit. With stale = "unpaired", any other absent sire is treated as NA for this breeding event. An unpaired female skips breeding unless require_mate = FALSE, in which case her offspring have an unknown sire.

mate_min_kinship() gives each female the eligible male with whom her kinship is lowest (polygyny: a male can sire several litters). It needs pva_state(pedigree = TRUE). Kinships are compared on a grid of \(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

A function suitable for the corresponding argument of reproduction_process().

Examples

cubs <- litter_categorical(sizes = 1:3, probabilities = c(0.2, 0.6, 0.2))
pop <- pva_population(sex = c("F", "F", "M"), age = 6)
set.seed(1)
cubs(mothers = 1:2, pop = pop, state = NULL, context = NULL, params = NULL)
#> [1] 2 2

Density-feedback multipliers

Description

Multipliers in (0, 1] for a vital rate. ceiling_density_multiplier() is 1 up to capacity and capacity / n above it. beverton_holt_multiplier() is 1 / (1 + (growth - 1) n / capacity) and ricker_multiplier() is growth^(-n / capacity); both equal 1 / growth at capacity, so a rate that supports growth growth at low density gives zero growth at capacity.

Usage

ceiling_density_multiplier(n, capacity)

beverton_holt_multiplier(n, capacity, growth)

ricker_multiplier(n, capacity, growth)

Arguments

Value

A numeric vector of multipliers.

Examples

n <- c(0, 50, 100, 200)
beverton_holt_multiplier(n, capacity = 100, growth = 1.5)
#> [1] 1.0000000 0.8000000 0.6666667 0.5000000
ricker_multiplier(n, capacity = 100, growth = 1.5)
#> [1] 1.0000000 0.8164966 0.6666667 0.4444444
ceiling_density_multiplier(n, capacity = 100)
#> [1] 1.0 1.0 1.0 0.5

Environmental variation and catastrophes

Description

environment_process() draws the interval's shared environmental conditions into globals, where rate functions read them. catastrophe_process() draws a Bernoulli catastrophe flag and can apply direct mortality. qbeta_norm() maps a standard normal through its CDF and the beta quantile function, preserving a chosen beta mean and standard deviation. beta_shapes() converts moments to beta shape parameters, and shift_logit() perturbs probabilities on the logit scale. env_ar1() and env_trend() build variables for environment_process(): a temporally autocorrelated, cross-correlated anomaly and a deterministic trend or regime shift.

Usage

environment_process(
  variables,
  name = "environment",
  requires = character(),
  params = list()
)

env_ar1(sd = 1, phi = 0, cor = NULL, names = NULL)

env_trend(level, anomaly = NULL)

spatial_correlation(patches = NULL, rho = NULL, distances = NULL, scale = NULL)

catastrophe_process(
  probability,
  mortality = NULL,
  eligible = NULL,
  name = "catastrophe",
  global = name,
  requires = character(),
  params = list()
)

beta_shapes(mean, sd)

qbeta_norm(z, mean, sd)

shift_logit(probability, deviation)

Arguments

Details

env_ar1() generates \(z_t = \phi z_{t-1} + \sqrt{1 - \phi^2}\,\sigma\,L\epsilon_t\), where \(LL^\top\) is cor and \(\epsilon_t\) is standard normal. The first value is drawn from the stationary distribution, so every interval has mean zero, standard deviation sd and correlation cor, and the covariance at lag \(k\) is \(\phi^k\) times the lag-zero covariance. Changing 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.

spatial_correlation() constructs a matrix for cor using a common rho across patches or exponential decay with distance.

env_trend() returns the level for the current interval and, when anomaly is named, adds that interval's anomaly. Because the level is added after the autoregression, a trend or regime shift takes full effect in its own interval.

Value

The process constructors return a pva_process. spatial_correlation() returns a square numeric matrix. env_ar1() and env_trend() return functions for variables; their values are numeric vectors with one element per component. beta_shapes() returns a list with shape1 and shape2; shift_logit() returns probabilities.

Examples

weather <- environment_process(
  variables = list(survival_deviate = function(state, context, params) rnorm(1, 0, 0.3))
)
cyclone <- catastrophe_process(probability = 0.05, mortality = 0.4, name = "cyclone")
survival <- survival_process(
  probability = function(pop, state, context, params) {
    shift_logit(0.85, state$globals$survival_deviate)
  },
  requires = "globals.survival_deviate"
)
state <- pva_state(
  pva_population(sex = rep(c("F", "M"), 25), age = 2),
  globals = list(survival_deviate = 0, cyclone = FALSE)
)
set.seed(3)
execute_processes(state, list(weather, cyclone, survival, census_process()))$census
#>   run time    phase process_name occurrence n_alive n_female n_male
#> 1   1    0 interval       census          1      44       23     21
# Red noise shared by two patches (correlation 0.6) around a warming step.
climate <- environment_process(list(
  anomaly = env_ar1(sd = 0.3, phi = 0.5,
                    cor = spatial_correlation(c("a", "b"), rho = 0.6)),
  climate = env_trend(function(time) if (time >= 1) 0.5 else 0, anomaly = "anomaly")
))
state <- pva_state(pva_population(sex = c("F", "M"), age = 2))
state <- execute_processes(state, list(climate), time = 0)$state
execute_processes(state, list(climate), time = 1)$state$globals
#> $anomaly
#>         a         b 
#> 0.1735557 0.1440104 
#> 
#> $climate
#>         a         b 
#> 0.6735557 0.6440104 

Movement among discrete patches

Description

dispersal_process() moves eligible individuals to modeller-chosen patches; markov_dispersal_process() draws each destination from a transition matrix. The dispersal event counts movers. Each patch_transition row reports one realised origin, destination and count, including selected individuals assigned their original patch. For a count target, dispersal + dispersal_shortfall equals the requested count. A selected animal assigned its current patch contributes one to the shortfall. Unselected animals stay in place. patch_counts() tabulates abundance by patch for patch-specific density feedback.

Usage

patch_counts(pop, patches, field = "patch_id")

dispersal_process(
  destination,
  patches,
  eligible = NULL,
  field = "patch_id",
  name = "dispersal",
  requires = character(),
  params = list(),
  count = NULL,
  weights = NULL
)

markov_dispersal_process(
  transition,
  eligible = NULL,
  field = "patch_id",
  name = "dispersal",
  requires = character()
)

Arguments

Value

The constructors return a pva_process; patch_counts() returns a named integer vector.

Examples

transition <- matrix(c(0.9, 0.1, 0.2, 0.8), 2, byrow = TRUE,
                     dimnames = list(c("north", "south"), c("north", "south")))
state <- pva_state(pva_population(sex = rep(c("F", "M"), 10), age = 2, patch_id = "north"))
set.seed(4)
moved <- execute_processes(state, list(markov_dispersal_process(transition)))
patch_counts(moved$state$population, c("north", "south"))
#> north south 
#>    15     5 

Targeted management and seasonal mating

Description

removal_process() takes individuals out of the population as accounted removals (harvest, culling, capture). ceiling_process() imposes a hard abundance ceiling by random deaths. introduction_process() adds individuals (supplementation, release, immigration). 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.

Usage

removal_process(
  count = NULL,
  probability = NULL,
  select = NULL,
  eligible = NULL,
  order = c("random", "id"),
  cause = "removal",
  name = "removal",
  requires = character(),
  params = list(),
  weights = NULL
)

ceiling_process(
  capacity,
  eligible = NULL,
  cause = "ceiling",
  name = "ceiling",
  requires = character(),
  params = list(),
  weights = NULL
)

introduction_process(
  count,
  fields,
  creates = c("sex", "age"),
  source = "introduction",
  name = "introduction",
  requires = character(),
  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,
  priority = c("id", "lottery", "kinship", "mean_kinship"),
  field = "mate_id",
  name = "pairing",
  requires = character(),
  params = list(),
  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

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 assigned and, for counts, assigned_shortfall.

On scheduled occasions mating_process() writes a sire ID to each mated female. With the default 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 by is set. Skipping an occasion preserves the field. The events mated_females and unmated_females count eligible females with and without a new mate. Both counts are zero on a skipped occasion. Use mate_from_field() at birth.

pairing_process() forms a new set of pairs each time it runs. With priority = "kinship" it needs pva_state(pedigree = TRUE) and solves an exact assignment: it forms the largest number of pairs allowed by capacity and max_kinship and, among all such sets, one with the smallest sum of within-pair kinships. With 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 \(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

A pva_process.

Examples

state <- pva_state(pva_population(
  sex = rep(c("F", "M"), each = 4), age = 2, mate_id = NA_integer_
))
territories <- pairing_process(
  eligible = function(pop, state, context, params) pop$age >= 1,
  capacity = 2
)
cull <- removal_process(count = 1, cause = "cull")
release <- introduction_process(
  count = 2,
  fields = function(n, state, context, params) {
    list(sex = c("F", "M"), age = 1L, mate_id = NA_integer_)
  },
  creates = c("sex", "age", "mate_id")
)
set.seed(1)
out <- execute_processes(state, list(territories, cull, release, census_process()))
out$events[, c("process_name", "event_type", "value")]
#>   process_name        event_type value
#> 1      pairing      pairs_formed     2
#> 2      pairing unpaired_eligible     4
#> 3      removal           removal     1
#> 4      removal removal_shortfall     0
#> 5 introduction      introduction     2

Imperfect surveys and observation-based management

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.

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

Details

Each visit writes run, time, dt, phase, visited, count and the vector of detected individual IDs (ids) into state$globals[[field]]. Its events are survey_visit and survey_detection. A skipped visit writes NA_integer_ for the count, clears the IDs to integer(0) and emits survey_skip. Surveys within a replicate use the same advancing cursor in execution order. In direct 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

survey_process() returns a pva_process. 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
#>   run time    phase process_index process_name occurrence       event_type
#> 1   1    0 interval             1       survey          1     survey_visit
#> 2   1    0 interval             1       survey          1 survey_detection
#> 3   1    0 interval             2 introduction          1     introduction
#>   value        label origin_patch_id destination_patch_id
#> 1     1       survey            <NA>                 <NA>
#> 2     0       survey            <NA>                 <NA>
#> 3     1 introduction            <NA>                 <NA>

Pedigree summaries and inbreeding depression

Description

summarise_pedigree() reports exact mean and maximum individual inbreeding, mean living kinship (including self-kinship), gene diversity and founder genome equivalents, \(1 / (2 \bar{K})\), where \(\bar{K}\) averages every living pair including each individual with itself; \(N\) unrelated, non-inbred founders give exactly \(N\). mean_kinship(state, ids) returns each requested individual's mean kinship with every living individual, itself included. kinship_matrix(state, ids, against) returns the coancestry block for the two sets of living IDs in their supplied order. The retained ancestry grows with the recorded pedigree. Starting animals with nonzero mutual kinship retain a covariance block. A full returned matrix requires quadratic space. inbreeding_multiplier() scales a particular fitness component by exp(-B * F) using lethal equivalents for that component and period.

Usage

summarise_pedigree(state)

kinship_matrix(state, ids = state$population$id, against = ids)

mean_kinship(state, ids = state$population$id)

inbreeding_multiplier(inbreeding, lethal_equivalents)

inbreeding_proxy_process(
  effective_size,
  generation_time,
  migration = NULL,
  name = "inbreeding_proxy",
  global = "inbreeding_proxy",
  requires = character(),
  params = list()
)

sex_ratio_effective_size(n_females, n_males)

Arguments

Details

The scalar proxy converts per-generation drift to per-interval drift \(d = 1 - (1 - 1/(2N_e))^{1/G}\), with generation time \(G\). The per-generation drift is capped at one, and zero effective size leaves drift at zero. The update is \((d + (1-d)F)(1-m)^2\), where \(m\) is the interval's immigrant gene fraction. Initialise the target global with a coefficient in [0, 1]. An interval with introductions and no migration function raises an error in strict mode and a warning in fast mode. This scalar approximation misses F1 heterosis under supplementation. Use pedigree = TRUE to distinguish the kinships of individual matings. sex_ratio_effective_size() gives \(4N_fN_m/(N_f+N_m)\).

Value

summarise_pedigree() returns a one-row data frame; kinship_matrix() a numeric matrix; mean_kinship(), inbreeding_multiplier() and sex_ratio_effective_size() numeric vectors; inbreeding_proxy_process() a pva_process.

Examples

inbreeding_multiplier(c(0, 0.125, 0.25), lethal_equivalents = 3)
#> [1] 1.0000000 0.6872893 0.4723666
scenario <- scenario_spec(
  name = "one_pair", n_runs = 1, n_steps = 4, seed = 2,
  init_fun = function() {
    pva_state(pva_population(sex = c("F", "M"), age = 2), pedigree = TRUE)
  },
  processes = list(
    age_process(),
    reproduction_process(
      breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2),
      litter_size = litter_categorical(2, 1),
      offspring_sex = offspring_sex_bernoulli(0.5),
      mate = mate_random(function(pop, state, context, params) pop$age >= 2),
      require_mate = TRUE
    ),
    census_process()
  )
)
summarise_pedigree(run_scenario(scenario, keep = "state")$states[[1]])
#>   n_living n_founders mean_inbreeding max_inbreeding mean_kinship
#> 1       14          2      0.07142857           0.25    0.2806122
#>   gene_diversity founder_genome_equivalents
#> 1      0.7193878                   1.781818

Neutral-locus gene drop and genetic census metrics

Description

pva_state(n_loci = L) drops \(L\) unlinked neutral loci through the simulated pedigree. summarise_markers() reports heterozygosity, allelic richness and the retention of the starting population's alleles; marker_founder_shares() reports the share of the living gene pool that descends from each source individual; genetic_metrics() supplies both pedigree and marker metrics to census_process().

Usage

summarise_markers(state)

marker_founder_shares(state)

genetic_metrics()

Arguments

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 or a sire retained through pva_state(mate_field = ) still transmits its alleles. The alleles issued to the initial population are the native alleles.

Member builders, initial gene drops and subsequent segregation in each replicate use distinct L'Ecuyer substreams. When init_fun returns a prebuilt family, replicates share its initial genotypes and draw offspring independently. Repeated direct 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 n_loci = 0 nothing is stored or drawn. The genotypes are engine-owned: a process cannot change them. A supplied starting kinship matrix is accepted together with n_loci > 0 only if recorded initial parentage reproduces it, because unique founder alleles would otherwise contradict the stated relationships.

The metrics are: observed_heterozygosity, the proportion of living individual-locus genotypes with two different alleles; expected_heterozygosity, \(1 - \frac{1}{L}\sum_{l,a} p_{l,a}^2\) with \(p\) the allele frequencies among the living (no small-sample correction); allelic_richness, the mean number of distinct alleles per locus; allelic_retention, the mean proportion of native alleles still present, which later introductions cannot raise; and native_share, the proportion of living gene copies that are native. Conditional on the pedigree, expected heterozygosity has mean \(1 - \bar{K}\) and observed heterozygosity mean \(1 - \bar{F}\) when the founders are unrelated. At extinction richness is zero. Retention is zero when the initial population contributed alleles and otherwise undefined. Heterozygosity, native share and founder genome equivalents are undefined (NA).

genetic_metrics() returns n_alive, then, with pedigree = TRUE, mean_inbreeding, mean_kinship, gene_diversity and founder_genome_equivalents, then the five marker metrics when n_loci > 0.

Value

summarise_markers() returns a one-row data frame. marker_founder_shares() returns one row per source individual with its id, whether its alleles are native, and its share; every native source is listed, including those whose alleles are lost. genetic_metrics() returns a function for the metrics argument of census_process().

Examples

scenario <- scenario_spec(
  name = "gene_drop", n_runs = 20, n_steps = 10, seed = 5,
  init_fun = function() {
    pva_state(pva_population(sex = rep(c("F", "M"), 4), age = 2),
              pedigree = TRUE, n_loci = 20)
  },
  processes = list(
    survival_process(0.8),
    age_process(),
    reproduction_process(
      breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2),
      litter_size = litter_poisson(1.5),
      offspring_sex = offspring_sex_bernoulli(0.5),
      mate = mate_min_kinship(function(pop, state, context, params) pop$age >= 2),
      requires = "population.age"
    ),
    census_process(genetic_metrics())
  ),
  initial_census = census_process(genetic_metrics())
)
run <- run_scenario(scenario, keep = c("census", "state"))
summarise_trajectory(run, metric = "expected_heterozygosity")[
  c(1, 11), c("year", "n_observed", "mean", "q05", "q95")]
#>    year n_observed      mean       q05       q95
#> 1     0         20 0.9375000 0.9375000 0.9375000
#> 11   10         20 0.8217618 0.7047929 0.8923916
summarise_markers(run$states[[1]])
#>   n_living n_loci n_native_alleles observed_heterozygosity
#> 1      130     20               16               0.9330769
#>   expected_heterozygosity allelic_richness allelic_retention native_share
#> 1               0.8456731               10             0.625            1
head(marker_founder_shares(run$states[[1]]), 3)
#>   id native     share
#> 1  1   TRUE 0.2036538
#> 2  2   TRUE 0.4000000
#> 3  3   TRUE 0.1148077

Run a designed ensemble of scenarios

Description

Separates the outer design (structure, parameters, management) from the inner Monte Carlo replicates. For an authored model, the coordinator compiles each design row once and passes the scenario to the worker. A function builder runs on the worker. Each worker returns the member summary.

Usage

run_pva_ensemble(
  design,
  build,
  n_runs,
  summarise = NULL,
  seed = NULL,
  seed_by = NULL,
  workers = 1L,
  backend = c("auto", "fork", "psock"),
  cluster = NULL,
  validation = c("strict", "fast"),
  cache_dir = NULL,
  cache_key = NULL
)

Arguments

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, full RNG specification (including the binomial generator when available), replicate count, validation mode and cache key. Member seeds are a deterministic function of seed and the design order, so the ensemble is reproducible and independent of the number of workers and of the backend.

With a model as build, a design cell that is NA leaves the parameter at its base value, declared parameters take precedence over descriptive columns (label and scenario) and may also appear in seed_by. A named list of structural models reserves model for selection. Any other column that is not a parameter is an error, as is an override that cannot change the row's model (see compile_scenario()). Every row is compiled and validated before a seed is drawn or a worker started, and each cache entry records its own selected model's parameters, rate tables and steps. Editing one structure recomputes its members.

A shared seed gives the rows the same replicate streams at the start of every run. Environmental draws and demography share one stream, so rows whose trajectories diverge then consume it differently: pairing removes between-row seed noise but does not hold the environmental sequence fixed.

Value

A data frame of class pva_ensemble: the design rows, member, member_seed and the summary columns. Provenance is attached as an attribute. plot() contrasts the members.

Examples

design <- expand.grid(survival = c(0.7, 0.9), harvest = c(0, 2))
build <- function(row) {
  list(
    n_steps = 10,
    init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 1),
    processes = list(
      survival_process(row$survival),
      removal_process(count = row$harvest),
      census_process()
    )
  )
}
run_pva_ensemble(design, build, n_runs = 40, seed = 7,
  summarise = function(result, row) summarise_pva(result, threshold = 5)
)[, c("survival", "harvest", "p_ever_below", "p_ever_below_mcse")]
#> <pva_ensemble | rows: 4 | runs/member: 40 | root seed: 7>
#>   survival harvest p_ever_below p_ever_below_mcse
#> 1      0.7       0        1.000        0.00000000
#> 2      0.9       0        0.075        0.04164583
#> 3      0.7       2        1.000        0.00000000
#> 4      0.9       2        1.000        0.00000000

Define and run replicated scenarios

Description

scenario_spec() bundles an initial state, an ordered lifecycle and a replicate design. run_scenario() executes it serially or in parallel.

Usage

scenario_spec(
  name,
  n_runs,
  n_steps,
  init_fun,
  processes,
  seed = NULL,
  dt = 1,
  initial_census = NULL
)

run_scenario(
  scenario,
  parallel = FALSE,
  workers = 2L,
  backend = c("auto", "fork", "psock"),
  cluster = NULL,
  validation = c("strict", "fast"),
  keep = c("census", "events", "accounting")
)

Arguments

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 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 --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

scenario_spec() returns a pva_scenario. run_scenario() returns a pva_run: a list with the scenario, data frames census, events and accounting, lists states and ledgers, and provenance (root seed, streams, validation mode, process plan and versions).

Examples

scenario <- scenario_spec(
  name = "decline",
  n_runs = 50, n_steps = 15, seed = 42,
  init_fun = function() pva_population(sex = rep(c("F", "M"), 6), age = 1),
  processes = list(survival_process(0.8), age_process(), census_process())
)
run <- run_scenario(scenario, keep = c("census", "accounting"))
summarise_pva(run, threshold = 2)
#>    metric census_process census_occurrence threshold n_runs horizon
#> 1 n_alive         census                 1         2     50      15
#>   p_below_at_horizon p_below_at_horizon_mcse p_below_at_horizon_lower
#> 1               0.88               0.0459565                0.7619518
#>   p_below_at_horizon_upper p_ever_below p_ever_below_mcse p_ever_below_lower
#> 1                 0.943824         0.88         0.0459565          0.7619518
#>   p_ever_below_upper time_to_threshold_mean time_to_threshold_median
#> 1           0.943824               9.931818                       10
#>   time_to_threshold_restricted_mean time_to_threshold_restricted_mcse
#> 1                             10.54                         0.4644154
#>   final_mean final_mcse final_q05 final_q25 final_median final_q75 final_q95
#> 1        0.5  0.1078548         0         0            0         1         2
#>   ema  ema_mcse
#> 1 0.5 0.1078548
all(summarise_accounting(run)$reconciled)
#> [1] TRUE

Viability, trajectory and accounting summaries

Description

summarise_pva() reports the probability of being below the threshold at the horizon, the probability of ever falling below it (first crossing), time to threshold and final abundance, each with a Monte Carlo standard error or interval. summarise_trajectory() gives the same quantities by year. summarise_accounting() reconciles every interval by cohort.

Usage

summarise_pva(
  result,
  metric = "n_alive",
  threshold = 1,
  process_name = NULL,
  include_initial = NULL,
  occurrence = NULL
)

summarise_trajectory(
  result,
  metric = "n_alive",
  threshold = 1,
  process_name = NULL,
  include_initial = NULL,
  occurrence = NULL
)

summarise_accounting(result)

Arguments

Details

Proportions carry a binomial Monte Carlo standard error and a 95 percent Wilson interval. The restricted mean time to threshold counts runs that never cross as reaching the horizon. Year t is the census taken in interval t - 1; year 0 is the initial census. Both risk functions apply the same year-zero and census selection. Passing the whole run checks every scheduled run and interval, including extinct replicates. A bare census table only identifies runs and times present in that table.

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.

summarise_trajectory() requires finite recorded abundances and accepts a missing metric only alongside n_alive = 0. Each year reports n_observed values, their 5th, 25th, 50th, 75th and 95th percentiles, and 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. summarise_pva() requires a finite value for every run and interval. For the selected metric, ema is the mean of replicate minima across the evaluated censuses. The final two columns are ema and 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

summarise_pva() returns a one-row data frame, summarise_trajectory() one row per year, and summarise_accounting() one row per run and interval with a logical reconciled.

Examples

scenario <- scenario_spec(
  name = "small_population", n_runs = 60, n_steps = 12, seed = 11,
  init_fun = function() pva_population(sex = rep(c("F", "M"), 5), age = 1),
  processes = list(
    survival_process(0.75),
    age_process(),
    reproduction_process(
      breeding_probability = 0.5, litter_size = litter_poisson(1.1),
      offspring_sex = offspring_sex_bernoulli(0.5)
    ),
    census_process()
  ),
  initial_census = census_process()
)
run <- run_scenario(scenario)
summarise_pva(run, threshold = 5)[, c("p_ever_below", "p_ever_below_lower",
                                      "p_ever_below_upper", "final_median")]
#>   p_ever_below p_ever_below_lower p_ever_below_upper final_median
#> 1    0.6833333          0.5576623          0.7869413          2.5
tail(summarise_trajectory(run, threshold = 5)[, c("year", "median", "q05", "q95",
                                                  "p_ever_below")], 3)
#>    year median q05   q95 p_ever_below
#> 11   10    4.0   0 19.05    0.6000000
#> 12   11    3.0   0 17.15    0.6500000
#> 13   12    2.5   0 18.20    0.6833333
all(summarise_accounting(run)$reconciled)
#> [1] TRUE

Inspect and diagram a model lifecycle

Description

Translate any OpenPVA process list, scenario or run into an ordered audit table, a base-graphics node-and-edge lifecycle flow diagram or a Mermaid/Graphviz specification. Inspection draws no random numbers.

Usage

describe_lifecycle(x, state = NULL)

format_lifecycle(x, format = c("text", "mermaid", "dot"), state = NULL)

## S3 method for class 'pva_scenario'
plot(
  x,
  state = NULL,
  show_flows = TRUE,
  main = NULL,
  ...
)

## S3 method for class 'pva_model'
plot(x, state = NULL, show_flows = TRUE, main = NULL, ...)

## S3 method for class 'pva_lifecycle'
plot(x, show_flows = TRUE, main = NULL, ...)

Arguments

Details

describe_lifecycle() classifies each process into an ecological role (environment, demography, spatial, management, survey, census or custom) and infers inter-process data flows from declared writes and requires paths. A field required before it is written later in the same interval is recorded as a carryover dependency for the next interval. A role stored on a process is used as given. pva_process(role = ) sets one explicitly. A built-in constructor stores the role its process name and declared effects indicate, so a survival_process() named "autumn_harvest" is shown under management as in earlier versions, and falls back to the constructor's own role when they indicate none. A process with no stored role is classified from its name and declared effects each time it is inspected.

A pva_model is compiled with its base parameters and described with its own initial state. For a model, or a scenario or run compiled from one, the result also carries an "authoring" attribute with each step's formulas and the parameter values bound into them, and the text summary lists them under "Authored steps". Mermaid, DOT and diagram output are the same for authored and hand-written lifecycles.

plot.pva_scenario() and plot.pva_lifecycle() render a pure-base-R node-and-edge flow diagram: a single left-to-right row for up to five interval processes, or a two-row clockwise cycle for six or more processes, with dashed data-flow arcs and an interval-return loop.

format_lifecycle() returns a single character string ready to paste into Markdown/Quarto ("mermaid"), Graphviz ("dot") or plain-text reports ("text").

Value

describe_lifecycle() returns a data frame of class pva_lifecycle with one row per ordered step and "edges" and "metadata" attributes. format_lifecycle() returns a length-one character string. The plot() methods return the pva_lifecycle object invisibly.

Examples

scenario <- scenario_spec(
  name = "island-adaptive", n_runs = 50, n_steps = 20, seed = 1,
  init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 2),
  processes = list(
    environment_process(list(env = env_ar1(sd = 0.3, phi = 0.4))),
    survival_process(
      function(pop, state, context, params) shift_logit(0.85, state$globals$env),
      requires = "globals.env"
    ),
    age_process(),
    survey_process(0.7, field = "obs"),
    introduction_process(
      count = survey_quota(function(obs, state, context, params) as.integer(obs$count < 10L),
                           field = "obs", on_skip = 0L),
      fields = function(n, state, context, params) list(sex = rep("F", n), age = rep(2L, n))
    ),
    census_process()
  ),
  initial_census = census_process()
)
lc <- describe_lifecycle(scenario)
lc
#> <pva_lifecycle 'island-adaptive' | 50 runs x 20 steps (dt = 1) | 6 interval processes + initial census>
#>  step phase    name         role        requires                        
#>  0    initial  census       census      population.sex, population.alive
#>  1    interval environment  environment -                               
#>  2    interval survival     demography  population.alive, globals.env   
#>  3    interval age          demography  population.age                  
#>  4    interval survey       survey      -                               
#>  5    interval introduction management  globals.obs                     
#>  6    interval census       census      population.sex, population.alive
#>  writes           creates 
#>  -                -       
#>  globals.env      -       
#>  population.alive -       
#>  population.age   -       
#>  globals.obs      -       
#>  -                sex, age
#>  -                -       
#> Data flows (2): environment -> survival (globals.env); survey -> introduction (globals.obs)
plot(scenario)

A plot recorded by xfun::record()

cat(format_lifecycle(scenario, "mermaid"), "\n")
#> flowchart LR
#>   S0["0. census (t = 0)"]:::census
#>   S1["1. environment (writes: env)"]:::environment
#>   S2["2. survival (writes: alive)"]:::demography
#>   S3["3. age (writes: age)"]:::demography
#>   S4["4. survey (writes: obs)"]:::survey
#>   S5["5. introduction (creates: sex, age)"]:::management
#>   S6["6. census"]:::census
#>   S0 --> S1
#>   S1 ==> S2
#>   S2 ==> S3
#>   S3 ==> S4
#>   S4 ==> S5
#>   S5 ==> S6
#>   S6 -. "t + 1" .-> S1
#>   S1 -. "env" .-> S2
#>   S4 -. "obs" .-> S5
#>   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 

Diagnostic plots of runs and ensembles

Description

Base-graphics views of a run or an ensemble. Each view draws one exported summary and returns it, so the numbers behind a figure are always available.

Usage

## S3 method for class 'pva_run'
plot(
  x,
  type = c("trajectory", "risk", "accounting"),
  metric = "n_alive",
  threshold = 1,
  runs = 20L,
  process_name = NULL,
  include_initial = NULL,
  occurrence = NULL,
  add = FALSE,
  ...
)

## S3 method for class 'pva_ensemble'
plot(x, y = "p_ever_below", by = NULL, ...)

Arguments

Details

The trajectory and risk views plot summarise_trajectory(). A metric that is missing for extinct replicates is summarised over the extant ones. The accounting view plots summarise_accounting(): births and introductions above zero, deaths and removals below, the mean net change as points, and a cross on any interval in which a replicate fails to reconcile.

plot.pva_ensemble() shows one point per ensemble row with an interval: <y>_lower and <y>_upper when the summary has them (as the proportions of summarise_pva() do), otherwise 1.96 Monte Carlo standard errors from <y>_mcse.

The methods preserve styling, respect the current layout and leave the plotted coordinates active for abline(), lines() or legend(). Use plot(other_run, add = TRUE) to overlay a second run. Plotting draws no random numbers.

Value

Invisibly, the plotted table: summarise_trajectory() for the trajectory and risk views, summarise_accounting() for the accounting view, and for an ensemble a data frame with label, estimate, lower and upper.

Examples

scenario <- scenario_spec(
  name = "decline", n_runs = 60, n_steps = 15, seed = 42,
  init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 1),
  processes = list(survival_process(0.85), age_process(), census_process()),
  initial_census = census_process()
)
run <- run_scenario(scenario)
plot(run, threshold = 4)

A plot recorded by xfun::record()

risk <- plot(run, type = "risk", threshold = 4)

A plot recorded by xfun::record()

tail(risk[, c("year", "p_ever_below", "p_ever_below_lower", "p_ever_below_upper")], 2)
#>    year p_ever_below p_ever_below_lower p_ever_below_upper
#> 15   14         0.95          0.8629948          0.9828505
#> 16   15         0.95          0.8629948          0.9828505
plot(run, type = "accounting")

A plot recorded by xfun::record()

design <- data.frame(survival = c(0.75, 0.85, 0.95))
build <- function(row) {
  list(n_steps = 15,
       init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 1),
       processes = list(survival_process(row$survival), census_process()))
}
ensemble <- run_pva_ensemble(design, build, n_runs = 60, seed = 7,
  summarise = function(result, row) summarise_pva(result, threshold = 4))
plot(ensemble)

A plot recorded by xfun::record()

Print and subset OpenPVA objects

Description

Summarise an OpenPVA object, subset a pva_ensemble data frame while preserving its provenance metadata, or slice a pva_lifecycle table into a plain data frame.

Usage

## S3 method for class 'pva_state'
print(x, ...)

## S3 method for class 'pva_process'
print(x, ...)

## S3 method for class 'pva_scenario'
print(x, ...)

## S3 method for class 'pva_lifecycle'
print(x, ...)

## S3 method for class 'pva_run'
print(x, ...)

## S3 method for class 'pva_ensemble'
print(x, ...)

## S3 method for class 'pva_model'
print(x, ...)

## S3 method for class 'pva_model_audit'
print(x, ...)

## S3 method for class 'pva_formula'
print(x, ...)

## S3 method for class 'pva_deferred'
print(x, ...)

## S3 method for class 'pva_ensemble'
x[...]

## S3 method for class 'pva_lifecycle'
x[...]

Arguments

Value

For print methods, x invisibly. For [ on pva_ensemble, a subsetted pva_ensemble data frame (preserving provenance) or a vector when reduced to a single column. For [ on pva_lifecycle, a plain data frame or vector.