---
title: "Using cropwatMUL for Crop-Water Assessment Across Multiple Locations"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Using cropwatMUL for Crop-Water Assessment Across Multiple Locations}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5
)
```

## Introduction

`cropwatMUL` is an R package for estimating reference
evapotranspiration, crop evapotranspiration, effective rainfall,
crop-water requirements, root-zone water balance, and irrigation
schedules for one crop across multiple locations.

The package uses a temperature-based implementation of the FAO-56
Penman-Monteith method and a workflow inspired by the 'CROPWAT' software.

The package is an independent implementation and is not affiliated
with or endorsed by the Food and Agriculture Organization of the
United Nations.

## Input workbook structure

The input Excel workbook requires three worksheets:

1. `climate`
2. `soil`
3. `crop`

### Climate worksheet

The climate worksheet contains one row for every month and location.

Important fields include:

- `DISTRICT`
- `MONTH` or `month_no`
- `TMAX_C`
- `TMIN_C`
- `RAINFALL_mm`
- `LATITUDE`
- `LONGITUDE`

Optional fields include:

- `ALTITUDE_M`
- `wind_speed_m_s`
- `krs`
- `ETO_MM_DAY`

### Soil worksheet

The soil worksheet contains one record for each location.

Required fields include:

- `DISTRICT`
- `AWC_mm_m`
- `Soil_textuure`

### Crop worksheet

The crop worksheet contains crop growth and crop-coefficient
parameters.

Required fields include:

- `crop`
- `planting_date`
- `Initial_Days`
- `Development_days`
- `Mid_days`
- `Late_days`
- `Kc_initial`
- `Kc_mid`
- `Kc_end`
- `rooting_depth_m`

## Load the package

```{r load-package}
library(cropwatMUL)
```

## Locate the representative workbook

The package includes a synthetic workbook generated for demonstration.

```{r example-file}
input_file <- system.file(
  "extdata",
  "cropwat_example.xlsx",
  package = "cropwatMUL"
)

stopifnot(nzchar(input_file))
basename(input_file)
```

The example data are simulated and should not be interpreted as
observed climate, soil, or crop measurements.

## Validate the input workbook

Validate the workbook before running the simulation:

```{r validate-input}
validate_cropwat_input(
  input_file = input_file,
  crop_name = "Potato"
)
```

The validation function checks:

- whether the file exists;
- whether the required worksheets exist;
- whether required columns are present;
- whether each location contains 12 monthly climate records;
- whether soil records exist for the locations;
- whether the selected crop exists.

## Run the multilocation simulation

```{r run-model}
result <- run_cropwat_one_crop_multilocation(
  input_file = input_file,
  crop_name = "Potato",
  irrigation_efficiency = 0.70,
  critical_depletion = 0.35,
  root_initial_m = 0.15,
  u2 = 2,
  krs = 0.16,
  altitude_m = 0,
  initial_depletion_mm = 0
)
```

## Examine the result object

The returned object is a named list.

```{r result-names}
names(result)
```

Important components include:

- `summaries`
- `daily`
- `dekadal`
- `monthly`
- `soil`
- `climate`
- `crop`
- `settings`
- `location_results`

## Seasonal summary

```{r seasonal-summary}
result$summaries
```

The summary includes:

- planting and harvest dates;
- crop duration;
- annual rainfall;
- annual effective rainfall;
- seasonal crop evapotranspiration;
- seasonal effective rainfall;
- irrigation requirement;
- net irrigation;
- gross irrigation;
- irrigation efficiency;
- critical depletion.

## Monthly climate and reference evapotranspiration

```{r monthly-output}
head(result$monthly)
```

The monthly output includes:

- maximum temperature;
- minimum temperature;
- rainfall;
- effective rainfall;
- mid-month reference evapotranspiration;
- estimated monthly reference evapotranspiration total.

## Dekadal crop-water requirement

```{r dekadal-output}
head(result$dekadal)
```

The dekadal table includes:

- period start and end;
- number of days;
- reference evapotranspiration;
- mean crop coefficient;
- crop evapotranspiration;
- effective rainfall;
- rainfall events;
- irrigation requirement.

## Daily irrigation schedule

```{r daily-output}
head(
  result$daily[
    result$daily$in_crop,
  ]
)
```

The daily schedule includes:

- day after sowing;
- reference evapotranspiration;
- crop coefficient;
- crop evapotranspiration;
- rainfall;
- effective rainfall;
- rooting depth;
- total available water;
- readily available water;
- root-zone depletion;
- net irrigation;
- gross irrigation.

## Export results

The export function creates:

- one Excel workbook;
- location-specific crop-water-requirement TXT files;
- location-specific irrigation-schedule TXT files;
- one complete TXT output for each location;
- one all-location summary TXT file.

```{r export-results, warning=FALSE, message=FALSE}
vignette_output_dir <- tempfile("cropwatMUL-vignette-")
dir.create(
  vignette_output_dir,
  recursive = TRUE,
  showWarnings = FALSE
)

output <- write_cropwat_outputs(
  results = result,
  output_dir = vignette_output_dir,
  prefix = "Potato_cropwatMUL_example"
)

c(
  excel_file = basename(output$excel_file),
  txt_directory = basename(output$txt_dir),
  summary_file = basename(output$all_locations_summary)
)

unlink(
  vignette_output_dir,
  recursive = TRUE,
  force = TRUE
)
```

The example writes only to an R session temporary directory and removes
the generated files immediately after the demonstration. The TXT outputs
are tab-delimited and contain complete rows and columns without tibble
abbreviation.

## Reference evapotranspiration assumptions

When measured humidity, radiation, or wind data are unavailable:

- actual vapour pressure is estimated from minimum temperature;
- solar radiation is estimated using temperature range and
  extraterrestrial radiation;
- wind speed defaults to the user-supplied value;
- altitude defaults to the user-supplied value;
- the radiation coefficient defaults to the user-supplied `krs`.

These assumptions should be evaluated for the climatic region in
which the package is applied.

## Effective rainfall

Monthly effective rainfall is estimated using the USDA-SCS
relationship implemented in:

```{r effective-rainfall}
usda_scs_effective_rain(
  c(50, 150, 300)
)
```

## Reference evapotranspiration example

```{r eto-example}
pm_temp_estimated(
  tmax = 25,
  tmin = 15,
  lat = 25.7,
  doy = 100,
  altitude_m = 1000,
  u2 = 2,
  krs = 0.16
)
```

## Limitations

The package does not claim exact numerical equivalence with every
version or configuration of the official CROPWAT software.

Differences may arise from:

- temperature-based estimation of missing climate variables;
- interpolation of monthly climate values;
- rainfall-event allocation;
- effective-rainfall conversion;
- irrigation-trigger assumptions;
- crop and soil input parameters.

Users should validate the outputs against local observations,
independent calculations, or established software before operational
decision-making.