Title: | Implementation of the Vegetation Model ModVege |
---|---|
Description: | Run grass growth simulations using a grass growth model based on ModVege (Jouven, M., P. Carrère, and R. Baumont "Model Predicting Dynamics of Biomass, Structure and Digestibility of Herbage in Managed Permanent Pastures. 1. Model Description." (2006) <doi:10.1111/j.1365-2494.2006.00515.x>). The implementation in this package contains a few additions to the above cited version of ModVege, such as simulations of management decisions, and influences of snow cover. As such, the model is fit to simulate grass growth in mountainous regions, such as the Swiss Alps. The package also contains routines for calibrating the model and helpful tools for analysing model outputs and performance. |
Authors: | Kevin Kramer [aut, cre, cph] |
Maintainer: | Kevin Kramer <[email protected]> |
License: | MIT + file LICENSE |
Version: | 1.3.0.9001 |
Built: | 2025-01-26 02:55:31 UTC |
Source: | https://github.com/kuadrat/growr |
Inverse of 'atmospheric_CO2': retrieve the year by which a given CO2 concentration is reached.
aCO2_inverse(aCO2)
aCO2_inverse(aCO2)
aCO2 |
Target CO2 concentration in ppm. |
Does not give a reasonable result for values below 317ppm, corresponding to the year 1949, as this is where the minimum of the parabola is located in the second order fit to the data that was used in aCO2.fct.
year Approximate year (as floating point number) by which target concentration is reached.
aCO2_inverse(420) aCO2_inverse(700) # Insensible aCO2_inverse(100)
aCO2_inverse(420) aCO2_inverse(700) # Insensible aCO2_inverse(100)
Add a lineplot of the *x_key* and *y_key* columns in *data* to the supplied ggplot object *ax*. If none is supplied, a new one is created.
add_lines( data, ax = NULL, y_key = "dBM_smooth", x_key = "DOY", style = "line", label = NULL, ... )
add_lines( data, ax = NULL, y_key = "dBM_smooth", x_key = "DOY", style = "line", label = NULL, ... )
data |
data.frame or similar object interpretable by ggplot. |
ax |
list as returned by ggplot() and related functions. |
x_key , y_key
|
Column names in *data* to be plotted. |
style |
XXX in ggplot geom_XXX to use. |
label |
Codename for this line to be used in legend creation. If NULL, use *y_key*. |
... |
All further arguments are passed to the selected ggplot geom. |
ax A ggplot list (like the input *ax*).
library(ggplot2) # Add first set of data ax = add_lines(mtcars, x_key = "wt", y_key = "mpg", label = "First Line") # Add one more line to the plot ax = add_lines(mtcars, ax = ax, x_key = "wt", y_key = "qsec", label = "Second Line") print(ax)
library(ggplot2) # Add first set of data ax = add_lines(mtcars, x_key = "wt", y_key = "mpg", label = "First Line") # Add one more line to the plot ax = add_lines(mtcars, ax = ax, x_key = "wt", y_key = "qsec", label = "Second Line") print(ax)
Analyze results of a parameter scan
analyze_parameter_scan( parameter_scan_results, datafile = "", smooth_interval = 28 )
analyze_parameter_scan( parameter_scan_results, datafile = "", smooth_interval = 28 )
parameter_scan_results |
String or List. If a string, it is
interpreted as the name of a |
datafile |
Name or path to a file containing measured data. The model results in parameter_scan_results are compared to the data therein. If empty, the site is inferred from the ModvegeSite objects in parameter_scan_results and a corresponding data file is searched for in 'getOption("growR.data_dir", default = "data"). |
smooth_interval |
Int. Number of days over which the variable |
analyzed A list with five keys: dBM
, cBM
, cBM_end
, metrics
and params
.
A data.frame with 1 + n_params + n_metrics
columns
where each row represents a different parameter combination.
The first column (n
) gives the row number and is used to identify a
parameter combination. The subsequent n_params
columns give the
values of the parameters used in this combination. The final n_metrics
columns give the resulting performance score of the model run with
these parameters for each metric applied to model variable dBM
.
A data.frame of same format as for the key dBM. The first
n_params + 1
columns are identical to the data.frame in dBM. The
difference is that the final n_metrics
columns give performance
scores with respect to the model variable cBM
.
A data.frame analogous to dBM and cBM, only this time
the last n_metrics
columns give performance scores with respect to
the variable cBM_end
, which is the final value of cBM
, i.e. the
cumulative grown biomass at the end of the year.
A vector containing the names of the scanned parameters.
These are also the column names of columns 2:(n_params+1)
in
results.
A vector containing the names of the employed
performance metrics. These are also the column names of the last
n_metrics
columns in results.
run_parameter_scan()
, readRDS()
# There needs to be data available with which the model is to be compared. # For this example, use data provided by the package. path = system.file("extdata", package = "growR") datafile = file.path(path, "posieux1.csv") # We also use example parameter scan data provided by the package. # In the real world, you would generally create your own data using # `run_parameter_scan()`. analyze_parameter_scan(parameter_scan_example, datafile = datafile)
# There needs to be data available with which the model is to be compared. # For this example, use data provided by the package. path = system.file("extdata", package = "growR") datafile = file.path(path, "posieux1.csv") # We also use example parameter scan data provided by the package. # In the real world, you would generally create your own data using # `run_parameter_scan()`. analyze_parameter_scan(parameter_scan_example, datafile = datafile)
This function essentially wraps 'write.table' with a calling handler that suppresses appending warnings that would appear with the argument 'col.names = TRUE'.
append_to_table(data, filename, ...)
append_to_table(data, filename, ...)
data |
Any object which can be handled by 'write.table'. |
filename |
Name of file to append to. |
... |
All additional arguments are passed to 'write.table'. |
Retrieve CO2 concentration (in ppm) for given calendar year.
atmospheric_CO2(year)
atmospheric_CO2(year)
year |
Calender year for which to extract CO2 concentration. |
This function defines the CO2 concentration as a function of calendar year. it is based on a polynomial fit to the annual CO2 data published by NOAA <https://gml.noaa.gov/webdata/ccgg/trends/co2/co2_annmean_gl.txt>
Approximate CO2 concentration in ppm for given year.
This is only approximately valid for years in the range 1949 - 2020
atmospheric_CO2(1990) atmospheric_CO2(2020) # Insensible atmospheric_CO2(1800)
atmospheric_CO2(1990) atmospheric_CO2(2020) # Insensible atmospheric_CO2(1800)
An algorithm to determine grass cut dates if none are provided.
This is an abstract class and not intended for direct use. Instead, use
its subclasses that implement a determine_cut()
method.
The expected number of cuts is estimated from management intensity and site altitude based on data for Swiss grasslands by Huguenin et al.
MVS
The ModvegeSite object for which to take the cut decision.
n_cuts
Number of cuts expected for this altitude and management intensity.
new()
Constructor
Autocut$new(MVS)
MVS
The ModvegeSite object for which cuts shall be determined.
Get number of expected cuts
Return the number of expected cuts for a site at a given elevation and management intensity.
This uses data.frame management_parameters
as a lookup table and
interpolates linearly in between the specified values.
get_expected_n_cuts()
Autocut$get_expected_n_cuts(elevation, intensity = "high")
elevation
The elevation of the considered site in meters above sea level.
intensity
One of ("high", "middle", "low", "extensive"). Management intensity for considered site.
Number of expected cuts per season.
determine_cut()
Empty method stub intended for overriding by inheriting subclasses.
Autocut$determine_cut(DOY)
DOY
Integer day-of-the-year.
clone()
The objects of this class are cloneable with this method.
Autocut$clone(deep = FALSE)
deep
Whether to make a deep clone.
Huguenin-Elie I, Mosimann E, Schlegel P, Lüscher A, Kessler W, Jeangros B (2017). “Grundlagen für die Düngung landwirtschaftlicher Kulturen in der Schweiz (GRUD), Kapitel 9: Düngung von Grasland.” Agrarforschung Schweiz. https://www.agrarforschungschweiz.ch/2017/06/9-duengung-von-grasland-grud-2017/.
Smooth data in vector x to its endpoint.
box_smooth(x, box_width = 28)
box_smooth(x, box_width = 28)
x |
1D data to be smoothed. |
box_width |
Width (in units of vector steps) of the box used for smoothing. |
Employ an endpoint box filter (aka "running mean" or endpoint smoother) to the 1-D data in x:
x_smoothed[i] = mean(x[i-box_width:i])
Where x is considered to be zero-padded vor values of i-box_width < 1.
x_smooth Smoothened version of x.
# Create a sine wave with noise x = seq(0, 4*pi, 0.1) y = sin(x) + runif(length(x)) # Apply endpoint smoothing y_smooth = box_smooth(y, box_width = 5)
# Create a sine wave with noise x = seq(0, 4*pi, 0.1) y = sin(x) + runif(length(x)) # Apply endpoint smoothing y_smooth = box_smooth(y, box_width = 5)
Debug specified function func by entering a browser()
right at the
beginning (browse()
) or end (browse_end()
) of the function.
browse(func, ...) browse_end(func, ...)
browse(func, ...) browse_end(func, ...)
func |
An R function to be browsed. |
... |
Arguments to the function func that is to be browsed. |
These are convenience shorthands for R's builtin debug tools, like
debugonce()
and the trace()
/untrace()
combination.
Returns the result of func(...)
. Enters a browser()
.
browse_end()
: Enter browser()
at the end of the function call to func(...)
. This
only works, if the function can execute without error until its end.
Otherwise, the error will be thrown.
browser()
, debugonce()
, trace()
# Define a simple function for this example my_func = function(a) { for (i in 1:5) { a = a + i }; return(a) } # Enter a browser at the beginning of the function browse(my_func, 0) # Enter a browser at the end of the function. This allows us to inspect # the function's local variables without having to go through the whole loop. browse_end(my_func, 0)
# Define a simple function for this example my_func = function(a) { for (i in 1:5) { a = a + i }; return(a) } # Enter a browser at the beginning of the function browse(my_func, 0) # Enter a browser at the end of the function. This allows us to inspect # the function's local variables without having to go through the whole loop. browse_end(my_func, 0)
Uses the weights found in :param:P
to construct the effective functional
groups and updates functional group parameters in P.
build_functional_group(P)
build_functional_group(P)
P |
list; name-value pairs of parameters. Should contain at least one non-zero functional group weight w_FGX with X in (A, B, C, D). Any weights not present are assumed to be 0. |
A FunctionalGroup object composed of a linear combination of the four groups FG_A, FG_B, FG_C and FG_D.
parameters = list(w_FGA = 0.5, w_FGB = 0.5) build_functional_group(parameters) # The w_FGX weights in the input are interpreted as relative to each other. # Thus, they do not need to satisfy the sum rule. The following is # equivalent to the previous example: parameters = list(w_FGA = 1, w_FGB = 1) build_functional_group(parameters)
parameters = list(w_FGA = 0.5, w_FGB = 0.5) build_functional_group(parameters) # The w_FGX weights in the input are interpreted as relative to each other. # Thus, they do not need to satisfy the sum rule. The following is # equivalent to the previous example: parameters = list(w_FGA = 1, w_FGB = 1) build_functional_group(parameters)
Some functions not pertaining to the package core require additional libraries. These libraries are listed as *suggested* in the 'DESCRIPTION' When such a function is called by a user who does not have the respective libraries installed, we should notice that and notify the user. This is the purpose of this *function* 'check_for_package'.
check_for_package(package, stop = TRUE)
check_for_package(package, stop = TRUE)
package |
Name of the package to check for. |
stop |
Toggle whether an error should be thrown ('TRUE') or a warning generated ('FALSE'). |
The function checks if *package* is installed and loaded. If not, it either produces a warning or throws an error, depending on the value of *stop*.
‘TRUE' if the package was found. 'FALSE' if it wasn’t found and *stop* is 'FALSE'. Otherwise, an error will be thrown.
Helps to find all possible combinations for a given set of values.
combinations
list Once run, holds all valid parameter combinations as named lists.
eps
float Numerical precision to require when checking the functional group weight sum criterion.
create_combinations()
Find possible combinations
Combinator$create_combinations(param_values)
param_values
A list giving all options for the parameter values which are to be combined. As an example:
list(w_FGA = c(0, 0.5, 1), w_FGB = c(0, 0.5, 1), NI = c(0.5, 0.9))
This would generate the combinations
w_FGA | w_FGB | NI |
0 | 1 | 0.5 |
0 | 1 | 0.9 |
0.5 | 0.5 | 0.5 |
0.5 | 0.5 | 0.9 |
1 | 0 | 0.5 |
1 | 0 | 0.9 |
eps
Precision to be used when checking if the sum citerion of the functional groups (w_FGA + w_FGB + w_FGC + w_FGD = 1) is fulfilled.
combinations A list containing vectors of parameter value combinations.
clone()
The objects of this class are cloneable with this method.
Combinator$clone(deep = FALSE)
deep
Whether to make a deep clone.
The script compare.R
which ships with the growR package and is
automatically put into the working directory with
setup_directory()
can be used to compare results of growR simulation runs.
It is a simple script, so it can and should be adjusted to your personal needs.
The script makes use of the packages ggplot2, patchwork and some growR functions which facilitate data loading and plotting, like load_measured_data() and add_lines().
Generate a list which contains all possible combinations of the provided
parameter values. This excludes combinations that are invalid because the
sum criterion for functional groups w_FGA + w_FGB + w_FGC + w_FGD = 1
is
not fulfilled.
create_combinations(param_values, eps = 0.02)
create_combinations(param_values, eps = 0.02)
param_values |
A list giving all options for the parameter values
which are to be combined. The format is |
eps |
Float specifying the precision to which the sum criterion for functional group has to be satisfied. The criterion is considered satisfied, if “' abs(w_FGA + w_FGB + w_FGC + w_FGD) - 1) <= eps |
Assume for example the following list as argument param_values:
list(w_FGA = c(0, 0.5, 1), w_FGB = c(0, 0.5, 1), NI = c(0.5, 0.9))
This would generate the combinations
w_FGA | w_FGB | NI |
0 | 1 | 0.5 |
0 | 1 | 0.9 |
0.5 | 0.5 | 0.5 |
0.5 | 0.5 | 0.9 |
1 | 0 | 0.5 |
1 | 0 | 0.9 |
One can see that the input param_values has to be set up carefully: one
has to ensure that the given w_FGX
values can actually add up to 1. The
following would be a bad counterexample, where only one single valid
combination is found, even though many values for w_FGA
and w_FGB
are
provided:
list(w_FGA = seq(0.5, 1, 0.01), w_FGB = c(0.5, 1, 0.01))
Similarly, if the steps in the w_FGX
don't match, we might not end up
with many valid combinations, even though the ranges are reasonabl:
list(w_FGA = seq(0.5, 1, 0.1), w_FGB = c(0, 0.5, 0.25))
Here, no combination can be made with w_FGA
in c(0.6, 0.7, 0.8, 0.9)
or
w_FGB = 0.25
.
combinations An unnamed list where every entry is a list containing the parameter values (named as in the input param_values) for a valid combination.
# Define the parameter steps you want to explore. This is a minimal example. # A more realistic one follows below. param_values = list(w_FGA = c(0, 0.5, 1), w_FGB = c(0, 0.5, 1), NI = c(0.5, 0.9) ) # Create all valid combinations of the defined steps create_combinations(param_values) # More realistic example for an initial exploration of parameter space, # where we suspect that functional groups A and B should be more prevalent # than C and D. This produces 54 parameter combinations, which is a number # of model evaluations that can run within a reasonable timeframe # (depending on your system). param_values = list(w_FGA = seq(0, 1, 0.33), w_FGB = seq(0, 1, 0.33), w_FGC = seq(0, 0.7, 0.33), w_FGD = seq(0, 0.7, 0.33), NI = seq(0.5, 1.0, 0.25) ) length(create_combinations(param_values)) # The default value for *eps* made sure that combinations of 0.33 + 0.66 = # 0.99 etc. are considered "valid". If we make *eps* too small, no valid # combinations can be found: length(create_combinations(param_values, eps = 1e-3))
# Define the parameter steps you want to explore. This is a minimal example. # A more realistic one follows below. param_values = list(w_FGA = c(0, 0.5, 1), w_FGB = c(0, 0.5, 1), NI = c(0.5, 0.9) ) # Create all valid combinations of the defined steps create_combinations(param_values) # More realistic example for an initial exploration of parameter space, # where we suspect that functional groups A and B should be more prevalent # than C and D. This produces 54 parameter combinations, which is a number # of model evaluations that can run within a reasonable timeframe # (depending on your system). param_values = list(w_FGA = seq(0, 1, 0.33), w_FGB = seq(0, 1, 0.33), w_FGC = seq(0, 0.7, 0.33), w_FGD = seq(0, 0.7, 0.33), NI = seq(0.5, 1.0, 0.25) ) length(create_combinations(param_values)) # The default value for *eps* made sure that combinations of 0.33 + 0.66 = # 0.99 etc. are considered "valid". If we make *eps* too small, no valid # combinations can be found: length(create_combinations(param_values, eps = 1e-3))
This is intended for testing and for the examples in the documentation.
create_example_environment(site = "posieux")
create_example_environment(site = "posieux")
site |
Choose for which example site an environment is to be created.
Options: |
E A [ModvegeEnvironment]
instance based on the example data for
site which is shipped with this package.
extdata = system.file("extdata", package = "growR") print(extdata) list.files(extdata, recursive = TRUE) create_example_environment()
extdata = system.file("extdata", package = "growR") print(extdata) list.files(extdata, recursive = TRUE) create_example_environment()
Logs an error if any variable is missing and lists the missing variables in the error message along with *data_name*.
ensure_table_columns(required, data, data_name = "the data table")
ensure_table_columns(required, data, data_name = "the data table")
required |
List of names of required variables. |
data |
data.frame or similar object to be checked. |
data_name |
Name to be displayed in the error message if any variable is missing. |
Replace given filename by a version that contains an incremental number in order to prevent overwriting existing files.
ensure_unique_filename(path, add_num = TRUE)
ensure_unique_filename(path, add_num = TRUE)
path |
string; Filename including path for which to check uniqueness. |
add_num |
boolean; if TRUE, add the incremental number anyways, even if no filename conflict exists. |
A unique filename.
Function describing the effects of elevated CO2 on growth.
fCO2_growth_mod(c_CO2, b = 0.5, c_ref = 360)
fCO2_growth_mod(c_CO2, b = 0.5, c_ref = 360)
c_CO2 |
numeric Atmospheric CO2 concentration in ppm |
b |
numeric Strength of CO2 effect on growth. Kellner et al. report values bewtween 0 and 2 with the interval of highest likelihood (0.1, 0.3). However, Soltani and Sinclair discuss that b = 0.4 in C4 plants and b = 0.8 in C3 plants. The difference on the output of this function of choosing a small (0.1) and large (0.8) value for b has an effect on the result for an atmospheric concentration of 700 ppm of roughly 40 percent!. |
c_ref |
numeric Reference CO2 concentration in ppm. |
The function for the effects on growth is as proposed by Soltani et al (2012) and later adapted by equation (5) in Kellner et al. (2017)
Soltani A, Sinclair TR (2012). Modeling Physiology of Crop Development, Growth and Yield. CABI. ISBN 978-1-84593-971-7, xnHT6YOlk00C.
Kellner J, Multsch S, Houska T, Kraft P, Müller C, Breuer L (2017). “A Coupled Hydrological-Plant Growth Model for Simulating the Effect of Elevated CO2 on a Temperate Grassland.” Agricultural and Forest Meteorology, 246, 42–50. ISSN 0168-1923, doi:10.1016/j.agrformet.2017.05.017, https://www.sciencedirect.com/science/article/pii/S0168192317301831.
fCO2_growth_mod(420) # The modifier is always relative to *c_ref*. This returns 1. fCO2_growth_mod(420, c_ref = 420)
fCO2_growth_mod(420) # The modifier is always relative to *c_ref*. This returns 1. fCO2_growth_mod(420, c_ref = 420)
Function describing the effects of elevated CO2 on transpiration.
fCO2_transpiration_mod(c_CO2, c_ref = 360)
fCO2_transpiration_mod(c_CO2, c_ref = 360)
c_CO2 |
numeric Atmospheric CO2 concentration in ppm |
c_ref |
numeric Reference CO2 concentration in ppm. |
The function for the effect on transpiration is from equations (2-6) in Kruijt et al.
It appears in this paper that there is a small formal mistake in said equations. With the stated values, it is not possible to reproduce the tabulated values of $c$ close to 1, as in their table 3. Instead, we conclude that equation (4) should read:
c = 1 + s_gs * s_T * F_T * deltaCO2
with the multiplicative terms giving small negative numbers. The factors $s_gs$, $s_T$ and $F_T$ for grasslands are taken from pages 260 and 261 in Kruijt et al. where we averaged over the stated ranges to get:
c ~= 1 + 0.0001 * deltaCO2
Kruijt B, Witte JM, Jacobs CMJ, Kroon T (2008). “Effects of Rising Atmospheric CO2 on Evapotranspiration and Soil Moisture: A Practical Approach for the Netherlands.” Journal of Hydrology, 349(3), 257–267. ISSN 0022-1694, doi:10.1016/j.jhydrol.2007.10.052, https://www.sciencedirect.com/science/article/pii/S0022169407006373.
fCO2_transpiration_mod(420) # The modifier is always relative to *c_ref*. This returns 1. fCO2_transpiration_mod(420, c_ref = 420)
fCO2_transpiration_mod(420) # The modifier is always relative to *c_ref*. This returns 1. fCO2_transpiration_mod(420, c_ref = 420)
Functional group A
FG_A
FG_A
An object of class FunctionalGroup
(inherits from R6
) of length 23.
[FunctionalGroup]
Functional group B
FG_B
FG_B
An object of class FunctionalGroup
(inherits from R6
) of length 23.
[FunctionalGroup]
Functional group C
FG_C
FG_C
An object of class FunctionalGroup
(inherits from R6
) of length 23.
[FunctionalGroup]
Functional group D
FG_D
FG_D
An object of class FunctionalGroup
(inherits from R6
) of length 23.
[FunctionalGroup]
Threshold function representing growth limitation due to lack of photosynthetically active radiation (PAR).
fPAR(PAR)
fPAR(PAR)
PAR |
float Photosynthetically active radiation in MJ/m^2 |
A value in the range [0, 1], acting as a multiplicative factor to plant growth.
fPAR(4)
fPAR(4)
Threshold function representing growth limitation by temperature.
fT(t, T0 = 4, T1 = 10, T2 = 20)
fT(t, T0 = 4, T1 = 10, T2 = 20)
t |
float Temperature in degree Celsius. |
T0 |
float Photosynthesis activation temperature in degree Celsius. |
T1 |
float Photosynthesis plateau temperature in degree Celsius. |
T2 |
float Photosynthesis max temperature in degree Celsius. |
Photosynthesis is suppressed below T0, increases until it reaches its maximum at temperatures in the interval (T1, T2). For temperatures exceeding T2, photosynthetic activity decreases again until it reaches 0 at a final temperature of 40 degree Celsius.
A value in the range (0, 1), acting as a multiplicative factor to plant growth.
fT(4) fT(10) fT(15)
fT(4) fT(10) fT(15)
A functional group is a representation of a grassland plant population with certain functional attributes.
It contains many plant parameters that are collected under the hood of functional groups. The class implements S3 style operator overloading such that one can do things like
mixed_functional_group = 0.8 * FG_A + 0.2 * FG_B
SLA
Specific Leaf Area in m^2^ per g.
pcLAM
Percentage of laminae (number between 0 and 1).
ST1
Temperature sum in degree Celsiues days after which the
seasonality function SEA
starts to decrease from its maximum plateau.
See also SEA()
.
ST2
Temperature sum in degree Celsiues days after which the
seasonality function SEA
has decreased back to its minimum value.
See also SEA()
.
maxSEA
Maximum value of the seasonality function SEA()
minSEA
Minimum value of the seasonality function SEA()
. Usually,
minSEA = 1 - (maxSEA - 1)
.
maxOMDGV
Maximum organic matter digestability for green vegetative
matter in arbitrary units.
minOMDGV
Minimum organic matter digestability for green vegetative
matter in arbitrary units.
maxOMDGR
Maximum organic matter digestability for green reproductive
matter in arbitrary units.
minOMDGR
Minimum organic matter digestability for green reproductive
matter in arbitrary units.
BDGV
Bulk density of green vegetative dry matter in g per m^3^.
BDDV
Bulk density of dead vegetative dry matter in g per m^3^.
BDGR
Bulk density of green reproductive dry matter in g per m^3^.
BDDR
Bulk density of dead reproductive dry matter in g per m^3^.
fg_parameter_names
Vector of strings of the variable names of all
vegetation parameters governed by functional group composition.
Default values for parameters are taken from functional group A in Jouven et al.
fg_parameter_names
Names of the vegetation parameters governed by functional group composition.
new()
Constructor
FunctionalGroup$new(...)
...
Key-value pairs of parameters to be set.
get_parameters()
Convenient getter
Returns all parameters with their names in a list.
FunctionalGroup$get_parameters()
get_parameters_ordered()
Ordered getter
Returns all parameters in reproducible order in a vector.
FunctionalGroup$get_parameters_ordered()
set_parameters()
Convenient setter
Set all specified parameters.
FunctionalGroup$set_parameters(...)
...
Key-value pairs of parameters to be set.
set_parameters_ordered()
Efficient setter, assumes parameters come in known order.
FunctionalGroup$set_parameters_ordered(ordered_parameter_values)
ordered_parameter_values
Parameter values to be set. Need to be
in the same order as pFunctionalGroup]$fg_parameter_names
.
clone()
The objects of this class are cloneable with this method.
FunctionalGroup$clone(deep = FALSE)
deep
Whether to make a deep clone.
Jouven M, Carrère P, Baumont R (2006). “Model Predicting Dynamics of Biomass, Structure and Digestibility of Herbage in Managed Permanent Pastures. 1. Model Description.” Grass and Forage Science, 61(2), 112–124. ISSN 1365-2494, doi:10.1111/j.1365-2494.2006.00515.x, https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1365-2494.2006.00515.x.
Threshold function representing growth limitation due to water stress.
fW(W, PET)
fW(W, PET)
W |
Water stress given as the ratio of water reserves to water holding capacity. |
PET |
Potential evapotranspiration in mm per day. |
After equation (6) in McCall et al. (2003).#'
A value in the range (0, 1), acting as a multiplicative factor to plant growth.
McCall DG, Bishop-Hurley GJ (2003). “A Pasture Growth Model for Use in a Whole-Farm Dairy Production Model.” Agricultural Systems, 76(3), 1183–1205. ISSN 0308-521X, doi:10.1016/S0308-521X(02)00104-X, https://www.sciencedirect.com/science/article/pii/S0308521X0200104X.
fW(0.5, 7) fW(0.5, 5) fW(0.5, 3)
fW(0.5, 7) fW(0.5, 5) fW(0.5, 3)
Functions to calculate different performance metrics.
In the case of get_bias: Calculate the bias b, i.e. the average difference between predicted y and observed z values:
bias = mean(y - z)
get_bias(predicted, observed, ...) root_mean_squared(predicted, observed, ...) mean_absolute_error(predicted, observed, ...)
get_bias(predicted, observed, ...) root_mean_squared(predicted, observed, ...) mean_absolute_error(predicted, observed, ...)
predicted |
Vector containing the predictions y. |
observed |
Vector containing the observations z. |
... |
relative Boolean. If true give the result as a ratio to the
average observation |
m A number representing the relative or absolute value for the metric.
root_mean_squared()
: Calculate the square root of the average squared difference between
prediction and observation:
RMSE = sqrt(sum(predicted - observed)^2) / length(predicted)
mean_absolute_error()
: Calculate the average of the absolute differences between
prediction and observation:
MAE = mean(abs(predicted - observed))
NA values are completely ignored.
predicted = c(21.5, 22.2, 19.1) observed = c(20, 20, 20) get_bias(predicted, observed) get_bias(predicted, observed, relative = FALSE) root_mean_squared(predicted, observed) root_mean_squared(predicted, observed, relative = FALSE) mean_absolute_error(predicted, observed) mean_absolute_error(predicted, observed, relative = FALSE)
predicted = c(21.5, 22.2, 19.1) observed = c(20, 20, 20) get_bias(predicted, observed) get_bias(predicted, observed, relative = FALSE) root_mean_squared(predicted, observed) root_mean_squared(predicted, observed, relative = FALSE) mean_absolute_error(predicted, observed) mean_absolute_error(predicted, observed, relative = FALSE)
This function assumes the filenames to begin with the site name, potentially followed by an underscore and further characters.
get_site_name(filename)
get_site_name(filename)
filename |
String of a 'ModvegeSite' output filename. |
These are the default options, set when the package is loaded by 'library(growR)'. To get or change the current value of an option, use the 'options()' function.
Integer that controls how much console output is generated by growR functions. Higher numbers mean more output. See [logger()].
Name of the directory in which to look for input files.
Name of the directory into which output files are written.
Name of the directory in which to look for measured data files.
growR_package_options
growR_package_options
An object of class list
of length 4.
[options()]
Start the loop over runs specified in the config file.
growR_run_loop(modvege_environments, output_dir = "", independent = TRUE)
growR_run_loop(modvege_environments, output_dir = "", independent = TRUE)
modvege_environments |
A list of ModvegeEnvironment instances. |
output_dir |
string; name of directory to which output files are to
be written. If |
independent |
boolean; If |
By default, returns an empty list but writes output to the output files
as specified in the site_name and run_name fields of the supplied
ModvegeEnvironment instances. Change this behaviour through the
write_files
and store_results
arguments.
A list of the format [[run]][[year]]
containing clones of
the ModvegeSite instances that were run. Also write to files, if
output_dir is nonempty.
env1 = create_example_environment(site = "posieux") env2 = create_example_environment(site = "sorens") growR_run_loop(c(env1, env2), output_dir = "")
env1 = create_example_environment(site = "posieux") env2 = create_example_environment(site = "sorens") growR_run_loop(c(env1, env2), output_dir = "")
Load all datasets stored in the supplied files.
Upon loading, the cumulative biomass growth cBM is automatically calculated from the given daily biomass growth dBM values.
load_measured_data(filenames, sep = ",") load_data_for_sites(sites) load_matching_data(filenames)
load_measured_data(filenames, sep = ",") load_data_for_sites(sites) load_matching_data(filenames)
filenames |
Vector of strings representing simulation output filenames for which matching data files are searched and loaded. |
sep |
String Field separator used in the datafiles. |
sites |
Vector of site names for which data to load. |
load_matching_data()
internally uses get_site_name()
and makes the same
assumptions about the output filename formats. It further assumes measured
data to be located in "data/" and adhere to the filename format x.csv
with x
being the site name.
measured_data list of data.frame each corresponding to one of the sites detected in filenames. Each data.frame contains the keys
dBM
: average daily biomass growth since last observation in kg/ha.
cBM
: cumulative biomass growth up to this DOY in kg/ha.
year
: year of observation.
DOY
: day of year of observation.
load_data_for_sites()
: Data filenames are generated on the convention 'SITE.csv' and are searched
for in the subdirectory 'getOption("growR.data_dir")', which defaults
to 'data/'.
load_matching_data()
: Accepts a vector of output filenames as generated by
ModvegeSite$write_output()
out of which the site names are inferred.
The input data files are expected to consist of four columns containing the following fileds, in order:
Date of measurement in yyyy-mm-dd format.
Year of measurement. Identical to yyyy in date field.
Day of year of the measurement. Jan 1st corresponds to 1, Dec 31st corresponds to 365 (except in gap years).
Observed average daily biomass growth since last cut in kg/ha.
The first row is expected to be a header row containing the exact field names as in the description above. Columns may be separated by an arbitrary character, specified by the sep argument. The example data uses a comma (",").
Primitive logger for debugging.
logger(msg = "", level = DEBUG, stop_on_error = TRUE)
logger(msg = "", level = DEBUG, stop_on_error = TRUE)
msg |
The message to print. |
level |
The message will only be printed if its level is lower
or equal to |
stop_on_error |
Can be set to FALSE in order to continue execution despite emitting a message of level ERROR. |
None Prints console output.
logger("A standard message", level = 3) logger("A debug message", level = 4) logger("A deep debug message", level = 5)
logger("A standard message", level = 3) logger("A debug message", level = 4) logger("A deep debug message", level = 5)
Return numbers of the form YYYYDDD where YYYY is the year and DDD the DOY.
make_yearDOY(years, DOYs)
make_yearDOY(years, DOYs)
years |
int vector. |
DOYs |
int vector of same length as *years*. |
int vector of same length as *years* containing numbers of the form YYYYDDD, where the first four digits represent a year and the last four represent a DOY.
Expected yields, uncertainties and average number of cuts as function of altitude and management intensity.
management_parameters
management_parameters
A data.frame with 15 rows and 5 variables:
Management intensity
Altitude in m.a.s.l.
Average number of cuts
Expected gross dry matter yield in t / ha
Uncertainty on yield in t / ha
Data after table 1b in
Olivier Huguenin et al.
Huguenin-Elie I, Mosimann E, Schlegel P, Lüscher A, Kessler W, Jeangros B (2017). “Grundlagen für die Düngung landwirtschaftlicher Kulturen in der Schweiz (GRUD), Kapitel 9: Düngung von Grasland.” Agrarforschung Schweiz. https://www.agrarforschungschweiz.ch/2017/06/9-duengung-von-grasland-grud-2017/.
Management Data Class
Management Data Class
Data structure that contains management data which can serve as input to a ModvegeSite simulation run.
management_file
string The file that was read.
is_empty
boolean Used to determine if management data is present or not. In the latter case, ModvegeSite will simulate management decisions automatically.
years
List of unique years for which data is available.
cut_years
numeric Vector of length N where N is the total number of cuts read from the input file. Gives the year in which corresponding cut was made.
cut_DOY
numeric Vector of length N giving the day of year (as an integer) on which a cut was made.
intensity
string Management intensity for "autocut". One of c("high", "middle", "low").
new()
Create a new ManagementData object.
ManagementData$new(management_file = NULL, years = NULL)
management_file
string Path to file containing the management data to be read.
years
numeric Vector of years for which the management is to be extracted.
read_management()
Read management data from supplied management_file.
ManagementData$read_management(management_file, years = NULL)
management_file
Path to or name of file containing management data.
years
Years for which the management is to be extracted. Default (NULL) is to read in all found years.
None The object's field are filled.
ensure_file_integrity()
Check that all required columns are present and that cut DOYs are only increasing in a given year.
ManagementData$ensure_file_integrity(cut_data)
cut_data
data.frame containing the cut data.
get_management_for_year()
Extract management data for given year
This simply filters out all data not matching year and returns a list with the relevant keys.
ManagementData$get_management_for_year(year)
year
integer Year for which to extract management data.
M A list containing the keys:
boolean Used to determine if management data is present or not. In the latter case, ModvegeSite will simulate management decisions automatically.
numeric Vector of length N where N is the total number of cuts for this year, as read from the input file. Gives the year in which corresponding cut was made.
numeric Vector of length N giving the day of year (as an integer) on which a cut was made.
string Management intensity for "autocut". One of c("high", "middle", "low").
integer Number of cuts occurring in given year.
The two vectors in cut_DOY
and cut_years
differ from this object's respective fields in that only data for
selected year is present.
clone()
The objects of this class are cloneable with this method.
ManagementData$clone(deep = FALSE)
deep
Whether to make a deep clone.
ManagementData$read_management()
This list provides some common metrics of model performance along with their "best value".
metric_map
metric_map
A list where each item is a sublist containing the keys func and target.
The function used to calculate given metric.
The value that would be reached in the case of optimal performance.
Reasonable limits to be used when plotting.
Data structure that contains inputs (parameters pertaining to a site, to the vegetation, to the weather and to the management) to growR simulations.
This class contains site parameters, weather and management data for one simulation run of growR on a given site over several years. Methods are provided to allow access to relevant data for a given year.
All inputs are read in from data files through the respective data classes
WeatherData, ManagementData and ModvegeParameters. These parameters
can be simultaneously specified through a config file using read_config()
.
site_name
Name of site to be simulated.
run_name
Name of simulation run. Allows distinguishing between different simulations at the same site. Defaults to "-" for no name.
run_name_in_filename
How the run name will be represented in an
output file. If run_name
is the default "-", indicating no name, this
will be an empty string. Otherwise, it will be the run_name
prepended
by and underscore _
.
years
Years for which environment data (weather & management) is present.
param_file
Name of supplied parameter file.
weather_file
Name of supplied weather file.
management_file
Name of supplied management file.
parameters
A ModvegeParameters object.
weather
A WeatherData object.
management
A ManagementData object.
input_dir
Directory in which parameter, weather and management files are searched for. Defaults to 'getOption("growR.input_dir").
new()
Instantiate a new ModvegeEnvironment
ModvegeEnvironment$new( site_name, run_name = "-", years = NULL, param_file = "-", weather_file = "-", management_file = "-", input_dir = NULL )
site_name
string Name of the simulated site.
run_name
string Name of the simulation run. Used to differentiate between different simulation conditions at the same site. Defaults to "-", which indicates no specific run name.
years
numeric Vector of integer years to be simulated.
param_file
string Name of file that contains site and
vegetation parameters. If default value "-"
is provided, it is
assumed to be "SITENAME_parameters.csv".
weather_file
string Analogous to param_file.
management_file
string Analogous to param_file.
input_dir
string Path to directory containing input files.
Defaults to getOption("growR.input_dir")
.
set_run_name()
Set run name and update run_name_in_filename.
ModvegeEnvironment$set_run_name(run_name)
run_name
Str. New value of self$run_name
.
load_inputs()
Load simulation inputs.
Stores parameters, management and weather data from files specified in self$parameter_file, self$weather_file and self$management_file, respectively.
ModvegeEnvironment$load_inputs()
make_filename_for_run()
Ensure a readable filename for given run_name.
ModvegeEnvironment$make_filename_for_run(run_name)
run_name
Name of run to be converted into a filename.
A version of run_name that can be used in a filename.
get_environment_for_year()
Get weather and environment for given year
Convenience function to retrieve environmental and management
inputs for given year from multi-year data containers self$weather
and self$management
.
ModvegeEnvironment$get_environment_for_year(year)
year
int; year for which to extract data.
list(W, M)
where W
is the WeatherData and M
the
ManagementData object for given year.
clone()
The objects of this class are cloneable with this method.
ModvegeEnvironment$clone(deep = FALSE)
deep
Whether to make a deep clone.
WeatherData$get_weather_for_year()
,
ManagementData$get_management_for_year()
Data structure that contains site and vegetation parameters necessary for the configuration of an growR simulation run.
The following is a list and description of model parameters, including the vegetation parameters, which are defined through the functional group composition.
LON
geographic longitude of site in degree.
LAT
geographic latitude of site in degree.
ELV
geographic elevation of site in m.a.s.l.
WHC
water-holding capacity of site in mm.
NI
site nutritional index (dimensionless).
RUEmax
maximum radiuation use efficiency in g DM per MJ.
w_FGA
relative weight of functional group A.
w_FGB
relative weight of functional group B.
w_FGC
relative weight of functional group C.
w_FGD
relative weight of functional group D.
sigmaGV
rate of GV respirative biomass loss (dimensionless).
sigmaGR
rate of GR respirative biomass loss (dimensionless).
T0
photosynthesis activation temperature (degree C).
T1
photosynthesis plateau temperature (degree C).
T2
photosynthesis max temperature (degree C).
KGV
basic senescence rate GV (dimensionless).
KGR
basic senescence rate GR (dimensionless).
KlGV
basic abscission rate GV (dimensionless).
KlGR
basic abscission rate GR (dimensionless).
maxOMDDV
organic matter digestibility in gram per gram DV.
minOMDDR
organic matter digestibility in gram per gram DR.
CO2_growth_factor
strength of effect of CO2 concentration on growth. See
parameter b in fCO2_growth_mod()
.
crop_coefficient
multiplicative factor K~c~ by which
reference evapotranspiration ET~0~ has to be multiplied to get the crop
evapotranspiration ET~c~:
ET~c~ = K~c~ ET~0~
senescence_cap
fraction c~s~ of GRO to which SEN is
limited: SEN~i~^max^ = c~s~ GRO~i~
for i in GV, GR. Makes it less likely for grass population to die out.
Can be set to large values in order to effectively disable senescence capping.
stubble_height
float. Minimum height the grass can assume. The
biomass will not fall below that height. This effectively presents a simple
model of plant reserves.
SGS_method
string. Choice of method to determine the start of the growing
season. Can be either "MTD"
for the multicriterial thermal definition
(see start_of_growing_season_mtd()
) or "simple"
for a commonly used
approach as described in start_of_growing_season()
).
AgeGV
Age of green vegetative matter in degree Celsius days.
AgeGR
Age of green reproductive matter in degree Celsius days.
AgeDV
Age of dead vegetative matter in degree Celsius days.
AgeDR
Age of dead reproductive matter in degree Celsius days.
BMGV
biomass of GV (kg DM per ha).
BMGR
biomass of GR (kg DM per ha).
BMDV
biomass of DV (kg DM per ha).
BMDR
biomass of DR (kg DM per ha).
BMDR
biomass of DR (kg DM per ha).
SENG
senescence of GV (kg DM per ha).
SENG
senescence of GR (kg DM per ha).
ABSG
abscission of DV (kg DM per ha).
ABSG
abscission of DR (kg DM per ha).
ST
thermal time (degree days).
cBM
cumulative total biomass (kg per ha).
SLA
Specific Leaf Area in m^2^ per g.
pcLAM
Percentage of laminae (number between 0 and 1).
ST1
Temperature sum in degree Celsiues days after which the
seasonality function SEA
starts to decrease from its maximum plateau.
See also SEA()
.
ST2
Temperature sum in degree Celsiues days after which the
seasonality function SEA
has decreased back to its minimum value.
See also SEA()
.
maxSEA
Maximum value of the seasonality function SEA()
minSEA
Minimum value of the seasonality function SEA()
. Usually,
minSEA = 1 - (maxSEA - 1)
.
maxOMDGV
Maximum organic matter digestability for green vegetative
matter in arbitrary units.
minOMDGV
Minimum organic matter digestability for green vegetative
matter in arbitrary units.
maxOMDGR
Maximum organic matter digestability for green reproductive
matter in arbitrary units.
minOMDGR
Minimum organic matter digestability for green reproductive
matter in arbitrary units.
BDGV
Bulk density of green vegetative dry matter in g per m^3^.
BDDV
Bulk density of dead vegetative dry matter in g per m^3^.
BDGR
Bulk density of green reproductive dry matter in g per m^3^.
BDDR
Bulk density of dead reproductive dry matter in g per m^3^.
fg_parameter_names
Vector of strings of the variable names of all
vegetation parameters governed by functional group composition.
required_parameter_names
Names of parameters that do not have a default value and are therefore strictly required.
parameter_names
Names of all required and optional parameters and state variables.
n_parameters
Number of total parameters.
functional_group
The FunctionalGroup instance holding the vegetation parameters.
fg_parameter_names
Names of vegetation parameters defined by the functional group composition.
initial_condition_names
Names of initial conditions.
param_file
Name of the parameter file from which initial parameter values were read.
new()
Constructor
ModvegeParameters$new(param_file = NULL)
param_file
Name of file containing the site and vegetation parameters.
read_parameters()
Read parameters from parameter file
Reads in parameters from the supplied param_file and stores them in internal fields.
This function carries out some basic sanity checks of the supplied param_file and reports on unidentified and missing parameter names.
ModvegeParameters$read_parameters(param_file)
param_file
Path or name of file to read parameters from.
P List with field names as in the class variable
parameter_names
.
set_parameters()
Savely update the given parameters
This is the preferred method for changing the internal parameter values, because special care is taken to account for potential changes to functional group weights.
ModvegeParameters$set_parameters(params)
params
List of name-value pairs of the parameters to update.
update_functional_group()
Update functional group parameters
Should be run whenever the functional group composition is changed in
order to reflect the changes in the parameter list self$P
.
ModvegeParameters$update_functional_group()
check_parameters()
Parameter Sanity Check
Ensure that the supplied params are valid ModVege parameters and,
if requested, check that all required parameters are present.
Issues a warning for any invalid parameters and throws an error if
completeness is not satisfied (only when check_for_completeness = TRUE
).
ModvegeParameters$check_parameters(param_names, check_for_completeness = TRUE)
param_names
A list of parameter names to be checked.
check_for_completeness
Boolean Toggle whether only the validity of supplied param_names is checked or whether we want to check that all required parameters to be present (default). In the latter case, if any required parameter is missing, an error is thrown.
not_known The list of unrecognized parameter names.
clone()
The objects of this class are cloneable with this method.
ModvegeParameters$clone(deep = FALSE)
deep
Whether to make a deep clone.
Programmatically speaking, all parameters described under Parameter description are also fields of this R6Class.
Implements the ModVege grass growth model based off of Jouven et al. (2006).
This class contains model and site parameters and state variables as attributes and has methods for running ModVege with weather and management input.
Use the run()
method to carry out a simulation for a given year. The
results are stored in the state variables in this instance and can be written
to file using write_output()
.
See Jouven et al. (2006) for a thorough description of all model variables.
BM
Standing biomass in kg DM per ha.
BMG
Standing green biomass (kg DM / ha).
cBM
Cumulativeley grown biomass (kg DM / ha).
dBM
Daily grown biomass (kg DM / ha).
hvBM
Cumulative harvested biomass (kg DM / ha).
OMD
Organic matter digestibility (kg / kg).
OMDG
OMD of green matter (kg / kg).
ST
Temperature sum in degree Celsius days.
REP
Reproductive function. Gives the fraction of growth that is
assigned to reproductive growth. The remainder goes into vegetative growth.
Dimensionless.
PGRO
Potential growth in kg DM / ha.
GRO
Effective growth in kg DM / ha.
LAI
Leaf area index, accounting for the proportion of light intercepted by the
sward. Dimensionless.
LAIGV
LAI of green vegetative biomass. Dimensionless.
AET
Actual evapotranspiration in mm.
WR
Water reserves in mm.
ENV
Function representing environmental effects on growth. Acts as a
multiplicative factor. Dimensionless.
ENVfPAR
Part of ENV due to strength of incident radiation. Dimensionless.
ENVfT
Part of ENV due to temperature. Dimensionless.
ENVfW
Part of ENV due to water limitation. Dimensionless.
AgeGV
Age of green vegetative matter in degree Celsius days.
AgeGR
Age of green reproductive matter in degree Celsius days.
AgeDV
Age of dead vegetative matter in degree Celsius days.
AgeDR
Age of dead reproductive matter in degree Celsius days.
BMGV
biomass of GV (kg DM per ha).
BMGR
biomass of GR (kg DM per ha).
BMDV
biomass of DV (kg DM per ha).
BMDR
biomass of DR (kg DM per ha).
BMDR
biomass of DR (kg DM per ha).
SENG
senescence of GV (kg DM per ha).
SENG
senescence of GR (kg DM per ha).
ABSG
abscission of DV (kg DM per ha).
ABSG
abscission of DR (kg DM per ha).
ST
thermal time (degree days).
cBM
cumulative total biomass (kg per ha).
time_step
Used time step in the model in days (untested).
state_variable_names
Vector containing the names of the model's state variables.
n_state_variables
Number of state variables.
version
Version number of the growR package. Is written into output files.
site_name
Name of the site to be simulated.
run_name
Name of the simulation run. Used to distinguish between different runs at the same site.
year
Year to be simulated.
days_per_year
Number of days in this year.
j_start_of_growing_season
Index (DOY) of the day the growing season was determined to begin.
cut_height
Height of remaining grass after cut in m.
parameters
A ModvegeParameters object.
determine_cut
Function used to decide whether a cut occurs on a given DOY. Is overloaded depending on whether management data is provided or not.
cut_DOYs
List of DOYs on which a cut occurred.
cut_during_growth_preriod
Boolean to indicate whether a cut occurred during the growth period, in which case reproductive growth is stopped.
BM_after_cut
Amount of biomass that remains after a cut #' (determined through cut_height and biomass densities BDGV, BDDV, BDGR, BDDR).
weather
A list created by a WeatherData object's
get_weather_for_year()
method.
management
A list containing management data as returned by
ModvegeEnvironment's get_environment_for_year()
method. If its
is_empty
field is TRUE
, the Autocut routine will be employed.
Autocut
A subclass of Autocut. The algorithm used to determine cut events.
new()
Constructor
ModvegeSite$new(parameters, site_name = "-", run_name = "-")
parameters
A ModvegeParameters object.
site_name
string Name of the simulated site.
run_name
string Name of the simulation run. Used to differentiate between different simulation conditions at the same site. Defaults to "-", which indicates no specific run name.
get_weather()
Return weather data if it exists
ModvegeSite$get_weather()
The WeatherData object, if it exists.
get_management()
Return management data if it exists
ModvegeSite$get_management()
The ManagementData object, if it exists.
set_SGS_method()
Choose which method to be used for determination of SGS
Options for the determination of the start of growing season (SGS) are:
Multicriterial thermal definition,
start_of_growing_season_mtd()
Commonly used, simple SGS definition based on
temperature sum, start_of_growing_season()
ModvegeSite$set_SGS_method(method)
method
str Name of the method to use. Options: "MTD", "simple".
none
determine_cut_from_input()
Read from the input whether a cut occurs on day DOY.
ModvegeSite$determine_cut_from_input(DOY)
DOY
Integer day of the year for which to check.
Boolean TRUE
if a cut happens on day DOY.
run()
Carry out a ModVege simulation for one year.
ModvegeSite$run(year, weather, management)
year
Integer specifying the year to consider.
weather
Weather list for given year as returned by
WeatherData$get_weather_for_year
.
management
Management list for given year as provided by
ModvegeEnvironment$get_environment_for_year()
.
None Fills the state variables of this instance with the
simulated values. Access them programmatically or write them to
file using write_output()
.
write_output()
Write values of ModVege results into given file.
A header with metadata is prepended to the actual data.
ModvegeSite$write_output(filename, force = FALSE)
filename
Path or name of filename to be created or overwritten.
force
Boolean If TRUE
, do not prompt user before writing.
None Writes simulation results to file filename.
set_parameters()
Savely update the values in self$parameters
.
This is just a shorthand to the underlying ModvegeParameters
object's set_parameters()
function. Special care is taken to
account for potential changes to functional group weights.
ModvegeSite$set_parameters(params)
params
List of name-value pairs of the parameters to update.
None Updates this object's parameter values.
plot()
Create an overview plot for 16 state variables.
Creates a simple base R plot showing the temporal evolution of 16 modeled state variables.
Can only be sensibly run after a simulation has been carried out,
i.e. after this instance's run()
method has been called.
ModvegeSite$plot(...)
...
Further arguments are discarded.
NULL Creates a plot of the result in the active device.
plot_bm()
Create an overview plot for biomass.
Creates a simple base R plot showing the BM with cutting events and,
if applicable, target biomass, dBM, cBM and hvBM.
Can only be sensibly run after a simulation has been carried out,
i.e. after this instance's run()
method has been called.
ModvegeSite$plot_bm(smooth_interval = 28, ...)
smooth_interval
Int. Number of days over which the variable
dBM
is smoothened.
...
Further arguments are discarded.
NULL Creates a plot of the result in the active device.
plot_limitations()
Create an overview plot of limiting factors.
Creates a simple base R plot showing the different environmental
limitation functions over time.
Can only be sensibly run after a simulation has been carried out,
i.e. after this instance's run()
method has been called.
ModvegeSite$plot_limitations(...)
...
Further arguments are discarded.
NULL Creates a plot of the result in the active device.
plot_water()
Create an overview plot of the water balance.
Creates a simple base R plot showing different variables pertaining to the water balance, namely water reserves WR, actual evapotranspiration AET, leaf area index LAI and LAI of the green vegetative compartment LAIGV.
Can only be sensibly run after a simulation has been carried out,
i.e. after this instance's run()
method has been called.
ModvegeSite$plot_water(...)
...
Further arguments are discarded.
NULL Creates a plot of the result in the active device.
plot_growth()
Create an overview plot of growth dynamics.
Creates a simple base R plot showing different variables pertaining to the growth dynamics, namely potential growth PGRO, effective growth GRO, the reproductive function REP and the temperature sum ST.
Can only be sensibly run after a simulation has been carried out,
i.e. after this instance's run()
method has been called.
ModvegeSite$plot_growth(...)
...
Further arguments are discarded.
NULL Creates a plot of the result in the active device.
plot_var()
Plot the temporal evolution of a modeled state variable.
ModvegeSite$plot_var(var, ...)
var
String. Name of the state variable to plot.
...
Further arguments are passed to the base plot()
function.
None, but plots to the current device.
clone()
The objects of this class are cloneable with this method.
ModvegeSite$clone(deep = FALSE)
deep
Whether to make a deep clone.
Jouven M, Carrère P, Baumont R (2006). “Model Predicting Dynamics of Biomass, Structure and Digestibility of Herbage in Managed Permanent Pastures. 1. Model Description.” Grass and Forage Science, 61(2), 112–124. ISSN 1365-2494, doi:10.1111/j.1365-2494.2006.00515.x, https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1365-2494.2006.00515.x.
start_of_growing_season_mtd()
, start_of_growing_season()
ModvegeParameters$set_parameters()
The function run_parameter_scan()
can take a significant time to
execute, as it typically requires a few dozen model evaluations or more.
In order to still showcase what its output can look like, and to
facilitate testing and giving examples in the documentation of tools that
make use of the output of run_parameter_scan()
(such as e.g.
analyze_parameter_scan()
), this example dataset is provided.
parameter_scan_example
parameter_scan_example
A list containing an entry for each supplied parameter set in param_values. Each entry is itself a list containing the following keys:
The parameter set that was used to run growR for this entry.
A list containing for each simulated year a ModvegeSite object which was run for the respective year and therefore carries the respective results.
The input for the parameter scan that produced this output was:
w_FGB = seq(0.25, 1, 0.25), w_FGC = seq(0, 0.25, 0.25), w_FGD = c(0), NI = seq(0.75, 1.0, 0.25)
- `eps = 2e-2` )
Parse and generate lists of years.
parse_year_strings(year_strings)
parse_year_strings(year_strings)
year_strings |
A vector of strings that each either represents a single year or a sequence of year in the format 'start:stop'. |
run_years List of integer vectors, representing the years to simulate for each run.
Simulation routine to realistically predict grass cutting events. This follows an implementation described in Petersen et al. (2021).
The decision to cut is made based on two criteria.
First, it is checked whether a target biomass is reached on given
DOY. The defined target depends on the DOY and is given through
:func:get_target_biomass
. If said biomass is present, return TRUE
.
Otherwise, it is checked whether a given amount of time has passed
since the last cut. Depending on whether this is the first cut of
the season or not, the relevant parameters are
:int:last_DOY_for_initial_cut
and :int:max_cut_period
.
If that amount of time has passed, return TRUE
, otherwise return
FALSE
.
The target biomass for a given day is determined following the principles described in Petersen et al.
The exact regression for the target biomass is based on Fig. S2 in the supplementary material of Petersen et al.
A refinement to expected yield as function of altitude has been implemented according to Table 1a in Huguenin et al. (2017).
growR::Autocut
-> PetersenAutocut
last_DOY_for_initial_cut
Start cutting after this DOY, even if yield target is not reached.
max_cut_period
Maximum period to wait between subsequent cuts.
dry_precipitation_limit
Maximum amount of allowed precipitation (mm) to consider a day.
dry_days_before_cut
Number of days that shold be dry before a cut is made.
dry_days_after_cut
Number of days that shold be dry after a cut is made.
max_cut_delay
Number of days a farmer is willing to wait for dry conditions before a cut is made anyways.
cut_delays
Vector to keep track of cut delay times.
dry_window
Logical that indicates if DOY at index is considered dry enough to cut.
target_biomass
Biomass amount that should to be reached by given DOY for a cut to be made.
end_of_cutting_season
Determined DOY after which no more cuts are made.
new()
Constructor
PetersenAutocut$new(MVS)
MVS
The ModvegeSite object for which cuts shall be determined.
get_annual_gross_yield()
Lookup table returning expected annual gross yields as function of elevation and management intensity.
Based on data from Table 1a in Lookup Table of expected yield as functions of height and management intensity after Olivier Huguenin et al. (2017).
PetersenAutocut$get_annual_gross_yield(elevation, intensity = "high")
elevation
The elevation of the considered site in meters above sea level.
intensity
One of ("high", "middle", "low", "extensive"). Management intensity for considered site.
Annual gross yield in t / ha (metric tons per hectare). Note that 1 t/ha = 0.1 kg/m^2.
get_target_biomass()
Get target value of biomass on given DOY, which determines whether a cut is to occur.
The regression for the target biomass is based on Fig. S2 in the supplementary material of Petersen, Krischan, David Kraus, Pierluigi Calanca, Mikhail A. Semenov, Klaus Butterbach-Bahl, and Ralf Kiese. “Dynamic Simulation of Management Events for Assessing Impacts of Climate Change on Pre-Alpine Grassland Productivity.” European Journal of Agronomy 128 (August 1, 2021): 126306. https://doi.org/10.1016/j.eja.2021.126306.
A refinement to expected yield as function of altitude has been implemented according to Table 1a in Huguenen-Elie et al. "Düngung von Grasland", Agrarforschung Schweiz, 8, (6), 2017, https://www.agrarforschungschweiz.ch/2017/06/9-duengung-von-grasland-grud-2017/
PetersenAutocut$get_target_biomass(DOY, intensity = "high")
DOY
Integer day of the year to consider.
intensity
One of ("high", "middle", "low") specifying management intensity.
target Biomass (kg / ha) that should be reached on day DOY for this management intensity.
get_relative_cut_contribution()
Relative cut contribution
Get the fraction of the total annual harvested biomass that a cut at given DOY is expected to contribute.
The regression for the target biomass is based on Fig. S2 in the supplementary material of Petersen et al. (2021).
PetersenAutocut$get_relative_cut_contribution(DOY)
DOY
Integer representing the day of the year on which a cut occurs.
The fraction (between 0 and 1) of biomass harvested at the cut at given DOY divided by the total annual biomass.
get_end_of_cutting_season()
Last day of cutting season
Estimate the last day on which it still makes sense to cut. This is done
by checking at which point the expected target biomass (see
self$get_relative_cut_contribution()
) goes below the minimally harvestable
standing biomass.
PetersenAutocut$get_end_of_cutting_season( min_biomass, elevation, intensity = "high" )
min_biomass
float A standing biomass below this value cannot even be harvested,
elevation
float Altitude in m.a.s.l.
intensity
string Management intensity. One of "high", "middle", "low"
float Last (fractional) day of the year on which a cut still makes sense.
determine_cut()
Decide based on simple criteria whether day of year DOY would be a good day to cut.
This follows an implementation described in Petersen, Krischan, David Kraus, Pierluigi Calanca, Mikhail A. Semenov, Klaus Butterbach-Bahl, and Ralf Kiese. “Dynamic Simulation of Management Events for Assessing Impacts of Climate Change on Pre-Alpine Grassland Productivity.” European Journal of Agronomy 128 (August 1, 2021): 126306. https://doi.org/10.1016/j.eja.2021.126306.
The decision to cut is made based on two criteria.
First, it is checked whether a target biomass is reached on given
DOY. The defined target depends on the DOY and is given through
:func:get_target_biomass
. If said biomass is present, return TRUE
.
Otherwise, it is checked whether a given amount of time has passed
since the last cut. Depending on whether this is the first cut of
the season or not, the relevant parameters are
:int:last_DOY_for_initial_cut
and :int:max_cut_period
.
If that amount of time has passed, return TRUE
, otherwise return
FALSE
.
PetersenAutocut$determine_cut(DOY)
DOY
Integer day of the year for which to make a cut decision.
Boolean TRUE
if a cut happens on day DOY.
clone()
The objects of this class are cloneable with this method.
PetersenAutocut$clone(deep = FALSE)
deep
Whether to make a deep clone.
Huguenin-Elie I, Mosimann E, Schlegel P, Lüscher A, Kessler W, Jeangros B (2017). “Grundlagen für die Düngung landwirtschaftlicher Kulturen in der Schweiz (GRUD), Kapitel 9: Düngung von Grasland.” Agrarforschung Schweiz. https://www.agrarforschungschweiz.ch/2017/06/9-duengung-von-grasland-grud-2017/. Petersen K, Kraus D, Calanca P, Semenov MA, Butterbach-Bahl K, Kiese R (2021). “Dynamic Simulation of Management Events for Assessing Impacts of Climate Change on Pre-Alpine Grassland Productivity.” European Journal of Agronomy, 128, 126306. ISSN 1161-0301, doi:10.1016/j.eja.2021.126306, https://www.sciencedirect.com/science/article/pii/S1161030121000782.
Huguenin-Elie I, Mosimann E, Schlegel P, Lüscher A, Kessler W, Jeangros B (2017). “Grundlagen für die Düngung landwirtschaftlicher Kulturen in der Schweiz (GRUD), Kapitel 9: Düngung von Grasland.” Agrarforschung Schweiz. https://www.agrarforschungschweiz.ch/2017/06/9-duengung-von-grasland-grud-2017/.
Petersen K, Kraus D, Calanca P, Semenov MA, Butterbach-Bahl K, Kiese R (2021). “Dynamic Simulation of Management Events for Assessing Impacts of Climate Change on Pre-Alpine Grassland Productivity.” European Journal of Agronomy, 128, 126306. ISSN 1161-0301, doi:10.1016/j.eja.2021.126306, https://www.sciencedirect.com/science/article/pii/S1161030121000782.
get_relative_cut_contribution()
get_target_biomass()
An algorithm to determine grass cut dates if none are provided. This uses empirical data for Switzerland to determine the first and last cut dates of the season from meteorological data. The number of cuts is inferred from Huguenen et al. and these cut events are distributed equally between first and last cut dates.
growR::Autocut
-> PhenologicalAutocut
cut_DOYs
vector containing the integer day-of-year's on which cuts occur.
new()
Constructor
Valid cut dates are calculated upon initialization.
PhenologicalAutocut$new(MVS)
MVS
The ModvegeSite object for which cuts shall be determined.
determine_cut()
Does a cut occur on DOY?
Check if DOY is in self$cut_DOYs
. If so, return TRUE
. Return
FALSE
otherwise.
PhenologicalAutocut$determine_cut(DOY)
DOY
Integer day of the year (1-366).
Boolean
clone()
The objects of this class are cloneable with this method.
PhenologicalAutocut$clone(deep = FALSE)
deep
Whether to make a deep clone.
Huguenin-Elie I, Mosimann E, Schlegel P, Lüscher A, Kessler W, Jeangros B (2017). “Grundlagen für die Düngung landwirtschaftlicher Kulturen in der Schweiz (GRUD), Kapitel 9: Düngung von Grasland.” Agrarforschung Schweiz. https://www.agrarforschungschweiz.ch/2017/06/9-duengung-von-grasland-grud-2017/.
management_parameters, PetersenAutocut
Visualize the results of a parameter scan and allow interactive inspection of model performance in parameter space.
plot_parameter_scan(analyzed, variable = "dBM", interactive = TRUE)
plot_parameter_scan(analyzed, variable = "dBM", interactive = TRUE)
analyzed |
List; Output of |
variable |
Str; Name of variable in analyzed to visualize. Can
be changed later with |
interactive |
boolean; Toggle between just creating a static plot
( |
Under the hood this function just creates a PscanPlotter object and calls its
analyze
method.
A PscanPlotter object.
analyze_parameter_scan()
, PscanPlotter$analyze()
# There needs to be data available with which the modle is to be compared. # For this example, use data provided by the package. path = system.file("extdata", package = "growR") datafile = file.path(path, "posieux1.csv") # Analyze example output of `run_parameter_scan()`. results = analyze_parameter_scan(parameter_scan_example, datafile = datafile) # The following plots the results. psp = plot_parameter_scan(results, interactive = FALSE) # The interactive session can still be entered later from the returned # PscanPlotter object psp$analyze()
# There needs to be data available with which the modle is to be compared. # For this example, use data provided by the package. path = system.file("extdata", package = "growR") datafile = file.path(path, "posieux1.csv") # Analyze example output of `run_parameter_scan()`. results = analyze_parameter_scan(parameter_scan_example, datafile = datafile) # The following plots the results. psp = plot_parameter_scan(results, interactive = FALSE) # The interactive session can still be entered later from the returned # PscanPlotter object psp$analyze()
This wraps the ModvegeSite
instance's plot()
method.
## S3 method for class 'ModvegeSite' plot(x, ...)
## S3 method for class 'ModvegeSite' plot(x, ...)
x |
A ModvegeSite instance. |
... |
Arguments are passed on to ModvegeSite |
NULL, but plots to the active device.
The different [modvegeSite]$plot_XXX()
methods.
Datasets containing the weather input parameters as used by growR. The
same data is made available as plain text files by the package and
automatically found in the input
directory created by setup_directory()
if the include_examples
option is set to TRUE
(default).
posieux_weather
posieux_weather
A data.frame with 3652 rows and 10 variables:
Year as an integer
Day of year as an integer
Average temperature of the day in degree Celsius
Minimum temperature of the day in degree Celsius
Maximum temperature of the day in degree Celsius
Daily precipitation in mm
Relative sunshine duration in percent
Sun irradiance in J / s / m^2. This can be converted into photosynthetically active radiation (PAR) in MJ / m^2 as: PAR = SRad * 0.47 * 24 * 60 * 60 / 1e6
Evapotranspiration in mm.
Precipitation in the form of snow in mm
For use in growR, a WeatherData object has to be created from a plain
text file. Therefore, this dataset is only provided for convenient
inspection. In order to run growR, use the plain text files provided by
the package. Use system.file("extdata", package = "growR")
to locate them.
The snow column is not actually used by growR but rather calculated
through precipitation and temperatures in WeatherData$read_weather()
.
Likewise, the rSSD column is deprecated, currently unused and only kept for backwards compatibility.
setup_directory()
, WeatherData
This class facilitates interactive visual analysis of parameter scan results.
analyzed
List, as output by analyze_parameter_scan()
.
params
Vector of names of scanned parameters.
metrics
Vector of names of model performance metrics to use.
n_params
Number of scanned parameters.
n_metrics
Number of performance metrics to apply.
res
data.frame holding parameter scan results. It contains
n_params + n_metrics + 1
columns: one column for each scanned
parameter, one for each employed metric and an additional column
(name n
) to give each parameter combination (i.e. each row) an
identifying number.
n_combinations
Number of rowns in res
.
sorted
List containing copies of res
which are each sorted by
a different performance metric. List keys are the values in
self$metrics
.
selection
Vector of integers corresponding to the ID number of
combinations (column n
in self$res
) that is to be highlighted.
new()
Construct and set up a PscanPlotter instance.
PscanPlotter$new(analyzed, variable = "dBM")
analyzed
List; Output of analyze_parameter_scan()
.
variable
Str; Name of variable in analyzed to visualize. Can
be changed later with set_variable()
. Allowed values are the keys
in analyzed except for params
and metrics
.
set_variable()
Choose which variable to visualize.
PscanPlotter$set_variable(variable)
variable
Chosen variable name. One of "dBM", "cBM", "cBM_end"
analyze()
Enter analysis loop.
This plots the analysis results and enters a simple command-line interface through which more insights can be gathered. Particularly, it allows highlighting specific parameter combinations, either by their index number or by selecting the best performers according to a given metric.
PscanPlotter$analyze()
plot()
Plot parameter scan results.
For every combination of scanned parameter and metric, a subplot is generated in which the parameter values are plotted against performance score in that metric for every parameter combination.
The result of this is static. Use PscanPlotter$analyze()
for an interactive version.
PscanPlotter$plot()
print_info()
Print information on selected parameter combinations.
The parameter values and performance scores of all combinations referred to by the integers in selection are printed to console.
PscanPlotter$print_info(selection)
selection
Vector of integers representing IDs of parameter
combinations (i.e. column n
in self$res
).
clone()
The objects of this class are cloneable with this method.
PscanPlotter$clone(deep = FALSE)
deep
Whether to make a deep clone.
PscanPlotter$plot()
The format of the configuration file is expected to contain 6 space-separated columns representing, in order:
Name of simulated site. This is used, for example, when an output file is created.
Name of this simulation run. Used to differentiate
between different runs at the same site. Can be -
to indicate
no particular name, in which case nothing will be appended in
the resulting output file.
Specification of years to be simulated. Either a single
number or a sequence in R's :
notation, i.e. 2013:2022
to
indicate all years from 2013 to (including) 2022.
Filename (not full path) of parameter file to use. The file is assumed to be located in input_dir (confer documentation for that parameter).
Filename (not full path) of weather file. See also param_file.
Filename (not full path) of management file.
See also param_file. Can be set to high
, middle
, low
or
-
if no management data is to be used and the autocut
routine shall be employed to simulate cutting events.
Rows starting with a #
are skipped.
read_config(config_file, input_dir = NULL)
read_config(config_file, input_dir = NULL)
config_file |
Path to the configuration file to be read. |
input_dir |
Path to directory where input files are located. Defaults
to |
A list of ModvegeEnvironment instances corresponding to the configurations in the order they appear in config_file.
# First, we set up the expected directory structure in a temporary place tmp = file.path(tempdir(), "test-read_config") dir.create(tmp) # We need `force = TRUE` here in order to make the example work in # non-interactive settings. setup_directory(root = tmp, include_examples = TRUE, force = TRUE) # Now we can test `read_config`. read_config(file.path(tmp, "example_config.txt"), input_dir = file.path(tmp, "input"))
# First, we set up the expected directory structure in a temporary place tmp = file.path(tempdir(), "test-read_config") dir.create(tmp) # We need `force = TRUE` here in order to make the example work in # non-interactive settings. setup_directory(root = tmp, include_examples = TRUE, force = TRUE) # Now we can test `read_config`. read_config(file.path(tmp, "example_config.txt"), input_dir = file.path(tmp, "input"))
Run ModVege for a different sets of parameters.
run_parameter_scan(environment, param_values, force = FALSE, outfilename = "")
run_parameter_scan(environment, param_values, force = FALSE, outfilename = "")
environment |
Either a ModvegeEnvironment instance with all the site,
management and weather inputs expected by ModvegeSite |
param_values |
A named list where each key stands for a ModVege
parameter, i.e. a member of ModvegeParameters |
force |
Boolean. By default ( |
outfilename |
String. If nonempty, the results are stored as an |
results A list containing an entry for each supplied parameter set in param_values. Each entry is itself a list containing the following keys:
The parameter set that was used to run ModVege for this entry.
A list containing for each simulated year a ModvegeSite object which was run for the respective year and therefore carries the respective results.
Special care has to be taken in the creation of the param_values argument.
It's possible to choose values that do not allow for any valid combination.
Confer create_combinations()
.
ModvegeParameters, saveRDS()
, create_combinations()
env = create_example_environment() # We're creating a trivial list of parameters to explore here in order to # prevent the example from requiring a long time to execute. See # [create_combinations()] for more realistic uses of param_values. param_values = list(w_FGA = c(0, 1), w_FGB = c(0, 1)) run_parameter_scan(env, param_values, force = TRUE)
env = create_example_environment() # We're creating a trivial list of parameters to explore here in order to # prevent the example from requiring a long time to execute. See # [create_combinations()] for more realistic uses of param_values. param_values = list(w_FGA = c(0, 1), w_FGB = c(0, 1)) run_parameter_scan(env, param_values, force = TRUE)
Function representing the strategy of plants adjusting their roots:shoots ratios during the season.
SEA(ST, minSEA = 0.65, maxSEA = 1.35, ST1 = 800, ST2 = 1450)
SEA(ST, minSEA = 0.65, maxSEA = 1.35, ST1 = 800, ST2 = 1450)
ST |
float Temperature sum in degree(C)-days. |
minSEA |
float < 1. Minimum value of SEA. |
maxSEA |
float > 1. Maximum value of SEA. |
ST1 |
float Temperature sum after which SEA declines from the maximum plateau. |
ST2 |
float Temperature sum after which SEA reaches and remains at its minimum. |
SEA(800)
SEA(800)
Set verbosity of growR output.
set_growR_verbosity(level = 3)
set_growR_verbosity(level = 3)
level |
Integer representing one of the following levels: 1: ERROR, 2: WARNING, 3: INFO, 4: DEBUG, 5: TRACE Messages with a level higher than the specified level are suppressed. In other words, higher values of level lead to more output and vice versa. |
None Sets the option “"growR.verbosity"'.
# At level 3, only one of the three following messages are printed. set_growR_verbosity(3) logger("Message on level 5.", level = 5) logger("Message on level 4.", level = 4) logger("Message on level 3.", level = 3) # At level 5, all three are printed. set_growR_verbosity(5) logger("Message on level 5.", level = 5) logger("Message on level 4.", level = 4) logger("Message on level 3.", level = 3) # Reset to default. set_growR_verbosity()
# At level 3, only one of the three following messages are printed. set_growR_verbosity(3) logger("Message on level 5.", level = 5) logger("Message on level 4.", level = 4) logger("Message on level 3.", level = 3) # At level 5, all three are printed. set_growR_verbosity(5) logger("Message on level 5.", level = 5) logger("Message on level 4.", level = 4) logger("Message on level 3.", level = 3) # Reset to default. set_growR_verbosity()
Creates directories in which growR by default looks for or deposits certain files. Also, optionally populates these directories with example files, which are useful to familiarize oneself with the growR simulation framework.
setup_directory(root, include_examples = TRUE, force = FALSE)
setup_directory(root, include_examples = TRUE, force = FALSE)
root |
Path to directory in which to initialize. |
include_examples |
If |
force |
boolean If |
# Prepare a temporary directory to write to tmp = file.path(tempdir(), "test-setup_directory") dir.create(tmp) # We need `force = TRUE` here in order to make the example work in # non-interactive settings. setup_directory(root = tmp, include_examples = FALSE, force = TRUE) # The `input`, `output` and `data` directories are now present. list.files(tmp) # Warnings are issued if directories are already present. Example files # are still copied and potentially overwritten. setup_directory(root = tmp, include_examples = TRUE, force = TRUE) # Example files are now present list.files(tmp, recursive = TRUE) # End of the example. The following code is for cleaning up. unlink(tmp, recursive = TRUE)
# Prepare a temporary directory to write to tmp = file.path(tempdir(), "test-setup_directory") dir.create(tmp) # We need `force = TRUE` here in order to make the example work in # non-interactive settings. setup_directory(root = tmp, include_examples = FALSE, force = TRUE) # The `input`, `output` and `data` directories are now present. list.files(tmp) # Warnings are issued if directories are already present. Example files # are still copied and potentially overwritten. setup_directory(root = tmp, include_examples = TRUE, force = TRUE) # Example files are now present list.files(tmp, recursive = TRUE) # End of the example. The following code is for cleaning up. unlink(tmp, recursive = TRUE)
This implements a conventional method for the determination of the start of the growing season (SGS) based on daily average temperatures.
start_of_growing_season(temperatures)
start_of_growing_season(temperatures)
temperatures |
vector Daily average temperatures in degree Celsius. |
A temperature sum is constructed using [weighted_temperature_sum()], i.e. by summing the average daily temperature for each day, but applying a weight factor of 0.5 for January and 0.75 for February.
The SGS is defined as the first day where the so constructed temperature sum crosses 200 degree days.
[start_of_growing_season_mtd()], [weighted_temperature_sum()]
ts = rep(2, 365) start_of_growing_season(ts)
ts = rep(2, 365) start_of_growing_season(ts)
Find the start of the growing season based on daily average temperatures.
start_of_growing_season_mtd(temperatures, first_possible_DOY = 1)
start_of_growing_season_mtd(temperatures, first_possible_DOY = 1)
temperatures |
vector Daily average temperatures in degree Celsius. |
first_possible_DOY |
int Only consider days of the year from this value onward. |
This function implements the *multicriterial thermal definition* (MTD) as described in chapter 2.3.1.3 of the dissertation of Andreas Schaumberger: Räumliche Modelle zur Vegetations- und Ertragsdynamik im Wirtschaftsgrünland, 2011, ISBN-13: 978-3-902559-67-8
int DOY of the growing season start according to the MTD.
[start_of_growing_season()]
# Create fake temperatures ts = c(0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 6, 6, 6, 6, 3, 3, 3, 3, 3, 6, 6, 6, 6, 5, 6, 7, 8, 9, 10, 11, 12) start_of_growing_season_mtd(ts)
# Create fake temperatures ts = c(0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 6, 6, 6, 6, 3, 3, 3, 3, 3, 6, 6, 6, 6, 5, 6, 7, 8, 9, 10, 11, 12) start_of_growing_season_mtd(ts)
Data structure containing weather data for a given site for several years.
All fields representing weather variables are vectors of length 365 times N, where N is the number of years for which weather data is stored. In other words, every variable has one value for each of the 365 of each of the N years.
The weather input file should be organized as space separated columns
with a year
column and at least the following parameters as headers
(further columns are ignored):
DOY
day of year in given year
Ta
average temperature of given day (Celsius).
precip
precipitation in millimeter per day.
PAR
photosynthetically active radiation in MJ/m^2^. Can be calculated
from average sunlight irradiance SRad
in J/s/m^2^ as:
PAR = SRad * 0.47 * 24 * 60 * 60 / 1e6
ET0
evapotranspiration in mm.
These parameters are stored in this object in the respective PARAM_vec
fields.
The precipitation and temperature inputs are used in order to estimate the snow cover for each day by use of a snow model. The employed model is as formulated by Kokkonen et al. 2006 and makes use of parameters from Rango and Martinec, 1995.
weather_file
Name of provided weather data file.
years
numeric Integer representation of the contained years.
vec_size
Length of the PARAM_vec vectors, which is equal to number of contained years times 365.
year_vec
Vector of length vec_size, holding the year for the respective index.
W
A list generated by get_weather_for_year()
which contains
weather data only for a given year. The keys in the list are:
aCO2 (atmospheric CO2 concentration in ppm)
year
DOY
Ta
Ta_sm (smoothed daily average temperature)
PAR
PP
PET
liquidP
melt
snow
ndays (number of days in this year)
new()
Create a new WeatherData object.
WeatherData$new(weather_file = NULL, years = NULL)
weather_file
string Path to file containing the weather data to be read.
years
numeric Vector of years for which the weather is to be extracted.
read_weather()
Read weather data from supplied weather_file.
WeatherData$read_weather(weather_file, years = NULL)
weather_file
Path to or name of file containing weather data.
years
Years for which the weather is to be extracted. Default (NULL) is to read in all found years.
ensure_file_integrity()
Check if supplied input file is formatted correctly.
Check if required column names are present and fix NA entries.
WeatherData$ensure_file_integrity(weather)
weather
data.table of the read input file with header = TRUE
.
calculate_day_length()
Calculate the expected length of day based on a site's geographical latitude.
WeatherData$calculate_day_length(latitude)
latitude
numeric; geographical latitude in degrees.
get_weather_for_year()
Extract state variables to the weather data for given year and return them as a list.
WeatherData$get_weather_for_year(year)
year
integer Year for which to extract weather data.
W List containing the keys aCO2, year, DOY, Ta, Ta_sm, PAR, PP, PET, liquidP, melt, snow, ndays.
clone()
The objects of this class are cloneable with this method.
WeatherData$clone(deep = FALSE)
deep
Whether to make a deep clone.
Rango A, Martinec J (1995). “Revisiting the Degree-Day Method for Snowmelt Computations.” JAWRA Journal of the American Water Resources Association, 31(4), 657–669. ISSN 1752-1688, doi:10.1111/j.1752-1688.1995.tb03392.x.
Kokkonen T, Koivusalo H, Jakeman A, Norton J (2006). “Construction of a Degree-Day Snow Model in the Light of the Ten Iterative Steps in Model Development.” In iEMSs Third Biennial Meeting: "Summit on Environmental Modelling and Software". International Environmental Modelling and Software Society, Burlington, USA, July 2006.
WeatherData$read_weather()
A temperature sum is constructed by summing the average daily temperature for each day, but applying a weight factor of 0.5 for January and 0.75 for February.
weighted_temperature_sum(temperatures, negative = FALSE)
weighted_temperature_sum(temperatures, negative = FALSE)
temperatures |
vector Daily average temperatures in degree Celsius. |
negative |
boolean Whether to include negative temperature values in the summation. By default, negative values are set to 0, meaning that the temperature sum is monotonically increasing. |
Weighted temperature sum.
# Use fake temperatures ts = rep(2, 365) weighted_temperature_sum(ts)
# Use fake temperatures ts = rep(2, 365) weighted_temperature_sum(ts)
Willmott's index of model performance as described in Willmott (2012).
willmott(predicted, observed, ...)
willmott(predicted, observed, ...)
predicted |
Vector containing the predictions y. |
observed |
Vector containing the observations z. |
... |
Scaling factor c in the denominator in the Willmott index. The originally proposed value of 2 should be fine. |
This index takes on values from -1 to 1, where values closer to 1 are generally indicating better model performance. Values close to -1 can either mean that the model predictions differ strongly from the observation, or that the observations show small variance (or both).
willmott Value between -1 and 1
Willmott CJ, Robeson SM, Matsuura K (2012). “A Refined Index of Model Performance.” International Journal of Climatology, 32(13), 2088–2094. ISSN 1097-0088, doi:10.1002/joc.2419, https://rmets.onlinelibrary.wiley.com/doi/abs/10.1002/joc.2419.
predicted = c(21.5, 22.2, 19.1) observed = c(20, 20, 20) # The Willmott index "fails" in this case, as the variance in the # observation is 0. willmott(predicted, observed) # Try with more realistic observations observed = c(20.5, 19.5, 20.0) willmott(predicted, observed)
predicted = c(21.5, 22.2, 19.1) observed = c(20, 20, 20) # The Willmott index "fails" in this case, as the variance in the # observation is 0. willmott(predicted, observed) # Try with more realistic observations observed = c(20.5, 19.5, 20.0) willmott(predicted, observed)
The dataset contains the parameters a and b used to model the expected gross dry matter yield (in t / ha) as a function of altitude (in m.a.s.l.) as yield = a + b * altitude.
yield_parameters
yield_parameters
A data.frame with 4 rows and 3 variables:
Management intensity
Offset a in t / ha
Slope b in t / ha / m
Lookup Table of expected yield as functions of height and management intensity after table 1a in Olivier Huguenin et al.
Huguenin-Elie I, Mosimann E, Schlegel P, Lüscher A, Kessler W, Jeangros B (2017). “Grundlagen für die Düngung landwirtschaftlicher Kulturen in der Schweiz (GRUD), Kapitel 9: Düngung von Grasland.” Agrarforschung Schweiz. https://www.agrarforschungschweiz.ch/2017/06/9-duengung-von-grasland-grud-2017/.