Package 'plant'

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

Help Index


Add strategies (or a mutant) to Parameters

Description

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

Usage

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

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

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

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

Arguments

p

A Parameters object.

traits

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

hyperpar

Hyperparameter function to use. By default links to the standard function for this strategy type.

birth_rate

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

keep_existing

Should existing resident strategies be retained?

trait_matrix

Deprecated (expand_parameters/mutant_parameters); use traits.

birth_rate_list

Deprecated; use birth_rate.

keep_existing_strategies

Deprecated; use keep_existing.


Control presets

Description

Construct a Control object. control() is a lowercase alias for the Control() constructor, whose defaults are the pragmatic, fast-ish settings used for essentially all of plant's runs (see control.cpp). control_accurate() tightens the ODE and schedule tolerances for high-accuracy runs at the cost of speed.

Usage

control(...)

control_accurate(base = Control())

Arguments

...

Named control fields, passed to Control().

base

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

Value

A Control object.


Control parameters

Description

Control parameters that tune various aspects of the numerical solvers.

Usage

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

Arguments

..., values

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


Disturbance regime

Description

Base class of representing patch disturbance

Usage

Disturbance_Regime()

Creates an environment object of specified type

Description

Creates an environment object of specified type

Usage

environment_type(type)

Environment(type = NULL)

Arguments

type

Any environment name as a string, e.g.: "FF16_Env".


Export patch state from an SCM

Description

Export the full state of a patch from a (run) SCM so it can be re-imported to seed 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.

Usage

export_patch_state(scm, step = NULL)

Arguments

scm

An SCM object that has been run.

step

Optional 1-based index into scm$history (requires the run to have been performed with collect = TRUE); when NULL (default) the SCM's current/final patch is used.

Value

A list describing the patch state, suitable for set_initial_state: time, n (nodes per species), ode_state (flat), the per-species lists node_times, patch_density and pr_patch_survival, and the residual node_schedule_times.

See Also

set_initial_state, run_scm


Create an FF16_Environment object.

Description

Create an FF16_Environment object.

Usage

FF16_Environment()

K93_Environment()

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

Description

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

Usage

FF16_expand_state(results)

K93_expand_state(results)

expand_state(results)

TF24_expand_state(results)

TF24f_expand_state(results)

Arguments

results

from 'tidy_patch'

Value

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


Generates a report on stand grown with FF16 strategy

Description

Builds a detailed report on stand grown with FF16 strategy, based on the template Rmd file provided. The reports are rendered as html files and saved in the specified output folder.

Usage

FF16_generate_stand_report(
  results,
  output_file = "FF16_report.html",
  overwrite = FALSE,
  target_ages = NA,
  input_file = system.file("reports", "FF16_report.Rmd", package = "plant"),
  quiet = TRUE
)

Arguments

results

results of running run_scm(..., collect = TRUE)

output_file

name of output file

overwrite

logical value to determine whether to overwrite existing report

target_ages

Patches ages at which to make plots

input_file

report script (.Rmd) file to build study report

quiet

An option to suppress printing during rendering from knitr, pandoc command line and others.

Value

html file of the rendered report located in the specified output folder.


Hyperparameter function for FF16 physiological model

Description

Hyperparameter function for FF16 physiological model

Usage

FF16_hyperpar(m, s, filter = TRUE)

Arguments

m

A matrix of trait values, as returned by trait_matrix

s

A strategy object

filter

A flag indicating whether to filter columns. If TRUE, any numbers that are within eps of the default strategy are not replaced.


Create a FF16 Individual

Description

Create a FF16 Individual

Usage

FF16_Individual(s = FF16_Strategy())

Arguments

s

A FF16_Strategy object

Examples

pl <- FF16_Individual()
pl$height

Setup an a model system with default or specified parameters

Description

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

Usage

FF16_Parameters(...)

K93_Parameters()

Arguments

...

Arguments to be passed to the model constructor. These include

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

Examples

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

FF16 strategy parameters

Description

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

Usage

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

Arguments

..., values

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


Strategy parameters

Description

Strategy parameters that tune various aspects of the biological model.

Usage

FF16_Strategy(..., values = list(...))

Arguments

..., values

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


Generate strategies from traits

Description

