% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/griddata_class.R
\name{grid}
\alias{grid}
\title{An rts grid object}
\description{
An rts grid object

An rts grid object
}
\details{
An rts grid object is an R6 class holding the spatial data with data, model fitting, and analysis functions.

\strong{INTRODUCTION}

The various methods of the class include examples and details of their implementation. The \pkg{sf} package is used for
all spatial data. A typical workflow with this class would
be:
\enumerate{
\item Create a new grid object. The class is initialized with either a single polygon describing the area of interest or a collection
of polygons if spatially aggregated data are used.
\item If the location (and times) of cases are available (i.e. the data are not spatially aggregated), then we map the points to the computational
grid. The function \link[rts2]{create_points} can generate point data in the correct \pkg{sf} format. The member function \code{points_to_grid} will then
map these data to the grid. Counts can also be manually added to grid data. For region data, since the counts are assumed to be already aggregated, these
must be manually provided by the user. The case counts must appear in columns with specific names. If there is only a single time period then the counts
must be in a column named \code{y}. If there are multiple time periods then the counts must be in columns names \code{t1}, \code{t2}, \code{t3},... Associated columns labelled
\code{date1}, \code{date2}, etc. will permit use of some functionality regarding specific time intervals.
\item If any covariates are to be used for the modelling, then these can be mapped to the compuational grid using the function \code{add_covariates()}. Other
functions, \code{add_time_indicators()} and \code{get_dow()} will also generate relevant temporal indicators where required. At a minimum we would recommend including
a measure of population density.
\item Fit a model. There are multiple methods for model fitting, which are available through the member functions \code{lgcp_ml()} and \code{lgcp_bayes()} for maximum likelihood
and Bayesian approaches, respectively. The results are stored internally and optionally returned as a \code{rtsFit} object.
\item Summarise the output. The main functions for summarising the output are \code{extract_preds()}, which will generate predictions of relative risk, incidence rate
ratios, and predicted incidence, and \code{hotspots()}, which will estimate probabilities that these statistics exceed given thresholds. For spatially-aggregated data models,
the relative risk applies to the grid, whereas rate ratios and predicted incidence applies to the areas.
\item Predictions can be visualised or aggregated to relevant geographies with the \code{plot()} and \code{aggregate()} functions.
}
Specific details of the implementation of each of these functions along with examples appear below.

\strong{PLOTTING}

If \code{zcol} is not specified then only the geometry is plotted, otherwise the covariates specified will be plotted.
The user can also use sf plotting functions on self$grid_data and self$region_data directly.

\strong{POINTS TO GRID}

Given the sf object with the point locations and date output from
\code{create_points()}, the functions will add columns to \code{grid_data} indicating
the case count in each cell in each time period.

Case counts are generated for each grid cell for each time period. The user
can specify the length of each time period; currently \code{day}, \code{week}, and \code{month}
are supported.

The user must also specify the number of time periods to include with the
\code{laglength} argument. The total number of time periods is the specified lag
length counting back from the most recent case. The columns in the output
will be named \code{t1}, \code{t2},... up to the lag length, where the highest number
is the most recent period.

\strong{ADDING COVARIATES}

\emph{Spatially-varying data only}

\code{cov_data} is an object describing covariate over the area of interest.
sf, RasterLayer and SpatRaster objects are supported, with rasters converted internally to sf.
The mapping can use a spatially-smoothed method (pynchophylatic) or a variance or entropy minimising
method or a simple "flat" mapping using only the weighted average of intersections between the grid and
covariate polygons. For non-"flat" mapping,  \code{lambda_smooth} controls the degree of spatial smoothing - if set to zero then no spatial smoothing
is used. The argument \code{lambda_e} adds a small amount to reduce numerical instability. One can also map strictly positive covariates (e.g. population density)
by setting the \code{is_positive} argument to true. In this case, \code{lambda_e} is used to add an entropy minimising criterion (instead of, or in addition to)
spatial smoothing crtierion. If population density information, then this can be accounted for in the smoothing by setting
\code{weight_type} to \code{pop} and specifying the name of covariate to \code{popdens}, which should be on the grid.

\emph{Temporally-varying only data}

\code{cov_data} is a data frame with number of rows
equal to the number of time periods. One of the columns must be called \code{t} and
have values from 1 to the number of time periods. The other columns of the data
frame have the values of the covariates for each time period. See
\code{get_dow()} for day of week data. A total of
length(zcols)*(number of time periods) columns are added to the output: for each
covariate there will be columns appended with each time period number. For example,
\code{dayMon1}, \code{dayMon2}, etc.

\emph{Spatially and temporally varying data}

There are two ways to add data that
vary both spatially and temporally. The final output for use in analysis must
have a column for each covariate and each time period with the same name appended
by the time period number, e.g. \code{covariateA1},\code{covariateA2},... If the covariate
values for different time periods are in separate sf objects, one can follow
the method for spatially-varying only data above and append the time period number
using the argument \code{t_label}. If the values for different time periods are in the same
sf object then they should be named as described above and then can be added
as for spatially-varying covariates, e.g. \code{zcols=c("covariateA1","covariateA2")}.

\strong{BAYESIAN MODEL FITTING}

The grid data must contain columns \verb{t*}, giving the case
count in each time period (see \code{points_to_grid}), or a column \code{y} in single time period cases, as well as any covariates to include in the model
(see \code{add_covariates}). If the population density is not provided it is set to one. If the data are regional data, then the outcome
counts must be in self$region_data

The statistical model is a Log Gaussian cox process,
whose realisation is observed on the Cartesian area of interest
A and time period T. The resulting data are relaisations of an inhomogeneous
Poisson process with stochastic intensity function \eqn{\{\lambda{s,t}:s\in A, t \in T\}}.
We specify a log-linear model for the intensity:

\deqn{\lambda(s,t) = r(s,t)exp(X(s,t)'\gamma + Z(s,t))}

where r(s,t) is a spatio-temporally varying Poisson offset.
X(s,t) is a length Q vector of covariates including an intercept and
Z(s,t) is a latent field. We use an auto-regressive specification for the
latent field, with spatial innovation in each field specified as a spatial
Gaussian process.

The argument \code{approx} specifies whether to use a full LGCP model (\code{approx='none'}) or whether
to use either a nearest neighbour approximation (\code{approx='nngp'}) or a "Hilbert space" approximation
(\code{approx='hsgp'}). For full details of NNGPs see XX and for Hilbert space approximations see references (1) and (2).

\emph{Priors}

For Bayesian model fitting, the priors should be provided as a list to the griddata object:

\if{html}{\out{<div class="sourceCode">}}\preformatted{griddata$priors <- list(
  prior_lscale=c(0,0.5),
  prior_var=c(0,0.5),
  prior_linpred_mean=c(-5,rep(0,7)),
  prior_linpred_sd=c(3,rep(1,7))
)
}\if{html}{\out{</div>}}

where these refer to the priors:
\code{prior_lscale}: the length scale parameter has a half-normal prior \eqn{N(a,b^2)I[0,\infty)}. The vector is \code{c(a,b)}.
\code{prior_var}: the standard deviation term has a half normal prior \eqn{\sigma ~ N(a,b^2)I[0,\infty)}. The vector is \code{c(a,b)}.
\code{prior_linpred_mean} and \code{prior_linpred_sd}: The parameters of the linear predictor.
If X is the nT x Q matrix of covariates, with the first column as ones for the intercept,
then the linear prediction contains the term \eqn{X'\gamma}. Each parameter in \eqn{\gamma} has prior
\eqn{\gamma_q ~ N(a_q,b_q^2)}.
\code{prior_linpred_mean} should be the vector \verb{(a_1,a_2,...,a_Q)} and
\code{prior_linpred_sd} should be \verb{(b_1,b_2,...,b_Q)}.

\strong{MAXIMUM LIKELIHOOD MODEL FITTING}

The grid or region data must contain columns \verb{t*}, giving the case
count in each time period (see \code{points_to_grid}), or \code{y} if single time period, as well as any covariates to include in the model
(see \code{add_covariates}). If a population density variable is not provided it is set to one. If the data are regional data then the outcome
counts must be in self$region_data. See \code{lgcp_bayes()} for Bayesian approaches to model fitting and more details on the model.

Model fitting uses a fast stochastic maximum likelihood algorithms, which have three steps:
\enumerate{
\item Sample random effects. The argument \code{iter_sampling} specifies the iterations for this step.
\item Fit fixed effect parameters using a Newton-Raphson step.
\item Fit covariance parameters using a Newton-Raphson step.
}

The algorithm uses Bayes Factor termination criterion to measure the evidence of convergence. The algorithm terminates when
the Bayes Factor is greater than \code{tol} (default is 10). The prior is based on the expected number of iterations until convergence,
given by \code{k0} (defaul is 10).

\strong{EXTRACTING PREDICTIONS}

Three outputs can be extracted from the model fit, which will be added as columns to \code{grid_data}:

Predicted incidence: If type includes \code{pred} then \code{pred_mean_total} and
\code{pred_mean_total_sd} provide the
predicted mean total incidence and its standard deviation, respectively.
\code{pred_mean_pp} and \code{pred_mean_pp_sd} provide the predicted population
standardised incidence and its standard deviation.

Relative risk: if type includes \code{rr} then the relative risk is reported in
the columns \code{rr} and \code{rr_sd}. The relative risk here is the exponential
of the latent field, which describes the relative difference between
expexted mean and predicted mean incidence.

Incidence risk ratio: if type includes \code{irr} then the incidence rate ratio (IRR)
is reported in the columns \code{irr} and \code{irr_sd}. This is the ratio of the predicted
incidence in the last period (minus \code{t_lag}) to the predicted incidence in the
last period minus \code{irr_lag} (minus \code{t_lag}). For example, if the time period
is in days then setting \code{irr_lag} to 7 and leaving \code{t_lag=0} then the IRR
is the relative change in incidence in the present period compared to a week
prior.
}
\examples{

## ------------------------------------------------
## Method `grid$new`
## ------------------------------------------------

# a simple example with a square and a small number of cells
# this same running example is used for the other functions 
b1 = sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)

# an example with multiple polygons
data("birmingham_crime")
g2 <- grid$new(birmingham_crime,cellsize = 1000)

## ------------------------------------------------
## Method `grid$plot`
## ------------------------------------------------

b1 = sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
g1$plot()

# a plot with covariates - we simulate covariates first
g1$grid_data$cov <- stats::rnorm(nrow(g1$grid_data))
g1$plot("cov")

## ------------------------------------------------
## Method `grid$points_to_grid`
## ------------------------------------------------

b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
# simulate some points
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20)) 
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
g1$points_to_grid(dp, laglength=5)

## ------------------------------------------------
## Method `grid$add_covariates`
## ------------------------------------------------

b1 <-  sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
cov1 <- grid$new(b1,0.8)
cov1$grid_data$cov <- runif(nrow(cov1$grid_data))
g1$add_covariates(cov1$grid_data,
                  zcols="cov")

\donttest{
# mapping population data from some other polygons
data("boundary")
data("birmingham_crime")
g2 <- grid$new(boundary,cellsize=0.008)
msoa <- sf::st_transform(birmingham_crime,crs = 4326)
suppressWarnings(sf::st_crs(msoa) <- sf::st_crs(g2$grid_data)) # ensure crs matches
g2$add_covariates(msoa,
                  zcols="pop",
                  weight_type="area")
                  
# add a case count                  
g2$add_covariates(msoa,
                  zcols=c("t1"),
                  weight_type="area",
                  is_positive = TRUE,
                  lambda_smooth = 0,
                  lambda_e = 1e-6)

g2$grid_data$t1 <- round(g2$grid_data$t1,0)
g2$plot("pop")
}

## ------------------------------------------------
## Method `grid$get_dow`
## ------------------------------------------------

b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20))
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
g1$points_to_grid(dp, laglength=5)
dow <- g1$get_dow()
g1$add_covariates(dow,zcols = colnames(dow)[3:ncol(dow)])

