---
title: "Modeling and Diagnostics Report"

date: "`r Sys.Date()`"
output:
  html_document:
  theme: flatly
highlight: tango

params:
  robj: NULL
---

```{r setup_model, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(data.table)
library(mgcv)
library(ggplot2)
library(dplyr)
library(stringr)
library(growthTrendR)
library(ggeffects)
# library(cowplot)
library(patchwork)

```
<br>


```{r, warning=FALSE, message=FALSE}

robj <- params$robj
```

This report presents the results of a generalized additive model (GAM) analysis.  
The objective is to evaluate predictor contributions, describe the functional forms of relationships,  
and assess the adequacy of the fitted model.  
The following sections include a model summary, smooth term importance, partial effect visualizations,  
and diagnostic checks to ensure the robustness of the analysis.

<br>


### Model Summary

The following output provides the summary of the fitted GAM model.  
It includes estimated coefficients, smooth terms, approximate significance of predictors,  
and overall model fit statistics.

```{r}
if (is.list(robj$model) && all(c("gam", "lme") %in% names(robj$model))) gam_model <- robj$model$gam else gam_model <- robj$model
summary(gam_model)

if (nrow(robj$stable) > 0){
term_important <- sterm_imp( gam_model)

method <- unique(term_important$method)
}else method <- ""

```

<br>

### Importance of Smooth Terms

The relative contribution of predictors is evaluated by calculating the importance percentage of each smooth term,
based on <b><u>`r method `</b></u> method.
This indicates how much each variable contributes to explaining variation in the response.


```{r, echo=FALSE, results='asis', warning=FALSE, message=FALSE, fig.width=12, fig.height=8, fig.align='left'}
if (nrow(robj$stable) > 0){
# term_important <- sterm_imp( gam_model)
# 
# method <- unique(term_important$method)
tab <- term_important[, c(1,2)]
colnames(tab) <- c("Term", "Score (%)")
knitr::kable(tab, caption = "Relative importance of smooth terms",
      align = c("l", "r"))
}else{
  cat("\n**no smooth term in the model...**\n")
  cat("<br>")
}
```


<br>

<br>

### Partial Effects of Smooth Terms

Partial effect plots illustrate the shape of the relationship between the response and each predictor,
while holding other predictors constant.
These visualizations help identify nonlinear trends and assess whether effects are monotonic, threshold-like, or more complex.
<br>

```{r, echo=FALSE, results='asis', warning=FALSE, message=FALSE, fig.width=12, fig.height=8, fig.align='left'}
if (nrow(robj$stable) > 0){
if ("bam" %in% class(robj$model)) {
  cat("\n**Predicting smooth terms on the response scale is not yet supported for bam models. The plots shown here are based on mgcv::plot.gam()**\n")
  cat("<br>")
  plot.gam(robj$model, pages = 1)
}else{
plot_list <- plot_resp(robj = robj)

# combined <- plot_grid(
#   plotlist = plot_list,
#   ncol = 2,
#   labels = LETTERS[1:length(plot_list)]
# )

combined <- wrap_plots(plot_list, ncol = 2) + 
  plot_annotation(tag_levels = 'a',
      tag_suffix = ")")

print(combined)
}
}else{
  cat("\n**no smooth term in the model...**\n")
  cat("<br>")
}
```
<br>

### Model Diagnostics

Diagnostic checks evaluate whether the fitted GAM meets assumptions of independence, normality,
and sufficient smoothness.
Residuals, k-index, and qq-plots provide evidence of model adequacy or potential overfitting.
<br>

```{r, echo=FALSE,   warning=FALSE, message=FALSE, fig.width=12, fig.height=8, fig.align='left'}

 # Check smoothness, residuals, K-index

 # 2x2 layout on one page
par(mfrow = c(2, 2))
  if (is.list(robj$model) && all(c("gam", "lme") %in% names(robj$model))) gam_model <- robj$model$gam else gam_model <- robj$model
gam.check(gam_model, rep = 100, verbose = TRUE)

# reset plotting layout to default
par(mfrow = c(1, 1))
 

```