Convert a matrix of trait values into a list of Strategy objects, one per row, by applying the hyperparameter function and inserting the resulting parameters into a copy of the default strategy.

Usage

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

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

Arguments

p

A Parameters object containing a default strategy to modify. Any hyperparameterisation included will be applied.

traits

Trait values as a matrix, with column names corresponding to traits (see trait_matrix); one row per strategy.

hyperpar

Hyperparameter function to use. By default links to the standard function for this strategy type. It translates ecological traits (e.g. lma, wood density) into the low-level strategy parameters, encoding the model's trade-offs.

birth_rate

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

x

Deprecated (strategy_list); use traits.

parameters

Deprecated (strategy_list); use p.

birth_rate_list

Deprecated; use birth_rate.


Grow individual to given size

Description

Grow an individual up to particular sizes.

Usage

grow_individual_to_size(
  individual,
  sizes,
  size_name,
  env,
  time_max = Inf,
  warn = TRUE,
  filter = FALSE
)

grow_individual_to_height(individual, heights, env, ...)

Arguments

individual

An Individual object.

sizes

A vector of sizes to grow the plant to (increasing in size).

size_name

The name of the size variable within individual$rates (e.g., height).

env

An Environment object.

time_max

Time to run the ODE out for – only exists to prevent an infinite loop (say, on an unreachable size).

warn

Warn if requesting a plant that is too large?

filter

Filter individuals that are too large?

heights

Heights (when using grow_individual_to_height)

...

Additional parameters passed to grow_individual_to_size.

Value

A list with elements time (the time that a given size was reached), state (the ode state at these times, as a matrix) and plant a list of individuals grown to the appropriate size. Note that if only a single size is given, a list of length 1 is returned.


Grow a plant

Description

Grow a plant up for particular time lengths

Usage

grow_individual_to_time(individual, times, env)

Arguments

individual

An Individual object

times

A vector of times

env

An Environment object


Individual object

Description

Individual object

Usage

Individual(T, E)

Arguments

T

String containing class of plant strategy to create;

E

String containing class of environmnet to create;


Integrate over the size distribution for each species at each time point, to give totals of each variable Integrations are performed using trapezium integration

Description

Integrate over the size distribution for each species at each time point, to give totals of each variable Integrations are performed using trapezium integration

Usage

integrate_over_size_distribution(tidy_species_data)

Arguments

tidy_species_data

output of either 'tidy_patch' or 'tidy_species'

Value

a tibble whose columns provide metrics on integrated totals for each variable for each species at each time


Extract Internals from plant object

Description

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

Usage

Internals(s_size, a_size)

Arguments

s_size

???

a_size

???


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

Description

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

Usage

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

Arguments

tidy_species_data

output of either 'tidy_patch' or 'tidy_species'

heights

heights to interpolate to

method

Method for interpolation. For more info see help on stats::spline

min_log_density

Set minimum possible value of log_density

Value

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


Interpolate data on size distributions for each species to specific timer points, using specified interpolation method

Description

Interpolate data on size distributions for each species to specific timer points, using specified interpolation method

Usage

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

Arguments

tidy_species_data

output of either 'tidy_patch' or 'tidy_species'

times

times to interpolate to

method

Method for interpolation. For more info see help on stats::spline

Value

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


Spline interpolation

Description

Spline interpolation

Usage

Interpolator()

Hyperparameter function for K93 physiological model

Description

Hyperparameter function for K93 physiological model

Usage

K93_hyperpar(m, s, filter = TRUE)

Arguments

m

A matrix of trait values, as returned by trait_matrix

s

A strategy object

filter

A flag indicating whether to filter columns. If TRUE, any numbers that are within eps of the default strategy are not replaced.


Create a K93 Individual or Node

Description

Create a K93 Individual or Node

Usage

K93_Individual(s = K93_Strategy())

Arguments

s

A K93_Strategy object

Examples

pl <- K93_Individual()
pl$height

K93 strategy parameters

Description

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

Usage

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

Arguments

..., values

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


Strategy parameters

Description

Strategy parameters that tune various aspects of the biological model.

Usage

K93_Strategy(..., values = list(...))

Arguments

..., values

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


Leaf model

Description

Leaf model

Usage

