% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/build_temporal_gam.R
\name{build_temporal_gam}
\alias{build_temporal_gam}
\title{Build Temporal GAM Models Across Cross-Validation Folds}
\usage{
build_temporal_gam(partition_result, pseudoabsence_result, model_formula,
                   link = "logit", gam_params = list(method = "REML"),
                   threshold_method  = "tss",
                   output_dir = file.path(tempdir(), "GAM_Models"),
                   create_plot = TRUE, plot_palette = "Dark 2",
                   overwrite = FALSE, time_cols = NULL, verbose = TRUE)
}
\arguments{
\item{partition_result}{List or character. Output from
\code{\link{spatiotemporal_partition}} or path to an \code{.rds}
file containing that output.}

\item{pseudoabsence_result}{List or character. Output from
\code{\link{generate_absences}} or path to an \code{.rds} file
containing that output.}

\item{model_formula}{Formula or character. The right-hand side of the model
formula supplied as either a formula object or a character string. The
response variable (\code{presence}) is always added automatically on the
left-hand side, so only the right-hand side needs to be provided. Both of
the following are accepted and equivalent:
\itemize{
  \item \code{~ s(Var1) + s(Var2) + Var3}
  \item \code{"~ s(Var1) + s(Var2) + Var3"}
}
Standard \pkg{mgcv} formula syntax applies. Smooth terms are specified
with \code{s()} for univariate smooths, \code{te()} for tensor product
smooths of two or more variables, and \code{ti()} for tensor product
interaction terms. Parametric terms can be included alongside smooth terms
using \code{+}. The basis type and dimension can be controlled via
arguments to \code{s()}, e.g. \code{s(Var1, k = 5, bs = "tp")}. All
predictor names referenced in the formula must be present as columns in
both the presence and pseudoabsence data.}

\item{link}{Character. The link function for the binomial GAM. One of
\code{"logit"} (default), \code{"probit"}, \code{"cloglog"}, or
\code{"cauchit"}. See \code{\link[stats]{binomial}} for details on each
link function.}

\item{gam_params}{Named list. Additional arguments passed to
\code{\link[mgcv]{gam}}, such as \code{method} for the smoothing
parameter estimation method (e.g. \code{"REML"}) or
\code{select} for additional shrinkage. Default is
\code{list(method = "REML")}.}

\item{threshold_method}{Character or numeric. Method used to convert
continuous predicted probabilities to binary suitability. Accepted values:
\itemize{
  \item \code{"prevalence"}: Sets threshold equal to the prevalence
    (proportion of presences) in the training data for that fold.
  \item \code{"tss"}: Selects the threshold that maximizes the True Skill
    Statistic (sensitivity + specificity - 1) on the training data.
    Default.
  \item A numeric value between 0 and 1 (e.g. \code{0.4}): Uses that
    value as a fixed threshold for all folds directly.
}}

\item{output_dir}{Character. Directory to write output files including saved
model objects and plots. Default is \code{file.path(tempdir(), "GAM_Models")}.}

\item{create_plot}{Logical. If \code{TRUE}, generates per-fold response
curve plots and a combined ROC curve summary. Default is \code{TRUE}.}

\item{plot_palette}{Character. Name of an HCL or RColorBrewer palette used
to color folds in diagnostic plots. Accepts any HCL palette name (see
\code{\link[grDevices]{hcl.pals}}) or, if \pkg{RColorBrewer} is installed,
any Brewer palette name. Default is \code{"Dark 2"}.}

\item{overwrite}{Logical. If \code{TRUE}, overwrites existing saved model
files. If \code{FALSE}, loads existing files when available. Default is
\code{FALSE}.}

\item{time_cols}{Character. Name of the column(s) containing year or time
step values in the occurrence data. Must match \code{time_cols} used in
\code{\link{spatiotemporal_partition}}. Default is \code{NULL}.}

\item{verbose}{Logical. If \code{TRUE} (default), prints progress
messages during processing. Includes per-fold training summaries and
file-saved messages. The completion summary and metrics table are
always printed regardless of this setting.}
}
\value{
A list with class \code{"TemporalGAM"} containing:
\itemize{
  \item \code{models}: Named list of fitted \code{gam} objects, one per
    fold.
  \item \code{thresholds}: Named numeric vector of probability thresholds
    used for binary classification, one per fold.
  \item \code{threshold_method}: Character string recording the thresholding
    method used.
  \item \code{model_formula}: The formula object as passed to the fitting
    function.
  \item \code{link}: Character string recording the link function used.
  \item \code{model_vars}: Character vector of predictor names extracted
    from the formula right-hand side.
  \item \code{fold_training_data}: Named list of training data frames used
    to fit each fold model, retained for downstream prediction.
  \item \code{fold_test_metrics}: Data frame of held-out test fold metrics
    per fold: \code{Threshold}, \code{AUC}, \code{TSS}, \code{Kappa},
    \code{Sensitivity}, and \code{Specificity}. Also written to
    \code{Fold_Test_Metrics.csv} in \code{output_dir}.
  \item \code{output_dir}: Path to the output directory.
  \item \code{model_type}: Character string \code{"gam"}, used by
    \code{\link{generate_spatiotemporal_predictions}}.
  \item \code{plots}: Named list of recorded plot objects when
    \code{create_plot = TRUE}. Plots can be replayed with
    \code{grDevices::replayPlot()}.
}
}
\description{
Modeling function that constructs binomial generalized additive models (GAMs)
for each cross-validation fold using presence and pseudoabsence data. Each
model reserves one fold as testing data and uses the remaining folds as
training data. The user supplies the model formula directly using standard
\pkg{mgcv} formula syntax, including smooth terms such as \code{s()},
\code{te()}, and \code{ti()}. Supports automatic or manual probability
thresholding for converting continuous predictions to binary suitability
classifications necessary for downstream analyses. The returned object follows the same
structure as \code{\link{build_temporal_glm}}, \code{\link{build_temporal_hv}},
and \code{\link{build_temporal_rf}}, and is accepted directly by
\code{\link{generate_spatiotemporal_predictions}}.
}
\details{
GAMs are fit using \code{\link[mgcv]{gam}} from the \pkg{mgcv} package with
\code{family = binomial(link = link)}. Smooth terms default to thin plate
regression splines (\code{bs = "tp"}) with the basis dimension \code{k}
chosen automatically by \pkg{mgcv} unless specified in the formula. Smoothing
parameters are estimated by REML by default.

The returned object is recognized by
\code{\link{generate_spatiotemporal_predictions}}, which uses the
\code{model_type} field to use the correct prediction and evaluation
logic.
}
\examples{
data(tmr_partition, package = "TemporalModelR")

data(tmr_absences,  package = "TemporalModelR")

build_temporal_gam(
  partition_result     = tmr_partition,
  pseudoabsence_result = tmr_absences,
  model_formula        = ~ s(elevation) + s(forest_cover) + s(prseas),
  threshold_method     = "tss",
  output_dir           = tempdir(),
  create_plot          = FALSE,
  time_cols            = c("year", "season"),
  verbose              = FALSE
)
}
\seealso{
Preprocessing: \code{\link{spatiotemporal_partition}},
  \code{\link{generate_absences}}

Modeling: \code{\link{build_temporal_glm}}, \code{\link{build_temporal_rf}},
  \code{\link{build_temporal_hv}},
  \code{\link{generate_spatiotemporal_predictions}}

External: \code{\link[mgcv]{gam}}, \code{\link[mgcv]{s}}
}
