---
title: "Surface Energy Balance using **METRIC** model and **water** package: 2.  *advanced procedure*"
author: "Guillermo Federico Olmedo and Daniel de la Fuente-Saiz"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{METRIC advanced}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

This vignette presents the procedure to estimate the Land Surface Energy Balance (LSEB) using Landsat imagery and the
**water** package. There are two versions of this vignette: a simple and an advanced one. In the first one the procedure is simpler and most of the parameters are selected automatically by the package. In the second approach the procedure is longer, because the user has more control over all input parameters and coefficients. Both vignettes follow the METRIC model methodology (Allen et al., 2007) to estimate the LSEB from Landsat images. The examples use Landsat 7 data; for Landsat 8 and 9 see the vignette "Landsat 8 and 9".

Also, in the simple procedure we assume flat terrain, while in the advanced procedure we use a digital elevation model (DEM). However, it is possible to use a DEM in the simple procedure by setting the argument `plain` to `FALSE` and providing a `DEM`.


## Introduction

One of the most cited models to estimate land surface evapotranspiration from satellite-based energy balance is the *Mapping EvapoTranspiration at high Resolution with Internalized Calibration* (**METRIC**). This model was developed by Allen et al. (2007) based on the well-known SEBAL model (Bastiaanssen et al., 1998). It has been widely applied in many countries around the world to estimate crop evapotranspiration (ET) at field scale and over large areas using satellite images. The model has been applied to different vegetation and crop types, such as wheat, corn, soybean and alfalfa, with good results (3-20% error), and in recent years also over sparse woody canopies such as vineyards and olive orchards, in both flat and mountainous terrain. Thus, ET is estimated as a residual of the surface energy equation:
\begin{equation}
\label{eq:EB}
LE = R_n - G - H
\end{equation}
where $LE$ is the latent energy consumed by ET; $R_n$ is the net radiation; $G$ is the soil heat flux (sensible heat conducted into the ground); and $H$ is the sensible heat flux convected to the air (all in $W \cdot m^{-2}$).

We estimate $R_n$, $G$ and $H$ for each pixel of a *Landsat scene*, supported by one weather station. Then we estimate $LE$ with the previous equation and, after that, the instantaneous evapotranspiration as:

\begin{equation}
ET_{inst} = 3600 \cdot \frac{LE}{\lambda \rho_w}
\end{equation}

where $ET_{inst}$ is the instantaneous ET at the satellite overpass ($mm \cdot h^{-1}$); 3600 is the conversion factor from seconds to hours; $\rho_w$ is the density of water = 1000 $kg\cdot m^{-3}$; and $\lambda$ is the latent heat of vaporization of water ($J\cdot kg^{-1}$).

Finally, the daily ET is computed pixel by pixel (30 x 30 m) as:
\begin{equation}
ET_{24} = \frac{ET_{inst}}{ET_r} ET_{r\_24}
\label{eq:et24}
\end{equation}

where $ET_r$ is the hourly reference ET at the time of the satellite overpass and $ET_{r\_24}$ is the daily reference ET.

To begin this procedure, first we load the **water** package:

```{r, message=FALSE}
library(water)

```

## Base data preparation

To estimate crop evapotranspiration with METRIC, the **water** package and the advanced procedure, we use four inputs:

- A raw (Level-1) Landsat 7, 8 or 9 image (original .TIF files from USGS EarthExplorer or GloVis).
- Weather station data (a .csv file).
- A digital elevation model (DEM) of the area.

With a full scene, crop an area of interest when loading the image, `loadImage(path, aoi = createAoi(...))` (see `?createAoi`); the example image used here is already cropped.

First, we load the weather station data with `read.WSdata()`, which converts our .csv file into a `waterWeatherStation` object. If we provide a Landsat metadata (MTL) file, it also computes the weather conditions at the time of the satellite overpass. Always set `tz`, the time zone of the weather station clock, because the overpass time in the MTL file is UTC.