Leaf(
  vcmax_25,
  c,
  b,
  psi_crit,
  root_c,
  root_b,
  root_psi_crit,
  beta2,
  jmax_25,
  a,
  curv_fact_elec_trans,
  curv_fact_colim,
  GSS_tol_abs,
  vulnerability_curve_ncontrol,
  ci_abs_tol,
  ci_niter,
  g1_TF24,
  beta_R_H,
  beta_R_V
)

Arguments

vcmax_25

Maximum Carboxylation Rate (umol m^-2 s^-1)

c

shape parameter of hydraulic vulnerability curve (unitless)

b

sensitivity parameter of hydraulic vulnerability curve (MPa)

psi_crit

critical psi stem (-MPa )

root_c

shape parameter of hydraulic vulnerability curve for roots(unitless)

root_b

sensitivity parameter of hydraulic vulnerability curve for roots (MPa)

root_psi_crit

critical psi stem for roots (-MPa )

beta2

exponent for effect of hydraulic risk (unitless)

jmax_25

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

a

quantum yield of photosynthetic electron transport (mol mol^-1)

curv_fact_elec_trans

curvature factor for the light response curve (unitless)

curv_fact_colim

curvature factor for the colimited photosythnthesis equatiom

GSS_tol_abs

tolereance 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

g1_TF24

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

beta_R_H

proportionality constant between minimum horizontal (intralayer) root hydraulic resistance and C_r^-1 (MPa s mol C / mol H2O)

beta_R_V

proportionality constant between minimum vertical (interlayer) root hydraulic resistance and dz^2/C_r (MPa mol C s / mol H2O / m^2)


Hyperparameters for FF16 physiological model

Description

Hyperparameters for FF16 physiological model

Usage

make_FF16_hyperpar(
  lma_0 = 0.1978791,
  B_kl1 = 0.4565855,
  B_kl2 = 1.71,
  rho_0 = 608,
  B_dI1 = 0.01,
  B_dI2 = 0,
  B_ks1 = 0.2,
  B_ks2 = 0,
  B_rs1 = 4012,
  B_rb1 = 2 * 4012,
  B_f1 = 3,
  narea = 0.00187,
  narea_0 = 0.00187,
  B_lf1 = 5120.738 * 0.00187 * 24 * 3600/1e+06,
  B_lf2 = 0.5,
  B_lf3 = 0.04,
  B_lf4 = 21000,
  B_lf5 = 1,
  latitude = 0
)

Arguments

lma_0

Central (mean) value for leaf mass per area [kg /m2]

B_kl1

Rate of leaf turnover at lma_0 [/yr]

B_kl2

Scaling slope for phi in leaf turnover [dimensionless]

rho_0

Central (mean) value for wood density [kg /m3]

B_dI1

Rate of instantaneous mortality at rho_0 [/yr]

B_dI2

Scaling slope for wood density in intrinsic mortality [dimensionless]

B_ks1

Rate of sapwood turnover at rho_0 [/yr]

B_ks2

Scaling slope for rho in sapwood turnover [dimensionless]

B_rs1

CO_2 respiration per unit sapwood volume [mol / yr / m3 ]

B_rb1

CO_2 respiration per unit sapwood volume [mol / yr / m3 ]

B_f1

Cost of seed accessories per unit seed mass [dimensionless]

narea

nitrogen per leaf area [kg / m2]

narea_0

central (mean) value for nitrogen per leaf area [kg / m2]

B_lf1

Potential CO_2 photosynthesis at average leaf nitrogen [mol / d / m2]

B_lf2

Curvature of leaf photosynthetic light response curve [dimensionless]

B_lf3

Quantum yield of leaf photosynthetic light response curve [dimensionless]

B_lf4

CO_2 respiration per unit leaf nitrogen [mol / yr / kg]

B_lf5

Scaling exponent for leaf nitrogen in maximum leaf photosynthesis [dimensionless]

latitude

degrees from equator (0-90), used in solar model [deg]


Hyperparameters for physiological model

Description

Set a suitable hyperparameter function for chosen physiological model

Usage

make_hyperpar(type)

param_hyperpar(parameters)

hyperpar(type)

Arguments

type

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

parameters

A parameters object


Build an initial size distribution

Description

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

Usage

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

