Package 'plant'

Title: A Package for Modelling Forest Trait Ecology and Evolution
Description: Solves trait, size and patch structured model from (Falster et al. 2016) using either method of characteristics or as stochastic, finite-sized population.
Authors: Daniel Falster [aut, cre] (ORCID: <https://orcid.org/0000-0002-9814-092X>), Richard FitzJohn [aut], Andrew O'Reilly-Nugent [aut], Isaac Towers [aut], Mitchell Henry [ctb], Rafael Schouten [ctb], John Wilshire [ctb]
Maintainer: Daniel Falster <[email protected]>
License: AGPL (>= 3)
Version: 2.0.0.9002
Built: 2026-11-24 09:42:01 UTC
Source: https://github.com/traitecoevo/plant

Help Index


Add strategies (or a mutant) to Parameters

Description

Add strategies to a Parameters object. add_strategies appends the new strategies to any existing residents (controlled by keep_existing); add_mutant introduces strategies as mutants (i.e. replacing the resident set). Both translate trait values into strategies via generate_strategy and are pipe-friendly (the Parameters object is the first argument).

Usage

add_strategies(
  p,
  traits,
  hyperpar = param_hyperpar(p),
  birth_rate = 1,
  keep_existing = TRUE
)

add_mutant(p, traits, hyperpar = param_hyperpar(p), birth_rate = 1)

expand_parameters(
  trait_matrix,
  p,
  hyperpar = param_hyperpar(p),
  birth_rate_list = 1,
  keep_existing_strategies = TRUE
)

mutant_parameters(
  trait_matrix,
  p,
  hyperpar = param_hyperpar(p),
  birth_rate_list = 1,
  keep_existing_strategies = FALSE
)

Arguments

p

A Parameters object.

traits

A matrix of traits corresponding to the new strategies to introduce (see trait_matrix).

hyperpar

Trade-off (hyperparameter) function to use. Defaults to the one p carries (param_hyperpar(p), see default_parameters); NULL is the explicit identity.

birth_rate

Birth rate(s), one per row of traits. See generate_strategy.

keep_existing

Should existing resident strategies be retained?

trait_matrix

Deprecated (expand_parameters/mutant_parameters); use traits.

birth_rate_list

Deprecated; use birth_rate.

keep_existing_strategies

Deprecated; use keep_existing.


A model's bare parameters

Description

A model's bare Parameters: its defaults, with no strategies and no trade-offs attached, so a trait given to add_strategies is written straight to pars. default_parameters attaches plant's testing trade-offs to the same object. The environment named here only picks the template; a run takes its Environment separately (see run).

Usage

base_parameters(type = NA, env = environment_type(type))

Arguments

type

Any model name as a string, e.g.: "FF16".

env

The environment type's name; by default the model's own.

Value

A Parameters object.

Author(s)

Rich FitzJohn


A strategy's crown shape

Description

The vertical distribution of a plant's leaf area, as the model computes it through its crown shape (CanopyShape): Q, the fraction of the leaf area above relative height u = z / H, which is the shade the plant casts at u; and q = -dQ/du, the leaf area's density in u. For FF16, TF24 and K93 alike this is the Yokozawa profile set by pars$eta. K93's profile spreads basal area over stem diameter rather than leaf area over height.

Usage

canopy_profile(strategy, u = seq(0, 1, length.out = 101), control = NULL)

Arguments

strategy

A strategy (a FF16_Model, TF24_Model, K93_Model, ...), such as p$strategies[[1]].

u

Relative heights, in [0, 1].

control

The run's Control, or NULL for the strategy's own.

Details

Under FF16's "flat-top-soft-box" shading model Q is instead the smoothed step of shade the model has the crown cast, and q its density; eta_c is still the Yokozawa profile's, which the model's sapwood and the step's centre read, so it is the mean of u under q only where the step lies wholly within the crown (eta_c > 0.5).

The shading model is resolved from the strategy's own control, with each model's default where it is empty. A strategy taken from a run's parameters carries an empty one, so pass the run's control, which tidy() keeps as $control.

Value

A list: profile, a tibble of u, Q and q; and eta_c, the Yokozawa profile's leaf-area-weighted mean of u.

See Also

model_size

Examples

crown <- canopy_profile(FF16_Model(), u = seq(0, 1, by = 0.25))
crown$profile
crown$eta_c

Check how a driver's control points survive interpolation

Description

Extrinsic drivers are interpolated with a monotone (shape-preserving) cubic Hermite spline, so an interpolated series stays between its neighbouring control points and a non-negative series never evaluates negative. What the interpolation does change is the integral: between two control points the curve is a cubic, not the series' own shape, so a daily record of discrete depths is smeared across each interval and the total it delivers departs from the sum supplied. For intermittent forcing such as daily rainfall, rainfall_pulse events are the faithful route; this check is for deciding whether a continuous driver is acceptable before committing to a long run.

Usage

check_driver_interpolation(
  environment,
  driver_name,
  x,
  y,
  n_eval = 20001,
  warn = TRUE,
  tol_integral = 0.01
)

Arguments

environment

An Environment object with the driver already set (via environment$extrinsic_drivers_set_variable(driver_name, x, y)).

driver_name

Name of the driver to check, e.g. "rainfall".

x, y

The control points that were supplied for this driver. Used to compute the intended integral and value range to compare against.

n_eval

Number of points on the fine evaluation grid.

warn

If TRUE (default), raise a warning when the interpolated series goes negative or its integral departs from the supplied series by more than tol_integral.

tol_integral

Relative tolerance on the integral mismatch before warning.

Details

This runs that inspection: it evaluates the driver on a fine grid and compares the result against the control points you supplied. The negative excursion statistics are kept for drivers set from a series that is itself partly negative, and as a guard should the interpolation ever change.

Value

Invisibly, a list with the evaluated min, max, frac_negative, the integral_supplied and integral_evaluated (trapezoid), their integral_rel_error, and negative_area — the amount spuriously removed by undershoot. Printed as a short summary as a side effect.

Examples

e <- TF24_Environment()
t <- seq(0, 2, length.out = 730)
# intermittent daily rainfall: wet season only, most days dry
set.seed(1)
y <- ifelse((t %% 1) > 0.5 & runif(length(t)) < 0.3, 5, 0)
e$extrinsic_drivers_set_variable("rainfall", t, y)
check_driver_interpolation(e, "rainfall", t, y)

Control presets

Description

Construct a Control object. control() is a lowercase alias for the Control() constructor, whose defaults are the pragmatic, fast-ish settings used for essentially all of plant's runs (see control.cpp). control_accurate() tightens the ODE and schedule tolerances for high-accuracy runs at the cost of speed. control_tf24() sets TF24's step control: the relative and absolute tolerances at tol, the soil substepped, and the soil layers' tolerance at 10 times that. Against Control() on a TF24 stand under daily rain it takes about 60% of the steps, at about a third of the error.

Usage

control(...)

control_accurate(base = Control())

control_tf24(tol = 1e-05, base = Control())

Arguments

...

Named control fields, passed to Control().

base

An optional Control object to start from; defaults are used if omitted.

tol

The relative tolerance, ode_tol_rel.

Details

ode_tol_scale_soil multiplies the tolerance on TF24's soil layers in the deterministic runner's adaptive steps, which decides which steps it takes and nothing else. Its default of 1 leaves every step as it was. The stochastic runner ignores it, and warns. ode_soil_substep_tol is the relative tolerance that chooses the soil's substeps inside a step (default 1e-9).

Two fields are read by the stochastic solver alone: stochastic_patch_area, the patch's ground area in m2 (default 100), and stochastic_death_interval, the years between death draws (default 0.01). run describes both.

Value

A Control object.


Control parameters

Description

Control parameters that tune various aspects of the numerical solvers.

Usage

Control(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Plant's testing parameter set: today's defaults plus frozen trade-offs

Description

default_parameters(model) is base_parameters(model) with plant's testing trade-off function attached as p$hyperpar. It exists so that every test and golden in plant is self-contained: the trade-offs it attaches are the ones plant's defaults were tuned with, frozen as they stood when they moved out of the model files, and they are not a recommended parameterisation of any species or site. Curated species and site parameter sets, and the recommended, living trade-off functions, are in the fieldtrial package. Changing the frozen copy here means re-blessing plant's goldens.

Usage

default_parameters(model, quiet = FALSE)

default_hyperpar(model, ...)

param_hyperpar(parameters)

Arguments

model

A model name: "FF16", "TF24", "TF24f", "TF24t", "TF24w" or "K93".

quiet

If FALSE (the default), warn that this is a testing set.

...

For default_hyperpar, coefficient overrides passed to the frozen maker (B_kl1, B_Hv1, narea, ...; see frozen_FF16_hyperpar and frozen_TF24_hyperpar for the lists). For tests and diagnostics only: with a coefficient moved the result is no longer the testing set. K93 accepts none.

parameters

A Parameters object.

Details

A Parameters object carries its own trade-offs in p$hyperpar: an R closure satisfying the contract f(m, s, filter = TRUE) (a trait matrix in, the matrix with derived parameter columns appended out, with filter = TRUE dropping columns that sit at the strategy's defaults; optionally carrying attr(f, "input_traits"), the traits it reads that are not fields of pars), or NULL. generate_strategy, add_strategies, add_mutant, stand_gradient and fixed_point_fitness read it through param_hyperpar(p) as their default, so a set built by fieldtrial, regnans or by hand works through one API; passing hyperpar = explicitly still overrides, and hyperpar = NULL is the explicit identity. The slot is a field of the C++ Parameters, held opaquely, so it survives validate(), run (including the result's scenario$p) and a saved object.

The bare base_parameters(model) attaches no trade-offs: a trait named in a trait matrix is written straight to pars, and generate_strategy says so once per session.

Value

For default_parameters, a Parameters object with hyperpar set.

For default_hyperpar, the frozen trade-off closure for model. TF24's serves TF24, TF24f, TF24t and TF24w, which share TF24_Pars; K93 has no trade-offs and gets the identity function. The closure carries attr(f, "traits") (every trait-matrix column it reads), attr(f, "input_traits") (those that are not fields of pars) and attr(f, "coefficients") (the coefficients it was built with, overrides applied).

For param_hyperpar, the trade-off function parameters carries in $hyperpar, or the identity when it carries none.

See Also

base_parameters, parameter_table, generate_strategy

Examples

p <- default_parameters("FF16", quiet = TRUE)
p <- add_strategies(p, trait_matrix(0.0825, "lma"))
p$strategies[[1]]$pars$k_l   # derived from lma by the attached trade-off

p0 <- base_parameters("FF16")
is.null(p0$hyperpar)          # TRUE: nothing attached

Disturbance regime

Description

Base class of representing patch disturbance

Usage

Disturbance_Regime()

Creates an environment object of specified type

Description

An environment is a live C++ object, which saveRDS() cannot keep. A scenario therefore keeps its environment as a recipe: plain values for everything a run reads from it (for TF24, the soil column, its parameters, the soil water a run starts from and the drivers; FF16 and K93 read nothing a run does not reset). Given a recipe, Environment() builds the environment it describes, so Environment(res$scenario$env) gives back the one a result ran in, after readRDS() as well.

Usage

environment_type(type)

Environment(type = NULL)

Arguments

type

Any environment name as a string, e.g.: "FF16_Env", or a recipe, as a scenario's env holds one.


Discrete events applied during a run.

Description

An event is a (time, action) pair applied between solver legs: the integrator is stopped at the event time, the action changes the patch, the system is recomputed, and integration resumes from the new state. Node introduction has always worked this way; these functions make the same mechanism available for resource pulses, harvest and climate extremes.

Usage

events(...)

events_default(p)

node_introductions(p)

resource_pulse(time, resource, amount)

harvest(time, fraction, size_min = 0, size_max = Inf, species = NULL)

climate_extreme(
  time,
  intensity,
  duration = 14/365,
  threshold = 40,
  sensitivity = 1,
  species = NULL
)

Arguments

...

For events, objects returned by the individual event constructors, or whole Events objects; these are concatenated. Each constructor is vectorised over its arguments, so a whole series of pulses is one call.

p

Parameters object, whose node_schedule_times supply the introduction times.

time

Event time(s), in years of patch age.

resource

Index of the environment's resource pool to add to. What a resource is depends on the environment: TF24's are its soil layers, so resource = 1 is the surface. See rainfall_pulse for that case under a name that reads correctly.

amount

How much to add, in whatever the environment measures that resource in. What the pool cannot hold is shed rather than forced in; solver$event_log reports how much of each.

fraction

Fraction of individuals removed, in [0, 1]. The deterministic solver needs it below 1, since it scales each cohort's density; the stochastic solver removes each individual with this probability, so 1 removes them all.

size_min, size_max

Only individuals whose size falls in this band are removed. Size is the individual's size coordinate — height, for plant's models. The defaults take the whole population.

species

Index of the species to act on; NULL (the default) acts on every species in the patch.

intensity

Peak level reached during the episode, in whatever the model measures the stressor in (deg C for a heatwave, say).

duration

Nominal duration of the episode (years; a fortnight is 14 / 365). The action sub-integrates over it at half-hourly steps; patch time does not advance.

threshold

Level above which dose accrues; below it the episode does nothing.

sensitivity

Dose accrued per unit-year above threshold.

Details

The vocabulary here is deliberately model-agnostic, because the machinery is shared by every strategy and environment and nothing about it is specific to plants: a resource pulse is water in TF24 and could be anything countable in a size-structured animal model, and a climate extreme is heat in one model and could be cold or salinity in another. Names that are only true of one model live with that model — rainfall_pulse is a resource pulse of water into TF24's surface soil layer.

Each event carries when it happens, what kind of thing it is, what it acts on, and the values it needs. The target is "environment" (its resource pools and drivers), "patch" (every species) or "species" (one, named by species). There is deliberately no per-cohort target: a cohort has no stable address across a run, because nodes are appended and never removed and schedule refinement changes how many exist. Selecting particular cohorts is expressed as a size range instead, which is both well defined and what size-selective removal needs.

Events are instantaneous to the solver: patch time does not advance across one. An action is still free to reach its answer by integrating its own fast sub-model over a nominal duration — climate_extreme does — with demography frozen. The solver sees one jump either way.

Events sharing a time are applied in a fixed order: the stochastic solver's own death check first (it settles the interval just ended), then environment events, then demographic ones, then node introductions — so a node introduced at that instant starts life in the post-event environment.

The stochastic solver (run(method = "stochastic")) takes the same harvests, pulses and climate extremes, drawing each individual's removal by chance, so that each matches the deterministic event in expectation. Its arrivals are drawn from the birth rates; introductions named in its events replace them, one arrival per time.

Because an event is also a stop time for the integrator, adding one changes the adaptive step sequence. A run with events legitimately differs from one without, at solver tolerance, even away from the events themselves.

What each event actually did — as against what was asked of it — is recorded, and readable afterwards as solver$event_log. The two differ routinely: a pulse is capped at what the pool can hold, and harvesting a size class removes whatever was in it. A removal reports the fraction applied, then, in the deterministic solver, the cohorts touched and the sum of their point densities removed (per unit size), and in the stochastic one the individuals drawn for and those removed per unit area. Only the fraction compares across the two.

events_default(p) is the schedule a run gets when no events are supplied: the node introductions from p$node_schedule_times and nothing else. Pass it on its own to reproduce the default run exactly. An events list that names no introduction takes p's, so events(harvest(...)) is the default run plus a harvest, in both solvers; one that names any introduction replaces p's, so events(events_default(p), harvest(...)) is the same run deterministically.

harvest covers removal generally, not only the forestry sense: leave the size band at its defaults and it is an across-the-board knock-down; set size_min and it takes everything above a size; set both and it thins one size class. They are one action, differing only in which individuals are selected.

Value

An Events object: a list with time, type, target, target_index and params, in schedule order.

Examples

p <- default_parameters("FF16", quiet = TRUE)
p <- add_strategies(p, trait_matrix(1, "lma"))
ev <- events(
  events_default(p),
  harvest(time = 20, fraction = 0.3)
)
## The same run plus a harvest, in either solver; the stochastic one draws
## its arrivals from the birth rates:
ev_harvest <- events(harvest(time = 20, fraction = 0.3))

Export patch state from a deterministic runner

Description

Export the full state of a patch from a (run) DeterministicPatchRunner so it can be re-imported to initialise a new run (see set_initial_state). The exported object captures everything needed to reproduce the patch's forward trajectory: every node's ODE state plus the per-node birth bookkeeping (introduction time, patch-age density and survival probability at birth) that is not part of the ODE state but feeds the rates and lifetime-fitness integrals, the patch age, and the not-yet-introduced ("residual") portion of the node-introduction schedule. A resume re-derives the two birth weights from its own regime (see set_initial_state); they are exported as a record of the run that made them.

Usage

export_patch_state(x, step = NULL)

Arguments

x

A plant_run, or a DeterministicPatchRunner object that has been run.

step

Optional 1-based index into x$history (requires the run to have recorded its steps, record = "steps"); when NULL (default) the deterministic runner's current/final patch is used.

Value

A list describing the patch state, suitable for set_initial_state: time, n (nodes per species), ode_state (flat), the per-species lists node_times, patch_density and pr_patch_survival, the residual node_schedule_times, and events, the run's events still to come – its residual introductions and every action the run had not yet applied when the state was taken (an action at the export time itself is pending in a collected snapshot and in a run that DeterministicPatchRunner$run_to() stopped there, and applied in a finished run's final patch). Events are a run argument rather than a field of Parameters: run(p, from = state) applies them, and a run of set_initial_state(p, state) must be given events = state$events, or it re-runs the residual introductions alone and silently loses any pulse or harvest still ahead.

With the absorbing top layer on (Control$absorb_epsilon), each species' block of ode_state ends with the layer: its pinned individual's states, then its density, its two fitness weights and its two seed totals. A state exported without the layer has no such block, so resuming it with the layer on needs that many zeros inserted after each species' nodes.

See Also

set_initial_state, run


Create an FF16_Environment object.

Description

Create an FF16_Environment object.

Usage

FF16_Environment()

K93_Environment()

Add additional state variables to the species component in output of a model.

Description

Add additional state variables to the species component in output of a model.

Usage

FF16_expand_state(results)

K93_expand_state(results)

expand_state(results)

TF24_expand_state(results)

TF24f_expand_state(results)

TF24t_expand_state(results)

TF24w_expand_state(results)

Arguments

results

from 'tidy_patch'

Value

similar format to input, but with additional columns for additional state variables


Create a FF16 Individual

Description

Create a FF16 Individual

Usage

FF16_Individual(s = FF16_Model())

Arguments

s

A FF16_Model object

Examples

pl <- FF16_Individual()
pl$height

The FF16 model

Description

The FF16 model: the rules that map a plant's traits, size and environment to its growth, fecundity and mortality, with the parameters (pars) and controls they read.

Usage

FF16_Model(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Setup an a model system with default or specified parameters

Description

Setup an a model system with default or specified parameters. This function enables you initialize a model system. Use the model name to start different models.

Usage

FF16_Parameters(...)

K93_Parameters()

Arguments

...

Arguments to be passed to the model constructor. These include

*'max_patch_lifetime': The maximum time in years we want to simulate *'strategies': A list of strategies to simulate. The default is an empty list. *'strategy_default': Values for the default strategy. The default values are those specified in the C++ code for the model. *'node_schedule_times_default': Default vector of times at which to introduce nodes. The default is chosen to have close spacing at the start of the simulation. *'node_schedule_times': A list with each element containing the vector of times we want to introduce nodes for each strategy. The default is an empty list. *'ode_times': A vector of patch ages we want the ode solver to stop at

Examples

p1 <- FF16_Parameters()
p2 <- FF16_Parameters(max_patch_lifetime = 10.0, strategies = list(FF16_Model()), strategy_default = FF16_Model(), node_schedule_times_default = node_schedule_times_default(10.0), node_schedule_times = list(node_schedule_times_default(10.0)), ode_times = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

FF16 model parameters

Description

Biological trait/parameters for the FF16 model. Held as the nested pars element of an FF16_Model (access as s$pars$lma).

Usage

FF16_Pars(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Weight arrivals by a window

Description

Weight arrivals by a window of the run: the continuous patch's regime (plant issue #519). Where the default fitness_weighting = "patch_age" weights a cohort by the density of patches at its age under a Weibull disturbance regime, this weights it by when it arrived in one long run: a cohort born inside [start, end] carries the tabulated weight at its birth date and a cohort born outside carries zero. The net reproduction ratio is then the weighted mean, over the cohorts the run introduced, of a cohort's lifetime output: the trapezium over birth dates of output times weight, divided by the trapezium of the weight on the same grid, so a uniform window is the exact mean however its edges sit against the introduction grid. Patch survival is one.

Usage

fitness_window(p, start, end, weight_x = numeric(0), weight_y = numeric(0))

Arguments

p

A Parameters object.

start, end

The window, in years of the run.

weight_x, weight_y

Optional knots of the weight over the window; weight_x increasing, weight_y non-negative. Omit both for a uniform window.

Details

With no knots the window is uniform, each birth date weighted 1 / (end - start). Knots give a piecewise-linear weight, constant at the end knots' values beyond them: a germination opportunity built from the same rainfall series that drives the run, say.

The run must extend past end by the longest lifespan that matters, or the last arrivals' output is truncated; and the window should open after the stand's burn-in, which export_patch_state lets a run pay once.

The window is closed at both ends, because the trapezium over [start, end] needs a cohort at each. Invaders introduced only inside the window need one at end too: node_schedule_times_periodic(start, end, by, include_end = TRUE).

Value

The modified Parameters object, with fitness_weighting = "window".

See Also

node_schedule_times_periodic


Invader fitness at a fixed point

Description

Fitness of invaders at a resident's fixed point

Usage

fixed_point_fitness(
  x,
  p,
  traits,
  hyperpar = param_hyperpar(p),
  lifetime = 3000,
  survival_tol = 1e-08,
  grid_tol = 0.001
)

Arguments

x

The resident's plant_run or DeterministicPatchRunner, run to its fixed point.

p

The resident's Parameters; each invader's strategy is built from them as add_mutant builds one.

traits

A trait matrix, one row per invader.

hyperpar

Hyperparameter function, as for add_strategies.

lifetime

Years each invader runs for. It has to outlive the cohort: the call fails unless, at the end, none of the cohort survives, or its survival since establishment is below survival_tol and it has stopped growing. A cohort still growing may be on its way to the canopy, where most of its output lies, however few of it are left. An invader that never establishes scores zero.

survival_tol

The survival since establishment below which a cohort that has stopped growing counts as dead.

grid_tol

The largest change in an invader's fitness between the field x stands in and the field half an introduction interval later that passes without a warning, relative to the larger of the two fitnesses and one (so absolute for an invader far below one); NULL skips the check.

Details

A resident at a fixed point makes one field, so an invader of it needs no recording of the resident and no pinned run: it stands in that one field, constant, for its whole life. This runs each strategy in traits as one cohort born at time zero into the field x stands in now, until the cohort is dead, and returns each one's lifetime offspring per seed. Every arrival at a fixed point sees the same field, so that one cohort's output is the invader's fitness. The resident's own strategy scores a resident cohort's lifetime output per seed, which is one at the resident's demographic equilibrium (it is not the run's net_reproduction_ratios, which a continuous patch's ever-growing node list does not make a per-cohort quantity).

The field is taken from the state x has reached at the first call, and used for every later one; run the resident to its fixed point first, for instance with run_until_converged under constant drivers and the absorbing top layer (Control$absorb_epsilon). The invaders run together, as one community, since nothing they do moves a constant field. x is consumed: afterwards it holds the invaders, and the field is cleared, so a later run of it builds its own. A plant_run given here is refused afterwards, so pass every invader in one call.

The introduction grid has to make the stand a fixed point. Between two introductions the field swings, and a grid that is too coarse makes the stand a periodic orbit whose field, taken at an introduction, is the top of the swing: FF16 at its equilibrium birth rate swings by 1.8 % in constant-field fitness at a cohort a year and 0.02 % at four. So each call checks: it runs a copy of the resident on by half an introduction interval (the longest of the species' intervals, and at a species' last introduction the one before it), scores the invaders again in the field there, and warns when any invader's fitness moves by more than grid_tol. A warning means the stand is not at a fixed point between introductions: introduce cohorts more often, or run the resident on until it settles. An event inside that half interval moves the field too, and shows as a swing. The check costs the copy's half interval and a second run of the invaders; grid_tol = NULL skips it, and a check that fails warns and leaves the fitness returned as it is. run_mutant(..., constant = TRUE) holds a field without this check. The copy resumes the resident, so it needs the resident stopped at an introduction, as run(res, until = t) and run_until_converged leave it; a resident run to its end, or stopped between introductions, is warned of as unchecked.

Value

Lifetime offspring per seed, one per row of traits.

See Also

run_until_converged


Generate strategies from traits

Description

Convert a matrix of trait values into a list of strategies (<Name>_Model objects), one per row, by applying the hyperparameter function and inserting the resulting parameters into a copy of the default strategy.

Usage

generate_strategy(p, traits, hyperpar = param_hyperpar(p), birth_rate = 1)

strategy_list(
  x,
  parameters,
  hyperpar = param_hyperpar(parameters),
  birth_rate_list = 1
)

Arguments

p

A Parameters object containing a default strategy to modify. The trade-off function it carries in p$hyperpar (see default_parameters) is applied unless hyperpar is given.

traits

Trait values as a matrix, with column names corresponding to traits (see trait_matrix); one row per strategy. A column may name a field of the strategy's pars, a trait the trade-off function reads, or a numeric top-level strategy field (TF24t's thermal parameters); parameter_table lists them.

hyperpar

Trade-off (hyperparameter) function to use: a closure f(m, s, filter = TRUE) that translates ecological traits (e.g. lma, wood density) into the low-level strategy parameters, encoding the model's trade-offs. Defaults to the one p carries (param_hyperpar(p)); NULL is the explicit identity, which writes every trait straight to the strategy. A p carrying none is treated as the identity too, and said so once per session.

birth_rate

Birth rate(s) for each row of traits: a scalar or vector (constant birth rate, set as strategy$birth_rate_y) or a list with x, y control points (a varying birth rate, which also sets strategy$birth_rate_x and is_variable_birth_rate = TRUE).

x

Deprecated (strategy_list); use traits.

parameters

Deprecated (strategy_list); use p.

birth_rate_list

Deprecated; use birth_rate.


The Control entries a census gradient depends on.

Description

The entries inside a rate evaluation and the schedule that move the gradient. Three are tolerances of a model's inner solves: the leaf's (GSS_tol_abs, ci_abs_tol) and a newborn's height (offspring_height_tol). One is a finite-difference step (node_gradient_eps) and one the schedule's refinement tolerance (schedule_eps). The sixth, gradient_curvature_floor, moves no forward number and still decides which rows exist, by refusing a collar response the profit curvature is too small to support. The list is the same for every model, so it holds entries a model does not read (FF16 reads neither leaf tolerance nor the floor): two of its gradients that differ only there are refused although they are equal, and no two that differ in one are compared. The ODE integrator's tolerances and step bounds move the trajectory too, and are the run's own Control, not listed here. stand_gradient records these and stand_gradient_compare refuses a pair that disagrees.

Usage

gradient_control(x)

Arguments

x

A run DeterministicPatchRunner object, or a plant_run, for the FF16, TF24 or TF24f model, on the birth-date coordinate (TF24's default; control(node_density_coordinate = "birth_date") for FF16).

Value

A named numeric vector of length six.


Individual object

Description

Individual object

Usage

Individual(T, E)

Arguments

T

String containing class of plant strategy to create;

E

String containing class of environmnet to create;


Integrate over the size distribution for each species at each time point, to give totals of each variable

Description

A run carried in birth date ('control(node_density_coordinate = "birth_date")', the default for the TF24 models) is integrated over birth date: the density per unit birth date, and its product with each variable, are interpolated between nodes with a shape-preserving cubic and integrated exactly. Across a cohort that has just formed, density per unit height can fall several hundredfold, and a trapezium in height overcounts there; in birth date the integrand is smooth. A run carried in height is integrated over height with the trapezium rule.

Usage

integrate_over_size_distribution(
  tidy_species_data,
  lower = -Inf,
  upper = Inf,
  coordinate = c("auto", "birth_date", "height")
)

Arguments

tidy_species_data

output of either 'tidy_patch' or 'tidy_species'. Integrating over birth date needs every step of the run, because a node's birth date is the time it first appears.

lower, upper

heights bounding the integral; the defaults integrate over the whole size distribution. Over birth date, a bound cuts where the interpolated height of the cohorts crosses it. Over height, a bound that falls between two nodes takes the integrand by linear interpolation, as the trapezium rule already assumes. Either way, totals over adjacent ranges sum to the total over their union. For a finer height grid, interpolate with 'interpolate_to_heights()' first.

coordinate

'"auto"' (the default) integrates over birth date when the run carries density in birth date, and over height otherwise; '"birth_date"' and '"height"' choose one. '"height"' gives the trapezium totals this function returned before it integrated over birth date.

Value

a tibble whose columns provide metrics on integrated totals for each variable for each species at each time. 'min_height' is the lowest height in the integrated range, and is 'NA' when the range holds no individuals (the totals are then zero).


Extract Internals from plant object

Description

Internals class holding vectors of states, thier associated rates and auxiliary (aux) state which is calculated from the state through running compute_rates

Usage

Internals(s_size, a_size)

Arguments

s_size

???

a_size

???


Interpolate data on size distributions for each species to specific heights at every time point

Description

At each time, the state is interpolated across nodes in height with a shape-preserving cubic (PCHIP) by default, and density through its logarithm, so it stays between the values at neighbouring nodes. Density can fall several hundredfold between neighbouring nodes near the seedling end, and a natural spline through its logarithm then overshoots by orders of magnitude.

Usage

interpolate_to_heights(
  tidy_species_data,
  heights,
  method = "pchip",
  min_log_density = -100
)

Arguments

tidy_species_data

output of either 'tidy_patch' or 'tidy_species'

heights

heights to interpolate to

method

'"pchip"' (the default), or a method for [stats::spline()], such as '"natural"', which this function used before.

min_log_density

Set minimum possible value of log_density

Value

Returns a tibble of similar format to input, but with all outputs interpolated to specified hieghts.


Interpolate data on size distributions for each species to specific time points

Description

Each node's state is interpolated through time with a shape-preserving cubic (PCHIP) by default, which stays between the values at neighbouring steps: a height or a cumulative mortality never falls, and a density never goes negative. A natural spline overshoots wherever a node's trajectory bends sharply, as when a cohort fails to establish.

Usage

interpolate_to_times(tidy_species_data, times, method = "pchip")

Arguments

tidy_species_data

output of either 'tidy_patch' or 'tidy_species'

times

times to interpolate to

method

'"pchip"' (the default), or a method for [stats::spline()], such as '"natural"', which this function used before.

Value

Returns a tibble of similar format to input, but with all outputs interpolated to specified times.


Create a K93 Individual or Node

Description

Create a K93 Individual or Node

Usage

K93_Individual(s = K93_Model())

Arguments

s

A K93_Model object

Examples

pl <- K93_Individual()
pl$height

The K93 model

Description

The K93 model: the rules that map a plant's traits, size and environment to its growth, fecundity and mortality, with the parameters (pars) and controls they read.

Usage

K93_Model(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


K93 model parameters

Description

Biological trait/parameters for the K93 model. Held as the nested pars element of a K93_Model (access as s$pars$b_0).

Usage

K93_Pars(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Describe a landscape of linked patches

Description

A landscape is a set of patches and the flows that link them. Each patch is a scenario: its own species, environment, numerics and events, so patches can differ in anything a single run can. A flow says what passes from one patch to another. run takes a landscape as it takes a scenario.

Usage

landscape(patches, ..., area = NULL)

flow(from, to, type, out_of = 1L, into = out_of, weight = 1, ...)

Arguments

patches

A list of scenarios, one per patch. Its names are the patches' names; an unnamed list is named "1", "2", and so on.

...

For landscape, the flows between the patches, as flow returns them, or none for patches that run side by side unlinked. For flow, further values that its kind takes; a resource flow takes none.

area

The patches' areas, or any numbers in proportion to them, since only their ratios are read: one per patch, in the patches' order or named as they are. By default the patches are equal.

from, to

The names of the patch the flow leaves and the patch it reaches.

type

The kind of flow, which says what it carries: "resource" or "offspring".

out_of

Which part of from's patch the flow comes out of, an index that its kind reads. For a resource flow, a resource pool of the environment, as resource_pulse counts them: TF24's are its soil layers, so 1 is the surface. An offspring flow reads none.

into

Which part of to's patch it goes into, read the same way; by default the same index.

weight

How strongly the flow joins the two patches: what leaves from is multiplied by it on the way to to. For a resource flow, the share of what from sheds that reaches to; for an offspring flow, the share of from's seed that lands in to. Both are between 0 and 1.

Details

Nothing here is specific to a model, or to what flows. Every flow is one row of the same table: the patch it leaves (from) and the patch it reaches (to); its type, which says what it carries; which part of the source it comes out_of and which part of the receiver it goes into, each an index that the type reads; and its weight, how strongly it joins the two.

flow writes rows of that table. There are two kinds of flow:

  • "resource" carries whatever the patches' environments count as a resource, during the run. In TF24 that is water in a soil layer, and flow("ridge", "gully", "resource") passes the part of each rain pulse the ridge's surface cannot hold to the gully.

  • "offspring" says where a patch's seed lands: the share of it that reaches each patch, its own included. Together these flows are the landscape's dispersal matrix. They are read when a run is scored, not during it.

The patches run over one span of time and share its clock, so they must have the same max_patch_lifetime.

Each patch stands for a share of the landscape, set by area. Everything a patch reports is per unit of its own ground area, so an amount that leaves one patch reaches another scaled by the ratio of their areas: a patch three times the size of the one below it delivers three times the depth it shed. A run's landscape-wide fitness weights each patch by its share (see run).

Flows that pass something during the run must lead one way. A landscape is run patch by patch, each one whole, sources before the patches they feed, so a loop of resource flows (one patch feeding another that feeds it back) is refused. Offspring flows are read after the patches have run, so they may go any way.

A landscape is a plain list, and run checks it again, so a patch or a flow can be changed in place.

flow's arguments are vectorised over everything but type, so several flows of one kind are one call.

Value

A list of class plant_landscape with patches, the named scenarios; flows, a data frame with one row per flow (from, to, type, out_of, into and weight); and area, one number per patch.

Resource flows

A resource flow links two patches by what a resource pool cannot hold. A resource pulse is capped at what its pool can take, and the rest is shed (resource_pulse). With a flow out of that pool, the shed amount, times weight, becomes a pulse into the receiving patch's pool at the same instant, after any pulse the receiver has of its own at that instant. The receiver may shed it in turn, and pass it on down its own flows. The weights of the flows out of one pool sum to at most 1; what they leave over leaves the landscape. Between patches of unequal area the pulse that arrives is the share times the ratio of the areas, so that the water arriving is the water that left.

Only what a pulse sheds is passed. A resource a patch loses in any other way stays lost to the landscape: in TF24, the run-off and drainage of rain given as a continuous rate (the rainfall driver) are not passed on, so a patch whose rain all comes that way passes nothing. Nor does a flow out of a pool that no pulse reaches, or that the patch's environment does not have; a flow into a pool the receiving environment does not have stops the run at that patch.

Offspring flows

An offspring flow says what share of the seed produced in from lands in to. A patch may flow into itself, the share of its seed that stays, and two patches may each feed the other. The shares out of one patch sum to at most 1, and what they leave over is lost. An offspring flow joins two patches for every species alike, so it takes no out_of or into.

These flows are the landscape's dispersal matrix, and they are read when a run is scored: a landscape's net reproduction ratio is the dominant eigenvalue of the next-generation matrix they make with the patches' own ratios (see run). A patch's ratio already counts the seed lost in dispersal (the strategy's S_D), so a share is of the seed that survives it.

With no offspring flows, seed is taken to land evenly over the landscape, each patch receiving its share of the area from every patch. Once any is given, seed lands only where a flow takes it: a patch with no offspring flow out of it loses all its seed, and landscape warns of one.

They do not pass seed between patches during a run. Each patch's residents arrive at the birth rates its own Parameters give, and finding the birth rates that the residents' own seed would supply is left to whatever calls run. A share is of a patch's whole seed output, so between patches of unequal area the seed arriving per unit area of to is the share, times the seed produced per unit area of from, times the area of from over the area of to.

See Also

run, scenario, resource_pulse

Examples

p <- default_parameters("TF24", quiet = TRUE)
p$max_patch_lifetime <- 2
p <- add_strategies(p, trait_matrix(0.0825, "lma"))
## Two patches under the same storms, the upper one on a shallow soil.
storms <- events(rainfall_pulse(time = c(0.5, 1, 1.5), depth = 0.06))
shallow <- Environment("TF24")
shallow$set_soil_layer_widths(c(0.05, 0.1, 0.15, 0.2, 0.25))
land <- landscape(
  list(ridge = scenario(p, shallow, events = storms),
       gully = scenario(p, Environment("TF24"), events = storms)),
  flow("ridge", "gully", "resource"))

res <- run(land)
res$transfers                         # what the ridge passed to the gully
res$patches$gully$offspring_production

Leaf model

Description

Argument names match phylloptim's own 'Leaf()' binding exactly (#634): the arguments are positional in C++, so a name here that disagrees with the slot it lands in is a silent error rather than a compile one.

Usage

Leaf(
  vcmax_25,
  stem_c,
  stem_P50,
  root_c,
  root_P50,
  TF24_beta2,
  jmax_25,
  phi_J,
  curv_fact_elec_trans,
  curv_fact_colim,
  GSS_tol_abs,
  vulnerability_curve_ncontrol,
  ci_abs_tol,
  ci_niter,
  TF24_cost_scale
)

Arguments

vcmax_25

maximum carboxylation rate at 25 C (umol m^-2 s^-1)

stem_c

shape parameter of the STEM hydraulic vulnerability curve (unitless)

stem_P50

STEM potential at 50 positive magnitude). phylloptim derives 'stem_b' and 'psi_crit' from it – do not pass the scale.

root_c

shape parameter of the ROOT hydraulic vulnerability curve (unitless)

root_P50

ROOT potential at 50 positive magnitude)

TF24_beta2

exponent for the effect of hydraulic risk (unitless)

jmax_25

maximum rate of electron transport at 25 C (umol m^-2 s^-1)

phi_J

quantum yield of electron transport per ABSORBED photon (mol mol^-1); J reads phi_J * alpha_PAR_ * PPFD. Was 'a' (incident basis) before phylloptim 0.13.0: phi_J = a / alpha_PAR_.

curv_fact_elec_trans

curvature factor for the light response curve (unitless)

curv_fact_colim

curvature factor for the colimited photosynthesis equation

GSS_tol_abs

tolerance parameter for golden section search

vulnerability_curve_ncontrol

number of points for pre-calculating vulnerability curve

ci_abs_tol

absolute tolerance value for root-solving ci

ci_niter

maximum number of iterations for root-solving ci

TF24_cost_scale

cost parameter for the TF24 profit model (umol m^-2 s^-1)


Build an initial size distribution

Description

Build an initial patch state from a specified size distribution, for initialising a patch at age 0 with pre-existing plants instead of growing it from empty (the ecological motivation of plant issue #304). The returned object is consumed by set_initial_state.

Usage

make_initial_state(
  p,
  heights,
  densities = NULL,
  log_densities = NULL,
  env = NULL,
  ctrl = control()
)

Arguments

p

A Parameters object.

heights

Per-species node heights: a numeric vector (single species) or a list of numeric vectors (one per species).

densities

Per-species node densities (same shape as heights). Supply this or log_densities.

log_densities

Per-species node log-densities (alternative to densities).

env

Environment object, or a scenario's recipe of one (defaults to the strategy's environment).

ctrl

Control object.

Details

Each species' initial nodes are described by their heights and densities; the remaining ODE state (mortality, fecundity, accumulated reproduction, heartwood, ...) starts at zero, all nodes are introduced at patch age 0, and the recruitment schedule continues for t > 0 (the initialised distribution replaces the t = 0 recruit). Pathologically large/dense initial conditions can produce non-finite densities; run guards against this and errors with a suggestion to use more plausible inputs.

Value

A state list suitable for set_initial_state. It is marked established: on the birth-date coordinate the densities given are the densities carried, and only the nodes the run introduces take in establishment.

See Also

set_initial_state, export_patch_state


The model registry

Description

Reads plant's model registry: one record per equation of the size-structured layer plant's models share (and, as they are added, of each model), per parameter those equations read, and per slot (a quantity the shared layer reads and every model supplies). Each record names the C++ symbol that evaluates or holds it. The registry is a record of the model, not a second implementation of it; documents render their equations from it (see registry_equation).

Usage

model_registry(path = system.file("model-registry.yml", package = "plant"))

Arguments

path

The registry file; the installed one by default.

Details

An entry may link to another package's registry instead of restating it: TF24's leaf parameters are phylloptim's, and its equations read phylloptim's equations. A link is written package:id. A linked parameter takes its symbol, units, class and meaning from its target when the registry is read, so nothing is copied, and states its own source and placeholder, since its value is plant's. In an equation, a link in reads is something of the other package's that the equation's code reads or calls, and a link in writes is an input of the other package's that it seats. Links resolve against the installed package, which is the version plant compiles against (LinkingTo pins it exactly); a target that is missing there is an error, and an installed version other than the pinned one is a warning, because the other registry's ids are not versioned. Where the package is not installed, links stay unresolved and their borrowed fields are NA.

Value

A list of class plant_model_registry with package, sections (a named character vector, in document order), slots, parameters and equations (data frames, one row per entry, keyed by id; reads, writes and also are list columns; a linked parameter's link names its target), links (one row per link: the entry it is on, its target's package and id, the target's kind, and whether it resolved), linked (one row per package linked to: the installed and the pinned version), not_parameters (a named character vector of reasons), raw (the parsed YAML) and path.

Examples

reg <- model_registry()
reg$sections
registry_equation("density_pde_height", reg)

What a model's size variable is

Description

Every plant model integrates one size state, named height in its outputs, and competes through one size. They are not the same quantity in every model: K93's size is stem diameter and its competitive size is basal area. This reads both, with their units, from the model registry, so a caller labels them without knowing the model.

Usage

model_size(x, registry = model_registry())

Arguments

x

A model name ("FF16", "TF24f", ...), a Parameters object, a plant_run, or a tidied deterministic run, which carries its parameters as $p.

registry

A registry from model_registry.

Value

A list of model, size and size_units (the state named height), and competitive_size and competitive_size_units. A model that extends another inherits its entries.

See Also

canopy_profile, expand_state

Examples

model_size("K93")$size
model_size(base_parameters("FF16"))$size_units

Scientific version of a physiological model

Description

The scientific version increments only when a model's equations or default parameters change the simulation output for identical inputs. It is independent of the package Version (which also moves for refactors, performance and interface changes). Downstream tools such as logpile use it to decide when archived simulations must be re-run: reruns happen when the scientific version changes, not on every software release.

Usage

model_version(type)

model_id(type)

Arguments

type

Any strategy name as a string, e.g.: "FF16".

Details

The version is returned as a string. It is usually a single integer ("1"), but may be compound for a model defined relative to another: TF24f is an approximation of TF24, so its version is "<TF24 version>.<approximation revision>" (e.g. "2.1"); the major component auto-tracks TF24, so a TF24 scientific change also invalidates TF24f. TF24t is compound the same way, "<TF24 version>.<thermal revision>", the revision moving only for a change to its thermal-damage layer.

The number is authored in C++ (the scientific_version, approximation_revision and thermal_revision constants on each model class, see inst/include/plant/models/*_model.h) and read here through the compiled strategy_scientific_version(); there is no duplicated copy in R.

Value

For model_version, a version string (e.g. "1" or "2.1"). For model_id, a string of the form "FF16@v1" (model name and scientific version).


No disturbance regime No_Disturbance_Regime control object

Description

A disturbance-free regime for running individual patches

Usage

No_Disturbance()

Generate Default Node Introduction Times

Description

Generate a suitable set of default node introduction times, biased so that introductions are more closely packed at the beginning of time, become increasingly spread out.

Usage

node_schedule_times_default(max_time)

Arguments

max_time

Time to generate introduction times up to (the last introduction time will be at least max_time).

Details

The reason for the stepped distribution is to keep step sizes as series of doublings. Doing this limits the range of possible introduction times from an infinite set of possible values to a very limited subset of values (based on combinations of 1, 0.5, 0.25, 0.125 etc). The reason for doing this is to minimise the number of unique introduction times across all species. The ODE stepper needs to stop at each point where a node is introduced. If each species was selecting a bunch of points that was essentially unique (compared to those selected for all other species), the number of unique node introductions times could get very large, requiring more ODE steps.

Value

Vector of introduction times.

Author(s)

Rich FitzJohn, adapted from original C++ code by Daniel S. Falster.


Periodic node introduction times

Description

Node introduction times on a uniform grid, for a run that introduces a cohort periodically rather than on the front-loaded default schedule of node_schedule_times_default: the continuous patch (plant issue #519). Times run from start in steps of by. By default they stop short of end, so consecutive spans tile without repeating a time: periodic(0, 100, 1) and periodic(100, 200, 1) meet at 100 once. A cohort introduced at a run's max_patch_lifetime would never be integrated either.

Usage

node_schedule_times_periodic(start, end, by, include_end = FALSE)

Arguments

start

First introduction time.

end

The span's end.

by

Spacing between introductions, in years.

include_end

Whether a time landing on end is kept.

Details

A schedule for a fitness_window over [start, end] is the other case: the window weighs a cohort at each end, so a schedule ending at end needs include_end = TRUE to have the cohort there that the resident has. Without it the window average misses the last arrival (2 % low for a copy of the resident over ten). It must start before start: on the birth-date coordinate a species' first cohort takes establishment only from its birth on, so run_mutant refuses a window that weights an invader's first cohort.

Value

A numeric vector of introduction times, for one species of p$node_schedule_times.

See Also

fitness_window


ODE Control parameters

Description

Control parameters for the ode system

Usage

OdeControl(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


'optimise_individual_rate_at_size_by_trait' solves for the maximum of some rate (e.g. growth rate) at a specified height within the interval of the bounds of a given trait

Description

'optimise_individual_rate_at_size_by_trait' solves for the maximum of some rate (e.g. growth rate) at a specified height within the interval of the bounds of a given trait

Usage

optimise_individual_rate_at_size_by_trait(
  type = "FF16",
  bounds,
  log_scale = TRUE,
  tol = 0.001,
  size = 1,
  size_name = "height",
  rate = size_name,
  params = default_parameters(type, quiet = TRUE),
  env = Environment(type),
  hyperpars = param_hyperpar(params),
  set_state_directly = FALSE
)

Arguments

type

The type of model to use (e.g. "FF16"). Defaults to "FF16"

bounds

A vector giving the lower and upper bounds of the trait

log_scale

Should the trait be optimised on a log scale? Defaults to TRUE

tol

The tolerance for the optimisation

size

The size of the individual to optimise the rate at

size_name

The name of the size variable specified by size

rate

The name of the rate to optimise. Defaults to size_name

params

The parameters of the model. Defaults to plant's testing set, default_parameters(type, quiet = TRUE), so that the trade-offs apply to the trait being optimised.

env

The environment of the model

hyperpars

The trade-off function; defaults to the one params carries (param_hyperpar(params))

set_state_directly

If TRUE, set the state directly to the size, otherwise grows the plant to that size. Defaults to FALSE

Author(s)

Isaac Towers, Daniel Falster and Andrew O'Reilly-Nugent


Every parameter of a model, grouped by how a user reaches it

Description

One table of everything a model can be told, so the options are visible in one place (#698). Rows are grouped:

trait

what the trade-off function reads from a trait matrix: the ecological traits. A trait that is not itself a field of pars (FF16's narea) has no default here.

derived

what the trade-off function derives from the traits. Naming one of these in a trait matrix is refused, because the trade-off would overwrite it; set the trait it comes from, or build the strategies with hyperpar = NULL.

parameter

the remaining fields of pars: settable as traits, with no trade-off attached to them.

strategy

numeric fields a strategy carries at its top level, beside pars (TF24t's thermal parameters, TF24f's acclimation settings). A trait matrix reaches these too.

control

Control's numerical settings, which govern how the model is solved rather than what is solved.

Which rows are trait and derived depends on the trade-off function: with none attached every field of pars is a parameter. The coefficients of the trade-offs themselves (slopes and intercepts) are not model parameters and are not listed; they are documented with the trade-off functions (fieldtrial's coefficient tables, or frozen_TF24_hyperpar for plant's frozen copy).

Usage

parameter_table(x, hyperpar = NULL)

Arguments

x

A model name ("FF16", "TF24", ...), or a Parameters object, whose own trade-offs are then read.

hyperpar

The trade-off function to classify by. For a model name it defaults to plant's frozen testing trade-offs (default_hyperpar); for a Parameters object to param_hyperpar(x). Pass NULL explicitly for no trade-offs (every pars field becomes a parameter).

Value

A tibble with one row per parameter: name, group, default (the strategy's or control's default, as text; read the exact double from TF24_Model()$pars or Control()), description, symbol (LaTeX, in $) and unit (Unicode, "–" for a dimensionless one), from the model's entries in the model_registry and those of the models it extends. These are NA where the registry holds no entry: the control rows, a trait the trade-off reads that is not a field of the model (FF16's narea), and a linked leaf parameter when phylloptim is not installed.

See Also

default_parameters, generate_strategy, trait_matrix, model_registry

Examples

tab <- parameter_table("TF24")
table(tab$group)
tab[tab$group == "derived", "name"]

Activate logging (deprecated)

Description

Activate logging (deprecated)

Usage

plant_log_console(file_name = "console", colour = TRUE, threshold = "INFO")

Arguments

file_name, colour, threshold

Ignored.

Details

plant writes nothing to a log, so this has no effect. It is kept so that existing scripts still run, and will be removed in a later release.


Gauss-Kronrod Quadrature

Description

Gauss-Kronrod Quadrature

Usage

QK(rule)

Arguments

rule

Degree of the rule; valid sizes are 15, 21, 31, 41, 51, 61.


A rainfall pulse for TF24.

Description

TF24's resources are its soil layers, so a rainfall pulse is a resource_pulse of water into one of them. This is the motivating case for the event mechanism (#522): TF24 otherwise takes rainfall as a smooth cubic spline, which smears out exactly the variability that matters — large pulses.

Usage

rainfall_pulse(time, depth, layer = 1, env = NULL)

Arguments

time

Event time(s), in years of patch age.

depth

Depth of water delivered, in m — so 13 mm is 0.013.

layer

Soil layer to deliver it to. The default, 1, is the surface, i.e. rain. A deeper layer is irrigation, or a water table rising into the profile.

env

Optionally, the Environment the run will use, or a scenario's recipe of one. When given, rainfall_pulse() warns if that environment still carries a non-zero continuous rainfall driver — pulses add to the continuous forcing rather than replacing it, so supplying both silently double-counts the water. Set the driver to zero to model rainfall as pulses alone.

Details

The surface layer accepts what its free capacity allows and sheds the rest, which is not a corner case: a realistic dryland event (~13 mm) already exceeds a moderately wet layer's capacity. solver$event_log reports how much of each pulse landed and how much was shed.

Value

Event rows, to be combined with events.

See Also

events, resource_pulse

Examples

p <- default_parameters("TF24", quiet = TRUE)
p <- add_strategies(p, trait_matrix(1, "lma"))
ev <- events(
  events_default(p),
  rainfall_pulse(time = c(1.5, 3.2), depth = c(0.013, 0.050))
)

One equation's LaTeX, from the model registry

Description

The display a document renders for an equation, so that the page's LaTeX is the registry's. Write it into a page as a display, for example in a chunk with results = "asis": cat("$$", registry_equation(id), "$$").

Usage

registry_equation(id, registry = model_registry())

Arguments

id

The equation's id, or a link ("phylloptim:carbon") to an equation in a linked package's registry, whose LaTeX is returned.

registry

A registry from model_registry.

Value

The LaTeX, a single string without surrounding $$.


Parameter values, from the live model

Description

The registry stores no values; this reads each parameter's current default off the model, so a table rendered from the registry shows the number the model runs with. Parameters held on Parameters are read from base_parameters(model), and a model's own parameters (those of model and of any model it extends) from its default strategy's pars, or from the strategy itself for a subclass's traits held beside pars; a literal gives its own value. Other models' parameters, those held on the environment, and any not held as a single number, are NA.

Usage

registry_values(registry = model_registry(), model = "FF16")

Arguments

registry

A registry from model_registry.

model

The model whose defaults to read, e.g. "FF16".

Value

registry$parameters with a value column.


Whole plant light compensation point

Description

Compute the whole plant light compensation point for a single plant: the light level at which whole-plant carbon gain is zero.

Usage

resource_compensation_point(p, ...)

Arguments

p

An Individual, with strategy, height, etc set.

...

Additional arguments that are ignored

Author(s)

Rich FitzJohn


Run plant

Description

One verb for a run, whatever describes it:

Usage

run(x, ...)

## S3 method for class 'plant_scenario'
run(
  x,
  ...,
  until = NULL,
  from = NULL,
  record = character(0),
  refine_schedule = FALSE,
  method = c("deterministic", "stochastic")
)

## S3 method for class 'Parameters'
run(x, env = NULL, control = plant::control(), events = NULL, ...)

## S3 method for class 'plant_run'
run(x, ..., until = NULL)

## S3 method for class 'Individual'
run(x, env = NULL, ..., times = NULL, sizes = NULL, size_name = "height")

## S3 method for class 'plant_landscape'
run(
  x,
  ...,
  until = NULL,
  from = NULL,
  record = character(0),
  refine_schedule = FALSE,
  method = c("deterministic", "stochastic")
)

Arguments

x

What to run: a scenario, a Parameters object, a plant_run to continue, an Individual, or a landscape.

...

For a Parameters object, the arguments below. For an Individual grown to sizes: time_max, the time to stop at if a size is never reached (default Inf); warn, whether to warn when sizes are dropped (default TRUE); and filter, whether to drop sizes not reached from the result (default FALSE).

until

Where to stop: NULL runs the whole patch lifetime, and a time stops at the first step boundary at or past it. A time at or before the start builds the run without taking a step, for a caller that drives it: run_until_converged, or run(res, until = ). Continue with run(res).

from

Where to start: NULL starts the patch empty; a state exported with export_patch_state, or a plant_run (exported where it stands), resumes from it. The resumed run introduces nodes on the scenario's own schedule from the export on, and applies the events the state still had to come, so no pulse or harvest pending at the export is lost. Those events are the run's: a scenario given with from must carry none of its own. The schedule is p$node_schedule_times, so a run whose introductions came from its own events instead resumes on p's; set p$node_schedule_times to its times.

record

What to keep beyond the outputs every run reports: "steps", the patch at every step, which tidy() reads; and "states", the ODE state at every step, which a gradient sweeps (stand_gradient).

refine_schedule

Refine the node-introduction schedule before the run, bisecting the intervals whose nodes' error exceeds control$schedule_eps, up to control$schedule_nsteps times. The result is a run of the refined schedule: if the last pass still bisected, that schedule is run once more. An interval halved down to adjacent doubles cannot be bisected again; refinement leaves it, stops once nothing it flags can be split, and warns, the solver's unsplittable_node_times naming the node above each such interval. The schedule is in the result's scenario$p, with the ODE schedule that run took (ode_times, ode_step_sizes, ode_soil_input_slopes, ode_soil_substep_ends), so a later run of those parameters takes those steps exactly; where the scenario's events name the introductions, as a resumed run's do, their introductions are the refined schedule too, and a run of it steps to those ODE times, which agrees to rounding. A resumed run refines only the introductions still to come, and not the interval before the first of them. With record = "states", refinement's own passes keep no states, and the run the result reports keeps them; if the refinement converged, that is one more run.

method

"deterministic" (the default) or "stochastic".

env, control, events

For a Parameters object, as scenario takes them. For an Individual, env is the Environment it grows in, or a recipe of one, by default its model's.

times, sizes

For an Individual, the times to report it at, finite and not before the environment's time, or the sizes to grow it to; either increasing. Give one.

size_name

The size sizes are of.

Details

  • a scenario, the bundle of everything a run takes;

  • a Parameters object, with the rest given as arguments (run(p, env = env) is run(scenario(p, env)));

  • a previous result, which continues it to until;

  • an Individual, a single plant grown on its own;

  • a landscape, several patches and the flows that link them.

method chooses the solver: "deterministic", by the method of characteristics, or "stochastic", the finite population of individuals, arriving at random and each establishing and dying by chance. The stochastic run takes the scenario's p, env and control and runs the whole lifetime. Arrivals are drawn from each species' birth rate (the curve the deterministic run's inflow reads) over the patch's area, as a Poisson process in continuous time, not from p$node_schedule_times; the result's scenario$p carries the times drawn. Introductions named in events replace them, one arrival per time.

A stochastic patch is a finite stand of control$stochastic_patch_area m2, 100 by default, set in the run's control as in control = control(stochastic_patch_area = 400). Its mean is not the deterministic answer: the environment is a nonlinear function of a random population, so once the canopy closes a small patch's mean stand departs from the deterministic one, which is its limit as the area grows. For FF16's default strategy at age 40, the mean density is 50% below the deterministic density at 5 m2, 28% at 20, 14% at 80 and 3% at 320. Run time grows faster than the area. Averaging many small patches narrows the noise but not this gap, so a comparison with the deterministic run needs a large area. The deterministic run has no area: its state is a density per m2.

The stochastic run has no fitness integral, so its result's fitness values are NULL, and it refuses until, from, refine_schedule and record = "states". It takes events' harvests, resource pulses and climate extremes, drawing each individual's removal by chance. Its deaths are drawn every control$stochastic_death_interval years, 0.01 by default, which is set in the run's control, as in control = control(stochastic_death_interval = 0.05). Survival is exact at any interval, but a plant that has died shades the living until the next draw. Where shade is what kills, a longer interval runs faster and leaves fewer plants than continuous checks would: in a closing FF16 canopy about 2% fewer at 0.05 and 0.5% at 0.01. Seed R's random number generator to repeat one.

A single plant is grown by run(individual, times = ), which reports it at each time, or run(individual, sizes = ), which grows it to each size: the time a size is reached is located on the step that crosses it, and the run lands there, so the time, state and plant reported for a size describe the same instant. A plant grown on its own sees the environment it is given, not a patch's shading.

A landscape is run patch by patch. Each patch is run whole, as its own scenario would be, after the patches that feed it; what those passed down their flows is added to its scenario first. record, refine_schedule and method apply to every patch, and until and from are refused.

Value

A plant_run: a list with scenario (what was run, its p the solver's, carrying any refined schedule), time and complete (where the run stands), offspring_production and net_reproduction_ratios (per species, at time), event_log (what each event did), mutants (the invaders' Parameters for a run_mutant result, else NULL), method, and solver, the live DeterministicPatchRunner. A stochastic result's fitness values are NULL, its event_log holds what its events did (a removal reports individuals drawn for, and those removed per unit area), its steps hold what record = "steps" kept, and its solver is a StochasticPatchRunner. An Individual's run returns a plant_individual_run instead: a list with time (the times given, or when each size was reached, NA for one that was not), state (the ODE state at each time, as a matrix), individual (a list of the plant at each) and env, and when grown to sizes trajectory, the time and state at every step taken, the steps landed on each size among them.

A landscape's run returns a plant_landscape_run: a list with landscape (as given, so run(res$landscape) runs it again), patches (a plant_run per patch, by name; a patch's scenario is what that patch ran, including what reached it down the flows), transfers (a data frame of every amount passed between patches: time, from, to, type, out_of, into and amount, the amount that reached to, per unit of its area), offspring_production (per species, the seed produced per unit of the landscape's area: the patches' values, each weighted by its patch's share of the area), net_reproduction_ratios (per species, the dominant eigenvalue of the next-generation matrix, in which a seed arriving in a patch leaves that patch's own ratio of offspring and the landscape's offspring flows say where those land. With no offspring flows, seed lands evenly, and the value is the patches' ratios weighted by their shares of the area. It means what the patches' ratios mean: under the "patch_age" and "window" weightings, the factor by which a species' seed multiplies over a generation across the landscape; under "none", where a patch's ratio is its seed output over the whole run per unit of birth rate, a value that grows with the run's length and compares strategies on one landscape. It is NA for a species whose ratio is not finite in some patch. Both are given only where every patch holds the same strategies, in the same order, under the same fitness weighting, and are NULL otherwise, as for a stochastic run. Patches may differ in birth rate. Nothing here finds the birth rates at which the residents replace themselves), mutants (for a run_mutant result, the invaders' Parameters in each patch, else NULL) and method. tidy() of it is a list of each patch's.

A result holds until its solver moves. Whatever moves it – run() continuing it, run_mutant(), run_until_converged() – returns the result that describes it, and every function that takes a result refuses one whose solver has moved on since. fixed_point_fitness() uses a result up, so give it every invader in one trait matrix.

saveRDS() keeps everything but the solver: the values are copies and the scenario holds its environment as a recipe. A deterministic result read back runs again from its scenario: run(res, until = res$time) rebuilds it where it stood, taking the same steps, and run(res) carries on to the end. That repeats the run's work. An invaders' result is rebuilt by running its resident again and then run_mutant().

See Also

scenario, run_mutant, export_patch_state, stand_gradient


Run invaders against a resident

Description

The invaders in p run in the field the resident recorded, which they read and do not move; with constant = TRUE, in the one field the resident stands in now (see fixed_point_fitness).

Usage

run_mutant(resident, p, constant = FALSE)

Arguments

resident

A complete plant_run of the resident, or a landscape's run.

p

The invaders' Parameters, as add_mutant builds them. For a landscape, either one Parameters, whose strategies invade every patch under that patch's own Parameters (its fitness weighting, and introductions at every time its residents had one); or a list of one for each patch, named as the patches are and used as given, each built from its own patch's scenario$p.

constant

Hold the field the resident stands in now, rather than replay the one it recorded.

Details

Against a landscape's run, the invaders run in every patch, each in what that patch's resident recorded, what flowed into it included. They change nothing that flows. The result's landscape-wide fitness is theirs. Every patch's result is used up, as a single resident's is; if a patch refuses the invaders after others have run them, the landscape must be run again.

Invaders meet every event of the resident's run: its pulses, harvests and climate extremes. On the birth-date coordinate a cohort's density carries establishment averaged over the intervals beside it, and an invader species' first cohort has none before it. A fitness_window that weights an invader's first cohort born after the residents' first (or after the resume of a resumed resident) is refused: open the window after the invaders' first introduction. TF24w's invaders are refused, because its private water is not in the field a replay reads.

Value

A plant_run of the invaders: their outputs, with mutants set to p and scenario the resident's. It shares the resident's solver, which now holds the invaders, so the resident's result is refused from here on (see run). For a landscape, a plant_landscape_run of the invaders, its patches each such a result.


Check performance on current system using package bench

Description

Check performance on current system using package bench

Usage

run_plant_benchmarks(strategy_types = list(FF16 = FF16_Model), iterations = 1)

Arguments

strategy_types

A list of name strategy types to be tests

iterations

The number of iterations to be run

Details

For branch-to-branch performance comparisons, run 'make' before 'devtools::load_all(quiet = TRUE)' so compiled code is rebuilt with the package's intended optimization flags.

Value

A dataframe of results


Run until the stand's block means settle

Description

Run a patch until its stand has settled, judged on block means of its snapshots: the burn-in of a continuous patch (plant issue #519), paid once and then exported with export_patch_state.

Usage

run_until_converged(
  x,
  block = 20,
  tol = 0.02,
  t_max = x$parameters$max_patch_lifetime,
  statistics = c("density", "height_max", "environment"),
  snapshot_interval = 1,
  environment_entries = NULL,
  window = 3,
  tol_abs = 0
)

Arguments

x

A plant_run stopped before its end (run(p, until = 0)), or a DeterministicPatchRunner built and not yet run to the end, as run(p, ..., until = 0)$solver is, whose schedule reaches t_max. Its snapshot_interval is set to snapshot_interval if it is zero.

block

Years per block.

tol

Relative range of the last window block means below which a statistic counts as settled.

t_max

Time to give up at; defaults to the run's max_patch_lifetime.

statistics

Which of "density" (the species' carried density summed), "height_max" (the tallest cohort with density over the species), "n_live" (cohorts with density, summed) and "environment" (entries of the environment's state) to judge. The default leaves out "height_max" when the absorbing top layer is on, since the layer pins it at the absorbing height whatever the stand does.

snapshot_interval

Years between snapshots when the deterministic runner has none set.

environment_entries

Which entries of the environment's state the "environment" statistic reads. NULL (the default) reads every entry but the cumulative flux accumulators (TF24's last five), which grow without bound, so that their relative change shrinks with time whether or not anything has settled.

window

Number of consecutive block means that must agree.

tol_abs

Absolute range below which a statistic counts as settled whatever its size: for one that settles at or near zero. Zero, the default, judges every statistic relatively.

Details

The run advances one block at a time with x$run_to(). After each block the mean over that block's snapshots is taken of the chosen statistics, and the run is converged once the last window block means of every statistic agree: their range is below tol times the largest of them in magnitude, or below tol_abs. Judging the range over a window rather than the change between neighbouring blocks is what lets a steady drift accumulate into the test instead of passing block by block. It stops regardless at t_max, or when the schedule is consumed, and says which it was; a last block shorter than block runs the patch on to t_max without being tested. Under a stochastic driver the block has to span several of the driver's correlation times, or the test measures the driver and not the stand. A statistic that is NA in a block – the tallest cohort of a stand with none alive – cannot settle, and the function warns which.

A settled stand statistic is not a settled fitness. A drift slower than tol per window * block years passes, and an invader's fitness can be far more sensitive to the stand than the statistic is: a TF24 stand under constant rain at its equilibrium birth rate was still gaining 0.1 % density a century at year 5000, and the resident's fitness read off it at years 300 and 500 differed sixfold. Check the quantity you will use at two times.

Value

A list: converged, time (where the run stands), and trace, a data frame with one row per block of the block means and the relative range of each over the window ending there (rel_*, NA until window blocks have run). Given a plant_run, also run, the result where the run now stands.

See Also

tidy_snapshots, export_patch_state


Sample individuals from the size distribution

Description

Draws a random sample of individual plants from a stand simulated by [run()]: how many stand in a given ground area, and how big each one is. Given several times, the same individuals are followed through all of them, so each grows with its cohort and, once dead, stays dead.

Usage

sample_size_distribution(results, area, times = NULL)

Arguments

results

Output of 'tidy(run(p, control = ctrl, record = "steps"))', run with density in birth date.

area

Ground area to sample (m^2).

times

Times at which to report the sample. Defaults to the end of the run, a single snapshot.

Details

The deterministic solver carries density per unit ground area and per unit birth date. Individuals are drawn as a Poisson process over birth date, at the density at the first requested time they could be seen, interpolated between nodes with a shape-preserving cubic (PCHIP). Each then carries a fixed hazard budget, drawn from a unit exponential, and is dead from the first requested time at which the fall in log density at its birth date since then exceeds that budget. In birth date a cohort's density changes only through mortality, so at every requested time the number of individuals is Poisson, with mean the area times the integral of the density over birth date. The sample is exact apart from the interpolation between nodes. The set of nodes changes from frame to frame, so the interpolated density at a birth date can rise slightly, and so can the newest cohort's, which takes in establishment until the next cohort arrives; having no births to add, the sample then follows its running minimum. Individuals of a cohort that leaves the tracked nodes (as a continuous patch retires its oldest cohorts) drop out of the sample. Every other state variable is interpolated to an individual's birth date in the same way.

The run must carry density in birth date, 'control(node_density_coordinate = "birth_date")'. Set the seed with [set.seed()] to make a sample reproducible.

Value

A tibble with one row per individual alive at each requested time: 'species', 'individual' (the same at every time), 'birth_time', 'time', and each node state variable interpolated to the individual ('height', 'mortality', 'fecundity', ...).

Examples

## Not run: 
p <- default_parameters("FF16", quiet = TRUE)
p$max_patch_lifetime <- 50
p <- add_strategies(p, trait_matrix(0.0825, "lma"), birth_rate = 20)
results <- tidy(run(p, control = control(node_density_coordinate = "birth_date"),
                    record = "steps"))
set.seed(1)
trees <- sample_size_distribution(results, area = 400, times = c(10, 20, 50))

## End(Not run)

Describe a run of plant

Description

A scenario holds everything a run takes: who is present and how fitness is weighted (p), the forcing (env and events) and the numerics (control). run takes one, or builds one from the same arguments, and every result carries the scenario it ran as $scenario, so run(res$scenario) runs it again.

Usage

scenario(p, env = NULL, control = plant::control(), events = NULL)

Arguments

p

A Parameters object.

env

An Environment, or a recipe of one (a scenario's env); by default the model's own.

control

A Control object.

events

An events object, or NULL for the introductions in p$node_schedule_times alone.

Details

A scenario is a value: it keeps its environment as a recipe, plain values for everything a run reads from it, and each run builds the environment afresh from that recipe. So a scenario, and a result carrying one, survives saveRDS() and runs after readRDS(), and a change made to env after the scenario was made does not reach it. Environment(sc$env) builds the environment a scenario describes.

Value

A list of class plant_scenario with p, env (the environment's recipe), control and events.

See Also

run


The queue of scheduled events: node introductions, resource pulses, harvests and climate extremes

Description

The queue of scheduled events: node introductions, resource pulses, harvests and climate extremes

Usage

Schedule(n_species)

Arguments

n_species

number of species


Sequence in log space

Description

Sequence in log space

Usage

seq_log(from, to, length.out)

seq_log_range(r, length.out)

seq_range(r, length.out)

Arguments

from

Starting point

to

Ending point

length.out

Number of points to generate

r

range (i.e., c(from, to)

Details

Unlike the billions of options for seq, only length.out is supported here, and both from and to must be provided. For completeness, seq_range generates a range in non-log space.

Author(s)

Rich FitzJohn


Give Parameters an initial patch state

Description

Write an exported patch state (from export_patch_state) into a Parameters object so that the next run starts from that state instead of an empty patch. The state is carried on the Parameters object (rather than passed separately) so the run stays self-describing and reproducible, and so the initial state survives the reset at the start of every run / schedule refinement.

Usage

set_initial_state(p, state)

Arguments

p

A Parameters object (its strategies must match the exported state).

state

An exported state list from export_patch_state.

Details

Each initial cohort's patch density and survival at birth are read from the resuming parameters' own regime at its birth date, not taken from the export: a cohort initialised from a burn-in into a fitness_window run weighs what the window gives it. Under the regime that exported it they are the same numbers. The exported patch_density and pr_patch_survival are checked only for their lengths.

Value

The modified Parameters object. The state's events are not carried on it: pass them to run as events = state$events, or resume with run(p, from = state), which does both.

See Also

export_patch_state, run


Set a TF24 soil profile in one call

Description

Sets the layer geometry, then the per-layer parameters, then the water state, in that order – which is the only order that works, and the reason this function exists.

Usage

set_tf24_soil(
  env,
  widths = NULL,
  theta = NULL,
  soil_moist_sat = NULL,
  K_sat = NULL,
  a_psi = NULL,
  n_psi = NULL
)

Arguments

env

A TF24_Environment.

widths

Layer widths, m, top down – e.g. a profile grading from a thin surface layer, as fieldtrial's soil_widths_graded() builds. Must not get thinner with depth (equal is fine). A single number sets one layer of that width. If NULL the geometry is left alone.

theta

Initial volumetric soil moisture. A single number is used for every layer; a vector must have one entry per layer. If NULL the layers start at half saturation, matching the constructor.

soil_moist_sat, K_sat, a_psi, n_psi

Per-layer soil parameters, each either NULL (use the scalar field for every layer) or a vector with one entry per layer. If all four are NULL the layered-parameter path is not engaged at all. a_psi is the retention-curve scale in MPa.

Details

Changing the number of layers necessarily discards the water state and any per-layer parameters, because both are per layer and there is no defensible way to re-map them onto a different column. So a caller doing this by hand has to know that set_soil_layer_widths() comes before set_soil_parameters(), which comes before set_soil_water_state(). Getting it wrong is silent: the profile is simply the previous one, and both are valid geometries.

Value

env, modified in place and returned invisibly.

Examples

env <- Environment("TF24")
set_tf24_soil(env, c(0.02, 0.06, 0.18, 0.44, 0.80), theta = 0.2)
env$get_soil_layer_widths()

Metrics of a solved stand.

Description

stand_census reports the census metrics: the trapezium integral of nkψ(statek)n_k \psi(\mathrm{state}_k) over the size distribution, for each per-plant quantity ψ\psi, summed over the species. The grid is the coordinate the density is carried in – the birth date, or the height – and the inflow boundary node closes it, so the interval between it and the smallest cohort is in the sum.

Usage

stand_census(x)

stand_fitness(x)

Arguments

x

A run DeterministicPatchRunner object, or a plant_run, for the FF16, TF24 or TF24f model, on the birth-date coordinate (TF24's default; control(node_density_coordinate = "birth_date") for FF16).

Details

stand_fitness reports, for a model that declares its fitness differentiable (FF16, TF24 and TF24f), each species' net reproduction ratio and offspring production, named "<species>.net_reproduction_ratio" and "<species>.offspring_production". They are the same numbers as a run's net_reproduction_ratios and offspring_production, reported under the names stand_gradient differentiates them by.

Value

A named numeric vector, one entry per metric.


Sensitivity of the stand metrics to the ODE state at the current time.

Description

One row per metric – the census metrics, then for a model that declares its fitness differentiable each species' net reproduction ratio and offspring production, named as stand_gradient names them – and one column per ODE state entry, in the order x$patch$ode_state writes. This is what the reverse pass starts with. On the birth-date coordinate, the only one the gradient runs on, the trapezium weights are constants, so the cohort-height columns carry the integrand's response alone.

Usage

stand_census_state_adjoint(x)

Arguments

x

A run DeterministicPatchRunner object, or a plant_run, for the FF16, TF24 or TF24f model, on the birth-date coordinate (TF24's default; control(node_density_coordinate = "birth_date") for FF16).

Value

A numeric matrix, metrics by ODE state entries.


Gradient of a stand's metrics with respect to traits.

Description

Doubles in and doubles out: the active scalar is created and destroyed inside one call and never crosses into R.

Usage

stand_gradient(
  x,
  metrics = NULL,
  traits = NULL,
  hyperpar = param_hyperpar(x$parameters),
  mode = c("auto", "reverse", "forward")
)

Arguments

x

A run DeterministicPatchRunner object, or a plant_run, for the FF16, TF24 or TF24f model, on the birth-date coordinate (TF24's default; control(node_density_coordinate = "birth_date") for FF16). The sweep reads the state at every step. A run that kept none (one run without record = "states") is run again inside this call to keep them, which costs as much as the run did and gives the same numbers; the solver keeps them afterwards (x$keep_states is then TRUE), so a second call does not repeat it. Run with record = "states" to pay for the run once.

metrics

Metric names to differentiate; defaults to every metric the model declares: the census metrics (stand_census) and, for a model that declares its fitness differentiable, each species' "<species>.net_reproduction_ratio" and "<species>.offspring_production" (stand_fitness). The steps are recorded once for all the metrics asked for, and each further metric adds only a walk back over them, a small part of the first metric's cost; under the sweep, asking for fewer traits saves nothing (see mode).

traits

Column names to differentiate with respect to; defaults to every differentiable trait every species declares. A column is named for its species and its parameter, as "1.lma".

hyperpar

The hyperparameter function the strategies were built with, by default the one add_strategies() uses; or NULL for partial derivatives. See the section on traits and parameters.

mode

How the gradient is computed. "reverse" sweeps back over the recorded steps once per metric, at the same cost whatever the number of traits. "forward" walks forward over the same steps carrying one direction per trait column, up to eight in a walk, so its cost grows with the columns and does not depend on the number of metrics. It is for FF16 only, and an error for any other model. "auto", the default, takes the forward route where it can when fewer than nine columns are needed, and the sweep otherwise. The two routes give the same shape, names and refusals; a partial derivative agrees to rounding (about 1e-15 of the metric's largest entry), and a total through a hyperparameter function can lose more to cancellation in the chain rule. Under a hyperparameter function the columns counted are the ones the chain rule reads: the traits asked for and each parameter derived from them that moves with one (FF16's lma adds k_l and r_l).

Details

Two terms, because a census reads the traits as well as the state. The reverse pass starts on the states the census reads at the end of the run and runs back over the steps the adaptive pass resolved; added to it is the census's own reading of the traits at that state, which is not a sensitivity of the state and so no sweep produces it.

Value

A list with value, the metrics at the end of the run; gradient, a metrics-by-traits matrix; refusal, one entry per metric holding the reason and the species it was found in (NA where it belongs to none), or NULL where the metric answered; and control, the entries the gradient was taken at.

Refused outright, with an error: a run on the height coordinate or in a constant field; with the absorbing top layer on, a run with a harvest or climate extreme that reached any cohort; a strategy no gradient exists for whatever its run (TF24's deep-crown shading or sapwood acclimation, a_sw > 0), refused before a run that kept no states is repeated; and a trade-off that derives a parameter an equation reads and that has no column.

A run resumed from export_patch_state() is differentiated from its resume time, with the exported state held fixed: how that state depends on the traits is not in the gradient. For an invader of a resumed resident that is exact, since the invader's own cohorts all start after the resume. For the resident it is an approximation, to be stated beside any resident gradient taken that way. With the absorbing top layer on (Control$absorb_epsilon), which cohorts are absorbed is held as the run chose it, and what they carry into the layer and the height it is pinned at move with the traits.

Traits and parameters

A column is the derivative as its trait moves through the construction that built the strategy, which is what a difference through add_strategies() measures. The hyperparameter function derives some parameters from the traits (TF24's testing trade-offs, default_hyperpar("TF24"), which sets twelve parameters, among them k_l, r_l, d_I, a_f3 and the stem curve, from six traits including lma), so a trait's column is its own partial plus each derived parameter's partial times that parameter's derivative with respect to the trait. The function is closed-form, so that derivative is a central difference of the function itself, and costs no model run.

Every derived parameter leaves the columns, as colnames(hyperpar(matrix(numeric(0), 1, 0), s, filter = FALSE)) lists them for a strategy s. Each requested species' derived parameters are checked against its traits first: a strategy built by hand (TF24's default is not on its trade-off), edited after it was built, built at an input it does not keep (FF16's narea), or built through another function, is refused rather than differentiated along a trade-off it does not lie on. Pass the function it was built with, or hyperpar = NULL.

With hyperpar = NULL every parameter the model can differentiate has a column, and each is a partial derivative with every other parameter fixed.

A column can be zero because of another parameter's value. FF16, TF24 and TF24f offer the coarse-root pool's a_cr1, r_cr and k_cr. At the default a_cr1 = 0 the pool is empty, so the columns of its respiration and turnover rates, r_cr and k_cr, are exact zeros by construction, not findings about the pool; a_cr1's own column is live there. Set a_cr1 > 0 to read the other two.

A refused metric's whole row is NaN: a sum has no defined value with an undefined term, so refusal is metric-level and carries no localisation within a metric. Every other number is one the sweep computed, an exact zero included — a parameter no gradient exists for cannot be asked for, so it never reaches a column. psi_crit and root_psi_crit are two such: each is derived from its curve's (P50, c) pair, which phylloptim derives for itself, so setting one reaches no equation and asking for its gradient errors rather than returning a zero.

An invader against a recorded resident

After x$run_mutant(p), a gradient is of the invaders' metrics in the residents' recorded field, which the invaders read at each rate evaluation and do not move, so it carries no derivative: the rare-mutant derivative. A run of x$run_mutant_constant() is refused. An invasion that kept no states is run again, as an invasion, to keep them; set x$keep_states <- TRUE before it to save that run. Several invaders in p share one run and each has its own columns, and the sweep's cost grows with their cohorts, so a set of invaders costs about what running them one at a time does. An invader of a resumed resident starts at the resume time, as run_mutant requires.

The birth rate

For a species run at a constant birth rate the column "<species>.birth_rate" is the derivative with respect to that rate, which reaches the density every cohort is born at and the offspring integral. A species with a variable birth rate has no such column.

A single entry can dominate a second moment

A gradient taken where the run crosses an unresolved event — a cohort reaching hmat between two steps, say — is a derivative of the trajectory's step placement rather than of the model, and it can be two orders larger than its neighbours. One measured cell was 211 times the median of its grid.

Do not average such a grid, and do not form a covariance from one. A single outlying cell dominates any second moment, which is the first thing an active-subspace or sensitivity workflow computes, so the reduction inherits the step placement instead of the ecology. Treat a gradient far outside its neighbourhood as a diagnostic: nudge the trait a fraction of a percent and take the answer that is stable, or resolve the event by forcing a step at the crossing.


Compare two stand gradients.

Description

Two gradients are comparable only if they were taken at the same Control: five of the six entries change the trajectory and so change the function being differentiated, and the sixth, gradient_curvature_floor, decides which rows exist. See gradient_control.

Usage

stand_gradient_compare(a, b)

Arguments

a, b

Results of stand_gradient.

Value

The element-wise difference a$gradient - b$gradient, over the metrics and traits both carry.


Which of a gradient's metrics were refused.

Description

Refusal is metric-level: a sum has no defined value with an undefined term, so a refused metric's whole row is NaN and one reason serves it.

Usage

stand_gradient_refused(g)

Arguments

g

A result of stand_gradient.

Value

A named logical, one entry per metric.


Create an TF24_Environment object.

Description

This environment is used for the TF24 model, which includes soil moisture and hydraulic conductivity parameters.

Usage

TF24_Environment()

Height at which the stem hydraulic path is anchored [m].

Description

TF24's resistance depends on 'theta_tip' and 'K_s' only through their product, so there is exactly one free scalar and the height-dependent model can be made to agree with the older height-linear one at exactly **one** height – never two. 'TF24_H_ANCHOR' is that height. It is the pivot of a rotation: below it every plant is more resistant than under the linear model, above it every plant is less.

Usage

TF24_H_ANCHOR

Details

Anchored at 1 m, so resistance is unchanged at 1 m stature and falls progressively above it – reaching 0.21x by 60 m. Only sub-metre plants pay more than they did. It is deliberately a fixed constant rather than being read from 'pars$hmat': sweeping 'hmat' as a trait must not silently move the hydraulics with it.

This is provenance for a default, not a model parameter, which is why it does not live in 'TF24_Pars'. Exposing it would add a fourth knob to the grouping 'L_tip^beta / (K_s * theta_tip)', which is already identifiable only as a whole – and inviting independent calibration of its members is exactly what invariance criterion I5 forbids.


Create a TF24 Plant or Node

Description

Create a TF24 Plant or Node

Usage

TF24_Individual(s = TF24_Model())

Arguments

s

A TF24_Model object

Examples

pl <- TF24_Individual()
pl$height

The TF24 model

Description

The TF24 model: the rules that map a plant's traits, size and environment to its growth, fecundity and mortality, with the parameters (pars) and controls they read.

Usage

TF24_Model(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Setup an a TF24 system with default or specified parameters

Description

Setup an a model system with default or specified parameters.

Usage

TF24_Parameters(...)

Arguments

...

Arguments to be passed to the model constructor. These include

*'max_patch_lifetime': The maximum time in years we want to simulate *'strategies': A list of strategies to simulate. The default is an empty list. *'strategy_default': Values for the default strategy. The default values are those specified in the C++ code for the model. *'node_schedule_times_default': Default vector of times at which to introduce nodes. The default is chosen to have close spacing at the start of the simulation. *'node_schedule_times': A list with each element containing the vector of times we want to introduce nodes for each strategy. The default is an empty list. *'ode_times': A vector of patch ages we want the ode solver to stop at

Examples

p1 <- TF24_Parameters()
p2 <- TF24_Parameters(max_patch_lifetime = 10.0)

TF24 model parameters

Description

Biological trait/parameters for the TF24 model. Held as the nested pars element of a TF24_Model (access as s$pars$lma).

Usage

TF24_Pars(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Create a TF24f Plant or Node

Description

Create a TF24f Plant or Node

Usage

TF24f_Individual(s = TF24f_Model())

Arguments

s

A TF24f_Model object

Examples

pl <- TF24f_Individual()
pl$height

The TF24f model

Description

The TF24f model: the rules that map a plant's traits, size and environment to its growth, fecundity and mortality, with the parameters (pars) and controls they read.

Usage

TF24f_Model(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Set up a TF24f system with default or specified parameters

Description

Set up a model system with default or specified parameters.

Usage

TF24f_Parameters(...)

Arguments

...

Arguments to be passed to the model constructor. These include

*'max_patch_lifetime': The maximum time in years we want to simulate *'strategies': A list of strategies to simulate. The default is an empty list. *'strategy_default': Values for the default strategy. The default values are those specified in the C++ code for the model. *'node_schedule_times_default': Default vector of times at which to introduce nodes. The default is chosen to have close spacing at the start of the simulation. *'node_schedule_times': A list with each element containing the vector of times we want to introduce nodes for each strategy. The default is an empty list. *'ode_times': A vector of patch ages we want the ode solver to stop at

Examples

p1 <- TF24f_Parameters()
p2 <- TF24f_Parameters(max_patch_lifetime = 10.0)

Create a TF24t Plant or Node

Description

TF24t is TF24 with phylloptim's lasting leaf thermal-damage and acclimation layer switched on (#566). It adds four ODE states after TF24's: acclim_thermostab, impaired, damaged and mean_leaf_temp. Its thermal parameters sit at the top level of TF24t_Model, with every rate constant per day. The Penman-Monteith energy balance is always on, so the leaf_temp driver is read as air temperature.

Usage

TF24t_Individual(s = TF24t_Model())

Arguments

s

A TF24t_Model object

Examples

pl <- TF24t_Individual()
pl$height

The TF24t model

Description

The TF24t model: the rules that map a plant's traits, size and environment to its growth, fecundity and mortality, with the parameters (pars) and controls they read.

Usage

TF24t_Model(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Set up a TF24t system with default or specified parameters

Description

Set up a model system with default or specified parameters.

Usage

TF24t_Parameters(...)

Arguments

...

Arguments to be passed to the model constructor. These include

*'max_patch_lifetime': The maximum time in years we want to simulate *'strategies': A list of strategies to simulate. The default is an empty list. *'strategy_default': Values for the default strategy. The default values are those specified in the C++ code for the model. *'node_schedule_times_default': Default vector of times at which to introduce nodes. The default is chosen to have close spacing at the start of the simulation. *'node_schedule_times': A list with each element containing the vector of times we want to introduce nodes for each strategy. The default is an empty list. *'ode_times': A vector of patch ages we want the ode solver to stop at

Examples

p1 <- TF24t_Parameters()
p2 <- TF24t_Parameters(max_patch_lifetime = 10.0)

Create a TF24w Plant or Node

Description

Create a TF24w Plant or Node

Usage

TF24w_Individual(s = TF24w_Model())

Arguments

s

A TF24w_Model object

Examples

pl <- TF24w_Individual()
pl$height

The TF24w model

Description

The TF24w model: the rules that map a plant's traits, size and environment to its growth, fecundity and mortality, with the parameters (pars) and controls they read.

Usage

TF24w_Model(..., values = list(...))

Arguments

..., values

Values to initialise the struct with (either as variadic arguments, or as a list, but not both).


Set up a TF24w system with default or specified parameters

Description

Set up a model system with default or specified parameters.

Usage

TF24w_Parameters(...)

Arguments

...

Arguments to be passed to the model constructor. These include

*'max_patch_lifetime': The maximum time in years we want to simulate *'strategies': A list of strategies to simulate. The default is an empty list. *'strategy_default': Values for the default strategy. The default values are those specified in the C++ code for the model. *'node_schedule_times_default': Default vector of times at which to introduce nodes. The default is chosen to have close spacing at the start of the simulation. *'node_schedule_times': A list with each element containing the vector of times we want to introduce nodes for each strategy. The default is an empty list. *'ode_times': A vector of patch ages we want the ode solver to stop at

Examples

p1 <- TF24w_Parameters()
p2 <- TF24w_Parameters(max_patch_lifetime = 10.0)

Turn 'results' of plant solver, when solving individuals into a tidy data object

Description

Turn 'results' of plant solver, when solving individuals into a tidy data object

Usage

tidy_individual(results)

Arguments

results

plant solver output.

Value

a tibble with the step, the time, and one column per state the model integrates, named as the model names them


Tidy a run's snapshots

Description

Flatten the thinned record of a run. With x$snapshot_interval set before the run, the deterministic runner keeps one summary per interval instead of a copy of the whole patch per leg: per species the node counts, the tallest cohort carrying density, the trapezium of the carried density over the birth-date grid and every node's lifetime offspring output, plus the environment's own state.

Usage

tidy_snapshots(x)

Arguments

x

A DeterministicPatchRunner or plant_run that was run with a positive snapshot_interval.

Details

Read on the birth-date coordinate, which a continuous patch runs on: density is the trapezium of the carried density over the nodes' birth dates, a number of individuals per unit area, without the closing interval to the boundary node that a census adds; on the height coordinate it is the same trapezium over birth dates of a density in height, which is not a count. n_retired counts the nodes carrying no density, frozen or not, so it is n_nodes - n_live. The per-node fecundity vectors grow with the node list, so their memory grows with the square of the run's length (about 6 MB at a snapshot a year over 1000 years of one species); a coarser interval cuts it.

Value

A list of three: species, a data frame with one row per snapshot and species (time, species, n_nodes, n_live, n_retired, height_max, density, which includes what the absorbing top layer carries, and top_density); environment, a data frame with one row per snapshot of time and the environment's state entries (env_1, ...); and fecundity, a list over snapshots of lists over species of each node's lifetime offspring output.

See Also

run_until_converged


Tidy a run's recorded steps

Description

Tidy a run's recorded steps

Usage

## S3 method for class 'plant_run'
tidy(x, ...)

## S3 method for class 'plant_individual_run'
tidy(x, ...)

## S3 method for class 'plant_landscape_run'
tidy(x, ...)

Arguments

x

A plant_run run with record = "steps", a single plant's run, or a landscape's run with record = "steps".

...

Unused.

Value

For a deterministic run, a list: the tidied patch at every step, steps, n_spp, species and env (as tidy_patch gives them); then the run's offspring_production and net_reproduction_ratios; p, the solver's parameters (carrying any refined schedule); events, the events it was given; event_log, what each event did; and control, the run's Control, which says how its crowns cast shade (canopy_profile reads it) where the strategies in p do not. For a stochastic run, time, species (an array per species, [variable, time, individual], with an is_alive attribute), env and control. For a single plant, a tibble of its state at each reported time, as tidy_individual gives it. For a landscape's run, a list of each patch's, by name.


Create trait matrix

Description

Helper function to create trait matrices suitable for generate_strategy and add_strategies.

Usage

trait_matrix(x, trait_name)

Arguments

x

Values

trait_name

Name of a single trait

Author(s)

Rich FitzJohn


Make colours transparent

Description

Make colours transparent

Usage

util_colour_set_opacity(col, opacity = 0.5)

Arguments

col

Vector of colours

opacity

Vector of opacities

Examples

util_colour_set_opacity("red", seq(0, 1, length.out=6))
util_colour_set_opacity(c("red", "blue"), .5)

Weibull disturbance regime The frequency of disturbance in a meta-population of patches follows a Weibull distribution

Description

Weibull_Disturbance_Regime control object.

Usage

Weibull_Disturbance_Regime(max_patch_lifetime)

Arguments

max_patch_lifetime

Maximum lifetime of a patch, determines length of a simulation