---
title: "Basic water balance"
author: "Miquel De Caceres"
date: "`r Sys.Date()`"
output: 
  rmarkdown::html_vignette:
    toc: TRUE
vignette: >
  %\VignetteIndexEntry{Basic water balance}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignettePackage{medfate}
  \usepackage[utf8]{inputenc}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(medfate)
```

## About this vignette

The present document describes how to run the soil plant water balance model described in De Cáceres et al. (2015) using package `medfate`. The  document illustrates how to prepare the inputs, use the simulation functions and inspect the outputs. All the details of the model design and formulation can be found at https://emf-creaf.github.io/medfatebook/index.html. Because it introduces many basic features of simulations with package `medfate`, this document should be read before addressing advanced topics of water balance simulations or growth simulations. 

## Preparing model inputs

Model inputs are explained in greater detail in vignette '*Simulation inputs*'. Here we only review the different steps required to run function `spwb()`.

### Soil, vegetation, meteorology and species data

Soil information needs to be entered as a `data frame` with soil layers in rows and physical attributes in columns. Soil physical attributes can be initialized to default values, for a given number of layers, using function `defaultSoilParams()`:

```{r}
spar = defaultSoilParams(2)
```

The soil input for water balance simulation is actually a list of class `soil` that is created using a function with the same name:
```{r}
examplesoil = soil(spar)
```

As explained in the package overview, models included in `medfate` were primarily designed to be ran on **forest inventory plots**. Here we use the example object provided with the package:
```{r}
data(exampleforestMED)
exampleforestMED
```

In the basic water balance, only mean temperature, precipitation and potential evapotranspiration is required, but radiation may also be necessary to simulate snow melt. 
```{r}
data(examplemeteo)
head(examplemeteo)
```

Finally, simulations in `medfate` require a data frame with species parameter values, which we load using defaults for Catalonia (NE Spain):

```{r}
data("SpParamsMED")
```

### Simulation control

Apart from data inputs, the behaviour of simulation models can be controlled using a set of global parameters. The default parameterization is obtained using function `defaultControl()`:

```{r}
control = defaultControl("Granier")
```
Some parameters deserve explanation here: 

 1. Console output can be turned off by setting `verbose = FALSE`. 
 2. The soil water retention curves can be switched between Saxton's and Van Genuchten's using parameter `soilFunctions`. 
 3. The complexity of the soil water balance calculations will be very different if we set `transpirationMode = "Sperry"`. Most of the other options apply in the case of advanced soil water balance only. 
 
### Water balance input object

A last object is needed before calling simulation functions, called `spwbInput`. It consists in the compilation of aboveground and belowground parameters and the specification of additional parameter values for each plant cohort. This is done by calling function `spwbInput()`, but if one has a `forest` object, the object can be generated more directly using function `forest2spwbInput()`:

```{r}
x = forest2spwbInput(exampleforestMED, examplesoil, SpParamsMED, control)
```

Different parameter variables will be drawn depending on the value of `transpirationMode`. For the simple water balance model (`transpirationMode = "Granier"`), relatively few parameters are needed. All the input information for forest data and species parameter values can be inspected by accessing the different elements of this object, whose names are.
```{r}
names(x)
```
Note that (since **ver 2.0**) the water balance input object contains an element `soil` with the soil input. 

It is important to remember that, unlike normal objects in R, any water balance simulation will modify the `spwbInput` object. For example, the state of the soil at the end of the simulated process (i.e. `W`) will be stored. Hence, one can use the same object to simulate water balance sequentially and the final state of one simulation is the initial state of the next. In the case of soil water balance, these modifications are small, for example concerning `LAI_expanded`, but in the case of growth simulations the object is used to store the status of vegetation during and at the end of simulations. 

Finally, note that users can set cohort-specific parameters for soil water balance (instead of using species-level values) by modifying manually the parameter values in this object. Since some parameters may be coordinated by design, however, it is better to use specific package functions for this purpose.

## Executing the soil water balance model

### Water balance for a single day

Soil water balance simulations will normally span periods of several months or years, but since the model operates at a daily temporal scale, it is possible to perform soil water balance for one day only. This is done using function `spwb_day()`. In the following code we select day 100 from the meteorological input data and perform soil water balance for that day only:
```{r}
d = 100
sd1<-spwb_day(x, rownames(examplemeteo)[d],  
             examplemeteo$MinTemperature[d], examplemeteo$MaxTemperature[d], 
             examplemeteo$MinRelativeHumidity[d], examplemeteo$MaxRelativeHumidity[d], 
             examplemeteo$Radiation[d], examplemeteo$WindSpeed[d], 
             latitude = 41.82592, elevation = 100, 
             slope= 0, aspect = 0, prec = examplemeteo$Precipitation[d])
