---
output: github_document
---

<!-- README.md is generated from README.Rmd. Please edit that file -->

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)
```


# CropWat

<!-- badges: start -->

<!-- badges: end -->

CropWat is an R Implementation of the FAO CropWat Model.

This implements the functions describing water balance on
an irrigated crop as described in FAO publications of the Irrigation and
Drainage Series, namely, No. 56 "Crop Evapotranspiration - Guidelines for
computing crop water requirements” and No. 33 titled "Yield response to water".

## Installation

You can install the development version of CropWat like so:

``` r
# install.packages("remotes")
remotes::install_git("https://forgemia.inra.fr/umr-g-eau/cropwat.git")
```

## Example

This is a basic example which shows you how to simulate water balance of an
irrigated crop.

```{r example}
# Load library
library(CropWat)
library(dplyr)

# Import example climate dataset
data(ZH_3_clim)

# Selecting year 2010-2014
meteo <- ZH_3_clim[ZH_3_clim$Date >= as.Date("2010-01-01") &
                   ZH_3_clim$Date <= as.Date("2014-12-31"), ]

# Formatting model input
cw_input <- CW_create_input("SB2023-soja",
                            DatesR = meteo$Date,
                            ETo = meteo$ETP,
                            P = meteo$Ptot,
                            soil_depth = 1.2,
                            AWC = 140)
plot(cw_input)

# Set up of the initial state of the model
X <- CW_create_state(cw_input = cw_input)

# Choose an irrigation management
# Example: Fill Soil moisture depletion when half of RAW is reached
fun_irrig_125pc_RAW <- CW_irrig_fun_factory(RAW_ratio = 1.25, apply_Dr = TRUE)

# Simulate water balance with an irrigation management
cw_output <- CW_run_simulation(X, cw_input, FUN_IRRIG = fun_irrig_125pc_RAW)
plot(cw_output)

# Yearly amount of irrigation applied (mm)
cw_output |> group_by(lubridate::year(DatesR)) |> summarise(irrig_volume = sum(Ir))
```