---
title: "Generate apsimx file for sensitivity analysis"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Generate apsimx file for sensitivity analysis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

```{r setup, message=FALSE, warning=FALSE}
library(rapsimng)
library(tidyverse)
```

Sensitivity analysis is conducted to check output variations when a parameter is changed. This post is to show how to conduct sensitivity analysis using rapsimng package using factorial simulations.


We use the base phyllochron as an example to demonstrate how to generate a new apsimx file from a template. 


The base phyllochron is a key parameter for wheat phelonogy and leaf appearance rate. The range of base phyllochron is from 60 to 130 degree days. 

The data.frame requires three columns (i.e. parameter, value, name) and multiple parameters can be specified here. 

```{r define-parameter}
phyllochron_para <- tibble(parameter = "[Phenology].Phyllochron.BasePhyllochron.FixedValue", 
                           value = seq(60, 130, by = 1)) %>% 
  mutate(name = paste0("Cultivar", seq_len(n())))
head(phyllochron_para)
```

The template is an apsimx file setup for the actual experiment or the specified environments (i.e. locations, sowing date or years). I assume there is a factor `Cv` for culivar in the `Permutation` model which specified the cultivar by `[Sowing].Script.CultivarName`.

```{r}
template <- read_apsimx(system.file("extdata/wheat.apsimx", package = "rapsimng"))
```


`update_cultivar` can be used to add the list of cultivars in the `Replacements`. The `Specification` in the `Permutation.Cv` can be replace with new values.

```{r}
template <- update_cultivar(template, phyllochron_para)

node <- search_path(template, "[Permutation].Cv")    
if (length(node) == 0) {
  stop("[Permutation].Cv is not found")
}
new_value <- paste0("\\1", paste(phyllochron_para$name, collapse = ","))
node$node$Specification <- gsub("(.+ *= *)(.+)$", new_value, node$node$Specification)

node$node$Specification

template <- replace_model(template, node$path, node$node)
```

Finally the new model can be write into file system and run with APSIM NG. Uncomment the sections below, update the path to `Models.exe`. 
```{r}

# write_apsimx(template, "new-path.apsimx")
# models_path <- "path-to-Models.exe"
# run_models(models_path, sim_name, csv = TRUE, parallel = FALSE)
```

The example in this post can be modified into parallel codes for sensivity analysis in the large scales. 