Arguments

p

A Parameters object.

heights

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

densities

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

log_densities

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

env

Environment object (defaults to the strategy's environment).

ctrl

Control object.

Details

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

Value

A state list suitable for set_initial_state.

See Also

set_initial_state, export_patch_state


Hyperparameters for K93 physiological model

Description

Construct hyperparameter object for K93 physiological model

Usage

make_K93_hyperpar(
  b_0 = 0.059,
  b_1 = 0.012,
  b_2 = 0.00041,
  c_0 = 0.008,
  c_1 = 0.00044,
  d_0 = 0.00073,
  d_1 = 0.044,
  eta = 12,
  k_I = 0.01
)

Arguments

b_0

Growth intercept year-1

b_1

Growth asymptote year-1.(ln cm)-1

b_2

Growth suppression rate m2.cm-2.year-1

c_0

Mortality intercept year-1

c_1

Mortality suppression rate m2.cm-2.year-1

d_0

Recruitment rate (cm2.year-1)

d_1

Recruitment suppression rate (m2.cm-2)

eta

Crown shape parameter

k_I

Extinction coefficient used when estimating competitive effect


Hyperparameters for TF24 physiological model

Description

Hyperparameters for TF24 physiological model

Usage

make_TF24_hyperpar(
  lma_0 = 0.1978791,
  B_kl1 = 0.4565855,
  B_kl2 = 1.71,
  rho_0 = 608,
  B_dI1 = 0.01,
  B_dI2 = 0,
  B_hks1 = 7.5,
  B_hks2 = 0,
  B_ks1 = 0.2,
  B_ks2 = 0,
  B_rs1 = 4012,
  B_rb1 = 2 * 4012,
  B_f1 = 3,
  a_lf1 = 0.535,
  B_lf1 = 0.009,
  B_lf2 = 0.004,
  B_lf3 = 8e-04,
  B_lf4 = 21000,
  B_lf5 = 40000,
  latitude = 0,
  B_Hv1 = 0.4607063,
  B_Hv2 = -0.2,
  B_c1 = 2.04,
  B_c2 = 0
)

make_TF24f_hyperpar(...)

Arguments

lma_0

Central (mean) value for leaf mass per area [kg /m2]

B_kl1

Rate of leaf turnover at lma_0 [/yr]

B_kl2

Scaling slope for phi in leaf turnover [dimensionless]

rho_0

Central (mean) value for wood density [kg /m3]

B_dI1

Rate of instantaneous mortality at rho_0 [/yr]

B_dI2

Scaling slope for wood density in intrinsic mortality [dimensionless]

B_hks1

Intercept for the g1_TF24 ~ rho relationship at rho_0 [dimensionless]

B_hks2

Scaling slope for rho in the g1_TF24 relationship [dimensionless]

B_ks1

Rate of sapwood turnover at rho_0 [/yr]

B_ks2

Scaling slope for rho in sapwood turnover [dimensionless]

B_rs1

CO_2 respiration per unit sapwood volume [mol / yr / m3 ]

B_rb1

CO_2 respiration per unit sapwood volume [mol / yr / m3 ]

B_f1

Cost of seed accessories per unit seed mass [dimensionless]

a_lf1

intercept for empirical relationship between narea and vcmax, lma (Dong et al. 2022)

B_lf1

Beta coefficient for empirical relationship between narea_ls ~ lma [g/m2] (Dong et al. 2022)

B_lf2

Beta coefficient for empirical relationship between narea_lp ~ vcmax [g/m2] (Dong et al. 2022)

B_lf3

Beta coefficient for empirical relationship between narea_lp ~ jmax [umol / m2 / s] (Dong et al. 2022)

B_lf4

CO_2 respiration per unit structural leaf nitrogen [mol / yr / kg]

B_lf5

CO_2 respiration per unit photosynthetic leaf nitrogen [mol / yr / kg]

latitude

degrees from equator (0-90), used in solar model [deg]

B_Hv1

p50 at K_s = 1 [-MPa]

B_Hv2

Scaling slope for K_s in p50 [dimensionless]

B_c1

Shape parameter c of the vulnerability curve at p_50 = 0 [dimensionless]

B_c2

Scaling slope for p_50 in the vulnerability-curve shape parameter c [dimensionless]

...

Arguments passed to make_TF24_hyperpar


Scientific version of a physiological model

Description

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

Usage

model_version(type)

model_id(type)

Arguments

type

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

Details

The version is returned as a string. It is usually a single integer ("1"), but may be compound for a model defined relative to another: TF24f is a fast 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.

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

Value

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


No disturbance regime No_Disturbance_Regime control object

Description

A disturbance-free regime for running individual patches

Usage

No_Disturbance()

Generate Default Node Introduction Times

Description

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

Usage

node_schedule_times_default(max_time)

Arguments

max_time

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

Details

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

Value

Vector of introduction times.

Author(s)

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


Schedule of node introduction times

Description

Schedule of node introduction times

Usage

NodeSchedule(n_species)

Arguments

n_species

number of species


ODE Control parameters

Description

Control parameters for the ode system

Usage

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

Arguments

..., values

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


The function 'optimise_individual_rate_at_height_by_trait' and 'optimise_individual_rate_at_size_by_trait' solve for the maximum of some rate (e.g. growth rate) at a specified height within the interval of the bounds of a given trait

Description

The function 'optimise_individual_rate_at_height_by_trait' and 'optimise_individual_rate_at_size_by_trait' solve for the maximum of some rate (e.g. growth rate) at a specified height within the interval of the bounds of a given trait

Usage

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

optimise_individual_rate_at_height_by_trait(..., height = 1)

Arguments

type

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

bounds

A vector giving the lower and upper bounds of the trait

log_scale

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

tol

The tolerance for the optimisation

size

The size of the individual to optimise the rate at

size_name

The name of the size variable specified by size

rate

The name of the rate to optimise. Defaults to size_name

params

The parameters of the model

env

The environment of the model

hyperpars

The hyperparameter function of the model

set_state_directly

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

...

Additional parameters passed to optimise_individual_rate_at_size_by_trait

height

Heigh at which grow is optimsied. Defaults to 1

Author(s)

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


Activate logging

Description

Activate logging

Usage

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

Arguments

file_name

File to save output (default = "console")

colour

Use colour in console output?

threshold

Minimum log level to emit: "DEBUG", "INFO", etc.

Details

By default plant prints little information about its progress. This can be modified by enabling logging. Log entries include a timestamp and, where applicable, a routine label indicating which part of the model is running.

"Schedule" events (splitting) are sent to the DEBUG stream, everything else is sent to INFO.


Title

Description

Title

Usage

plot_size_distribution(data_species)

Arguments

data_species

??


Gauss-Kronrod Quadrature

Description

Gauss-Kronrod Quadrature

Usage

QK(rule)

Arguments

rule

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


Whole plant light compensation point

Description

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

Usage

resource_compensation_point(p, ...)

Arguments

p

An Individual, with strategy, height, etc set.

...

Additional arguments that are ignored

Author(s)

Rich FitzJohn


Check performance on current system using package bench

Description

Check performance on current system using package bench

Usage

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

Arguments

strategy_types

A list of name strategy types to be tests

iterations

The number of iterations to be run

Details

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

Value

A dataframe of results


Run SCM

Description

Run the SCM.

Usage

run_scm(
  p,
  env = NULL,
  ctrl = control(),
  refine_schedule = FALSE,
  collect = FALSE,
  use_ode_times = FALSE
)

Arguments

p

Parameters object

env

Environment object (defaults to the strategy's environment)

ctrl

Control object

refine_schedule

Should the node-introduction schedule be adaptively refined before/while running (using schedule_eps and schedule_nsteps from ctrl)?

collect

Should tidied results be collected at every step and returned (instead of the SCM object)?

use_ode_times

Should ODE times be used?

Details

The node-introduction schedule can be adaptively refined in C++ by setting refine_schedule = TRUE (this replaces the former build_schedule function). Setting collect = TRUE returns tidied output collected at every ODE step (replacing the former run_scm_collect); otherwise the SCM object itself is returned for interrogation.

Value

When collect = FALSE, an SCM object. When collect = TRUE, a list of tidied patch output with offspring_production, net_reproduction_ratios and the (possibly refined) parameters p.

Author(s)

Rich FitzJohn


Run a stochastic patch, Collecting Output

Description

Run a stochastic simulation of a patch, given a Parameters

Usage

run_stochastic_collect(p, env = NULL, ctrl = Control(), random_schedule = TRUE)

Arguments

p

A FF16_Parameters object

env

Environment object

ctrl

Control object

random_schedule

setting to TRUE causes algorithm to generate a random schedule based on offspring arrival and area.

Details

This one might need to be made differently so that different schedules can be added easily. Not sure if this is how we will generally want to do this. Consider this function liable to change.

Author(s)

Rich FitzJohn


Scenario evaluation framework for the TF24 / TF24f hydraulic models.

Description

These functions turn a table of qualitatively-described model scenarios (e.g. inst/scenarios/model_scenarios_hydraulic.csv, added in PR #555) into concrete TF24 parameterisations, run each through the SCM, classify the run as a success or a failure, and score the observed outcome against the expected outcome recorded in the table. The result is a provenance-stamped scorecard that can be re-run across branches as a gateway check: many scenarios are expected to fail on the current model and become targets to fix as new features (e.g. NSC storage, #554) land.

Usage

read_scenario_table(path = scenario_file("model_scenarios_hydraulic.csv"))

read_scenario_mapping(path = scenario_file("scenario_mapping.csv"))

scenario_to_config(row, mapping)

build_scenario(
  config,
  max_patch_lifetime = 100,
  ctrl = control(),
  birth_rate = 1
)

classify_scm_run(p, env, ctrl = control())

evaluate_scenario(row, mapping, ctrl = control(), max_patch_lifetime = 100)

run_scenarios(
  scenarios = read_scenario_table(),
  mapping = read_scenario_mapping(),
  ctrl = control(),
  max_patch_lifetime = 100,
  workers = 1L,
  cache = NULL
)

scenario_model_fingerprint()

scenario_run_metadata()

scenario_summary(scorecard)

scenario_generate_report(
  scorecard,
  output_file = "scenario_scorecard.html",
  input_file = system.file("reports", "scenario_scorecard.Rmd", package = "plant"),
  overwrite = FALSE,
  quiet = TRUE
)

Arguments

path

Path to the CSV file.

row

A one-row data frame / tibble from read_scenario_table.

mapping

A mapping tibble from read_scenario_mapping.

config

A config list from scenario_to_config.

max_patch_lifetime

Patch lifetime (years) for the SCM run.

ctrl

A Control object.

birth_rate

Birth rate passed to add_strategies.

p

A built Parameters object (e.g. build_scenario()$p).

env

An Environment object (e.g. build_scenario()$env).

scenarios

A scenario tibble from read_scenario_table.

workers

Number of parallel workers. > 1 uses **fork-based** parallelism (parallel::mclapply). Forking is deliberate: it inherits the currently-loaded namespace and compiled library, so it works when plant is loaded for development via pkgload::load_all / devtools::load_all. A PSOCK / future::multisession cluster would spawn fresh R sessions that see only the *installed* package, not the dev build, and would silently run stale (or missing) code — so it is not used here. Forking is unavailable on Windows, where the run falls back to sequential regardless of workers.

cache

Optional path to an .rds cache. When supplied, each scenario's result is keyed by a content hash of its resolved config, max_patch_lifetime and the model fingerprint (scenario_model_fingerprint); a scenario is rerun only when that key changes. The key covers every input that affects a result: the resolved config, max_patch_lifetime, all ctrl settings, and the model fingerprint. So a model recompile / R-source edit reruns everything (the fingerprint moves), a ctrl change reruns everything, and editing one mapping cell reruns only the scenarios it touches. The cache deliberately errs toward rerunning.

scorecard

A scorecard tibble from run_scenarios.

output_file

Output HTML path for the rendered report.

input_file

The report template (.Rmd).

overwrite

Overwrite an existing output_file?

quiet

Passed to rmarkdown::render.

Details

The qualitative-to-quantitative translation is data-driven: every High/Low/descriptor cell is looked up in an editable mapping table (inst/scenarios/scenario_mapping.csv) so the biology can be recalibrated without touching code.

Value

read_scenario_table returns a tibble of scenarios with an added scenario_id and is_duplicate flag; the raw descriptor columns are kept verbatim.

scenario_to_config returns a list with traits (named numeric), env (named list of Environment fields), driver (named list of extrinsic-driver settings) and expected ("failure" or "success").

build_scenario returns a list with the Parameters (p), configured Environment (env) and Control (ctrl) ready for run_scm.

classify_scm_run returns a list describing the run: status ("success"/"failure"), offspring_production, finite, error_message, warnings and run_seconds. A run is a success when it completes with finite, positive total offspring production; any thrown error or non-finite output is a failure. The C++ layer already fails fast on non-finite state, so classification does not depend on error wording.

evaluate_scenario returns a one-row scorecard tibble.

run_scenarios returns a scorecard tibble (one row per scenario) with a "metadata" attribute recording provenance. A crash in one scenario never aborts the batch. Scenario runs are deterministic (no RNG), so parallel and sequential runs produce identical scorecards.

scenario_model_fingerprint returns a hash string that changes whenever the model that produces scenario results could change: the package version, the compiled shared library, and all package R source plus the scenario data files. It is intentionally broad — the cache should rerun rather than risk a stale result.

scenario_run_metadata returns a list of provenance fields (git commit / branch / dirty flag, package version, R version, platform, timestamp) so a scorecard records the exact build it came from.

scenario_summary returns a one-row tibble with the headline counts: total scenarios, matches, match rate, and the expected-failure vs expected-success breakdown.

scenario_generate_report renders the scorecard report and returns the output path (invisibly).


Basic default parameters for a given strategy

Description

Basic default settings for a given strategy, environment only really used for templating initially and will be overloaded later by passing an environment to the SCM API (suggesting perhaps the template could be removed).

Usage

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

Arguments

type

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

env

And environment object

Author(s)

Rich FitzJohn


Sequence in log space

Description

Sequence in log space

Usage

seq_log(from, to, length.out)

seq_log_range(r, length.out)

seq_range(r, length.out)

Arguments

from

Starting point

to

Ending point

length.out

Number of points to generate

r

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

Details

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

Author(s)

Rich FitzJohn


Seed Parameters with an initial patch state

Description

Write an exported patch state (from export_patch_state) into a Parameters object so that the next run_scm 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 seeding survives the reset at the start of every run / schedule refinement.

Usage

set_initial_state(p, state)

Arguments

p

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

state

An exported state list from export_patch_state.

Value

The modified Parameters object.

See Also

export_patch_state, run_scm


Create an TF24_Environment object.

Description

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

Usage

TF24_Environment()

Generates a report on stand grown with TF24 strategy

Description

Builds a detailed report on stand grown with TF24 strategy, based on the template Rmd file provided. The reports are rendered as html files and saved in the specified output folder.

Usage

TF24_generate_stand_report(
  results,
  output_file = "TF24_report.html",
  overwrite = FALSE,
  target_ages = NA,
  input_file = system.file("reports", "TF24_report.Rmd", package = "plant"),
  quiet = TRUE
)

Arguments

results

results of running run_scm(..., collect = TRUE)

output_file

name of output file

overwrite

logical value to determine whether to overwrite existing report

target_ages

Patches ages at which to make plots

input_file

report script (.Rmd) file to build study report

quiet

An option to suppress printing during rendering from knitr, pandoc command line and others.

Value

html file of the rendered report located in the specified output folder.


Hyperparameter function for TF24 physiological model

Description

Hyperparameter function for TF24 physiological model

Usage

TF24_hyperpar(m, s, filter = TRUE)

Arguments

m

A matrix of trait values, as returned by trait_matrix

s

A strategy object

filter

A flag indicating whether to filter columns. If TRUE, any numbers that are within eps of the default strategy are not replaced.


Create a TF24 Plant or Node

Description

Create a TF24 Plant or Node

Usage

TF24_Individual(s = TF24_Strategy())

Arguments

s

A TF24_Strategy object

Examples

pl <- TF24_Individual()
pl$height

Setup an a TF24 system with default or specified parameters

Description

Setup an a model system with default or specified parameters.

Usage

TF24_Parameters(...)

Arguments

...

Arguments to be passed to the model constructor. These include

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

Examples

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

TF24 strategy parameters

Description

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

Usage

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

Arguments

..., values

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


Diagnostic panel plot for a TF24 stand

Description

Assembles a multi-panel diagnostic figure from a collected TF24 SCM run: patch leaf area, the size distribution, soil water potential, stem and root water potentials, profit, stomatal conductance, transpiration (total and per leaf area) and the rainfall driver. Panels are combined with 'patchwork'.

Usage

TF24_plot_diagnostics(results, x, y)

Arguments

results

A collected TF24 SCM run, i.e. the output of 'run_scm(..., collect = TRUE)' for a TF24 strategy/environment. Carries the tidied patch state ('results$species') and the environment series ('results$env$soil_moist', 'soil_depth', 'soil_moist_cumulative_flux').

x, y

Numeric vectors giving the rainfall time series — time (years) and rainfall rate (m yr^-1) — as supplied to the environment's extrinsic "rainfall" driver.

Details

'ggplot2' and 'patchwork' are Suggested packages; the function errors if either is unavailable. The returned plot is neither drawn nor saved — print it or pass it to [ggplot2::ggsave()] as needed.

Value

The assembled 'patchwork' plot.


Strategy parameters

Description

Strategy parameters that tune various aspects of the biological model.

Usage

TF24_Strategy(..., values = list(...))

Arguments

..., values

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


Generates a report on stand grown with TF24f strategy

Description

Builds a detailed report on stand grown with TF24f strategy, based on the template Rmd file provided. The reports are rendered as html files and saved in the specified output folder.

Usage

TF24f_generate_stand_report(
  results,
  output_file = "TF24f_report.html",
  overwrite = FALSE,
  target_ages = NA,
  input_file = system.file("reports", "TF24f_report.Rmd", package = "plant"),
  quiet = TRUE
)

Arguments

results

results of running run_scm(..., collect = TRUE)

output_file

name of output file

overwrite

logical value to determine whether to overwrite existing report

target_ages

Patches ages at which to make plots

input_file

report script (.Rmd) file to build study report

quiet

An option to suppress printing during rendering from knitr, pandoc command line and others.

Value

html file of the rendered report located in the specified output folder.


Hyperparameter function for TF24f physiological model

Description

Hyperparameter function for TF24f physiological model

Usage

TF24f_hyperpar(m, s, filter = TRUE)

Arguments

m

A matrix of trait values, as returned by trait_matrix

s

A strategy object

filter

A flag indicating whether to filter columns. If TRUE, any numbers that are within eps of the default strategy are not replaced.


Create a TF24f Plant or Node

Description

Create a TF24f Plant or Node

Usage

TF24f_Individual(s = TF24f_Strategy())

Arguments

s

A TF24f_Strategy object

Examples

pl <- TF24f_Individual()
pl$height

Set up a TF24f system with default or specified parameters

Description

Set up a model system with default or specified parameters.

Usage

TF24f_Parameters(...)

Arguments

...

Arguments to be passed to the model constructor. These include

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

Examples

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

Strategy parameters

Description

Strategy parameters that tune various aspects of the biological model.

Usage

TF24f_Strategy(..., values = list(...))

Arguments

..., values

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


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

Description

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

Usage

tidy_individual(results)

Arguments

results

plant solver output.

Value

a tibble whose columns provide metrics on each individual over time


Turn 'species' component of plant solver output into a tidy data object

Description

Turn 'species' component of plant solver output into a tidy data object

Turn 'env' component of solver output into a tidy data object

Turns output of plant solver into a tidy data object

Usage

tidy_species(results)

tidy_env(results)

tidy_patch(results)

Arguments

results

output of run_scm(..., collect = TRUE)

Value

a list, containing outputs of plant solver in tidy format


Create trait matrix

Description

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

Usage

trait_matrix(x, trait_name)

Arguments

x

Values

trait_name

Name of a single trait

Author(s)

Rich FitzJohn


Make colours transparent

Description

Make colours transparent

Usage

util_colour_set_opacity(col, opacity = 0.5)

Arguments

col

Vector of colours

opacity

Vector of opacities

Examples

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

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

Description

Weibull_Disturbance_Regime control object.

Usage

Weibull_Disturbance_Regime(max_patch_lifetime)

Arguments

max_patch_lifetime

Maximum lifetime of a patch, determines length of a simulation