## ------------------------------------------------
## Method `grid$lgcp_bayes`
## ------------------------------------------------

# the data are just random simulated points 
b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20))
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
cov1 <- grid$new(b1,0.8)
cov1$grid_data$cov <- runif(nrow(cov1$grid_data))
g1$add_covariates(cov1$grid_data,
                  zcols="cov")
g1$points_to_grid(dp, laglength=5)
g1$priors <- list(
  prior_lscale=c(0,0.5),
  prior_var=c(0,0.5),
  prior_linpred_mean=c(0),
  prior_linpred_sd=c(5)
  )
\donttest{
g1$lgcp_bayes(popdens="cov", approx = "hsgp", parallel_chains = 0)
g1$model_fit()
# we can extract predictions
g1$extract_preds("rr")
g1$plot("rr")
g1$hotspots(threshold = 2, stat = "rr")

 # this example uses real aggregated data but will take a relatively long time to run
 data("birmingham_crime")
 example_data <- birmingham_crime[,c(1:8,21)]
 example_data$y <- birmingham_crime$t12
 g2 <- grid$new(example_data,cellsize=1000)
 g2$priors <- list(
  prior_lscale=c(0,0.5),
  prior_var=c(0,0.5),
  prior_linpred_mean=c(-3),
  prior_linpred_sd=c(5)
)
g2$lgcp_bayes(popdens="pop", approx = "hsgp", parallel_chains = 0)
g2$model_fit()
g2$extract_preds("rr")
g2$plot("rr")
g2$hotspots(threshold = 2, stat = "rr")
}

