# To do only once: 
# remotes::install_github("SticsRPacks/SticsRPacks")
# SticsRPacks::SticsRPacks_update(ref = list(SticsRFiles= "46e6370c2d721068ca7117be285ce4accc0c14c8",
#                                            SticsOnR= "ea059e13b11cca2c6dadd9b8c3bf1d16492fec39"))
# remotes::install_github("SticsRPacks/CroPlotR")

library(tidyverse)
library(SticsRPacks)
library(CroPlotR)
source("functions.R")

# STICS version -----------------------------------------------------------

#Filepath for JavaSTICS version 8.5
javastics= "D:/Mes Donnees/10_STICS-Intercrop_ReMIX/STICS-Intercrop-Auzeville-Eric"

# workspace name: The location of this R project is the home directory.
# the workspace file path is relative to the R project.
workspace = "D:/Mes Donnees/10_STICS-Intercrop_ReMIX/STICS-Intercrop-Auzeville-Eric/Auzeville-Wheat-SC"


# Run the simulation ------------------------------------------------------

# Simulating the intercrop: 

usms= SticsRFiles::get_usms_list(usm_path = file.path(workspace,"usms.xml"))

# USMs we want to simulate: 
# usms_to_sim= c("SC_Pea_2005-2006_N0","SC_Pea_2005-2006_N1","IC_Wheat_Pea_2005-2006_N0")
usms_to_sim= usms # all usms here

# Choose the variables we want in output: 
sim_variables= c("lai(n)","QNplante","masec(n)","hauteur","CNgrain","fapar","mafruit")
# NB, use get_var_info() to get the variables by names or keywords if you don't remember, e.g.: get_var_info('laisen')
# get_var_info("lai")

# Generate the var.mod file:
SticsRFiles::gen_varmod(workspace, sim_variables)

run_javastics(javastics_path = javastics, workspace_path = workspace, 
              stics_exe = "Stics_v24-07-2020.exe",
              usms_list = usms_to_sim)


# Get the results ---------------------------------------------------------

sim= get_daily_results(workspace = workspace, usm_name = usms_to_sim)

# Get the observations ----------------------------------------------------

obs= get_obs(workspace =  workspace, usm_name = usms_to_sim)


# Plotting ----------------------------------------------------------------

# Plot in the plot panel in RStudio
plot(sim,obs=obs,type="dynamic",verbose=FALSE)

# Compute statistics and write a csv file ---------------------------------

stats = CroPlotR:::statistics_situations(sim,obs=obs,formater = CroPlotR:::format_stics,all_situations = TRUE)
# View(stats)
data.table::fwrite(stats,file = file.path(workspace,"plots_R","stats.csv"),sep = ";")


# Writting PDF files ------------------------------------------------------

# Plotting and writting pdf files:
# Dynamic plots
plot(sim,obs=obs,type="dynamic",verbose=FALSE,all_situations = FALSE)%>%
  plot_save2(.,path = file.path(workspace,"plots_R"),suffix = "_dynamic",device = "pdf")

# Scatter plots
plot(sim,obs=obs,type="scatter",verbose=FALSE)%>%
  plot_save2(.,path = file.path(workspace,"plots_R"),suffix = "_scatter",device = "pdf")

# end of program ------------------------------------------------------

