## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.align = "center",
  warning = FALSE,
  message = FALSE,
  fig.width = 7,
  fig.align = "center"
)

## ----load_package-------------------------------------------------------------
library(clim4health)

## ----vignette_objects, echo = FALSE-------------------------------------------
# c4h_downscale() requires CDO, which may not be available when this vignette
# is built. The code calls are shown but not run; the pre-computed results are
# loaded instead (see dev-utils/vignette_objects.R).
load_vignette_object <- function(name) {
  readRDS(system.file(
    "extdata",
    "vignette_objects",
    paste0("overview_", name, ".rds"),
    package = "clim4health",
    mustWork = TRUE
  ))
}

## ----input_functions_table, echo = FALSE--------------------------------------
knitr::kable(
  data.frame(
    Function = c(
      "`c4h_get_help()`",
      "`c4h_get()`",
      "`c4h_load()`",
      "`c4h_convert_units()`"
    ),
    Purpose = c(
      "List the available datasets and variables that can be downloaded from the CDS via clim4health.",
      "Download data from the CDS.",
      "Load climate data into an s2dv_cube object, either data downloaded using `c4h_get()` or data from a local csv file.",
      "Print or convert the units of a variable in an s2dv_cube object."
    )
  ),
  format = "markdown",
  caption = "Table 1: Overview of functions to prepare input data for clim4health."
)

## ----transform_functions_table, echo = FALSE----------------------------------
knitr::kable(
  data.frame(
    Function = c(
      "`c4h_space()`",
      "`c4h_time()`",
      "`c4h_downscale()`",
      "`c4h_verify()`",
      "`c4h_index()`",
      "`c4h_collapse()`"
    ),
    Purpose = c(
      "Spatially aggregate gridded data to administrative areas.",
      "Temporal aggregation to a desired time resolution.",
      "Downscale, calibrate and bias adjust climate data.",
      "Perform a forecast verification and quality assessment of forecast skill.",
      "Mask climate data by applying thresholds to the data.",
      "Collapse the data to a single value across one or more dimensions, e.g. calculating the ensemble mean or maximum value across time."
    )
  ),
  format = "markdown",
  caption = "Table 2: Overview of functions to transform and process data for clim4health."
)

## ----output_functions_table, echo = FALSE-------------------------------------
knitr::kable(
  data.frame(
    Function = c(
      "`c4h_plot()`",
      "`c4h_plotskill()`",
      "`c4h_convert()`",
      "`c4h_save()`"
    ),
    Purpose = c(
      "Plot aspects of the data.",
      "Plot forecast skill and its significance.",
      "Convert the data from s2dv_cube to a different data type, including areal, tabular, or raster.",
      "Save the transformed data."
    )
  ),
  format = "markdown",
  caption = "Table 3: Overview of functions to visualise and output data for clim4health."
)

## ----load_libraries-----------------------------------------------------------
library(clim4health)

## ----load_forecast_data-------------------------------------------------------
# Load the forecast data
fcst_path <- system.file("extdata/forecast/", package = "clim4health")
fcst_path <- paste0(fcst_path, "/")

fcst <- c4h_load(
  fcst_path,
  variable = "t2m",
  year = 2025,
  month = 1,
  leadtime_month = "all",
  ext = "nc"
)

# Print a summary of the values of the forecast data
summary(fcst$data)

## ----load_hindcast_reanalysis_data--------------------------------------------
# Load the hindcast data
hindcast_path <- system.file("extdata/hindcast/", package = "clim4health")
hindcast_path <- paste0(hindcast_path, "/")

hcst <- c4h_load(
  hindcast_path,
  variable = "t2m",
  year = 2010:2013,
  month = 1,
  leadtime_month = 1:3,
  ext = "nc"
)

reanalysis_path <- system.file("extdata/reanalysis/", package = "clim4health")
reanalysis_path <- paste0(reanalysis_path, "/")

# Load the reanalysis data
rean <- c4h_load(
  reanalysis_path,
  variable = "t2m",
  year = 2010:2013,
  month = 1,
  leadtime_month = 1:3,
  ext = "nc"
)

## ----print_raw_data-----------------------------------------------------------
print(fcst$dims)
print(hcst$dims)
print(rean$dims)

## ----check_units--------------------------------------------------------------
# Display the current units
c4h_convert_units(fcst, var = "t2m")

## ----convert_units------------------------------------------------------------
# Convert from Kelvin to Celsius
fcst <- c4h_convert_units(fcst, to = "celsius", var = "t2m", from = "K")
hcst <- c4h_convert_units(hcst, to = "celsius", var = "t2m", from = "K")
rean <- c4h_convert_units(rean, to = "celsius", var = "t2m", from = "K")

# Display the new units
print(c4h_convert_units(fcst, var = "t2m"))

