---
title: "Preparing your input file"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Preparing your input file}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  fig.width = 7,
  fig.height = 4.5,
  out.width = "100%"
)
```

```{r setup}
library(ambre)
set.seed(2024)
```

Every `ambre` analysis starts from one Excel file describing your reuse
scenario. Get that file right and the rest of the pipeline just runs; get a
label wrong and `create_scenario()` stops with an error. This vignette is the
reference for building that file: the nine columns, their allowed values, and
the traps to avoid. If you have not seen a run yet, read
`vignette("a-get-started", package = "ambre")` first.

## Anatomy of the file

The file has **ten columns**, one row per situation you want to assess. Here is
a bundled two-row example -- use it as a template:

```{r template}
readxl::read_excel(
  system.file("input_1culture_2pop.xlsx", package = "ambre")
) |>
  knitr::kable()
```

| Column | Meaning |
|---|---|
| `CropName` | the crop being irrigated |
| `Area` | irrigated area, in hectares |
| `PopulationName` | the exposed population for this crop |
| `nb_population` | how many people are exposed |
| `PathName` | the exposure pathway (how the water reaches the population exposed) |
| `STEPtreatmentName` | the Wastewater Treatment Plant (WWTP) process |
| `CollectiveTreatmentName` | additional treatment after the WWTP, common to all crop|
| `InitialProcessName` | individual process (equipment or practice) step currently in place |
| `SupplementaryProcessName` | individual process (equipment or practice) step of a new scenario to evaluate |
| `nb_decay` | an on-field barrier (equipment or practice) |

Each row is one **crop x population x pathway** combination. A scenario with two
crops, each exposing three populations, is six rows.

## Validity bounds and empty cells

Two numeric columns are range-checked when you build the scenario:

- `Area` must be **greater than 0 and below 10000** hectares;
- `nb_population` must be **greater than 0 and below 5000**.

The four barrier columns (`STEPtreatmentName`, `CollectiveTreatmentName`,
`InitialProcessName`, `SupplementaryProcessName`) may be left **empty
(`NA`)** when a scheme does not use that slot -- for instance a row with a plant
step and a field barrier but no collective treatment. On the other hand, a cell 
may contain **several processes separated by commas** (i.e. "P.9 - Peeling, P.8 - Drying").
The name columns, by contrast, **must** match a known value exactly 
(indicated in `instruction` sheet), 
and that is what the rest of this vignette is about.

## The allowed values

The names you type are resolved against `config_ambre`, the bundled database.
Printing the catalogs straight from that object guarantees this list stays true
to the package you actually have installed.

**Crops** -- the `CropName` column:

```{r crops}
config_ambre$crop[, c("CropName", "CropDescription", "CropHeight")]
```

**Populations** -- the `PopulationName` column:

```{r populations}
dplyr::distinct(
  config_ambre$path$description[, c("PopulationID", "PopulationName")]
)
```

**Exposure pathways** -- the `PathName` column must match exactly a `PathDescription`
listed below:

```{r paths}
config_ambre$path$description[, c("PathID", "PathDescription", "PopulationName")] |>
  knitr::kable()
```

**Barriers and treatments** -- any of the `STEPtreatmentName`,
`CollectiveTreatmentName`, `InitialProcessName` or
`SupplementaryProcessName` cells must be one or more of these names, separated 
by a **comma* (Q. = treatment, E. = equipment, P. = practice):

```{r barriers}
sort(unique(config_ambre$treatment$processes$TreatmentName))
```

The pathogens you simulate are *not* set in the Excel file -- you pass them to
`run_qmra_intial_situation()` / `run_qmra_supplementary_process()`. 
The 6 that can be simulated are :

```{r pathogen}
library(dplyr)

pathogen <- config_ambre$health %>%
  filter(!if_else(is.na(infection_to_illness) & is.na(dalys_per_case), TRUE, infection_to_illness == dalys_per_case, missing = FALSE))
pathogen$PathogenName

```
More pathogen are available in `config_ambre$health` but parameters 
`nfection_to_illness` and `dalys_per_case` are not yet available.

## Known pitfalls

- **Spelling is exact and unforgiving.** `PathName` must reproduce a
  `PathDescription` exactly, including case and punctuation; `CropName` must be
  `Potato`, `Corn seed`, etc. A stray "s" is enough to fail. Even a bundled
  example, `input_cas_apprentissage_complet.xlsx`, is worth cross-checking:

  ```{r check-complet}
  vals <- readxl::read_excel(
    system.file("input_cas_apprentissage_complet.xlsx", package = "ambre")
  )$CropName
  setdiff(unique(vals), config_ambre$crop$CropName)   # crop names with no match
  ```

  Anything returned here is a label the database will not recognise. 
  To help you complete the Excel file without making any mistakes, use the 
  ‘instructions’ table, where you will find the names to use.

- **`PathName` implies its population.** Each pathway is tied to a population in
  the database, so keep `PopulationName` consistent with the `PathName` you
  choose.

## Validate your file

The check is simply to build the scenario. On a good file it returns a tibble
with one row per input row and the resolved integer IDs:

```{r validate}
scenario <- create_scenario(
  system.file("input_1culture_2pop.xlsx", package = "ambre")
)
scenario[, c("CropName", "CropID", "PopulationName", "PopulationID",
             "PathName", "PathID")]
```

If a name is missing or misspelled, `create_scenario()` stops rather than
guessing. Fix the offending cell against the catalogs above and try again. Once
the scenario builds, you are ready to run the assessment -- see
`vignette("a-get-started", package = "ambre")` -- and to inspect or extend the
database behind these names in `vignette("h-config-ambre", package = "ambre")`.