```{r}
csvfile <- system.file("extdata", "apples.csv", package="water")
MTLfile <- system.file("extdata", "L7.MTL.txt", package="water")
# the wind speed in apples.csv is in km/h: cf converts it to m/s
WeatherStation <- read.WSdata(WSdata = csvfile, date.format = "%d/%m/%Y",
                              lat=-35.42222, long= -71.38639, elev=201, height= 2.2,
                              columns=c("date" = 1, "time" = 2, "radiation" = 3,
                              "wind" = 4, "RH" = 6, "temp" = 7, "rain" = 8),
                              cf = c(1, 0.2777778, 1), MTL = MTLfile,
                              tz = "America/Santiago")
```

We can visualize our weather station data with:
```{r, fig.width = 5}
print(WeatherStation)

plot(WeatherStation, hourly=TRUE)
```


After that, we load the Landsat image. Usually we use `loadImage()` to load a
Landsat image from the `.TIF` files downloaded from
USGS EarthExplorer. In this vignette we use the
Landsat 7 example data included in **water**, stored as a packed terra object, so we unpack it with `rast()`:
```{r, fig.width = 5}
image.DN <- rast(L7_Talca)
```

Finally, we need a digital elevation model (DEM) of the image area. `getDEM()` downloads the Copernicus DEM GLO-30 (30 m) tiles that cover the image and returns the DEM on the image grid. It needs an internet connection, so it is not run here:

```{r, eval = FALSE}
DEM <- getDEM(image.DN)
```

If you already have SRTM tiles, `checkSRTMgrids(image.DN)` lists the files needed and `prepareSRTMdata(extent = image.DN)` mosaics them on the image grid. In this vignette we use the example DEM provided with **water**:

```{r}
DEM <- rast(DEM_Talca)
```

## Net Radiation (R_n) estimation

To calculate the net radiation from the Landsat data, first we calculate a surface model (*slope and aspect*) from the DEM, then the solar angles (*latitude, declination, hour angle and solar incidence angles*), which we plot. Then we use them to calculate the *incoming solar radiation*.

```{r, fig.width = 5}
surface.model <-METRICtopo(DEM)

solar.angles.r <- solarAngles(surface.model = surface.model, 
                              WeatherStation = WeatherStation, MTL = MTLfile)

plot(solar.angles.r)

Rs.inc <- incSWradiation(surface.model = surface.model, 
                         solar.angles = solar.angles.r, 
                         WeatherStation = WeatherStation)
```

Then we calculate the top-of-atmosphere (TOA) reflectance and the surface reflectance of the Landsat image, and use the latter to calculate the *broadband albedo*:

```{r, fig.width=5, warning=FALSE}
image.TOAr <- calcTOAr(image.DN = image.DN, sat="L7", MTL = MTLfile, 
                       incidence.rel = solar.angles.r$incidence.rel)

image.SR <- calcSR(image.TOAr=image.TOAr, sat = "L7", 
                   surface.model=surface.model, 
                   incidence.hor = solar.angles.r$incidence.hor, 
                   WeatherStation=WeatherStation)

albedo <- albedo(image.SR = image.SR,  coeff="Tasumi", sat="L7")
```

Next, we calculate the *leaf area index* (LAI) from the satellite data and plot it. Several methods from the literature are available (see `?LAI`). In this vignette we use the *METRIC 2010* method:

```{r, fig.width = 5}
LAI <- LAI(method = "metric2010", image = image.TOAr, L=0.1)

plot(LAI)
```

Then we estimate the land surface temperature (Ts), using the LAI to estimate the *surface emissivity*, and the *brightness temperature* from the Landsat thermal band (TIR). With this information we compute the *incoming and outgoing long-wave radiation*:

```{r, warning=FALSE, fig.width = 5}
Ts <- surfaceTemperature(image.DN=image.DN, LAI=LAI, sat = "L7", 
                         WeatherStation = WeatherStation)

Rl.out <- outLWradiation(LAI = LAI, Ts=Ts)

Rl.inc <- incLWradiation(WeatherStation,DEM = surface.model$DEM, 
                         solar.angles = solar.angles.r, Ts= Ts)
```

Finally, we estimate the net radiation (R_n) pixel by pixel:

```{r, fig.width = 5}
Rn <- netRadiation(LAI, albedo, Rs.inc, Rl.inc, Rl.out)

plot(Rn)
```