## ----plot_raw_data 1, fig.height=2.5------------------------------------------
# Plot the forecast data
c4h_plot(fcst, var = "t2m", ensemble = TRUE)

## ----plot_raw_data 2, fig.height=6, fig.width=6-------------------------------
# Plot the hindcast data
c4h_plot(hcst, var = "t2m", ensemble = TRUE)
# Plot the reanalysis data
c4h_plot(rean, var = "t2m", ensemble = TRUE)

## ----spatial_aggregation------------------------------------------------------
# Load the sf package to read in spatial data
library(sf)

# Region municipalities
munip_path <- system.file(
  "extdata",
  "areas",
  "munip_vallecauca.gpkg",
  package = "clim4health"
)
munip <- read_sf(munip_path)

# Spatial aggregation
hcst_aggr <- c4h_space(hcst, munip)
rean_aggr <- c4h_space(rean, munip)

## ----print_dims---------------------------------------------------------------
print(hcst_aggr$dims)

## ----plot_aggregated_data, fig.height=6, fig.width=6--------------------------
# Plot the aggregated hindcast data
c4h_plot(hcst_aggr, ensemble = TRUE)
# Plot the aggregated reanalysis data
c4h_plot(rean_aggr, ensemble = TRUE)

## ----downscaling, eval = FALSE------------------------------------------------
# cal <- c4h_downscale(
#   downscale_function = "Intbc", # downscaling method
#   obs = rean, # observational data, used to bias adjust the experiment
#   exp = hcst, # the experimental data to calculate the bias adjustment parameters
#   exp_cor = fcst, # the experimental data to which the bias adjustment parameters will be applied
#   method_bc = "bias", # for "Intbc", the bias correction method to use
#   method_remap = "bilinear"
# ) # the method to remap the data to the new grid

## ----downscaling_load, echo = FALSE-------------------------------------------
cal <- load_vignette_object("fcst")

## ----downscale_hindcast, eval = FALSE-----------------------------------------
# cal_hcst <- c4h_downscale(
#   downscale_function = "Intbc",
#   obs = rean,
#   exp = hcst,
#   method_bc = "bias",
#   method_remap = "bilinear",
#   loocv = FALSE
# )

## ----downscale_hindcast_load, echo = FALSE------------------------------------
cal_hcst <- load_vignette_object("hcst")

## ----plot_downscaled_data 1, fig.height=2.5-----------------------------------
# Plot the downscaled forecast data
c4h_plot(cal$exp, ensemble = TRUE)

## ----plot_downscaled_data 2, fig.height=6, fig.width=6------------------------
# Plot the downscaled hindcast data
c4h_plot(cal_hcst$exp, ensemble = TRUE)

## ----verification-------------------------------------------------------------
skill <- c4h_verify(
  exp = cal_hcst$exp, # the experimental data (downscaled hindcast data)
  obs = cal_hcst$obs, # the observational data (downscaled hindcast data)
  metrics = c("CRPSS")
) # the desired metrics to calculate

## ----plot_skill_significance, fig.height=2.5----------------------------------
c4h_plotskill(skill$CRPSS$crpss, sign = skill$CRPSS$sign)

## ----apply_mask, fig.height=2.5-----------------------------------------------
mask <- c4h_index(data = cal$exp, return_mask = FALSE, lower_threshold = 20)
c4h_plot(mask, ensemble = TRUE)

## ----load_station_data--------------------------------------------------------
station_path <- system.file("extdata/stations/", package = "clim4health")
station_data <- c4h_load(station_path, variable = "temp_mean", ext = "csv")

## ----temporal_aggregation-----------------------------------------------------
weekly_data <- c4h_time(
  data = station_data,
  time_aggregation = "weekly",
  dim_aggregation = "time",
  fun = "mean",
  week_start = "Monday"
)

## ----climatology--------------------------------------------------------------
station_data <- c4h_load(
  station_path,
  variable = "temp_mean",
  ext = "csv",
  year = 2010:2013,
  month = 1,
  leadtime_month = 1:12
)

print(station_data$dims)

## ----climatology_2------------------------------------------------------------
yearly_stat <- c4h_time(
  data = station_data,
  time_aggregation = "yearly",
  dim_aggregation = "sdate",
  fun = "mean"
)

## ----climatology_3------------------------------------------------------------
climatology <- c4h_collapse(data = yearly_stat, dim = "sdate", fun = "mean")
print(climatology$dims)

## ----convert_data_type--------------------------------------------------------
csv_out <- c4h_convert(
  data = climatology,
  output_format = "data.frame",
  drop = TRUE
)
terra_out <- c4h_convert(data = cal$exp, output_format = "terra")
polygons_out <- c4h_convert(data = cal$exp, output_format = "sf")

## ----eval = FALSE-------------------------------------------------------------
# c4h_save(climatology, path = "path_to_file.csv")

