You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: vignettes/new_cost_function.Rmd
+87-24Lines changed: 87 additions & 24 deletions
Original file line number
Diff line number
Diff line change
@@ -19,22 +19,21 @@ library(dplyr)
19
19
library(ggplot2)
20
20
```
21
21
22
-
The `rsofun` package allows to calibrate parameters of the `pmodel` and `biomee` models via the `calib_sofun()` function. The implementation of the calibration is fairly flexible and can be adapted to a specific use-case via a cost function (used as metrics for the optimization routines in `calib_sofun()`). The package provides a set of standard cost functions named `cost_*`, which can be used for a variety of calibrations (different sets of model parameters, using various target variables, etc.). Alternatively, it's possible to write a more specific new cost function to be used together with `calib_sofun()`.
22
+
The `rsofun` package allows to calibrate parameters of the `pmodel` and `biomee` models via the `calib_sofun()` function. The implementation of the calibration is fairly flexible and can be adapted to a specific use-case via a tailor-made cost function (used as metrics for the optimization routines in `calib_sofun()`). The package provides a set of standard cost functions named `cost_*`, which can be used for a variety of calibrations (different sets of model parameters, using various target variables, etc.). Alternatively, it's possible to write a more specific new cost function to be used together with `calib_sofun()`.
23
23
24
-
In this vignette, we go over some examples on how to use the `rsofun` cost functions for parameter calibration and how to write your own custom one from scratch.
24
+
In this vignette, we go over some examples on how to use the `rsofun` cost functions for parameter calibration with `calib_sofun()`and how to write your own custom one from scratch.
25
25
26
26
### Calibration to GPP using RMSE and GenSA optimizer
27
27
28
28
A simple approach to parameter calibration is to find the parameter values that lead to the best prediction performance, in terms of the RMSE (root mean squared error). The function `cost_rmse_pmodel()` runs the P-model internally to calculate the RMSE between predicted target values (in this case GPP) and the corresponding observations.
29
29
30
-
The implementation of `cost_rmse_pmodel()` allows flexibility in various ways. We can simultaneously calibrate a subset of model parameters and also replicate the different calibration setups in Stocker et al., 2020 GMD. For example, following the `ORG` setup, only parameter `kphio` is calibrated. Furthermore, the standard cost functions allow to calibrate to several targets (fluxes and leaf traits predicted by the P-model) simultaneously and to parallelize the simulations. Since the P-model is run internally to make predictions, we must always specify which values the model parameters should take, i.e. the parameters that aren't calibrated (via argument `par_fixed`).
30
+
The implementations of `cost_rmse_pmodel()`and `calib_sofun()`allows flexibility in various ways. We can simultaneously calibrate a subset of model parameters and also replicate the different calibration setups in Stocker et al., 2020 GMD, simply by providing the appropriate inputs as `settings`, `par_fixed` and `targets`to `calib_sofun()`. Since the P-model is run internally to make predictions, we must always specify the values of the model parameters that aren't calibrated (via argument `par_fixed`). For example, following the `ORG` setup, only parameter `kphio` is calibrated with below code:
31
31
32
-
The syntax to run the calibration routine is as follows:
33
-
```{r eval = FALSE}
32
+
```{r run GenSA calibration, eval = TRUE}
34
33
# Define calibration settings and parameter ranges from previous work
35
34
settings_rmse <- list(
36
35
method = 'GenSA', # minimizes the RMSE
37
-
metric = cost_rmse_pmodel, # our cost function
36
+
metric = cost_rmse_pmodel, # our cost function returning the RMSE
38
37
control = list( # control parameters for optimizer GenSA
The output of `calib_sofun()` is a list containing the calibrated parameter values and the raw optimization output from the optimizer (here from `GenSA` or, as we see next, from `BayesianTools::runMCMC`).
69
+
The output of `calib_sofun()` is a list containing the calibrated parameter values (element `par`) and the raw optimization output from the optimizer (element `mod`; here from `GenSA` or, as we see next, from `BayesianTools::runMCMC`).
70
+
71
+
Note that the standard cost functions allow to calibrate to several targets (fluxes and leaf traits predicted by the P-model) simultaneously and to parallelize the simulations.
69
72
70
73
### Calibration to GPP using a simple likelihood function and BayesianTools
71
74
72
-
Let's calibrate the parameters involved in the temperature dependency of the quantum yield efficiency, `kphio`, `kphio_par_a` and `kphio_par_b`, taking a Bayesian calibration approach. We assume that the target variable (`'gpp'`) follows a normal distribution centered at the observations and with its standard deviation being a new calibratable parameter (`'err_gpp'`). We also assume a uniform prior distribution for all calibratable parameters.
73
-
By maximizing the normal log-likelihood, the MAP (maximum a posteriori) estimators for all 4 parameters are computed. With the function`cost_likelihood_pmodel()`, we can easily perform this calibration, as follows:
75
+
Let's calibrate the parameters involved in the temperature dependency of the quantum yield efficiency, `kphio`, `kphio_par_a` and `kphio_par_b`. Taking a Bayesian calibration approach, we need to define a likelihood as cost function (we'll use `cost_likelihood_pmodel()`). We assume that the target variable (`'gpp'`) follows a normal distribution centered at the observations and with its _unknown_standard deviation (`'err_gpp'`), that we need to add to the calibratable parameters. We also assume a uniform prior distribution for all calibratable parameters.
76
+
By maximizing the log-likelihood, the MAP (maximum a posteriori) estimators for all 4 parameters are computed. With the functions`cost_likelihood_pmodel()` and `calib_sofun()`, we can easily perform this type of calibration:
Furthermore, there are equivalent cost functions available for the BiomeE model. Check out the reference pages for more details on how to use `cost_likelihood_biomee()` and `cost_rmse_biomee()`.
115
120
116
121
### Calibration to GPP and Vcmax25 using the joint log-likelihood and BayesianTools
117
122
118
-
You may be interested in calibrating the model to different target variables simultaneously, like flux and leaf trait measurements. Here we present an example, where we use `cost_likelihood_pmodel()` to compute the joint normal likelihood of all the targets specified (that is, by summing the log-likelihoods of GPP and Vcmax25) and ultimately calibrate the `kc_jmax` parameter. It would be possible to follow this workflow for several-target calibration also with RMSE as the optimization metric, using `cost_rmse_pmodel()` and `GenSA` optimization.
123
+
You may be interested in calibrating the model to different target variables simultaneously, like flux and leaf trait measurements. Here we present an example, where we use `cost_likelihood_pmodel()` to compute the joint likelihood of all the targets specified (that is, by summing the log-likelihoods of GPP and Vcmax25) and ultimately calibrate the `kc_jmax` parameter. It would be possible to follow this workflow for several-target calibration also with RMSE as the optimization metric, using `cost_rmse_pmodel()` and `GenSA` optimization.
Note that GPP predictions are directly compared to GPP observations on that day, but Vcmax25 predicted by the P-model (being a leaf trait) is averaged over the growing season and compared to a single Vcmax25 observation taken per site. The cost functions provided in the package tell apart fluxes and leaf traits by the presence of a `"date"` column in the nested validation data frames `p_model_validation` and `p_model_validation_vcmax25`.
164
+
Note that GPP predictions are directly compared to GPP observations on that day, but Vcmax25 predicted by the P-model (being a leaf trait) is averaged over the growing season and compared to a single Vcmax25 observation taken per site.
165
+
166
+
The cost functions provided in the package tell apart fluxes and leaf traits by the presence of a `"date"` column in the nested validation data frames `p_model_validation` and `p_model_validation_vcmax25`.
159
167
160
168
### Write your custom cost function
161
169
162
-
If the RMSE or normal log-likelihood (for one or several targets) cost functions that we provide do not fit your use case, you can easily write a custom one. In this section, we drive you through the main ideas with an example.
170
+
If the RMSE or log-likelihood (for one or several targets) cost functions that we provide do not fit your use case, you can easily write a custom one. In this section, we drive you through the main ideas with an example.
171
+
To run the calibration, you can still use `calib_sofun()` in combination with
172
+
your custom cost function.
173
+
174
+
The routine `calib_sofun()` requires `drivers`, `obs`
175
+
and `settings` as mandatory arguments. These provide data.frames with driver and
176
+
observational data, as well as settings for the calibration.
177
+
The optional argument `optim_out` defines if the raw optimization output should
178
+
be returned.
179
+
All other (optional) arguments to `calib_sofun()` are passed through to the cost
180
+
function (e.g. `par_fixed` in above example).
181
+
They can be used freely inside of your custom cost function, e.g. to control
182
+
the simulation setup or the processing. On top of these optional arguments, it
183
+
is also possible to extend the `drivers` and `obs` data.frames with additional
184
+
columns that can be used freely for fine-grained control within your custom cost
185
+
function.
163
186
164
187
All cost functions must take at least three arguments:
165
188
@@ -175,16 +198,50 @@ Below we'll walk you through the definition of a custom cost function.
175
198
In this example, we'll calibrate the soil moisture stress parameters and use the
176
199
mean absolute error (MAE) as custom cost function.
177
200
178
-
Since we are calibrating the parameters based on model outputs, the cost function runs the P-model and compare its output to observed validation data.
179
-
```{r, eval = FALSE}
180
-
function(par, obs, drivers){
201
+
Since we are calibrating the parameters based on model outputs, the cost
202
+
function will eventually need to run the P-model and compare its output to
203
+
observed validation data.
204
+
205
+
To get started we suggest to write a dummy cost function and use it together
206
+
with `calib_sofun()` as shown below. Note that one way of developing the cost
207
+
function would be to use a `browser()` statement during the development. It
208
+
allows you to explore the variables that you have access to from within the cost
# Calibrate the model and optimize the free parameters
231
+
pars_calib_mae <- calib_sofun(
232
+
drivers = p_model_drivers,
233
+
obs = p_model_validation,
234
+
settings = settings_mae,
235
+
# optional arguments if needed in the cost function
236
+
my_own_message = "Hi from inside the cost_mae function."
237
+
)
238
+
239
+
pars_calib_mae
183
240
```
184
241
185
-
In the optimization procedure, the cost function only takes as argument the parameters `par` that are fed to `calib_sofun()` via `settings$par` (see previous sections). Nevertheless, within the cost function we call `runread_pmodel_f()`and this function needs a full set of model parameters. Therefore, the parameters that aren't being calibrated must be hard coded inside the cost function (or passed as an argument like the `rsofun` cost functions). In this example, we only want to calibrate the soil moisture stress parameters.
242
+
During the optimization procedure, the cost function receives as argument a suggestion of the parameters `par`. This might be just a subset of all needed parameters (defined via `settings$par`). Thus to call `runread_pmodel_f()`within the cost function, a full set of model parameters is needed. Here, we'll hardcode the parameters that aren't being calibrated inside the cost function. (Note, that in above examples they were passed as an additional argument `par_fixed`).
print(my_own_message) # useless, but showcases how to use additional arguments
269
+
browser() # can facilitate the development, remove afterwards
211
270
}
212
271
```
213
272
214
-
The following chunk defines the final function. We clean the observations and model output and align the data according to site and date, to compute the mean absolute error (MAE) on GPP. Finally, the function should return a scalar value, in this case the MAE, which we want to minimize. Keep in mind that the GenSA optimization will minimize the cost, but with the BayesianTools method the cost is always maximized.
215
-
```{r}
273
+
The following chunk defines the final function. We clean the observations and model output and align the data according to site and date, to compute the mean absolute error (MAE) on GPP. Finally, the function should return a scalar value, in this case the MAE, which we want to minimize. Keep in mind that the GenSA optimization will minimize the cost, but with the BayesianTools method the cost (i.e. the likelihood) is always maximized.
274
+
```{r define custom cost function, eval = TRUE}
216
275
cost_mae <- function(par, obs, drivers){
217
276
218
277
# Set values for the list of calibrated and non-calibrated model parameters
0 commit comments