## ------------------------------------------------
## Method `grid$lgcp_ml`
## ------------------------------------------------

# a simple example with simulated points using SPDE approximation
boundary <- st_set_crs(boundary, 4326)
g1 <- grid$new(boundary,cellsize=0.01)
g1$points_to_grid(point_data = create_points(example_points,
                                             pos_vars = c("Y","X")))
\donttest{
msoa <- sf::st_transform(birmingham_crime,crs = 4326)
g1$add_covariates(msoa,zcols="pop",weight_type="area")
set.seed(2345)
fit_spde <- g1$lgcp_ml("pop", model = "hsgp_matern1")
g1$extract_preds(type = c("rr"), popdens = "pop")
g1$plot("rr")


# this example uses real aggregated spatial data
# note that the full dataset has 12 time periods
# and can be used as a spatio-temporal example by removing
# the lines marked # spatial 
 data("birmingham_crime")
 example_data <- birmingham_crime[,c(1:8,21)] # spatial
 example_data$y <- birmingham_crime$t12 # spatial
 example_data <- sf::st_transform(example_data, crs = 4326)
 g2 <- grid$new(example_data,cellsize=0.006)
 set.seed(123)
 g2$lgcp_ml(popdens = "pop", model = "hsgp_matern1", L = 1.5, m = c(15,15))
 g2$extract_preds("rr")
 g2$plot("rr")
 
 #SPDE verison rescale to more stable coordinates
g2$transform(scale_factor = 50)
set.seed(101)
fitt <- suppressWarnings(g2$lgcp_ml("pop", model = "spde_matern1")) # use default mesh args
g2$extract_preds("rr")
g2$plot("rr")
}

## ------------------------------------------------
## Method `grid$extract_preds`
## ------------------------------------------------

# See examples for lgcp_bayes() and lgcp_ml()

## ------------------------------------------------
## Method `grid$hotspots`
## ------------------------------------------------

\dontrun{
# See examples for lgcp_bayes() and lgcp_ml()
}

## ------------------------------------------------
## Method `grid$aggregate_output`
## ------------------------------------------------

\donttest{
b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20))
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
cov1 <- grid$new(b1,0.8)
cov1$grid_data$cov <- runif(nrow(cov1$grid_data))
g1$add_covariates(cov1$grid_data,
                  zcols="cov")
g1$points_to_grid(dp, laglength=5)
g1$priors <- list(
  prior_lscale=c(0,0.5),
  prior_var=c(0,0.5),
  prior_linpred_mean=c(0),
  prior_linpred_sd=c(5)
  )
res <- g1$lgcp_bayes(popdens="cov", parallel_chains = 1)
g1$extract_preds(res,
                 type=c("pred","rr"),
                 popdens="cov")
new1 <- g1$aggregate_output(cov1$grid_data,
                            zcols="rr")
}

## ------------------------------------------------
## Method `grid$scale_conversion_factor`
## ------------------------------------------------

