% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fast.r
\name{fast}
\alias{fast}
\alias{fast,character-method}
\alias{fast,SpatRaster-method}
\alias{fast,SpatVector-method}
\alias{fast,sf-method}
\alias{fast,missing-method}
\alias{fast,numeric-method}
\alias{fast,data.frame-method}
\alias{fast,data.table-method}
\alias{fast,matrix-method}
\title{Create a GRaster or GVector}
\usage{
\S4method{fast}{character}(
  x,
  rastOrVect = NULL,
  levels = TRUE,
  extent = NULL,
  correct = TRUE,
  snap = NULL,
  area = NULL,
  steps = 10,
  dropTable = FALSE,
  resolve = NA,
  verbose = TRUE,
  ...
)

\S4method{fast}{SpatRaster}(x, ...)

\S4method{fast}{SpatVector}(
  x,
  extent = NULL,
  correct = TRUE,
  snap = NULL,
  area = NULL,
  steps = 10,
  dropTable = FALSE,
  resolve = NA,
  verbose = TRUE
)

\S4method{fast}{sf}(
  x,
  extent = NULL,
  correct = TRUE,
  snap = NULL,
  area = NULL,
  steps = 10,
  resolve = NA,
  dropTable = FALSE,
  verbose = TRUE
)

\S4method{fast}{missing}(x, rastOrVect, crs = "")

\S4method{fast}{numeric}(x, crs = "", keepgeom = FALSE)

\S4method{fast}{data.frame}(x, geom = 1:2, crs = "", keepgeom = FALSE)

\S4method{fast}{data.table}(x, geom = 1:2, crs = "", keepgeom = FALSE)

\S4method{fast}{matrix}(x, geom = 1:2, crs = "", keepgeom = FALSE)
}
\arguments{
\item{x}{Any one of:
\itemize{
\item A \code{SpatRaster} raster. Rasters can have one or more layers.
\item A \code{SpatVector} or \code{sf} spatial vector. See especially arguments \code{correct}, \code{area}, \code{snap}, \code{steps}, and \code{verbose}.
\item A character string or a vector of strings with the path(s) and filename(s) of one or more rasters or one vector to be loaded directly into \strong{GRASS}. The function will attempt to ascertain the type of object from the file extension (raster or vector), but it can help to indicate which it is using the \code{rastOrVect} argument if it is unclear. For rasters, see especially argument \code{levels}. For vectors, see especially arguments \code{correct}, \code{resolve}, \code{area}, \code{snap}, \code{steps}, and \code{verbose}.
\item A vector with an even number of numeric values representing longitude/latitude pairs. See arguments \code{geom}, \code{keepgeom}, and \code{crs}.
\item A \code{data.frame}, \code{data.table}, or \code{matrix}: Create a \code{points} \code{GVector}. Two of the columns must represent longitude and latitude. See arguments \code{geom}, \code{keepgeom}, and \code{crs}.
\item Missing: Creates a generic \code{GRaster} or \code{GVector}. You must specify \code{rastOrVect}; for example, \code{fast(rastOrVect = "raster")}. Also see argument \code{crs}.
}}

\item{rastOrVect}{Either \code{NULL} (default), or \code{"raster"} or \code{"vector"}: If \code{x} is a filename, then the function will try to ascertain whether it represents a raster or a vector, but sometimes this will fail. In that case, it can help to specify if the file holds a raster or vector. Partial matching is used.}

\item{levels}{(\code{GRaster}s only): Any of:
\itemize{
\item Logical: If \code{TRUE} (default) and at least one layer of a raster is of type \code{integer}, search for a "levels" file, load it, and attach levels. A levels file will have the same name as the raster file, but end with any of "rdata", "rdat", "rda", "rds", "csv", or "tab" (case will generally not matter). If such a file is not found, no levels will be assigned. The levels file must contain either a \code{data.frame}, \code{data.table}, or \code{list} of \code{data.frame}s or \code{data.table}s, or \code{NULL}.
\item A \code{data.frame}, \code{data.table}, or list of \code{data.frame}s or \code{data.table}s with categories for categorical rasters. The first column of a table corresponds to raster values and must be of type \code{integer}. A subsequent column corresponds to category labels. By default, the second column is assumed to represent labels, but this can be changed with \code{\link[fasterRaster]{activeCat<-}}. Level tables can also be \code{NULL} (e.g., \code{data.fame(NULL)}). You can also assign levels after loading a raster using \code{\link[fasterRaster]{levels<-}}.
\item \code{NULL}: Do not attach a levels table.
#'
}}

\item{extent}{(\code{GVector}s only): Either a \code{NULL} (default), or a \code{GVector}, a \code{SpatVector}, a \code{SpatExtent} object, an \code{sf} vector, a \code{bbox} object, or a numeric vector of 4 values providing a bounding box. If provided, only vector features within this bounding box are imported. If \code{extent} is a numeric vector, the values \emph{must} be in the order west, east, south, north. If \code{NULL}, the entire vector is imported.}

\item{correct}{Logical (\code{GVector}s only): Correct topological issues. See \emph{Details} for more details! By default, this is \code{TRUE}.}

\item{snap}{\code{GVector}s only: Numeric or \code{NULL} (default). The value of \code{snap} indicates how close vertices need to be for them to be shifted to to the same location. Units of \code{snap} are map units (usually meters), or degrees for unprojected CRSs. For lines and polygons vectors, a value of \code{NULL} will invoke an iterative procedure to find an optimal, smallest value of \code{snap}. To turn snapping off, set \code{snap = 0}. See \emph{Details} for more details!}

\item{area}{Polygon \code{GVector}s only: Either a positive numeric value or \code{NULL} (default). Remove polygons with an area smaller than this value. Units of \code{area} are in square meters (regardless of the CRS). If \code{NULL}, then an iterative procedure is used to identify a value of \code{area} that results in a topologically correct polygon vector. For point and lines vectors, this argument is ignored. To turn area removal off, set \code{area = 0}. See \emph{Details} for more details!}

\item{steps}{\code{GVector}s only: A positive integer > 1 (default is 10). When using automatic vector correction (i.e., either \code{snap = NULL} and/or \code{area = NULL}), this is the number of values of \code{snap} and/or \code{area} to try to generate a correct topology, including no snapping or polygon removal (i.e, \code{snap = 0} and \code{area = 0}).}

\item{dropTable}{\code{GVector}s only: Logical. If \code{TRUE}, then drop the data table associated with a vector. By default, this is \code{FALSE}. See \emph{Details} for more details!}

\item{resolve}{\code{GVector}s only: Character. If a \code{GVector} would be topologically invalid after a first attempt at creating it, then this method will be used to resolve the issue and create a valid \code{GVector}. Partial matching is used.
\itemize{
\item \code{"disaggregate"}: Coerce each area of overlap between polygons into its own geometry. The output will not have a data table associated with it.
\item \code{"aggregate"}: Coerce all geometries into a "multipart" geometry so it acts like a single geometry. The output will not have a data table associated with it.
\item \code{NA} (default): Do neither of the above and if either \code{snap} or \code{area} is \code{NULL}, keep trying to create the \code{GVector}. Upon success, the \code{GVector} will retain any data table associated with it unless \code{dropTable} is \code{FALSE}.
}}

\item{verbose}{\code{GVector}s only: Logical. Displays progress when using automatic topology correction.}

\item{...}{Other arguments::
\itemize{
\item \code{table} (\code{GVector}s--useful mainly to developers, not most users): A \code{data.frame} or \code{data.table} with one row per geometry in a \code{GVector}. Serves as an attribute table.
\item \code{xVect} (\code{GVector}s--useful mainly to developers, not most users): The \code{SpatVector} that corresponds to the file named by \code{x}.
}}

\item{crs}{String: Coordinate reference system (CRS) WKT2 string. This argument is used for creating a \code{GVector} from a \code{numeric} vector or a \code{data.frame} or similar, or from \code{fast(rastOrVect = "vector")} or \code{fast(rastOrVect = "raster")}. By default, the function will use the value of \code{\link[=crs]{crs()}} (no arguments), which is the CRS of the current \strong{GRASS} "project/location" (see \code{vignette("projects_mapsets", package = "fasterRaster")}).}

\item{keepgeom}{Logical: If \code{x} is a set of \code{numeric} coordinates, or a \code{data.frame} or similar, then they can be coerced into a \code{points} \code{GVector}. If \code{keepgeom} is \code{TRUE}, then the coordinates will be included in the data table of the \code{GVector}. The default is \code{FALSE}.}

\item{geom}{Character or integer vector: If \code{x} is a \code{data.frame}, \code{data.table}, or \code{matrix}, this specifies which columns of \code{x} represent longitude and latitude. Columns can be given by name (a character vector) or index (a numeric or integer vector). The default is to use the first two columns of \code{x}.}
}
\value{
A \code{GRaster} or \code{GVector}.
}
\description{
\code{fast()} creates a \code{GRaster} or \code{GVector} from 1) a file; 2) from a \code{SpatRaster}, \code{SpatVector}, or \code{sf} vector; or 3) from a numeric vector, \code{matrix}, \code{data.frame}, or \code{data.table}. Behind the scenes, this function will also create a connection to \strong{GRASS} if none has yet been made yet.

