---
title: "Stochastic Generation of Daily Temperature Anomalies using RGENERATE and RMAWGEN"
author: "Emanuele Cordano"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Stochastic Generation of Daily Temperature Anomalies using RGENERATE and RMAWGEN}
  %\VignetteEngine{knitr::rmarkdown}
  \VignetteEncoding{UTF-8}
---

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

## Rationale

The rationale of this vignette is the presentation of a stochastic generation of daily minimum and maximum temperature in two or more sites makes use of **RMAWGEN** and **RGENERATE** packages. The illustrated procedure refers to *trentino* dataset (**RMAWGEN** package), ad after loading the necessary packages and calling the  *trentino* dataset (**RMAWGEN** package), is organized as follows: 

- Selection of a generally 30-year long period within the dataset;
- Preparation of input data for the model setup, e.g. detection of temperature anomalies;
- Calibration of the stochastic generations, i.e. creation of a *GPCAvarest2* object instance for the model whose parameters like order of autocorrelation and number of GPCA iterations are inserted as function arguments;
- Usage of the model to generate a new time series of temperature anomalies. 

This tutorial aims at generating a time series of temperature anomalies stating from a time series of observations. The observations were cleaned from interpolations of the averages of each month of the year representing the actual climate conditions. The generated time series maintains the same statistical properties of the one of the observed anomalies. The anomalies can be added to different scenarios of climate conditions. 
<!-- This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>. -->

<!-- When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this: -->

## Necessary Package

```{r package,echo=TRUE}

rm(list=ls())

library(RMAWGEN)
library(RGENERATE)
library(magrittr)

```

## Dataset 

The dateset used is *trentino* dataset from **RMAWGEN** package, it contains new data frames TEMPERATURE_MAX and TEMPERATURE_MIN :
```{r dataset,echo=TRUE}
data(trentino)
str(TEMPERATURE_MAX)
str(TEMPERATURE_MIN)

```

## Reference Period 
```{r refperiod,echo=TRUE}
year_min <- 1978
year_max <- 2007
origin <- sprintf("%04d-1-1",year_min) 
origin_input <- origin
origin_output <- origin

####

station <- c("T0090","T0083")



```

## Settings


```{r settings,echo=TRUE}
sample <- "monthly"

###
n_GPCA_iteration <- 15 
n_GPCA_iteration_residuals <- 15
p <- 2

###
param <- setComprehensiveTemperatureGeneratorParameters(station=station,Tx_all=TEMPERATURE_MAX,Tn_all=TEMPERATURE_MIN,year_min=year_min,year_max=year_max,sample=sample)
std_tm=param[['stdTm']] ## Standard deviation for "mean" 
param$data_original

###


```

## Stochastic Model
```{r model,echo=TRUE}

exogen <- NULL ## GAUSSIANIZATION!!!


###
model <- getVARmodel(param$data_for_var,suffix=c("_T1","_T2"),sep="",p=p,exogen=exogen,n_GPCA_iteration_residuals=n_GPCA_iteration_residuals,n_GPCA_iteration=n_GPCA_iteration) 
###

```

## Generation of Anomalies

```{r generation,echo=TRUE}


gen1 <- generate(model,n=nrow(param$data_for_var),names=names(param$data_for_var)) 

gen1 <- gen1 %>% normalizeGaussian_severalstations(data=param$data_original,inverse=TRUE,type=3,sample=sample,origin_x=origin_output,origin_data=origin_input)
##res_multigen <- normalizeGaussian_severalstations(x=res_multigen0,data=original_data,inverse=TRUE,type=type,sample=sample,origin_x=origin_x,origin_data=origin_data,extremes=extremes)
###
```

## Observed and Generated Anomalies 

```{r plots,echo=TRUE}
###
for (i in 1:ncol(gen1)) {

  print(ks.test(param$data_original[,i],gen1[,i]))
}
##getVARmodel <-
##  function (data,suffix=c("_Tx","_Tn"),sep="",p=1,type="none",season=NULL,exogen=NULL,lag.max=NULL,ic="AIC",activateVARselect=FALSE,na.rm=TRUE,
##            n_GPCA_iteration=0,n_GPCA_iteration_residuals=n_GPCA_iteration,extremes=TRUE) { 

#####
#####










```

<!-- ## Including Plots -->

<!-- You can also embed plots, for example: -->

<!-- ```{r pressure, echo=FALSE} -->
<!-- plot(pressure) -->
<!-- ``` -->

<!-- Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. -->