b1 = sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
g1$scale_conversion_factor()
}
\references{
(1) Solin A, Särkkä S. Hilbert space methods for reduced-rank Gaussian
process regression. Stat Comput. 2020;30:419–46.
doi:10.1007/s11222-019-09886-w.

(2) Riutort-Mayol G, Bürkner P-C, Andersen MR, Solin A, Vehtari A.
Practical Hilbert space approximate Bayesian Gaussian processes for
probabilistic programming. Stat Comput. 2023;33:17.
doi:10.1007/s11222-022-10167-2.
}
\seealso{
\link[rts2]{create_points}

points_to_grid, add_covariates

points_to_grid, add_covariates
}
\section{Public fields}{
\if{html}{\out{<div class="r6-fields">}}
\describe{
\item{\code{grid_data}}{sf object specifying the computational grid for the analysis}

\item{\code{point_data}}{sf object with the event locations}

\item{\code{region_data}}{sf object specifying an irregular lattice, such as census areas,
within which case counts are aggregated. Only used if polygon data are provided on
class initialisation.}

\item{\code{priors}}{list of prior distributions for the analysis}

\item{\code{boundary}}{sf object showing the boundary of the area of interest}
}
\if{html}{\out{</div>}}
}
\section{Methods}{
\subsection{Public methods}{
\itemize{
\item \href{#method-grid-new}{\code{grid$new()}}
\item \href{#method-grid-print}{\code{grid$print()}}
\item \href{#method-grid-transform}{\code{grid$transform()}}
\item \href{#method-grid-plot}{\code{grid$plot()}}
\item \href{#method-grid-points_to_grid}{\code{grid$points_to_grid()}}
\item \href{#method-grid-model_data_frame}{\code{grid$model_data_frame()}}
\item \href{#method-grid-add_covariates}{\code{grid$add_covariates()}}
\item \href{#method-grid-get_dow}{\code{grid$get_dow()}}
\item \href{#method-grid-add_time_indicators}{\code{grid$add_time_indicators()}}
\item \href{#method-grid-lgcp_bayes}{\code{grid$lgcp_bayes()}}
\item \href{#method-grid-lgcp_ml}{\code{grid$lgcp_ml()}}
\item \href{#method-grid-extract_preds}{\code{grid$extract_preds()}}
\item \href{#method-grid-hotspots}{\code{grid$hotspots()}}
\item \href{#method-grid-aggregate_output}{\code{grid$aggregate_output()}}
\item \href{#method-grid-scale_conversion_factor}{\code{grid$scale_conversion_factor()}}
\item \href{#method-grid-build_spde_data}{\code{grid$build_spde_data()}}
\item \href{#method-grid-get_region_data}{\code{grid$get_region_data()}}
\item \href{#method-grid-variogram}{\code{grid$variogram()}}
\item \href{#method-grid-reorder}{\code{grid$reorder()}}
\item \href{#method-grid-data}{\code{grid$data()}}
\item \href{#method-grid-get_random_effects}{\code{grid$get_random_effects()}}
\item \href{#method-grid-model_fit}{\code{grid$model_fit()}}
\item \href{#method-grid-clone}{\code{grid$clone()}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-new"></a>}}
\if{latex}{\out{\hypertarget{method-grid-new}{}}}
\subsection{Method \code{new()}}{
Create a new grid object

Produces a regular grid over an area of interest as an sf object, see details for information on initialisation. If the model is
fit using maximum likelihood with SPDE approximation the grid is only used for prediction and interpolation of covariates.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$new(poly, cellsize, verbose = TRUE)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{poly}}{An sf object containing either one polygon describing the area of interest or multiple polygons
representing survey or census regions in which the case data counts are aggregated}

\item{\code{cellsize}}{The dimension of the grid cells}

\item{\code{verbose}}{Logical indicating whether to provide feedback to the console.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
NULL
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{# a simple example with a square and a small number of cells
# this same running example is used for the other functions 
b1 = sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)

# an example with multiple polygons
data("birmingham_crime")
g2 <- grid$new(birmingham_crime,cellsize = 1000)
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-print"></a>}}
\if{latex}{\out{\hypertarget{method-grid-print}{}}}
\subsection{Method \code{print()}}{
Prints this object
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$print()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
None. called for effects.
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-transform"></a>}}
\if{latex}{\out{\hypertarget{method-grid-transform}{}}}
\subsection{Method \code{transform()}}{
Reproject coordinates of spatial data in the object to a new CRS
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$transform(crs, scale_factor)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{crs}}{target coordinate reference system passed to \code{st_transform}}

\item{\code{scale_factor}}{A scale factor to multiply existing geometry by.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
None, called for effects
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-plot"></a>}}
\if{latex}{\out{\hypertarget{method-grid-plot}{}}}
\subsection{Method \code{plot()}}{
Plots the grid data
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$plot(zcol)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{zcol}}{Vector of strings specifying names of columns of \code{grid_data} to plot}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
A plot
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{b1 = sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
g1$plot()

# a plot with covariates - we simulate covariates first
g1$grid_data$cov <- stats::rnorm(nrow(g1$grid_data))
g1$plot("cov")
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-points_to_grid"></a>}}
\if{latex}{\out{\hypertarget{method-grid-points_to_grid}{}}}
\subsection{Method \code{points_to_grid()}}{
Generates case counts of points over the grid

Counts the number of cases in each time period in each grid cell
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$points_to_grid(
  point_data,
  t_win = c("day"),
  laglength = 14,
  date_format = "ymd",
  verbose = TRUE
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{point_data}}{sf object describing the point location of cases with a column
\code{t} of the date of the case in YYYY-MM-DD format. See \link[rts2]{create_points}}

\item{\code{t_win}}{character string. One of "day", "week", or "month" indicating the
length of the time windows in which to count cases}

\item{\code{laglength}}{integer The number of time periods to include counting back from the most
recent time period}

\item{\code{date_format}}{String describing the format of the date in the data as a combination of "d" days, "m" months,
and "y" years, either "dmy", "myd", "ymd", "ydm", "dym" "mdy" as used by the lubridate package.}

\item{\code{verbose}}{Logical indicating whether to report detailed output}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
NULL
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
# simulate some points
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20)) 
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
g1$points_to_grid(dp, laglength=5)
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-model_data_frame"></a>}}
\if{latex}{\out{\hypertarget{method-grid-model_data_frame}{}}}
\subsection{Method \code{model_data_frame()}}{
Returns a data frame with the grid data and coordinates

Returns a standard data frame with the grid data and coordinates, which may be useful to
run models in another package.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$model_data_frame()}\if{html}{\out{</div>}}
}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-add_covariates"></a>}}
\if{latex}{\out{\hypertarget{method-grid-add_covariates}{}}}
\subsection{Method \code{add_covariates()}}{
Adds covariate data to the grid

Maps spatial, temporal, or spatio-temporal covariate data onto the grid using different methods.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$add_covariates(
  cov_data,
  zcols,
  weight_type = "area",
  popdens = NULL,
  t_label = NULL,
  flat = TRUE,
  lambda_smooth = 1,
  lambda_e = 1e-06,
  is_positive = FALSE
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{cov_data}}{sf, RasterLayer, SpatRaster object or a data.frame. See details.}

\item{\code{zcols}}{vector of character strings with the names of the columns of \code{cov_data}
to include}

\item{\code{weight_type}}{character string. Either "area" for area-weighted average or "pop"
for population-weighted average}

\item{\code{popdens}}{character string. The name of the column in \code{cov_data} with the
population density. Required if weight_type="pop"}

\item{\code{t_label}}{integer. If adding spatio-temporally varying data by time period,
this time label should be appended to the column name. See details.}

\item{\code{flat}}{Logical indicating if the disaggregation should be flat and just a weighted average over intersections. Cannot be strictly positive.}

\item{\code{lambda_smooth}}{weight on spatial smoothness, used if \code{flat} is FALSE}

\item{\code{lambda_e}}{small ridge for numerical stability (needed because L is singular), or for
strictly positive covariates, the weight on entropy in the minimisation.}

\item{\code{is_positive}}{Logical. Should the disaggregation be strictly positive.}

\item{\code{verbose}}{logical. Whether to provide a progress bar}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
NULL
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{b1 <-  sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
cov1 <- grid$new(b1,0.8)
cov1$grid_data$cov <- runif(nrow(cov1$grid_data))
g1$add_covariates(cov1$grid_data,
                  zcols="cov")

\donttest{
# mapping population data from some other polygons
data("boundary")
data("birmingham_crime")
g2 <- grid$new(boundary,cellsize=0.008)
msoa <- sf::st_transform(birmingham_crime,crs = 4326)
suppressWarnings(sf::st_crs(msoa) <- sf::st_crs(g2$grid_data)) # ensure crs matches
g2$add_covariates(msoa,
                  zcols="pop",
                  weight_type="area")
                  
# add a case count                  
g2$add_covariates(msoa,
                  zcols=c("t1"),
                  weight_type="area",
                  is_positive = TRUE,
                  lambda_smooth = 0,
                  lambda_e = 1e-6)

g2$grid_data$t1 <- round(g2$grid_data$t1,0)
g2$plot("pop")
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-get_dow"></a>}}
\if{latex}{\out{\hypertarget{method-grid-get_dow}{}}}
\subsection{Method \code{get_dow()}}{
Generate day of week data

Create data frame with day of week indicators

Generates a data frame with indicator
variables for each day of the week for use in the \code{add_covariates()} function.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$get_dow()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
data.frame with columns \code{t}, \code{day}, and \code{dayMon} to \code{daySun}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20))
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
g1$points_to_grid(dp, laglength=5)
dow <- g1$get_dow()
g1$add_covariates(dow,zcols = colnames(dow)[3:ncol(dow)])
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-add_time_indicators"></a>}}
\if{latex}{\out{\hypertarget{method-grid-add_time_indicators}{}}}
\subsection{Method \code{add_time_indicators()}}{
Adds time period indicators to the data

Adds indicator variables for each time period to the data. To include
these in a model fitting procedure use, for example, \verb{covs = c("time1i, time2i,...)}
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$add_time_indicators()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
Nothing. Called for effects.
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-lgcp_bayes"></a>}}
\if{latex}{\out{\hypertarget{method-grid-lgcp_bayes}{}}}
\subsection{Method \code{lgcp_bayes()}}{
Fit an (approximate) log-Gaussian Cox Process model using Bayesian methods
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$lgcp_bayes(
  popdens = NULL,
  covs = NULL,
  covs_grid = NULL,
  approx = "nngp",
  m = 10,
  L = 1.5,
  model = "exp",
  known_theta = NULL,
  iter_warmup = 500,
  iter_sampling = 500,
  chains = 3,
  parallel_chains = 3,
  verbose = TRUE,
  vb = FALSE,
  return_stan_fit = FALSE,
  ...
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{popdens}}{character string. Name of the population density column}

\item{\code{covs}}{vector of character string. Base names of the covariates to
include. For temporally-varying covariates only the stem is required and not
the individual column names for each time period (e.g. \code{dayMon} and not \code{dayMon1},
\code{dayMon2}, etc.)}

\item{\code{covs_grid}}{If using a region model, covariates at the level of the grid can also be specified by providing their
names to this argument.}

\item{\code{approx}}{Either "rank" for reduced rank approximation, or "nngp" for nearest
neighbour Gaussian process.}

\item{\code{m}}{integer. Number of basis functions for reduced rank approximation, or
number of nearest neighbours for nearest neighbour Gaussian process. See Details.}

\item{\code{L}}{integer. For reduced rank approximation, boundary condition as proportionate extension of area, e.g.
\code{L=2} is a doubling of the analysis area. See Details.}

\item{\code{model}}{Either "exp" for exponential covariance function or "sqexp" for squared exponential
covariance function}

\item{\code{known_theta}}{An optional vector of two values of the covariance parameters. If these are provided
then the covariance parameters are assumed to be known and will not be estimated.}

\item{\code{iter_warmup}}{integer. Number of warmup iterations}

\item{\code{iter_sampling}}{integer. Number of sampling iterations}

\item{\code{chains}}{integer. Number of chains}

\item{\code{parallel_chains}}{integer. Number of parallel chains}

\item{\code{verbose}}{logical. Provide feedback on progress}

\item{\code{vb}}{Logical indicating whether to use variational Bayes (TRUE) or full MCMC sampling (FALSE)}

\item{\code{return_stan_fit}}{logical. The results of the model fit are stored internally as an \code{rstFit} object and
returned in that format. If this argument is set to TRUE, then the fitted stan object will instead be returned,
but the \code{rtsFit} object will still be saved.}

\item{\code{...}}{additional options to pass to `$sample()``.}

\item{\code{priors}}{list. See Details}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
A \link[rstan]{stanfit} or a \code{CmdStanMCMC} object
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{# the data are just random simulated points 
b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20))
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
cov1 <- grid$new(b1,0.8)
cov1$grid_data$cov <- runif(nrow(cov1$grid_data))
g1$add_covariates(cov1$grid_data,
                  zcols="cov")
g1$points_to_grid(dp, laglength=5)
g1$priors <- list(
  prior_lscale=c(0,0.5),
  prior_var=c(0,0.5),
  prior_linpred_mean=c(0),
  prior_linpred_sd=c(5)
  )
\donttest{
g1$lgcp_bayes(popdens="cov", approx = "hsgp", parallel_chains = 0)
g1$model_fit()
# we can extract predictions
g1$extract_preds("rr")
g1$plot("rr")
g1$hotspots(threshold = 2, stat = "rr")

 # this example uses real aggregated data but will take a relatively long time to run
 data("birmingham_crime")
 example_data <- birmingham_crime[,c(1:8,21)]
 example_data$y <- birmingham_crime$t12
 g2 <- grid$new(example_data,cellsize=1000)
 g2$priors <- list(
  prior_lscale=c(0,0.5),
  prior_var=c(0,0.5),
  prior_linpred_mean=c(-3),
  prior_linpred_sd=c(5)
)
g2$lgcp_bayes(popdens="pop", approx = "hsgp", parallel_chains = 0)
g2$model_fit()
g2$extract_preds("rr")
g2$plot("rr")
g2$hotspots(threshold = 2, stat = "rr")
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-lgcp_ml"></a>}}
\if{latex}{\out{\hypertarget{method-grid-lgcp_ml}{}}}
\subsection{Method \code{lgcp_ml()}}{
Fit an (approximate) log-Gaussian Cox Process model using Maximum Likelihood
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$lgcp_ml(
  popdens = NULL,
  covs = NULL,
  model = "fexp",
  max_iter = 30,
  iter_sampling = 200,
  tol = ifelse(iter_sampling == 1, 1, 10),
  hist = 5,
  k0 = 10,
  start_theta = NULL,
  m = c(10, 10),
  L = 1.2,
  se = "average",
  mesh_args = NULL,
  trace = 1
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{popdens}}{character string. Name of the population density column in grid data or region data}

\item{\code{covs}}{vector of strings. Base names of the covariates to
include. For temporally-varying covariates only the stem is required and not
the individual column names for each time period (e.g. \code{dayMon} and not \code{dayMon1},
\code{dayMon2}, etc.) For regional models, covariates should be mapped to the grid currently (see add_covariates)}

\item{\code{model}}{Either "fexp", "sqexp", "matern1", or "matern2" for exponential, squared exponential, and matern with shape of 1 or 2, respectively. Add \code{hsgp_} or \code{spde_} for hsgp or
spde approximation, respectively. For example \code{spde_matern1} or \code{hsgp_fexp}. SPDE is not yet available for spatio-temporal models.}

\item{\code{max_iter}}{Integer. Maximum number of iterations.}

\item{\code{iter_sampling}}{integer. Number of random effects samples to draw on each iteration.}

\item{\code{tol}}{Scalar. The tolerance for the Bayes Factor convergence criterion.}

\item{\code{hist}}{Integer. The length of the running mean for the convergence criterion for non-Gaussian models.}

\item{\code{k0}}{Integer. The expected nunb2mber of iterations until convergence.}

\item{\code{start_theta}}{Optional. Starting values for the covariance parameters (log(tau sq), log(lambda), rho), with rho only
required if more than one time period.}

\item{\code{m}}{Number of basis functions per dimension for HSGP approximation. If spatio-temporal model then three values are required.}

\item{\code{L}}{Multiplicative boundary extension for HSGP approximation.}

\item{\code{se}}{Either "average" for a Monte Carlo averaged standard error, or "point" for standard errors evaluated at the posterior mode of the random effects.}

\item{\code{mesh_args}}{If using spde, then a list with any of \code{max_edge}, \code{cutoff}, and \code{offset} specified, see help for \code{build_spde_data} function, which returns data in the appropriate format.}

\item{\code{trace}}{Integer. Level of detail of information printed to the console. 0 = none, 1 = some (default), 2 = most.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
Optionally, an \code{rtsFit} model fit object. This fit is stored internally and can be retrieved with \code{model_fit()}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{# a simple example with simulated points using SPDE approximation
boundary <- st_set_crs(boundary, 4326)
g1 <- grid$new(boundary,cellsize=0.01)
g1$points_to_grid(point_data = create_points(example_points,
                                             pos_vars = c("Y","X")))
\donttest{
msoa <- sf::st_transform(birmingham_crime,crs = 4326)
g1$add_covariates(msoa,zcols="pop",weight_type="area")
set.seed(2345)
fit_spde <- g1$lgcp_ml("pop", model = "hsgp_matern1")
g1$extract_preds(type = c("rr"), popdens = "pop")
g1$plot("rr")


# this example uses real aggregated spatial data
# note that the full dataset has 12 time periods
# and can be used as a spatio-temporal example by removing
# the lines marked # spatial 
 data("birmingham_crime")
 example_data <- birmingham_crime[,c(1:8,21)] # spatial
 example_data$y <- birmingham_crime$t12 # spatial
 example_data <- sf::st_transform(example_data, crs = 4326)
 g2 <- grid$new(example_data,cellsize=0.006)
 set.seed(123)
 g2$lgcp_ml(popdens = "pop", model = "hsgp_matern1", L = 1.5, m = c(15,15))
 g2$extract_preds("rr")
 g2$plot("rr")
 
 #SPDE verison rescale to more stable coordinates
g2$transform(scale_factor = 50)
set.seed(101)
fitt <- suppressWarnings(g2$lgcp_ml("pop", model = "spde_matern1")) # use default mesh args
g2$extract_preds("rr")
g2$plot("rr")
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-extract_preds"></a>}}
\if{latex}{\out{\hypertarget{method-grid-extract_preds}{}}}
\subsection{Method \code{extract_preds()}}{
Extract predictions

Extract incidence and relative risk predictions. The predictions will be extracted from the last model fit. If no previous model fit then use either \code{lgcp_ml()} or \code{lgcp_bayes()}, or see
\code{model_fit()} to update the stored model fit.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$extract_preds(
  type = c("pred", "rr", "irr"),
  irr.lag = NULL,
  t.lag = 0,
  popdens = NULL,
  level = 0.95
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{type}}{Vector of character strings. Any combination of "pred", "rr", and "irr", which are,
posterior mean incidence (overall and population standardised), relative risk,
and incidence rate ratio, respectively.}

\item{\code{irr.lag}}{integer. If "irr" is requested as \code{type} then the number of time
periods lag previous the ratio is in comparison to}

\item{\code{t.lag}}{integer. Extract predictions for previous time periods.}

\item{\code{popdens}}{character string. Name of the column in \code{grid_data} with the
population density data}

\item{\code{level}}{Scalar. The function returns the \code{level}\% prediction interval.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
NULL
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{# See examples for lgcp_bayes() and lgcp_ml()
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-hotspots"></a>}}
\if{latex}{\out{\hypertarget{method-grid-hotspots}{}}}
\subsection{Method \code{hotspots()}}{
Generate hotspot probabilities

Generate hotspot probabilities. The last model fit will be used to extract
predictions. If no previous model fit then use either \code{lgcp_ml()} or \code{lgcp_bayes()}, or see
\code{model_fit()} to update the stored model fit.

Given a definition of a hotspot in terms of threshold(s) for incidence,
relative risk, or incidence rate ratio, returns the probabilities
each area is a "hotspot". See Details of \code{extract_preds}. Columns
will be added to \code{grid_data}. Note that for incidence threshold, the threshold should
be specified as the per individual incidence.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$hotspots(threshold = NULL, stat = "rr", t.lag = 0, popdens = NULL)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{threshold}}{Numeric. Threshold of population standardised incidence
above which an area is a hotspot}

\item{\code{stat}}{Numeric. Threshold of incidence rate ratio
above which an area is a hotspot.}

\item{\code{t.lag}}{integer. Extract predictions for incidence or relative risk for previous time periods.}

\item{\code{popdens}}{character string. Name of variable in \code{grid_data}
specifying the population density. Needed if \code{incidence.threshold} is not
\code{NULL}}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
None, called for effects. Columns are added to grid or region data.
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\dontrun{
# See examples for lgcp_bayes() and lgcp_ml()
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-aggregate_output"></a>}}
\if{latex}{\out{\hypertarget{method-grid-aggregate_output}{}}}
\subsection{Method \code{aggregate_output()}}{
Aggregate output

Aggregate \code{lgcp_fit} output to another geography
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$aggregate_output(
  new_geom,
  zcols,
  weight_type = "area",
  popdens = NULL,
  verbose = TRUE
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{new_geom}}{sf object. A set of polygons covering the same area as \code{boundary}}

\item{\code{zcols}}{vector of character strings. Names of the variables in \code{grid_data} to
map to the new geography}

\item{\code{weight_type}}{character string, either "area" or "pop" for area-weighted
or population weighted averaging, respectively, or "sum" to take the weighted sum.}

\item{\code{popdens}}{character string. If \code{weight_type} is equal to "pop" then the
name of the column in \code{grid_data} with population density data}

\item{\code{verbose}}{logical. Whether to provide progress bar.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
An \code{sf} object identical to \code{new_geom} with additional columns with the
variables specified in \code{zcols}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\donttest{
b1 <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
dp <- data.frame(y=runif(10,0,3),x=runif(10,0,3),date=paste0("2021-01-",11:20))
dp <- create_points(dp,pos_vars = c('y','x'),t_var='date')
cov1 <- grid$new(b1,0.8)
cov1$grid_data$cov <- runif(nrow(cov1$grid_data))
g1$add_covariates(cov1$grid_data,
                  zcols="cov")
g1$points_to_grid(dp, laglength=5)
g1$priors <- list(
  prior_lscale=c(0,0.5),
  prior_var=c(0,0.5),
  prior_linpred_mean=c(0),
  prior_linpred_sd=c(5)
  )
res <- g1$lgcp_bayes(popdens="cov", parallel_chains = 1)
g1$extract_preds(res,
                 type=c("pred","rr"),
                 popdens="cov")
new1 <- g1$aggregate_output(cov1$grid_data,
                            zcols="rr")
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-scale_conversion_factor"></a>}}
\if{latex}{\out{\hypertarget{method-grid-scale_conversion_factor}{}}}
\subsection{Method \code{scale_conversion_factor()}}{
Returns scale conversion factor

Coordinates are scaled to \verb{[-1,1]} for LGCP models fit with HSGP. This function
returns the scaling factor for this conversion.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$scale_conversion_factor()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
numeric
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{b1 = sf::st_sf(sf::st_sfc(sf::st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))))
g1 <- grid$new(b1,0.5)
g1$scale_conversion_factor()
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-build_spde_data"></a>}}
\if{latex}{\out{\hypertarget{method-grid-build_spde_data}{}}}
\subsection{Method \code{build_spde_data()}}{
Builds the mesh and relevant matrices for SPDE estimation
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$build_spde_data(
  max_edge = NULL,
  cutoff = NULL,
  offset = NULL,
  integrate = TRUE
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{max_edge}}{The largest allowed triangle edge length. One or two values.}

\item{\code{cutoff}}{The minimum allowed distance between points. Point at most as far apart as this are replaced by a single vertex prior to the mesh refinement step.}

\item{\code{offset}}{The automatic extension distance. One or two values, for an inner and an optional outer extension. If negative, interpreted as a factor relative to the approximate data diameter}

\item{\code{integrate}}{Logical. If TRUE uses fm_int to generate quadrature weights, otherwise uses node to region mapping.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
A list with A, C, G, and W matrices.
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-get_region_data"></a>}}
\if{latex}{\out{\hypertarget{method-grid-get_region_data}{}}}
\subsection{Method \code{get_region_data()}}{
Returns summary data of the region/grid intersections

Information on the intersection between the region areas and the computational grid
including the number of cells intersecting each region (\code{n_cell}), the indexes of the
cells intersecting each region in order (\code{cell_id}), and the proportion of each region's
area covered by each intersecting grid cell (\code{q_weights}).
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$get_region_data()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
A named list
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-variogram"></a>}}
\if{latex}{\out{\hypertarget{method-grid-variogram}{}}}
\subsection{Method \code{variogram()}}{
Plots the empirical semi-variogram
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$variogram(popdens, yvar, nbins = 20)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{popdens}}{String naming the variable in the data specifying the offset. If not
provided then no offset is used.}

\item{\code{yvar}}{String naming the outcome variable to calculate the variogram for. Optional, if
not provided then the outcome count data will be used.}

\item{\code{nbins}}{The number of bins in the empirical semivariogram}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
A ggplot plot is printed and optionally returned
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-reorder"></a>}}
\if{latex}{\out{\hypertarget{method-grid-reorder}{}}}
\subsection{Method \code{reorder()}}{
Re-orders the computational grid

The quality of the nearest neighbour approximation can depend on the ordering of
the grid cells. This function reorders the grid cells. If this is a region data model,
then the intersections are recomputed.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$reorder(option = "y", verbose = TRUE)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{option}}{Either "y" for order of the y coordinate, "x" for order of the x coordinate,
"minimax"  in which the next observation in the order is the one which maximises the
minimum distance to the previous observations, or "random" which randomly orders them.}

\item{\code{verbose}}{Logical indicating whether to print a progress bar (TRUE) or not (FALSE).}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
No return, used for effects.
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-data"></a>}}
\if{latex}{\out{\hypertarget{method-grid-data}{}}}
\subsection{Method \code{data()}}{
A list of prepared data

The class prepares data for use in the in-built estimation functions. The same data could be used
for alternative models. This is a utility function to facilitate model fitting for custom models.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$data(m, approx, popdens, covs, covs_grid)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{The number of nearest neighbours or basis functions.}

\item{\code{approx}}{Either "rank" for reduced rank approximation, or "nngp" for nearest
neighbour Gaussian process.}

\item{\code{popdens}}{String naming the variable in the data specifying the offset. If not
provided then no offset is used.}

\item{\code{covs}}{An optional vector of covariate names. For regional data models, this is specifically for the region-level covariates.}

\item{\code{covs_grid}}{An optional vector of covariate names for region data models, identifying the covariates at the grid level.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
A named list of data items used in model fitting
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-get_random_effects"></a>}}
\if{latex}{\out{\hypertarget{method-grid-get_random_effects}{}}}
\subsection{Method \code{get_random_effects()}}{
Returns the random effects stored in the object (if any) after using ML fitting. It's main use is
if a fitting procedure is stopped, the random effects can still be returned.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$get_random_effects()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
A matrix of random effects samples if a MCMCML model has been initialised, otherwise returns FALSE
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-model_fit"></a>}}
\if{latex}{\out{\hypertarget{method-grid-model_fit}{}}}
\subsection{Method \code{model_fit()}}{
Either returns the stored last model fit with either \code{lgcp_ml} or \code{lgcp_bayes}, or updates
the saved model fit if an object is provided.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$model_fit(fit = NULL)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{fit}}{Optional. A previous \code{rtsFit} object. If provided then the function updates the internally stored model fit.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
Either a \code{rtsFit} object or nothing if no model has been previously fit, or if the fit is updated.
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-grid-clone"></a>}}
\if{latex}{\out{\hypertarget{method-grid-clone}{}}}
\subsection{Method \code{clone()}}{
The objects of this class are cloneable with this method.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{grid$clone(deep = FALSE)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{deep}}{Whether to make a deep clone.}
}
\if{html}{\out{</div>}}
}
}
}
