---
title: "First run of the model"
author: "David Dorchies"
date: "20 mai 2020"
output: html_document
---

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

## Load parameters of GR4 run-off model

```{r}
library(griwrm)
load("_cache/seine.RData")
```

Data comes from calibration of ClimAware project with naturalised flows.

```{r}
ClimAwareParams <- readr::read_csv(
  file = "https://stratus.irstea.fr/d/0b18e688851a45478f7a/files/?p=/climaware_hydro/Ident_NAT_P0P0.txt&dl=1"
)

ClimAwareParams
```

The lag $\tau_0$ and route $K_0$ parameters of TGR are expressed as time delay in hours corresponding to the delay time between the farest upstream inlet and the outlet of the sub-basin. 
Almost all sub basin has only a lag parameter. The only exception is for La Marne Ã  Noisiel (NOISI_17) that has a routing parameter which can be approximated to a single lag parameter equals to $\tau_0 + K_0$.

This lag parameter has to be converted in a speed in m/s used in the airGR lag model:

```{r}
# Convert TGR routing parameter into speed
params <- merge(ginet, ClimAwareParams, by.x = "id", by.y = "id_sgl")

for(id in girop$id) {
  # Maximum connection length with upstream nodes
  UpstrNodes <- which(ginet$down == id & !is.na(ginet$down))
  if(length(UpstrNodes) > 0) {
    maxLength <- max(ginet$length[UpstrNodes])
    params$LAG <- maxLength * 1000 / ((params$Tau0 + params$K0) * 3600)
    sLag <- "LAG"
  } else {
    sLag <- NULL
  }
  girop$params[girop$id == id] <- list(params[params$id == id, c("S", "IGF", "KR", "T", sLag)])
}

```

## Run the SD model for the whole basin

```{r}
# Time settings
library(lubridate)
IndPeriod_Run <- seq(
  which(gits$date == (gits$date[1] + months(12))), # Set aside warm-up period
  length(gits$date)) # Until the end of the time series
IndPeriod_WarmUp = seq(1,IndPeriod_Run[1]-1)

OutputsModels <- RunModelGriwrm(
  ginet, girop, gits, 
  IndPeriod_Run = IndPeriod_Run, 
  IndPeriod_WarmUp = IndPeriod_WarmUp
)
```

## Plot the result for each basin

```{r, fig.height = 5, fig.width = 8}
htmltools::tagList(lapply(
  names(OutputsModels), 
  function(x) {
    plot(OutputsModels[[x]], Qobs = gits[[x]]$Qobs[IndPeriod_Run] , main = x)
  }
))
```






