---
title: "Preparation of input data: creation of a stars object"
author: "Alban de Lavenne"
date: "`r Sys.Date()`"
bibliography: "../inst/REFERENCES.bib"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Preparation of input data: creation of a stars object}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
fig_width: 8 
fig_height: 4 
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

All time series in the transfR package must be georeferenced. To use discharge observations in transfR, two inputs are therefore required: the discharge time series and a georeferenced vector layer describing the locations of the gauged catchments. These two inputs are merged into one R object of class [stars](https://cran.r-project.org/package=stars). This vignette provides guidance on creating this object from common input formats.

For the sake of the example, we will create a shapefile and a text file from the 'Oudon' example dataset provided with the transfR package:
```{r, echo=TRUE, message=FALSE, results='hide', eval=TRUE}
library(transfR)
data(Oudon)

wd <- tempdir(check = TRUE)
st_write(st_sf(ID = paste0("ID", 1:6), geom = st_geometry(Oudon$obs)), 
         dsn = file.path(wd, "catchments.shp"), delete_layer = TRUE)
write.table(data.frame(DateTime = format(st_get_dimension_values(Oudon$obs,1),
                                         "%Y-%m-%d %H:%M:%S"), 
                       ID1 = Oudon$obs$Qobs[,1],
                       ID2 = Oudon$obs$Qobs[,2],
                       ID3 = Oudon$obs$Qobs[,3],
                       ID4 = Oudon$obs$Qobs[,4],
                       ID5 = Oudon$obs$Qobs[,5],
                       ID6 = Oudon$obs$Qobs[,6]),
            file = file.path(wd, "discharge.txt"), 
            col.names = TRUE, row.names = FALSE, sep = ";", quote = FALSE)
```

## 1. Reading a vector layer with sf


The spatial vector layer describes the locations of the catchments. It can contain catchment delineations, outlets or centroids. However, catchment delineations allow a better assessment of the distances between catchments [@deLavenne2016].
The [sf](https://cran.r-project.org/package=sf) package can be used to load this layer.

```{r, echo=TRUE, message=FALSE, results='hide', eval=TRUE}
library(sf)
catchments <- st_read(file.path(wd, "catchments.shp"), "catchments", stringsAsFactors = FALSE)
obs_sf <- catchments[1:5,] # Gauged catchments
sim_sf <- catchments[6,]   # Ungauged catchments
```

## 2. Reading a data frame of time series

The units of the discharge time series should be provided using the [units](https://cran.r-project.org/package=units) package.

```{r, echo=TRUE, message=FALSE, results='hide', eval=TRUE}
library(units)
Q <- read.table(file.path(wd, "discharge.txt"), header = TRUE, sep = ";", 
                colClasses = c("character", rep("numeric", 6)))
Qmatrix  <- as.matrix(Q[,-1])
Qmatrix  <- set_units(Qmatrix, "m^3/s")
```

## 3. Creating a stars object

These time series and the spatial vector layer are merged into one stars object. Make sure that both are organised in the same order. The stars object will have two dimensions (time and space) and one attribute (discharge observation) for gauged catchments. The ungauged catchments will have the same dimensions but no attribute for the moment.

```{r, echo=TRUE, message=FALSE, results='hide', eval=TRUE}
library(stars)
Qmatrix  <- Qmatrix[,obs_sf$ID] #to have the same order as in the spatial data layer
obs_st   <- st_as_stars(list(Qobs = Qmatrix), 
                            dimensions = st_dimensions(time = as.POSIXct(Q$DateTime, tz="UTC"), 
                                                       space = obs_sf$geometry))
sim_st   <- st_as_stars(dimensions = st_dimensions(time = as.POSIXct(Q$DateTime, tz="UTC"), 
                                                       space = sim_sf$geometry))
```
## 4. Creating a transfR object

These stars objects can then be used to create objects of class transfR with the `as_transfr()` function (argument `st`) and to perform simulations.

```{r, echo=TRUE, message=FALSE, results='hide', eval=TRUE}
obs <- as_transfr(st = obs_st, hl = Oudon$hl[1:5])
sim <- as_transfr(st = sim_st, hl = Oudon$hl[6])
```
Hydrographs can then be transferred from the gauged catchments to the ungauged catchments using the `quick_transfr()` function.

```{r, echo=TRUE, message=FALSE, results='hide', eval=TRUE}
sim <- quick_transfr(obs, sim)
```

The simulated time series will be available in its stars object as new attributes.
```{r, echo=TRUE, message=TRUE, eval=TRUE}
sim$st
```

## References

<div id="refs"></div>

```{r, echo=FALSE, message=FALSE, warning=FALSE, eval=TRUE, results='hide'}
# Cleaning temporary directory
unlink(wd, recursive = TRUE)
```