```
Function `spwb_day()` is most useful when working with the complex transpiration model. This is why so many meteorological variables are required. The output of `spwb_day()` is a list with five elements:
```{r}
names(sd1)
```

* **cohorts**: Table with the species code and species name of each cohort.
* **WaterBalance**: Contains the soil water balance flows (precipitation, infiltration, transpiration, ...)
* **Soil**: Contains output values by soil layer (i.e. water evaporated from each soil layer, water transpired from each soil layer and the final soil water potential).
* **Stand**: A list with stand LAI (expanded and dead leaves), canopy water retention capacity and the proportion of light (SWR or PAR) reaching the ground.
* **Plants**: Contains output values by plant cohort (i.e. LAI values, transpiration, water potential, drought stress index, ...).

```{r}
sd1
```

### Water balance for multiple days

Most often, users will use function `spwb()` to run the soil water balance model. This function requires the `spwbInput` object and the meteorological data frame. However, function `spwb_day()` modified the state variables of the input objects. In particular, the values of soil moisture are now:
```{r}
x$soil$W
```
We simply reset state variables to their default values so that new simulations are not affected by the end state of the previous simulation:
```{r}
resetInputs(x)
x$soil$W
```
Now we are ready to call function `spwb()`:
```{r}
S = spwb(x, examplemeteo, latitude = 41.82592, elevation = 100)
```
Function `spwb()` returns an object of class with the same name, actually a list:
```{r}
class(S)
```
If we inspect its elements, we realize that the output is arranged differently than in `spwb_day()`:
```{r}
names(S)
```
In particular, element `spwbInput` contains a copy of the input parameters that were used to run the model:
```{r}
names(S$spwbInput)
```
As before, `WaterBalance` contains water balance components, but in this case in form of a data frame with days in rows:
```{r}
head(S$WaterBalance)
```
Element `Plants` is in turn a list with several dataframes with plant output variables, for example plant water potentials are in:
```{r}
head(S$Plants$PlantPsi)
```


## Inspecting model outputs
### Plots

Package `medfate` provides a simple `plot` function for objects of class `spwb`. It can be used to show meteorological inputs, snow dynamics, and different components of the water balance:
```{r, fig=TRUE, fig.align="center", fig.width=5, fig.height = 3.5}
plot(S, type = "PET_Precipitation")
plot(S, type = "Snow")
plot(S, type = "Export")
```

```{r, fig=TRUE, fig.align="center", fig.width=7, fig.height = 3.5}
plot(S, type = "Evapotranspiration")
```

Function `plot` is also allows displaying soil moisture dynamics by layer, which can be done in four different ways (the first two only imply a change in axis units):
```{r, fig=TRUE, fig.align="center", fig.width=7, fig.height = 4}
plot(S, type="SoilTheta")
plot(S, type="SoilRWC")
plot(S, type="SoilPsi")
plot(S, type="SoilVol")
```

Finally, the same function can also be used to draw the dynamics of plant variables by cohorts, such as transpiration, gross photosynthesis, water potential or drought stress:

```{r, fig=TRUE, fig.align="center", fig.width=7, fig.height = 4}
plot(S, type="Transpiration")
plot(S, type="GrossPhotosynthesis")
plot(S, type="PlantPsi")
plot(S, type="PlantStress")
```

### General summaries
While the simulation model uses daily steps, users will normally be interested in outputs at larger time scales. The package provides a `summary` for objects of class `spwb`. This function can be used to summarize the model's output at different temporal steps (i.e. weekly, annual, ...). For example, to obtain the average soil moisture and water potentials by months one can use:

```{r}
summary(S, freq="months",FUN=mean, output="Soil")
```

Parameter `output` is used to indicate the element of the `spwb` object for which we desire summaries. Similarly, it is possible to calculate the average stress of plant cohorts by months:
```{r}
summary(S, freq="months",FUN=mean, output="PlantStress")
```
The `summary` function can be also used to aggregate the output by species. In this case, the values of plant cohorts belonging to the same species will be averaged using LAI values as weights. For example, we may average the daily drought stress across cohorts of the same species (here there is only one cohort by species, so this does not modify the output):
```{r}
head(summary(S, freq="day", output="PlantStress", bySpecies = TRUE))
```
Or we can combine the aggregation by species with a temporal aggregation (here monthly averages):
```{r}
summary(S, freq="month", FUN = mean, output="PlantStress", bySpecies = TRUE)
```

### Specific output functions
The package provides some functions to extract or transform specific outputs from soil plant water balance simulations. In particular, function `spwb_stress()` allows calculating several plant stress indices, such as the number of days with drought stress > 0.5 or the maximum drought stress:

```{r}
spwb_stress(S, index = "NDD", freq = "years", draw=FALSE)
spwb_stress(S, index = "MDS", freq = "years", draw=FALSE)
```
As the general summary function, `spwb_stress()` allows calculating stress indices at several temporal scales. For example the water stress index (integral of water potential values) can be calculated and drawn for every month:
```{r, fig=TRUE, fig.align="center", fig.width=7, fig.height = 4}
spwb_stress(S, index = "WSI", freq = "months", draw=TRUE)
```

Another specific summary function is `spwb_waterUseEfficiency()`. This is most useful with advanced water and energy balance modeling, but for simple water balance it calculates the ratio between photosynthesis and transpiration at the desired scale. In this case it is equal to the value of the input species parameter `WUE`:

```{r}
spwb_waterUseEfficiency(S, type = "Stand Ag/E", freq = "months", draw=FALSE)
```