\strong{GRASS} supports loading from disk a variety of raster formats (see the \strong{GRASS} manual page for \code{r.in.gdal} (see \code{grassHelp("r.in.gdal")}) and vector formats \code{v.in.ogr} (see grassHelp("v.in.ogr")`), though not all of them will work with this function.

Note that \code{GVectors} may fail to be created if they contain issues that do not coincide with the topological data model used by \strong{GRASS}. The most common of these is overlapping polygons. See \emph{Details} on how to fix these kinds of issues.

Note also that \strong{GRASS} (and thus, \strong{fasterRaster}) is \emph{not} very fast when loading vectors. So, if the vector is large and you only want a portion of it, consider using the \code{extent} argument to load the spatial subset you need.
}
\details{
\strong{GRASS} uses a "topological" model for vectors. Topological issues generally arise only with polygon vectors, not point or line vectors. Sometimes, polygons created in other software are topologically incorrect--the borders of adjacent polygons may cross one another, or there may be small gaps between them. These errors can be corrected by slightly shifting vertices and/or removing small polygons that result from intersections of larger ones that border one another. A topological system also recognizes that boundaries to adjacent polygons are shared by the areas, so should not be ascribed attributes that belong to both areas (e.g., the shared border between two countries "belongs" to both countries).

By default, \code{fast()} will try to correct topological errors in vectors. There are three levels of correction, and they are not necessarily mutually exclusive:
\enumerate{
\item \strong{Automatic correction}: By default, \code{fast()} will apply automatic topology correction. You can turn this off using the \code{correct = FALSE} argument, though in most cases this is not recommended.
\item \strong{\emph{Manual} snapping and/or area removal}: In addition to correction from step 1, you can cause vertices of polygons close to one another to be "snapped" to same place and/or polygons that are smaller than some threshold to be removed. Problems with mis-aligned vertices arise when adjacent polygons are meant to share borders, but slight differences in the locations of the vertices cause them to  mis-align. This mis-alignment can also produce small "slivers" of polygons that are the areas where they overlap. You can snap vertices within a given distance of one another using the \code{snap} argument followed by a numeric value, like \code{snap = 0.000001}. Units of \code{snap} are in map units (usually meters) for projected coordinate reference systems and degrees for unprojected systems (e.g., WGS84, NAD83, NAD27). You can also remove polygons that are smaller than a particular area using the \code{area} argument followed by a numeric value (e.g., \code{area = 1}). The units of \code{area} are in meters-squared, regardless of the coordinate reference system. Note that using \code{snap} and \code{area} entails some risk, as it is possible for nearby vertices to actually be distinct and for small areas to be legitimate.
\item \strong{Automatic snapping and/or area removal}: In addition to the correction from step 1, you can use automatic \code{snap} and/or \code{area} correction on polygons vectors by setting \code{snap} and/or \code{area} to \code{NULL} (i.e., their default values). If just \code{snap} is \code{NULL}, only automatic snapping will be performed, and if just \code{area} is \code{NULL}, then only automatic area removal will be performed. Regardless, you will also need to set an integer value for \code{steps}, which is the number of steps to take between the smallest value of \code{snap} and/or \code{area} and the maximum value attempted. The function will then proceed by first attempting \code{snap = 0} and/or \code{area = 0} (i.e., no snapping or area removal). If this does not produce a topologically correct vector, \strong{GRASS} will (internally) suggest a range for \code{snap}. The \code{fast()} function then creates \code{steps} values from the lowest to the highest values of this range evenly-spaced along the log values of this range, then proceed to repeat the importing process until either the vector is imported correctly or the maximum value of \code{snap} is reached and results in a failed topology. Smaller values of \code{step} will result in more fine-grained attempts so are less likely to yield overcorrection, but can also take more time. The value of \code{area} in automatic correction is set to \code{snap^2}. \strong{NB}: Automated snapping and area removal are only performed on polygons vectors, even if \code{snap} or \code{area} is \code{NULL}. To snap lines or points, you must set \code{snap} equal to a numeric value. The \code{area} correction is ignored for points and lines.
}

Issues can also arise due to:
\itemize{
\item \strong{Data table-vector mismatching}: If your vector has a data table ("attribute table") associated with it, errors can occur if there are more/fewer geometries (or multi-geometries) per row in the table. If you do not really need the data table to do your analysis, you can remove it (and thus obviate this error) using \code{dropTable = TRUE}.
\item \strong{Dissolving or aggregating "invalid" geometries}: Using the \code{resolve} argument, you can create a topologically valid vector by either coercing all overlapping portions of polygons into their own geometries (\code{resolve = "disaggregate"}), or by coercing them into a single, combined geometry (\code{resolve = "aggregate"}). Aggregation/disaggregation will be implemented after loading the vector into \strong{GRASS} using the settings given by \code{snap} and \code{area}. Aggregation/disaggregation will cause any associated data table to be dropped (it forces \code{dropTable} to be \code{TRUE}). The default action is to do neither aggregation nor disaggregation (\code{resolve = NA}). You can also do this outside \strong{fasterRaster} using \code{\link[terra:aggregate]{terra::aggregate()}} or \code{\link[terra:disaggregate]{terra::disagg()}}.
}

If none of these fixes work, you can try:
\itemize{
\item \strong{Correction outside of \emph{fasterRaster}}: Before you convert the vector into \strong{fasterRaster}'s \code{GVector} format, you can also try using the \code{\link[terra:is.valid]{terra::makeValid()}} or \code{\link[sf:valid]{sf::st_make_valid()}} tools to fix issues, then use \code{fast()}. You can also use \code{\link[terra:aggregate]{terra::aggregate()}} or \code{\link[terra:disaggregate]{terra::disagg()}} to combine/split problematic geometries.
\item \strong{Post-load correction}: If you do get a vector loaded into \code{GVector} format, you can also use a set of \strong{fasterRaster} vector-manipulation \link[=breakPolys]{tools} or \code{\link[=fillHoles]{fillHoles()}} to fix issues.
}
}
\examples{
if (grassStarted()) {

# Setup
library(sf)
library(terra)

# Example data
madElev <- fastData("madElev") # integer raster
madCover <- fastData("madCover") # categorical raster
madCoast4 <- fastData("madCoast4") # polygons vector
madRivers <- fastData("madRivers") # lines vector
madDypsis <- fastData("madDypsis") # points vector

### Create GRasters from SpatRasters

# Create an integer raster:
elev <- fast(madElev)
elev

# Create a categorical raster:
cover <- fast(madCover)
madCover
levels(madCover) # category levels

# Create a GRaster from a file on disk:
rastFile <- system.file("extdata", "madForest2000.tif", package = "fasterRaster")
forest2000 <- fast(rastFile)
forest2000

# Create a 1's raster that spans the world:
ones <- fast(rastOrVect = "raster", crs = "epsg:4326")
ones

### Create GVectors

# Create a GVector from an sf vector:
coast4 <- fast(madCoast4)
coast4

# Create a GVector from a SpatVector:
madRivers <- vect(madRivers)
class(madRivers)
rivers <- fast(madRivers)
rivers

# Create a GVector from a vector on disk:
vectFile <- system.file("extdata/shapes", "madCoast.shp",
   package = "fasterRaster")
coast0 <- fast(vectFile)
coast0

# Import only Dypsis occurrences in a restricted area:
ant <- coast4[coast4$NAME_4 == "Antanambe"]
dypsisRestrict <- fast(madDypsis, extent = ant)
dypsis <- fast(madDypsis)

plot(coast4)
plot(ant, col = "gray80", add = TRUE)
plot(dypsis, add = TRUE)
plot(dypsisRestrict, col = "red", add = TRUE)

# Create a generic GVector that spans the world:
wallToWall <- fast(rastOrVect = "vector", crs = "epsg:4326") # WGS84
wallToWall

# Create a GVector from a numeric vector
pts <- c(-90.2, 38.6, -122.3, 37.9)
pts <- fast(pts, crs = "epsg:4326") # WGS84

# Create a GVector from a matrix (can also use data.frame or data.table):
mat <- matrix(c(-90.2, 38.6, -122.3, 37.9), ncol = 2, byrow = TRUE)
mat <- fast(mat, crs = "epsg:4326", keepgeom = TRUE) # WGS84

}
}
\seealso{
\code{\link[rgrass]{read_RAST}} and \code{\link[rgrass]{read_VECT}}, \link[=breakPolys]{vector cleaning}, \code{\link[=fillHoles]{fillHoles()}}, plus \strong{GRASS} modules \code{v.in.ogr} (see \code{grassHelp("v.in.ogr")}) and \code{r.import} (\code{grassHelp("r.import")})
}
