| 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 |
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).
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 )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 )
p |
A |
traits |
A matrix of traits corresponding to the new strategies to
introduce (see |
hyperpar |
Trade-off (hyperparameter) function to use. Defaults to the
one |
birth_rate |
Birth rate(s), one per row of |
keep_existing |
Should existing resident strategies be retained? |
trait_matrix |
Deprecated ( |
birth_rate_list |
Deprecated; use |
keep_existing_strategies |
Deprecated; use |
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).
base_parameters(type = NA, env = environment_type(type))base_parameters(type = NA, env = environment_type(type))
type |
Any model name as a string, e.g.: |
env |
The environment type's name; by default the model's own. |
A Parameters object.
Rich FitzJohn
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.
canopy_profile(strategy, u = seq(0, 1, length.out = 101), control = NULL)canopy_profile(strategy, u = seq(0, 1, length.out = 101), control = NULL)
strategy |
A strategy (a |
u |
Relative heights, in [0, 1]. |
control |
The run's |
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.
A list: profile, a tibble of u, Q and
q; and eta_c, the Yokozawa profile's leaf-area-weighted
mean of u.
crown <- canopy_profile(FF16_Model(), u = seq(0, 1, by = 0.25)) crown$profile crown$eta_ccrown <- canopy_profile(FF16_Model(), u = seq(0, 1, by = 0.25)) crown$profile crown$eta_c
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.
check_driver_interpolation( environment, driver_name, x, y, n_eval = 20001, warn = TRUE, tol_integral = 0.01 )check_driver_interpolation( environment, driver_name, x, y, n_eval = 20001, warn = TRUE, tol_integral = 0.01 )
environment |
An |
driver_name |
Name of the driver to check, e.g. |
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 |
tol_integral |
Relative tolerance on the integral mismatch before warning. |
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.
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.
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)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)
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.
control(...) control_accurate(base = Control()) control_tf24(tol = 1e-05, base = Control())control(...) control_accurate(base = Control()) control_tf24(tol = 1e-05, base = Control())
... |
Named control fields, passed to |
base |
An optional |
tol |
The relative tolerance, |
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.
A Control object.
Control parameters that tune various aspects of the numerical solvers.
Control(..., values = list(...))Control(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
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.
default_parameters(model, quiet = FALSE) default_hyperpar(model, ...) param_hyperpar(parameters)default_parameters(model, quiet = FALSE) default_hyperpar(model, ...) param_hyperpar(parameters)
model |
A model name: |
quiet |
If |
... |
For |
parameters |
A |
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.
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.
base_parameters, parameter_table,
generate_strategy
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 attachedp <- 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
Base class of representing patch disturbance
Disturbance_Regime()Disturbance_Regime()
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.
environment_type(type) Environment(type = NULL)environment_type(type) Environment(type = NULL)
type |
Any environment name as a string, e.g.: |
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.
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 )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 )
... |
For |
p |
Parameters object, whose |
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
|
amount |
How much to add, in whatever the environment measures that
resource in. What the pool cannot hold is shed rather than forced in;
|
fraction |
Fraction of individuals removed, in |
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; |
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
|
threshold |
Level above which dose accrues; below it the episode does nothing. |
sensitivity |
Dose accrued per unit-year above |
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.
An Events object: a list with time, type,
target, target_index and params, in schedule order.
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))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 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.
export_patch_state(x, step = NULL)export_patch_state(x, step = NULL)
x |
A |
step |
Optional 1-based index into |
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.
Create an FF16_Environment object.
FF16_Environment() K93_Environment()FF16_Environment() K93_Environment()
Add additional state variables to the species component in output of a model.
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)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)
results |
from 'tidy_patch' |
similar format to input, but with additional columns for additional state variables
Create a FF16 Individual
FF16_Individual(s = FF16_Model())FF16_Individual(s = FF16_Model())
s |
A |
pl <- FF16_Individual() pl$heightpl <- FF16_Individual() pl$height
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.
FF16_Model(..., values = list(...))FF16_Model(..., values = list(...))
..., 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. This function enables you initialize a model system. Use the model name to start different models.
FF16_Parameters(...) K93_Parameters()FF16_Parameters(...) K93_Parameters()
... |
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 |
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))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))
Biological trait/parameters for the FF16 model. Held as the nested
pars element of an FF16_Model (access as
s$pars$lma).
FF16_Pars(..., values = list(...))FF16_Pars(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
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.
fitness_window(p, start, end, weight_x = numeric(0), weight_y = numeric(0))fitness_window(p, start, end, weight_x = numeric(0), weight_y = numeric(0))
p |
A |
start, end
|
The window, in years of the run. |
weight_x, weight_y
|
Optional knots of the weight over the window;
|
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).
The modified Parameters object, with
fitness_weighting = "window".
Fitness of invaders at a resident's fixed point
fixed_point_fitness( x, p, traits, hyperpar = param_hyperpar(p), lifetime = 3000, survival_tol = 1e-08, grid_tol = 0.001 )fixed_point_fitness( x, p, traits, hyperpar = param_hyperpar(p), lifetime = 3000, survival_tol = 1e-08, grid_tol = 0.001 )
x |
The resident's |
p |
The resident's |
traits |
A trait matrix, one row per invader. |
hyperpar |
Hyperparameter function, as for |
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 |
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 |
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.
Lifetime offspring per seed, one per row of traits.
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.
generate_strategy(p, traits, hyperpar = param_hyperpar(p), birth_rate = 1) strategy_list( x, parameters, hyperpar = param_hyperpar(parameters), birth_rate_list = 1 )generate_strategy(p, traits, hyperpar = param_hyperpar(p), birth_rate = 1) strategy_list( x, parameters, hyperpar = param_hyperpar(parameters), birth_rate_list = 1 )
p |
A |
traits |
Trait values as a matrix, with column names
corresponding to traits (see |
hyperpar |
Trade-off (hyperparameter) function to use: a closure
|
birth_rate |
Birth rate(s) for each row of |
x |
Deprecated ( |
parameters |
Deprecated ( |
birth_rate_list |
Deprecated; use |
Control entries a census gradient depends on.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.
gradient_control(x)gradient_control(x)
x |
A run |
A named numeric vector of length six.
Individual object
Individual(T, E)Individual(T, E)
T |
String containing class of plant strategy to create; |
E |
String containing class of environmnet to create; |
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.
integrate_over_size_distribution( tidy_species_data, lower = -Inf, upper = Inf, coordinate = c("auto", "birth_date", "height") )integrate_over_size_distribution( tidy_species_data, lower = -Inf, upper = Inf, coordinate = c("auto", "birth_date", "height") )
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. |
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).
Internals class holding vectors of states, thier associated rates and auxiliary (aux) state which is calculated from the state through running compute_rates
Internals(s_size, a_size)Internals(s_size, a_size)
s_size |
??? |
a_size |
??? |
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.
interpolate_to_heights( tidy_species_data, heights, method = "pchip", min_log_density = -100 )interpolate_to_heights( tidy_species_data, heights, method = "pchip", min_log_density = -100 )
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 |
Returns a tibble of similar format to input, but with all outputs interpolated to specified hieghts.
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.
interpolate_to_times(tidy_species_data, times, method = "pchip")interpolate_to_times(tidy_species_data, times, method = "pchip")
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. |
Returns a tibble of similar format to input, but with all outputs interpolated to specified times.
Create a K93 Individual or Node
K93_Individual(s = K93_Model())K93_Individual(s = K93_Model())
s |
A |
pl <- K93_Individual() pl$heightpl <- K93_Individual() pl$height
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.
K93_Model(..., values = list(...))K93_Model(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
Biological trait/parameters for the K93 model. Held as the nested
pars element of a K93_Model (access as
s$pars$b_0).
K93_Pars(..., values = list(...))K93_Pars(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
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.
landscape(patches, ..., area = NULL) flow(from, to, type, out_of = 1L, into = out_of, weight = 1, ...)landscape(patches, ..., area = NULL) flow(from, to, type, out_of = 1L, into = out_of, weight = 1, ...)
patches |
A list of |
... |
For |
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:
|
out_of |
Which part of |
into |
Which part of |
weight |
How strongly the flow joins the two patches: what leaves
|
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.
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.
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.
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.
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_productionp <- 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
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.
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 )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 )
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 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.
make_initial_state( p, heights, densities = NULL, log_densities = NULL, env = NULL, ctrl = control() )make_initial_state( p, heights, densities = NULL, log_densities = NULL, env = NULL, ctrl = control() )
p |
A |
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 |
log_densities |
Per-species node log-densities (alternative to
|
env |
Environment object, or a scenario's recipe of one (defaults to the strategy's environment). |
ctrl |
Control object. |
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.
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.
set_initial_state, export_patch_state
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).
model_registry(path = system.file("model-registry.yml", package = "plant"))model_registry(path = system.file("model-registry.yml", package = "plant"))
path |
The registry file; the installed one by default. |
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.
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.
reg <- model_registry() reg$sections registry_equation("density_pde_height", reg)reg <- model_registry() reg$sections registry_equation("density_pde_height", reg)
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.
model_size(x, registry = model_registry())model_size(x, registry = model_registry())
x |
A model name ( |
registry |
A registry from |
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.
model_size("K93")$size model_size(base_parameters("FF16"))$size_unitsmodel_size("K93")$size model_size(base_parameters("FF16"))$size_units
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.
model_version(type) model_id(type)model_version(type) model_id(type)
type |
Any strategy name as a string, e.g.: |
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.
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).
A disturbance-free regime for running individual patches
No_Disturbance()No_Disturbance()
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.
node_schedule_times_default(max_time)node_schedule_times_default(max_time)
max_time |
Time to generate introduction times up to (the
last introduction time will be at least |
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.
Vector of introduction times.
Rich FitzJohn, adapted from original C++ code by Daniel S. Falster.
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.
node_schedule_times_periodic(start, end, by, include_end = FALSE)node_schedule_times_periodic(start, end, by, include_end = FALSE)
start |
First introduction time. |
end |
The span's end. |
by |
Spacing between introductions, in years. |
include_end |
Whether a time landing on |
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.
A numeric vector of introduction times, for one species of
p$node_schedule_times.
Control parameters for the ode system
OdeControl(..., values = list(...))OdeControl(..., values = list(...))
..., 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
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 )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 )
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 |
rate |
The name of the rate to optimise. Defaults to |
params |
The parameters of the model. Defaults to plant's testing set,
|
env |
The environment of the model |
hyperpars |
The trade-off function; defaults to the one |
set_state_directly |
If TRUE, set the state directly to the size, otherwise grows the plant to that size. Defaults to FALSE |
Isaac Towers, Daniel Falster and Andrew O'Reilly-Nugent
One table of everything a model can be told, so the options are visible in
one place (#698). Rows are grouped:
traitwhat 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.
derivedwhat 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.
parameterthe remaining fields of pars: settable as
traits, with no trade-off attached to them.
strategynumeric fields a strategy carries at its top level,
beside pars (TF24t's thermal parameters, TF24f's acclimation
settings). A trait matrix reaches these too.
controlControl'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).
parameter_table(x, hyperpar = NULL)parameter_table(x, hyperpar = NULL)
x |
A model name ( |
hyperpar |
The trade-off function to classify by. For a model name it
defaults to plant's frozen testing trade-offs
( |
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.
default_parameters, generate_strategy,
trait_matrix, model_registry
tab <- parameter_table("TF24") table(tab$group) tab[tab$group == "derived", "name"]tab <- parameter_table("TF24") table(tab$group) tab[tab$group == "derived", "name"]
Activate logging (deprecated)
plant_log_console(file_name = "console", colour = TRUE, threshold = "INFO")plant_log_console(file_name = "console", colour = TRUE, threshold = "INFO")
file_name, colour, threshold
|
Ignored. |
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
QK(rule)QK(rule)
rule |
Degree of the rule; valid sizes are 15, 21, 31, 41, 51, 61. |
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.
rainfall_pulse(time, depth, layer = 1, env = NULL)rainfall_pulse(time, depth, layer = 1, env = NULL)
time |
Event time(s), in years of patch age. |
depth |
Depth of water delivered, in m — so 13 mm is |
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 |
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.
Event rows, to be combined with events.
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)) )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)) )
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), "$$").
registry_equation(id, registry = model_registry())registry_equation(id, registry = model_registry())
id |
The equation's id, or a link ( |
registry |
A registry from |
The LaTeX, a single string without surrounding $$.
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.
registry_values(registry = model_registry(), model = "FF16")registry_values(registry = model_registry(), model = "FF16")
registry |
A registry from |
model |
The model whose defaults to read, e.g. |
registry$parameters with a value column.
Compute the whole plant light compensation point for a single plant: the light level at which whole-plant carbon gain is zero.
resource_compensation_point(p, ...)resource_compensation_point(p, ...)
p |
An |
... |
Additional arguments that are ignored |
Rich FitzJohn
One verb for a run, whatever describes it:
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") )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") )
x |
What to run: a scenario, a |
... |
For a |
until |
Where to stop: |
from |
Where to start: |
record |
What to keep beyond the outputs every run reports:
|
refine_schedule |
Refine the node-introduction schedule before the
run, bisecting the intervals whose nodes' error exceeds
|
method |
|
env, control, events
|
For a |
times, sizes
|
For an |
size_name |
The size |
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.
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().
scenario, run_mutant,
export_patch_state, stand_gradient
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).
run_mutant(resident, p, constant = FALSE)run_mutant(resident, p, constant = FALSE)
resident |
A complete |
p |
The invaders' |
constant |
Hold the field the resident stands in now, rather than replay the one it recorded. |
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.
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
run_plant_benchmarks(strategy_types = list(FF16 = FF16_Model), iterations = 1)run_plant_benchmarks(strategy_types = list(FF16 = FF16_Model), iterations = 1)
strategy_types |
A list of name strategy types to be tests |
iterations |
The number of iterations to be run |
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.
A dataframe of results
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.
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 )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 )
x |
A |
block |
Years per block. |
tol |
Relative range of the last |
t_max |
Time to give up at; defaults to the run's
|
statistics |
Which of |
snapshot_interval |
Years between snapshots when the deterministic runner has none set. |
environment_entries |
Which entries of the environment's state the
|
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. |
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.
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.
tidy_snapshots, export_patch_state
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.
sample_size_distribution(results, area, times = NULL)sample_size_distribution(results, area, times = NULL)
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. |
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.
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', ...).
## 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)## 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)
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.
scenario(p, env = NULL, control = plant::control(), events = NULL)scenario(p, env = NULL, control = plant::control(), events = NULL)
p |
A |
env |
An |
control |
A |
events |
An |
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.
A list of class plant_scenario with p, env
(the environment's recipe), control and events.
The queue of scheduled events: node introductions, resource pulses, harvests and climate extremes
Schedule(n_species)Schedule(n_species)
n_species |
number of species |
Sequence in log space
seq_log(from, to, length.out) seq_log_range(r, length.out) seq_range(r, length.out)seq_log(from, to, length.out) seq_log_range(r, length.out) seq_range(r, length.out)
from |
Starting point |
to |
Ending point |
length.out |
Number of points to generate |
r |
range (i.e., c(from, to) |
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.
Rich FitzJohn
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.
set_initial_state(p, state)set_initial_state(p, state)
p |
A |
state |
An exported state list from |
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.
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.
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.
set_tf24_soil( env, widths = NULL, theta = NULL, soil_moist_sat = NULL, K_sat = NULL, a_psi = NULL, n_psi = NULL )set_tf24_soil( env, widths = NULL, theta = NULL, soil_moist_sat = NULL, K_sat = NULL, a_psi = NULL, n_psi = NULL )
env |
|
widths |
Layer widths, m, top down – e.g. a profile grading from a
thin surface layer, as fieldtrial's |
theta |
Initial volumetric soil moisture. A single number is used for
every layer; a vector must have one entry per layer. If |
soil_moist_sat, K_sat, a_psi, n_psi
|
Per-layer soil parameters, each either
|
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.
env, modified in place and returned invisibly.
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()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()
stand_census reports the census metrics: the trapezium integral of
over the size distribution, for each
per-plant quantity , 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.
stand_census(x) stand_fitness(x)stand_census(x) stand_fitness(x)
x |
A run |
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.
A named numeric vector, one entry per metric.
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.
stand_census_state_adjoint(x)stand_census_state_adjoint(x)
x |
A run |
A numeric matrix, metrics by ODE state entries.
Doubles in and doubles out: the active scalar is created and destroyed inside one call and never crosses into R.
stand_gradient( x, metrics = NULL, traits = NULL, hyperpar = param_hyperpar(x$parameters), mode = c("auto", "reverse", "forward") )stand_gradient( x, metrics = NULL, traits = NULL, hyperpar = param_hyperpar(x$parameters), mode = c("auto", "reverse", "forward") )
x |
A run |
metrics |
Metric names to differentiate; defaults to every metric the
model declares: the census metrics ( |
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 |
hyperpar |
The hyperparameter function the strategies were built with,
by default the one |
mode |
How the gradient is computed. |
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.
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.
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.
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.
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 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.
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.
stand_gradient_compare(a, b)stand_gradient_compare(a, b)
a, b
|
Results of |
The element-wise difference a$gradient - b$gradient, over the
metrics and traits both carry.
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.
stand_gradient_refused(g)stand_gradient_refused(g)
g |
A result of |
A named logical, one entry per metric.
This environment is used for the TF24 model, which includes soil moisture and hydraulic conductivity parameters.
TF24_Environment()TF24_Environment()
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.
TF24_H_ANCHORTF24_H_ANCHOR
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
TF24_Individual(s = TF24_Model())TF24_Individual(s = TF24_Model())
s |
A |
pl <- TF24_Individual() pl$heightpl <- TF24_Individual() pl$height
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.
TF24_Model(..., values = list(...))TF24_Model(..., values = list(...))
..., 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.
TF24_Parameters(...)TF24_Parameters(...)
... |
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 |
p1 <- TF24_Parameters() p2 <- TF24_Parameters(max_patch_lifetime = 10.0)p1 <- TF24_Parameters() p2 <- TF24_Parameters(max_patch_lifetime = 10.0)
Biological trait/parameters for the TF24 model. Held as the nested
pars element of a TF24_Model (access as
s$pars$lma).
TF24_Pars(..., values = list(...))TF24_Pars(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
Create a TF24f Plant or Node
TF24f_Individual(s = TF24f_Model())TF24f_Individual(s = TF24f_Model())
s |
A |
pl <- TF24f_Individual() pl$heightpl <- TF24f_Individual() pl$height
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.
TF24f_Model(..., values = list(...))TF24f_Model(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
Set up a model system with default or specified parameters.
TF24f_Parameters(...)TF24f_Parameters(...)
... |
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 |
p1 <- TF24f_Parameters() p2 <- TF24f_Parameters(max_patch_lifetime = 10.0)p1 <- TF24f_Parameters() p2 <- TF24f_Parameters(max_patch_lifetime = 10.0)
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.
TF24t_Individual(s = TF24t_Model())TF24t_Individual(s = TF24t_Model())
s |
A |
pl <- TF24t_Individual() pl$heightpl <- TF24t_Individual() pl$height
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.
TF24t_Model(..., values = list(...))TF24t_Model(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
Set up a model system with default or specified parameters.
TF24t_Parameters(...)TF24t_Parameters(...)
... |
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 |
p1 <- TF24t_Parameters() p2 <- TF24t_Parameters(max_patch_lifetime = 10.0)p1 <- TF24t_Parameters() p2 <- TF24t_Parameters(max_patch_lifetime = 10.0)
Create a TF24w Plant or Node
TF24w_Individual(s = TF24w_Model())TF24w_Individual(s = TF24w_Model())
s |
A |
pl <- TF24w_Individual() pl$heightpl <- TF24w_Individual() pl$height
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.
TF24w_Model(..., values = list(...))TF24w_Model(..., values = list(...))
..., values
|
Values to initialise the struct with (either as variadic arguments, or as a list, but not both). |
Set up a model system with default or specified parameters.
TF24w_Parameters(...)TF24w_Parameters(...)
... |
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 |
p1 <- TF24w_Parameters() p2 <- TF24w_Parameters(max_patch_lifetime = 10.0)p1 <- TF24w_Parameters() p2 <- TF24w_Parameters(max_patch_lifetime = 10.0)
Turn 'results' of plant solver, when solving individuals into a tidy data object
tidy_individual(results)tidy_individual(results)
results |
plant solver output. |
a tibble with the step, the time, and one column per state the model integrates, named as the model names them
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.
tidy_snapshots(x)tidy_snapshots(x)
x |
A |
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.
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.
Tidy a run's recorded steps
## 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, ...)## 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, ...)
x |
A |
... |
Unused. |
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.
Helper function to create trait matrices suitable for
generate_strategy and add_strategies.
trait_matrix(x, trait_name)trait_matrix(x, trait_name)
x |
Values |
trait_name |
Name of a single trait |
Rich FitzJohn
Make colours transparent
util_colour_set_opacity(col, opacity = 0.5)util_colour_set_opacity(col, opacity = 0.5)
col |
Vector of colours |
opacity |
Vector of opacities |
util_colour_set_opacity("red", seq(0, 1, length.out=6)) util_colour_set_opacity(c("red", "blue"), .5)util_colour_set_opacity("red", seq(0, 1, length.out=6)) util_colour_set_opacity(c("red", "blue"), .5)
Weibull_Disturbance_Regime control object.
Weibull_Disturbance_Regime(max_patch_lifetime)Weibull_Disturbance_Regime(max_patch_lifetime)
max_patch_lifetime |
Maximum lifetime of a patch, determines length of a simulation |