---
title: "How to produce precipitation-weighted annual average isoscapes in IsoriX?"
author: "The IsoriX core team"
date: "`r Sys.Date()`"
output:
    pdf_document
vignette: >
  %\VignetteIndexEntry{2_Weighting_using_precipitation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, initialization, echo=FALSE}
library(knitr)
set.seed(123)  ## set seed for entire manuscript
# set global options for knitr (if changed, all cashed chunked will be rerun!)
knitr::opts_chunk$set(cache = TRUE, cache.path = "./cache_knitr/", fig.path = "./fig_knitr/", global.par = TRUE, width = "\\linewidth", fig.align = "center", dev = "CairoPNG", dpi = 500) # use dpi=100 for small pdfs
```

Welcome to __IsoriX__, in this vignette we present the steps required for you to build an annual average isoscape weighted by the amount of monthly precipitation.

## Before starting

Please read the vignette ___Workflow___, if you haven't done so. You can access it by simply typing:

```{r workflow, eval=FALSE}
vignette("Workflow", package = "IsoriX")
```

Note that the current vignette, like the one introducing the workflow, takes some time to run. It has thus not been compiled by CRAN but by us. Again, due to constraints on how big this document could be, we had to reduce a lot the resolution of the figures.

Before starting, don't forget to load our package:

```{r load package, cache = FALSE}
library(IsoriX)
```

## Step 1 - Select the isoscape data

Start by selecting the precipitation data needed for you to build an isoscape. In this example, we will consider all the data available in `GNIPDataDE`. The difference with what we did in the vignette ___Workflow___ is that here the function `prepdata` is called with the argument `split.by = "month"`, which lead to data aggregated across years (as before), but not across months.

```{r GNIP}
GNIPDataDE12 <- prepdata(data = GNIPDataDE, split.by = "month")
```

The dataset we created contains up to twelve different rows per location (i.e. one per month if records are available for all twelve months) instead of the single one:

```{r GNIP2}
knitr::kable(head(GNIPDataDE12, 15L))
```


## Step 2 - Fit the geostatistical models

We will now fit not one pair of models as during the ___Workflow___ but twelve pairs of models. We indeed want to fit one mean model and one residual dispersion model for each of the twelve months of a year. Each of the twelve pairs of models are technically fitted independently, but to save you the manual labor of calling twelve times the function `isofit`, we have created the function `isomultifit` that does that for you. This latter function also combines all fitted models in one object of class `multiisofit` which other functions will recognize. As `isofit`, `isomultifit` can fit several model structures, but we will restrict the demonstration to a single example.

```{r isofits}
GermanyFit12 <- isomultifit(iso.data = GNIPDataDE12, split.by = "month")
```

We check that all models are there:
```{r models}
names(GermanyFit12$multi.fits)
```

You could then look at the output of a given model (here, January) by simply typing ```GermanyFit12$multi.fits$month_1```.


## Step 3 - Prepare the elevation raster

As for the ___Workflow___, we prepare the elevation raster from the tif file we downloaded (see  ___Workflow___ for details):

```{r elev, message = FALSE, cache = FALSE}
library(raster)
elevationraster <- raster("../vignette_workflow/gmted2010_30mn.tif")
elev <- relevate(elevation.raster = elevationraster, isofit = GermanyFit12)
```


## Step 4 - Prepare the precipitation rasters

We now need the rasters containing the average precipitation amount for each month of the year and each location from the elevation raster. We start by downloading such file (mind that the file is ca. 1Gb and takes a while to download):

```{r precip download}
getprecip()
```

Note that if the zip file is already in the working directory (as it is the case here), it won't be downloaded again.

We then resize the RasterBrick obtained to the size of the elevation raster:

```{r prep precipitation}
precipitations <- prepcipitate(elevation.raster = elev)
```


## Step 5 - Build the isoscape

To build the precipitation-weighted annual average isoscapes stemming from `GermanyFit12` we need to use the function `isomultiscape`. This function is a wrapper to `isoscape` handling several models at once. This is also the function to which we need to provide the prepared precipitation data:

```{r isomulti}
isoscapes <- isomultiscape(elevation.raster = elev,
                           isofit = GermanyFit12,
                           weighting = precipitations)
```

\newpage

## Step 6 - Plotting the isoscapes

We can finally plot the precipitation-weighted annual average isoscape as we did in the ___Workflow___:

```{r plot mean, out.width = "0.8\\linewidth"}
plot(x = isoscapes)
```

As for any isoscape fitted with __IsoriX__ we can also plot the isoscape for the prediction variance, the one for the residual variance, and the one for the response variance:

```{r plot predVar, fig.show = "hold", out.width = "0.4\\linewidth"}
plot(x = isoscapes, which = "mean.predVar")
plot(x = isoscapes, which = "mean.residVar")
plot(x = isoscapes, which = "mean.respVar")
```


## Does the isoscapes differ from the one not accounting for precitation?

Above two differences were introduced compared to the simple approach we followed during the ___Workflow___. First, models were fitted by month; second, they were weighted by precipitation amounts before the aggregation. We can simply study the influence of such additional steps by comparing the isoscapes produced by different workflows.

We will here compare the isoscape for point predictions produced between the two different workflow. To do so, we need to produce a simple isoscape for Germany using the simple workflow introduced in the vignette ___Workflow___:

```{r isoscape 2}
GNIPDataDEagg <- prepdata(data = GNIPDataDE)
GermanyFit    <- isofit(iso.data = GNIPDataDEagg)
isoscape      <- isoscape(elevation.raster = elev, isofit = GermanyFit)
```

We now compute the difference between the isoscapes produced by the two different workflows (mind that the two isoscapes must have same resolution and extent to do that directly, which is the case here):

```{r diff isoscapes}
isoscape.diff <- isoscape  ## We create a new object of class isoscape
isoscape.diff$isoscape <- isoscape$isoscape - isoscapes$isoscape  ## We replace the isoscape by 
                                                                  ## the difference in isoscapes
```

You could plot the point predictions as before, but we choose to add one small step to adjust the title:

```{r plot mean diff}
plotdiff <- plot(x = isoscape.diff,
                 palette = list(step = 1.25, range = c(-11, 4), n.labels = Inf),
                 plot = FALSE)
plotdiff$main <- "Difference in" ~ delta * D[p] ~ "(simple - weighted by monthly precipitation amounts)"
plotdiff
```

\newpage

## The End

That is all for now! Here are the information of the R session we used:

```{r R session}
sessionInfo()
```

