% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/generate_absences.R
\name{generate_absences}
\alias{generate_absences}
\title{Generate Temporally Explicit Pseudoabsence Points}
\usage{
generate_absences(partition_result, reference_shapefile_path, raster_dir,
                  variable_patterns, method = "random", ratio = 1,
                  buffer_distance = NULL, env_percentile = 0.05,
                  time_cols = NULL, pseudoabsence_times = NULL,
                  min_points_per_timestep = 1, user_absence_data = NULL,
                  xcol = NULL, ycol = NULL, points_crs = NULL,
                  create_plot = TRUE, plot_by_fold = FALSE,
                  plot_palette = "Dark 2", output_file = 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{reference_shapefile_path}{Character or sf object. Path to a polygon
file or an \code{sf} polygon object defining the study area.}

\item{raster_dir}{Character. Directory containing environmental raster
files (\code{.tif}), typically the output of
\code{\link{raster_align}} or \code{\link{scale_rasters}}. File names
must follow the patterns supplied in \code{variable_patterns}, with any
time placeholder substituted for the corresponding value from
\code{time_cols}. Required for all methods.}

\item{variable_patterns}{Named character vector mapping clean variable names
to raster filename patterns. For time-varying variables include the time
placeholder in the pattern (e.g. \code{"forest_cover" = "forest_cover_YEAR"});
for static variables omit it (e.g. \code{"elevation" = "elevation"}). Time
placeholders must match entries in \code{time_cols}.}

\item{method}{Character. Pseudoabsence generation method. One of
\code{"random"}, \code{"buffer"}, \code{"environmental"}, or
\code{"user_data"}. Default is \code{"random"}. When \code{"user_data"}
is specified, \code{user_absence_data} is used as the source of absence
locations instead of generating them. \code{ratio}, \code{buffer_distance},
\code{env_percentile}, and \code{pseudoabsence_times} are ignored.
\code{raster_dir} and \code{variable_patterns} are required for all
methods, including \code{"user_data"}, for temporally-matched environmental
extraction at the absence points.}

\item{ratio}{Numeric. Number of pseudoabsence points to generate per
presence point. Default is \code{1}. Values of 2, 10, 50, etc. are
accepted. Points are always distributed proportionally across time steps
within each fold. Set to \code{0} to disable proportional allocation and
use a fixed number of points per time step instead, in which case
\code{min_points_per_timestep} must be greater than 0. \code{ratio} and
\code{min_points_per_timestep} cannot both be 0.}

\item{buffer_distance}{Numeric. Distance in the units of the CRS (typically
meters for projected CRS) within which pseudoabsence points are sampled.
Required when \code{method = "buffer"}. When \code{method =
"environmental"}, supplying a value automatically applies a spatial buffer
constraint before environmental profiling, following the three-step approach
of Senay et al. (2013). If \code{NULL} for the environmental method, no
spatial constraint is applied. Default is \code{NULL}.}

\item{env_percentile}{Numeric between 0 and 1. Quantile threshold used to
define the boundary of the known environmental tolerance when
\code{method = "environmental"}. Environmental cells within this quantile
range across all variables are excluded from pseudoabsence sampling.
Default is \code{0.05} (5th to 95th percentile envelope).}

\item{time_cols}{Character or character vector. Name of the column(s)
containing the time step values. Must match \code{time_cols} used in
\code{\link{spatiotemporal_partition}} and the time placeholders used
in \code{variable_patterns}. Default is \code{NULL}.}

\item{pseudoabsence_times}{Vector. Optional vector of specific time step
values (for the first time column) at which to generate pseudoabsences.
When \code{NULL} (default), all time steps present in the occurrence data
are used.}

\item{min_points_per_timestep}{Integer. Minimum number of pseudoabsence
points to generate per time step per fold. Default is \code{1}. When
\code{ratio = 0}, this value sets the exact (fixed) number of points
generated per time step per fold, independent of the number of
presence points. \code{ratio} and \code{min_points_per_timestep} cannot
both be 0.}

\item{user_absence_data}{Character, sf object, sfc object, Spatial object,
or data frame. Path to occurrence data (\code{.csv}, \code{.shp},
\code{.geojson}, \code{.gpkg}) or a spatial object to be processed as absence
data for downstream operations. Required when \code{method = "user_data"}.
Should be preprocessed with \code{\link{spatiotemporal_rarefaction}} in the
same formatting as presence data if not already thinned.}

\item{xcol}{Character. Name of the x-coordinate column in \code{user_absence_data}.
Required when when \code{method = "environmental"} and \code{user_absence_data}
is a CSV file or data frame.}

\item{ycol}{Character. Name of the y-coordinate column in \code{user_absence_data}.
Required when when \code{method = "environmental"} and \code{user_absence_data}
is a CSV file or data frame.}

\item{points_crs}{Character or CRS object. CRS of the \code{user_absence_data}.
Required when when \code{method = "environmental"} and
\code{user_absence_data} is a CSV file or data frame.}

\item{create_plot}{Logical. If \code{TRUE} (default), generates diagnostic
plots showing the spatial and temporal distribution of generated
pseudoabsence points alongside presence points.}

\item{plot_by_fold}{Logical. If \code{TRUE}, generates one map per fold. If
\code{FALSE} (default), generates a single combined map.}

\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{output_file}{Character. Optional path to save the result as an
\code{.rds} file. The parent directory will be created if it does not
exist. Default is \code{NULL}.}

\item{verbose}{Logical. If \code{TRUE} (default), prints progress
messages during processing. Includes per-fold and per-time-step
pseudoabsence counts.}
}
\value{
Invisibly returns a list containing:
\itemize{
  \item \code{pseudoabsences}: An sf object of all generated pseudoabsence
    points with columns \code{fold}, \code{temporal_block}, \code{presence}
    (always 0), the time column(s) if provided, and extracted environmental
    variable values matched to each point's time step.
  \item \code{plots}: A named list of recorded plot objects when
    \code{create_plot = TRUE}. Contains \code{temporal_distribution} and
    either \code{spatial_combined} or one \code{spatial_fold_N} entry per
    fold. Plots can be replayed with \code{grDevices::replayPlot()}.
  \item \code{summary}: A data frame summarising points generated per fold
    with columns \code{fold}, \code{n_presences}, \code{n_pseudoabsences},
    and \code{ratio_achieved}.
}
}
\description{
Generates pseudoabsence or background points for each fold produced by
\code{\link{spatiotemporal_partition}}, distributed across time steps
proportionally to the number of presence points in each time step within each
fold. Three generation methods are supported: random sampling within the
study area, buffer-constrained sampling around presence points, and
environmentally biased sampling that targets areas outside the known
environmental tolerance of the species. Additionally, this function can be used
to process user defined absences to work with downflow operations. This may be
any list of points for which a user wants to count as 'absences' in downflow
operations, including negative occupancy surveys, or alternatively surveys for
similar species which may act as pseudoabsences for the presence of the species
of interest.
}
\details{
Generates sets of background data based on user-specified methodology that
can be used as pseudoabsence data for the purposes of training
presence/absence models.

The four generation methods differ in how the absence locations are obtained:
\itemize{
  \item \strong{Random}: Points are sampled uniformly at random from the
    full study area, excluding a negligible buffer around presence locations
    to prevent exact overlap.
  \item \strong{Buffer}: Points are sampled within buffers of radius
    \code{buffer_distance} drawn around all fold presences, clipped to the
    reference shapefile boundary.
  \item \strong{Environmental}: Raster cells whose values fall outside the
    species tolerance envelope in at least one variable are identified as
    candidates. K-means clustering then selects a spatially
    representative subset. If \code{buffer_distance} is supplied the
    environmental filtering is applied only within that buffered region,
    implementing the full three-step approach of Senay et al. (2013).
  \item \strong{User data}: Absence locations are taken directly from
    \code{user_absence_data} to be used when user has a predefined set of
    absense points. Points are assigned to folds by spatial join against the
    partition fold boundaries, with unmatched points routed to
    temporal folds by time value. Environmental values are then extracted
    at the supplied locations using the same time-matched logic as the
    generated methods.
}
}
\examples{
data(tmr_partition_small, package = "TemporalModelR")

scl_dir   <- system.file("extdata/rasters_scaled",
                         package = "TemporalModelR")

ref_file  <- system.file("extdata/rasters_raw/elevation.tif",
                         package = "TemporalModelR")

study_crs <- sf::st_crs(terra::rast(ref_file))

study_area_sf <- sf::st_as_sf(sf::st_as_sfc(
  sf::st_bbox(c(xmin = 0, xmax = 3000, ymin = 0, ymax = 1500),
              crs = study_crs)
))

generate_absences(
  partition_result         = tmr_partition_small,
  reference_shapefile_path = study_area_sf,
  raster_dir               = scl_dir,
  variable_patterns        = c(
    "elevation"    = "elevation",
    "forest_cover" = "forest_cover_YEAR"
  ),
  method                   = "random",
  ratio                    = 1,
  time_cols                = c("year"),
  create_plot              = FALSE,
  verbose                  = FALSE
)
}
\references{
Senay SD, Worner SP, Ikeda T (2013) Novel Three-Step Pseudo-Absence
Selection Technique for Improved Species Distribution Modeling.
PLoS ONE 8(8): e71218.
}
\seealso{
Preprocessing: \code{\link{spatiotemporal_partition}},
  \code{\link{temporally_explicit_extraction}}

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