## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse  = TRUE,
  comment   = "#>",
  fig.align = "center",
  warning   = FALSE,
  message   = FALSE,
  fig.width  = 8,
  fig.height = 5,
  out.width  = "100%"
)

## ----load-pkg-----------------------------------------------------------------
library(xaiHydro)

## ----sim-streamflow-----------------------------------------------------------
df_flow <- sim_streamflow_data(n = 365, seed = 2026)
head(df_flow, 6)

## ----sim-str------------------------------------------------------------------
str(df_flow)

## ----sim-drought-show---------------------------------------------------------
df_drought <- sim_drought_data(n = 240, seed = 2026)
head(df_drought, 6)

## ----train-rf, eval=FALSE-----------------------------------------------------
# library(randomForest)
# 
# # Separate predictors and response
# y_flow <- df_flow$streamflow
# X_flow <- df_flow[, setdiff(names(df_flow), "streamflow")]
# 
# set.seed(42)
# rf_model <- randomForest(
#   x         = X_flow,
#   y         = y_flow,
#   ntree     = 300,
#   mtry      = 3,
#   importance = TRUE
# )
# 
# print(rf_model)
# # Mean of squared residuals: ~X.XX
# # % Var explained:            ~XX.X

## ----train-xgb, eval=FALSE----------------------------------------------------
# library(xgboost)
# 
# y_spei   <- df_drought$spei
# X_drought <- df_drought[, setdiff(names(df_drought), "spei")]
# 
# xgb_mat   <- xgboost::xgb.DMatrix(as.matrix(X_drought), label = y_spei)
# xgb_model <- xgboost::xgboost(
#   data      = xgb_mat,
#   nrounds   = 150,
#   max_depth = 4,
#   eta       = 0.1,
#   objective = "reg:squarederror",
#   verbose   = 0
# )

## ----explainer, eval=FALSE----------------------------------------------------
# exp_flow <- hydro_explainer(
#   model    = rf_model,
#   data     = X_flow,
#   y        = y_flow,
#   variable = "streamflow",
#   units    = "m3/s",
#   label    = "RandomForest"
# )
# 
# print(exp_flow)
# # == xaiHydro Explainer ==
# #   Target variable : streamflow [m3/s]
# #   Model label     : RandomForest
# #   Observations    : 365
# #   Predictors      : 8
# #   Model class     : randomForest

## ----explainer-xgb, eval=FALSE------------------------------------------------
# pfun_xgb <- function(model, newdata) {
#   predict(model, xgboost::xgb.DMatrix(as.matrix(newdata)))
# }
# 
# exp_drought <- hydro_explainer(
#   model            = xgb_model,
#   data             = X_drought,
#   y                = y_spei,
#   variable         = "drought_index",
#   units            = "SPEI",
#   label            = "XGBoost",
#   predict_function = pfun_xgb
# )

## ----shap-compute, eval=FALSE-------------------------------------------------
# shap_vals <- hydro_shap(
#   explainer = exp_flow,
#   nsim      = 50,     # Monte Carlo replicates — increase for stability
#   seed      = 42
# )
# 
# # Returns a tidy data frame:
# # id | feature | shap_value | feature_value | mean_abs_shap
# head(shap_vals, 8)

## ----shap-summary, eval=FALSE-------------------------------------------------
# plot_shap_summary(shap_vals, top_n = 8)

## ----shap-waterfall, eval=FALSE-----------------------------------------------
# # Explain a high-flow day (e.g., observation 180 after a storm event)
# plot_shap_waterfall(shap_vals, obs_id = 180, top_n = 7)

## ----lime, eval=FALSE---------------------------------------------------------
# lime_result <- hydro_lime(
#   explainer    = exp_flow,
#   new_obs      = X_flow[180, , drop = FALSE],
#   n_features   = 6,      # top-6 features in the local model
#   kernel_width = 0.75
# )
# 
# # Local R² indicates surrogate model quality (closer to 1 = better)
# plot_lime_hydro(lime_result)

## ----pdp, eval=FALSE----------------------------------------------------------
# pdp_result <- hydro_pdp(
#   explainer   = exp_flow,
#   variable    = c("precipitation", "soil_moisture",
#                    "lag1_precip",  "temperature"),
#   type        = "partial",
#   grid_points = 60
# )
# 
# plot_pdp_hydro(pdp_result, ncol = 2)

## ----ale, eval=FALSE----------------------------------------------------------
# ale_result <- hydro_pdp(
#   explainer = exp_flow,
#   variable  = c("precipitation", "soil_moisture"),
#   type      = "accumulated"
# )
# 
# plot_pdp_hydro(ale_result, ncol = 2)

## ----importance, eval=FALSE---------------------------------------------------
# imp <- hydro_importance(
#   explainer     = exp_flow,
#   loss_function = "rmse",
#   B             = 20       # repetitions — reduces variance of estimate
# )
# 
# plot_importance_hydro(imp, top_n = 8)

## ----breakdown, eval=FALSE----------------------------------------------------
# bd <- hydro_breakdown(
#   explainer = exp_flow,
#   new_obs   = X_flow[180, , drop = FALSE],
#   type      = "shap",   # or "break_down"
#   B         = 25
# )
# 
# plot_breakdown_hydro(bd, max_features = 8)

## ----residuals, eval=FALSE----------------------------------------------------
# hydro_residuals(exp_flow)

## ----report, eval=FALSE-------------------------------------------------------
# hydro_xai_report(
#   explainer = exp_flow,
#   nsim      = 50,
#   top_n     = 6,
#   new_obs   = X_flow[180, , drop = FALSE],
#   seed      = 42,
#   save_path = "xaiHydro_streamflow_report.png",
#   width     = 16,
#   height    = 11,
#   dpi       = 300
# )

## ----drought-full, eval=FALSE-------------------------------------------------
# library(xgboost)
# 
# # Data
# df_d  <- sim_drought_data(n = 240, seed = 2026)
# y_d   <- df_d$spei
# X_d   <- df_d[, setdiff(names(df_d), "spei")]
# 
# # Model
# xgb_m <- xgboost::xgboost(
#   data      = xgboost::xgb.DMatrix(as.matrix(X_d), label = y_d),
#   nrounds   = 150, max_depth = 4, eta = 0.1,
#   objective = "reg:squarederror", verbose = 0
# )
# 
# # Explainer
# pfun  <- function(m, nd) predict(m, xgboost::xgb.DMatrix(as.matrix(nd)))
# exp_d <- hydro_explainer(xgb_m, X_d, y_d,
#                           variable         = "drought_index",
#                           units            = "SPEI",
#                           label            = "XGBoost",
#                           predict_function = pfun)
# 
# # XAI suite
# shap_d <- hydro_shap(exp_d, nsim = 50)
# imp_d  <- hydro_importance(exp_d, B = 20)
# pdp_d  <- hydro_pdp(exp_d, variable = c("spi_3", "spi_12", "et_deficit"))
# 
# plot_shap_summary(shap_d, top_n = 6,
#                   title = "SHAP Summary — SPEI drought model (XGBoost)")
# plot_importance_hydro(imp_d)
# plot_pdp_hydro(pdp_d, ncol = 3)
# hydro_residuals(exp_d)

## ----session------------------------------------------------------------------
sessionInfo()