## Soil Heat Flux (G) estimation

We estimate the soil heat flux using as inputs the *net radiation*, *surface reflectance*, *surface temperature*, *leaf area index* and *albedo*. In this vignette we use the default method (Tasumi, 2003), as in the original METRIC (2007):

```{r Soil Heat Flux, fig.width=5}
G <- soilHeatFlux(image = image.SR, Ts=Ts,albedo=albedo, 
                  Rn=Rn, LAI=LAI)

plot(G)
```

## Sensible Heat Flux (H) estimation
To estimate the sensible heat flux from the Landsat data, first we need to calculate the *momentum roughness length* (Zom). Several methods from the literature are available (see `?momentumRoughnessLength`). In this vignette we use the *short.crops* method.

Then, we use `calcAnchors()` to automatically search for end members (anchor pixels) within the scene (extreme wet and dry conditions). The default method of `METRIC.EB()` is "percentile" (anchors from percentiles of NDVI, albedo and Ts); in this vignette we use the *best* method (formerly called *CITRA-MCB*), which searches the scene with the parameters `n` and `deltaTemp` (see `?calcAnchors`).

Finally, we estimate H for each pixel with `calcH()`. This function applies the *CIMEC* self-calibration (calibration using inverse modelling at extreme conditions), iterating over the "hot" and "cold" pixels to absorb biases in the computation of H. With `plots = TRUE` the iterations are shown in a plot while `calcH()` runs. The argument `verbose` controls how much information about the anchor pixels and the iterations is printed.
```{r Ts, fig.width=5}
Z.om <- momentumRoughnessLength(LAI=LAI, mountainous = TRUE, 
                                method = "short.crops", 
                                surface.model = surface.model)

hot.and.cold <- calcAnchors(image = image.TOAr, Ts = Ts, LAI = LAI, plots = FALSE,
                            albedo = albedo, Z.om = Z.om, n = 5, 
                            anchors.method = "best", deltaTemp = 5,
                            WeatherStation = WeatherStation, verbose = FALSE)

H <- calcH(anchors = hot.and.cold, Ts = Ts, Z.om = Z.om, 
           WeatherStation = WeatherStation, ETp.coef = 1.05,
           Z.om.ws = 0.03, DEM = DEM, Rn = Rn, G = G, verbose = FALSE)
```

`calcH()` warns that the wind speed at the station at the overpass is very low (0.31 m/s), so the wind extrapolated to 200 m is below 2 m/s. In METRIC 2 m/s is used as the minimum (`calcH.control = calcH.control(u200.min = 2)`), because very low wind makes H, and the calibration, unreliable. Check the units of the wind speed (`cf` in `read.WSdata()`) and the sensor when you see this warning.

## Daily Crop Evapotranspiration (ET_24) estimation

To estimate the daily crop evapotranspiration from the *Landsat scene* we need the daily reference ET (ETr, ASCE-EWRI 2005) at the weather station, which we calculate with:

```{r}
ET_WS <- dailyET(WeatherStation = WeatherStation, MTL = MTLfile)
```

And finally, we can estimate daily crop ET pixel by pixel. With the result of `METRIC.EB()` this is just `ET24h(Energy.Balance)`; here we pass the layers we computed:

```{r, fig.width = 5}
ET.24 <- ET24h(Rn, G, H$H, Ts, WeatherStation = WeatherStation, ETr.daily=ET_WS)
plot(ET.24$ET24)
```


## References

Allen, R. G., Tasumi, M., & Trezza, R. (2007). Satellite-based energy balance for mapping evapotranspiration with internalized calibration (METRIC)-Model. Journal of Irrigation and Drainage Engineering, 133(4), 380-394. https://doi.org/10.1061/(ASCE)0733-9437(2007)133:4(380)

Bastiaanssen, W. G. M., Menenti, M., Feddes, R. A., & Holtslag, A. A. M. (1998). A remote sensing surface energy balance algorithm for land (SEBAL). 1. Formulation. Journal of Hydrology, 212-213, 198–212. https://doi.org/10.1016/S0022-1694(98)00253-4