| Title: | Spatial and Spatio-Temporal Models using 'INLA' |
|---|---|
| Description: | Prepare objects to implement models over spatial and spacetime domains with the 'INLA' package (<https://www.r-inla.org>). These objects contain data to for the 'cgeneric' interface in 'INLA', enabling fast parallel computations. We implemented the spatial barrier model, see Bakka et. al. (2019) <doi:10.1016/j.spasta.2019.01.002>, and some of the spatio-temporal models proposed in Lindgren et. al. (2024) <https://raco.cat/index.php/SORT/article/view/428665>. Details are provided in the available vignettes and from the URL bellow. |
| Authors: | Elias Teixeira Krainski [cre, aut, cph] (ORCID: <https://orcid.org/0000-0002-7063-2615>), Finn Lindgren [aut] (ORCID: <https://orcid.org/0000-0002-5833-2011>), Haavard Rue’ [aut] (ORCID: <https://orcid.org/0000-0002-0222-1881>) |
| Maintainer: | Elias Teixeira Krainski <[email protected]> |
| License: | GPL (>=2) |
| Version: | 0.1.14.901 |
| Built: | 2026-05-22 16:44:48 UTC |
| Source: | https://github.com/eliaskrainski/INLAspacetime |
Computes the auto-covariance for given coefficients.
ar2cov(a1, a2, k = 30, useC = FALSE)ar2cov(a1, a2, k = 30, useC = FALSE)
a1 |
the first auto-regression coefficient. |
a2 |
the second auto-regression coefficient. |
k |
maximum lag for evaluating the auto-correlation. |
useC |
just a test (to use C code). |
the autocorrelation as a vector or matrix,
whenever a1 or a2 are
scalar or vector.
Let the second order auto-regression model defined as
x_t + a_1 x_{t-1} + a_2 x_{t-2} = w_t
where w_t ~ N(0, 1).
ar2cov(c(-1.7, -1.8), 0.963, k = 5) plot(ar2cov(-1.7, 0.963), type = "o")ar2cov(c(-1.7, -1.8), 0.963, k = 5) plot(ar2cov(-1.7, 0.963), type = "o")
Creates a precision matrix as a sparse matrix object considering the specification stated in Details.
ar2precision(n, a)ar2precision(n, a)
n |
integer with the size of the precision matrix. |
a |
numeric vector with length three with the coefficients. |
Let the second order auto-regression model be defined as
The stationary assumption is to consider the variance of
to be the same for all .
This assumption gives the symmetric
precision matrix as a sparse matrix with the
following non-zero elements:
sparse matrix.
ar2precision(7, c(1, -1.5, 0.9))ar2precision(7, c(1, -1.5, 0.9))
f() call.Define a spacetime model object for the f() call.
barrierModel.define( mesh, barrier.triangles, prior.range, prior.sigma, range.fraction = 0.1, constr = FALSE, debug = FALSE, useINLAprecomp = TRUE, libpath = NULL )barrierModel.define( mesh, barrier.triangles, prior.range, prior.sigma, range.fraction = 0.1, constr = FALSE, debug = FALSE, useINLAprecomp = TRUE, libpath = NULL )
mesh |
a spatial mesh |
barrier.triangles |
a integer vector to specify which triangles centers are in the barrier domain, or a list with integer vector if more than one. |
prior.range |
numeric vector containing U and a to define the probability statements P(range < U) = a used to setup the PC-prior for range. If a = 0 or a = NA, then U is taken to be the fixed value for the range. |
prior.sigma |
numeric vector containing U and a to define the probability statements P(range > U) = a used to setup the PC-prior for sigma. If a = 0 or a = NA, then U is taken to be the fixed value for sigma. |
range.fraction |
numeric to specify the fraction of the range for the barrier domain. Default value is 0.1. This has to be specified with care in order to have it small enough to make it act as barrier but not too small in order to prevent numerical issues. |
constr |
logical, default is FALSE, to indicate if the integral of the field over the domain is to be constrained to zero. |
debug |
integer, default is zero, indicating the verbose level. Will be used as logical by INLA. |
useINLAprecomp |
logical, default is TRUE, indicating if it is to be used the shared object pre-compiled by INLA. This is not considered if 'libpath' is provided. |
libpath |
string, default is NULL, with the path to the shared object. |
See the paper.
objects to be used in the f() formula term in INLA.
Return an inlabru bru_mapper object that can be used for computing
model matrices for the space-time model components. The bru_get_mapper()
function is called by the inlabru methods to automatically obtain the
needed mapper object (from inlabru 2.7.0.9001; before that, use
mapper = bru_get_mapper(model) explicitly).
bru_get_mapper.stModel_cgeneric(model, ...)bru_get_mapper.stModel_cgeneric(model, ...)
model |
The model object (of class |
... |
Unused. |
A bru_mapper object of class bru_mapper_multi with
sub-mappers space and time based on the model smesh and tmesh
or mesh objects.
Define the stationary SPDE cgeneric model for INLA.
cgeneric_sspde(mesh, alpha, control.priors, constr = FALSE, ...)cgeneric_sspde(mesh, alpha, control.priors, constr = FALSE, ...)
mesh |
triangulation mesh to discretize the model. |
alpha |
integer used to compute the smoothness parameter. |
control.priors |
named list with parameter priors.
This shall contain |
constr |
logical, default is FALSE, to indicate if the integral of the field over the domain is to be constrained to zero. |
... |
additional arguments that will be passed on to
|
objects to be used in the f() formula term in INLA.
This is the stationary case of the inla.spde2.pcmatern function
in the INLA package with slight change on the marginal variance
when the domain is the sphere, as it follows the Eq. (23) in
Lindgren et. al. (2024).
Geir-Arne Fuglstad, Daniel Simpson, Finn Lindgren & Håvard Rue (2019). Constructing Priors that Penalize the Complexity of Gaussian Random Fields. Journal of the American Statistical Association, V. 114, Issue 525.
Finn Lindgren, Haakon Bakka, David Bolin, Elias Krainski and Håvard Rue (2024). A diffusion-based spatio-temporal extension of Gaussian Matérn fields. SORT vol. 48, no. 1, pp. 3-66 <doi: 10.57645/20.8080.02.13>
Download files from the NOAA's GHCN daily data
downloadUtilFiles(data.dir, year = 2022, force = FALSE)downloadUtilFiles(data.dir, year = 2022, force = FALSE)
data.dir |
the folder to store the files. |
year |
the year of the daily weather data. |
force |
logical indicating if it is to force the download. If FALSE each file will be downloaded if it does not exists locally yet. |
a named character vector with the local file names: daily.data, stations.all, elevation.
Function to define the boundary Earch polygon in longlat projection for a given resolution.
Earth_poly(resol = 300, crs = "+proj=moll +units=km")Earth_poly(resol = 300, crs = "+proj=moll +units=km")
resol |
is the number of subdivisions along the latitude coordinates and half the number of subdivisions along the longitude coordinates. |
crs |
a string with the projection. Default is the Mollweide projection with units in kilometers. |
a 'st_sfc' object with the Earth polygon.
Select data from the daily dataset
ghcndSelect( gzfile, variable = c("TMIN", "TAVG", "TMAX"), station = NULL, qflag = "", verbose = TRUE, astype = as.integer )ghcndSelect( gzfile, variable = c("TMIN", "TAVG", "TMAX"), station = NULL, qflag = "", verbose = TRUE, astype = as.integer )
gzfile |
the local filename for the daily data file file. E.g. 2023.csv.gz from the daily GHCN data repository at NCEI-NOAA, at "https://www.ncei.noaa.gov/pub/data/ghcn/daily/by_year/". Please see the references bellow. |
variable |
string with the variable name(s) to be selected |
station |
string (vector) with the station(s) to be selected |
qflag |
a string with quality control flag(s) |
verbose |
logical indicating if progress is to be printed |
astype |
function to convert data to a class, default is set to convert the data to integer. |
if more than one variable, it returns an array whose dimentions are days, stations, variables. If one variable, then it returns a matrix whose dimentions are days, stations.
The default selects TMIN, TAVG and TMAX and return it as integer because the original data is also integer with units in 10 Celcius degrees.
It can take time to execute if, for example, the data.table package is not available.
Menne, M., Durre, I., Vose, R., Gleason, B. and Houston, T. (2012) An overview of the global historical climatology network-daily database. Journal of Atmospheric and Oceanic Technology, 897–910.
This computes the area of a triangle given its three coordinates.
Heron(x, y) Area(x, y) s2trArea(tr, R = 1) flatArea(tr) Stiffness(tr)Heron(x, y) Area(x, y) s2trArea(tr, R = 1) flatArea(tr) Stiffness(tr)
x, y
|
coordinate vectors. |
tr |
the triangle coordinates |
R |
the radius of the spherical domain |
Function used internally to compute the area of a triangle.
the area of a 2d triangle
the area of a 2d polygon
the area of a triangle in S2
the area of a triangle
the stiffness matrix for a triangle
Internal functions, not exported.
This package main purpose is to provide user friendly functions to fit temporal, spatial and space-time models using the INLA software available at www.r-inla.org as well the inlabru package available
INLAspacetime()INLAspacetime()
opens the Vignettes directory on a browser
The 2nd order temporal matrices with boundary correction
Jmatrices(tmesh)Jmatrices(tmesh)
tmesh |
Temporal mesh |
Temporal GMRF representation with stationary boundary conditions as in Appendix E in Lindgren et. al. (2024).
return a list of temporal finite element method matrices for the supplied mesh.
Extracts the dual of a mesh object.
mesh.dual( mesh, returnclass = c("list", "sf", "sv", "SP"), mc.cores = getOption("mc.cores", 2L) )mesh.dual( mesh, returnclass = c("list", "sf", "sv", "SP"), mc.cores = getOption("mc.cores", 2L) )
mesh |
a 2d mesh object. |
returnclass |
if 'list' return a list of polygon coordinates, if "sf" return a 'sf' sfc_multipolygon object, if "sv" return a 'terra', SpatVector object, if "SP" return a 'sp' SpatialPolygons object. |
mc.cores |
number of threads to be used. |
one of the three in 'returnclass'
Creates a mesh object. This is just a test code. For efficient, reliable and general code use the fmesher package.
mesh2d(loc, domain, max.edge, offset, SP = TRUE)mesh2d(loc, domain, max.edge, offset, SP = TRUE)
loc |
a two column matrix with location coordinates. |
domain |
a two column matrix defining the domain. |
max.edge |
the maximum edge length. |
offset |
the length of the outer extension. |
SP |
logical indicating if the output will include the SpatialPolygons. |
a mesh object.
This is just for illustration purposes and one should consider the
efficient function fmesher::fm_mesh_2d() (and other related functions)
available a the fmesher package.
Illustrative code for Finite Element matrices of a mesh in 2d domain.
Illustrative code for Finite Element matrices when some triangles are in a barrier domain.
mesh2fem(mesh, order = 2, barrier.triangles = NULL) mesh2fem.barrier(mesh, barrier.triangles = NULL)mesh2fem(mesh, order = 2, barrier.triangles = NULL) mesh2fem.barrier(mesh, barrier.triangles = NULL)
mesh |
a 2d mesh object. |
order |
the desired order. |
barrier.triangles |
integer index to specify the triangles in the barrier domain |
a list object containing the FE matrices.
a list object containing the FE matrices for the barrier problem.
Creates a projector matrix object.
mesh2projector( mesh, loc = NULL, lattice = NULL, xlim = NULL, ylim = NULL, dims = c(100, 100) )mesh2projector( mesh, loc = NULL, lattice = NULL, xlim = NULL, ylim = NULL, dims = c(100, 100) )
mesh |
a 2d mesh object. |
loc |
a two columns matrix with the locations to project for. |
lattice |
Unused; feature not supported by this illustration. |
xlim, ylim
|
vector with the boundary limits. |
dims |
the number of subdivisions over each boundary limits. |
the projector matrix as a list with sparse matrix object at x$proj$A..
This is just for illustration purpose and one should consider the
efficient functions available in the fmesher package,
e.g. fmesher::fm_evaluator() and fmesher::fm_basis().
Detect outliers in a time series considering the raw data and a smoothed version of it.
outDetect(x, weights = NULL, ff = c(7, 7))outDetect(x, weights = NULL, ff = c(7, 7))
x |
numeric vector |
weights |
non-increasing numeric vector used as weights for
computing a smoothed vector as a rooling window average.
Default is null and then |
ff |
numeric length two vector with the factors used to consider how many times the standard deviation one data point is out to be considered as an outlier. |
logical vector indicating if the data is an outlier with attributes as detailed bellow.
attr(, 'm') is the mean of x.
attr(, 's') is the standard devation of x.
attr(, 'ss') is the standard deviation for
the smoothed data that is defined as
Both s and ss are used to define outliers if
or
attr(, 'xs') the smoothed time series
Functions to help converting from/to user/internal parametrization. The internal parameters are 'gamma_s, 'gamma_t', 'gamma_E' The user parameters are 'r_s', 'r_t', 'sigma'
lgsConstant(lg.s, alpha, smanifold) params2gammas( lparams, alpha.t, alpha.s, alpha.e, smanifold = "R2", verbose = FALSE ) gammas2params(lgammas, alpha.t, alpha.s, alpha.e, smanifold = "R2")lgsConstant(lg.s, alpha, smanifold) params2gammas( lparams, alpha.t, alpha.s, alpha.e, smanifold = "R2", verbose = FALSE ) gammas2params(lgammas, alpha.t, alpha.s, alpha.e, smanifold = "R2")
lg.s |
the logarithm of the SPDE parameter |
alpha |
the resulting spatial order. |
smanifold |
spatial domain manifold, which could be "S1", "S2", "R1", "R2" and "R3". |
lparams |
log(spatial range, temporal range, sigma) |
alpha.t |
temporal order of the SPDE |
alpha.s |
spatial order of the spatial differential operator in the non-separable part. |
alpha.e |
spatial order of the spatial differential operator in the separable part. |
verbose |
logical if it is to print internal variables |
lgammas |
numeric of length 3 with
|
See equation (23) in the paper.
See equations (19), (20) and (21) in the paper.
See equations (19), (20) and (21) in the paper.
the part of sigma from the spatial constant and \gamma_s.
log(gamma.s, gamma.t, gamma.e)
log(spatial range, temporal range, sigma)
params2gammas(log(c(1, 1, 1)), 1, 2, 1, "R2") gammas2params(log(c(0, 0, 0)), 1, 2, 1, "R2")params2gammas(log(c(1, 1, 1)), 1, 2, 1, "R2") gammas2params(log(c(0, 0, 0)), 1, 2, 1, "R2")
Creates a precision matrix as a sparse matrix object. For general code look at the functions in the INLA package.
spde2precision(kappa, fem, alpha)spde2precision(kappa, fem, alpha)
kappa |
the scale parameter. |
fem |
a list containing the Finite Element matrices. |
alpha |
the smoothness parameter. |
the precision matrix as a sparse matrix object.
This is just for illustration purpose and one should consider the efficient function available a the INLA package.
Extracts dic, waic and log-cpo from an output returned by the inla function from the INLA package or by the bru function from the inlabru package, and computes log-po, mse, mae, crps and scrps for a given input. A summary is applied considering the user imputed function, which by default is the mean.
stats.inla(m, i = NULL, y, fsummarize = mean)stats.inla(m, i = NULL, y, fsummarize = mean)
m |
an inla output object. |
i |
an index to subset the estimated values. |
y |
observed to compare against. |
fsummarize |
the summary function,
the default is |
A named numeric vector with the extracted statistics.
It assumes Gaussian posterior predictive distributions!
Considering the defaults, for n observations,
, we have
. dic
where is the dic computed for observation i.
. waic
where is the waic computed for observation i.
. lcpo
where is the cpo computed for observation i.
For the log-po, crps, and scrps scores it assumes a
Gaussian predictive distribution for each observation
which the following definitions:
,
is the posterior mean for the linear predictor,
,
is the observation posterior mean,
is the posterior variance of the
linear predictor for .
Then we consider the density of a standard
Gaussian variable and the corresponding
Cumulative Probability Distribution.
. lpo
. crps
where
. scrps
where
All the scores are negatively oriented which means that smaller scores are better.
Held, L. and Schrödle, B. and Rue, H. (2009). Posterior and Cross-validatory Predictive Checks: A Comparison of MCMC and INLA. Statistical Modelling and Regression Structures pp 91–110. https://link.springer.com/chapter/10.1007/978-3-7908-2413-1_6.
Bolin, D. and Wallin, J. (2022) Local scale invariance and robustness of proper scoring rules. Statistical Science. doi:10.1214/22-STS864.
To check unusual low/high variance segments
stdSubs(x, nsub = 12, fs = 15)stdSubs(x, nsub = 12, fs = 15)
x |
numeric vector |
nsub |
number for the segments length |
fs |
numeric to use for detecting too hight or too low local standard deviations. |
logical indicating if any of the
st are fs times lower/higher the average
of st, where is returned as an attribute:
attr(, 'st') numeric vector with the standard deviation at each segment of the data.
To visualize time series over space.
stlines( stdata, spatial, group = NULL, nmax.group = NULL, xscale = 1, yscale = 1, colour = NULL, ... ) stpoints( stdata, spatial, group = NULL, nmax.group = NULL, xscale = 1, yscale = 1, colour = NULL, ... )stlines( stdata, spatial, group = NULL, nmax.group = NULL, xscale = 1, yscale = 1, colour = NULL, ... ) stpoints( stdata, spatial, group = NULL, nmax.group = NULL, xscale = 1, yscale = 1, colour = NULL, ... )
stdata |
matrix with the data, each column is a location. |
spatial |
an object with one of class defined in the sp package. |
group |
an integer vector indicating to which spatial unit each time series belongs to. Default is NULL and them it is assumed that each time series belongs o each spatial unit. |
nmax.group |
an integer indicating the maximum number of time series to be plotted over each spatial unit. Default is NULL, so all will be drawn. |
xscale |
numeric to define a scaling factor in the horizontal direction. |
yscale |
numeric to define a scaling factor in the vertical direction. |
colour |
color (may be a vector, one for each time series).
Default is NULL and it will generate colors considering the
average of each time series.
These automatic colors are defined using the |
... |
further arguments to be passed for the lines function. |
Scaling the times series is needed before drawing it over the map.
The area of the bounding box for the spatial object
divided by the number of locations is the standard scaling factor.
This is further multiplied by the user given xcale and yscale.
add lines to an existing plot
stlines(): each time series over the map centered at the location.
stpoints(): each time series over the map centered at the location.
if there are too many geographical locations, it will not look good
f() call.Define a spacetime model object for the f() call.
stModel.define( smesh, tmesh, model, control.priors, constr = FALSE, debug = FALSE, useINLAprecomp = TRUE, libpath = NULL )stModel.define( smesh, tmesh, model, control.priors, constr = FALSE, debug = FALSE, useINLAprecomp = TRUE, libpath = NULL )
smesh |
a spatial mesh |
tmesh |
a temporal mesh |
model |
a three characters string to specify the
smoothness alpha (each one as integer) parameters.
Currently it considers the |
control.priors |
a named list with parameter priors,
named as |
constr |
logical, default is FALSE, to indicate if the integral of the field over the domain is to be constrained to zero. |
debug |
integer, default is zero, indicating the verbose level. Will be used as logical by INLA. |
useINLAprecomp |
logical, default is TRUE, indicating if it is to be used the shared object pre-compiled by INLA. This is not considered if 'libpath' is provided. |
libpath |
string, default is NULL, with the path to the shared object. |
This function compute the matrices for computing the precision matrix. These are each one of the Kronecker products in Theorem 4.1 of Lindgren et. al. (2024) computed with the stModel.matrices and the parameters are as in Eq (19-21). We use the log of these parameters internally.
objects to be used in the f() formula term in INLA.
Finn Lindgren, Haakon Bakka, David Bolin, Elias Krainski and Håvard Rue (2024). A diffusion-based spatio-temporal extension of Gaussian Matérn fields. SORT vol. 48, no. 1, pp. 3-66 <doi: 10.57645/20.8080.02.13>
This function computes all the matrices needed to build the precision matrix for spatio-temporal model, as in Lindgren et. al. (2024)
stModel.matrices(smesh, tmesh, model, constr = FALSE)stModel.matrices(smesh, tmesh, model, constr = FALSE)
smesh |
a mesh object over the spatial domain. |
tmesh |
a mesh object over the time domain. |
model |
a string identifying the model. So far we have the following models: '102', '121', '202' and '220' models. |
constr |
logical to indicate if the integral of the field over the domain is to be constrained to zero. Default value is FALSE. |
See the paper for details.
a list containing needed objects for model definition.
'manifold' to spedify the a string with the model identification
a length three vector with the constants c1, c2 and c3
the vector d
the matrix T
the model matrices M_1, ..., M_m
To build the the precision matrix for a spacetime model given the temporal and the spatial meshes.
stModel.precision(smesh, tmesh, model, theta, verbose = FALSE)stModel.precision(smesh, tmesh, model, theta, verbose = FALSE)
smesh |
a mesh object over the spatial domain. |
tmesh |
a mesh object over the time domain. |
model |
a string identifying the model. So far we have the following models: '102', '121', '202' and '220' models. |
theta |
numeric vector of length three with
|
verbose |
logical to print intermediate objects. |
a (sparse) precision matrix, as in Lindgren et. al. (2024)
Define a regular grid in 'Mollweide' projection, with units in kilometers.
world_grid(size = 50, domain)world_grid(size = 50, domain)
size |
the (in kilometers) of the grid cells. |
domain |
if provided it should be an |
a 'sf' points object with the centers of a grid set within Earth (and the supplied domain)
Retrieve the map of the countries
worldMap( crs = "+proj=moll +units=km", scale = "medium", returnclass = c("sf", "sv") )worldMap( crs = "+proj=moll +units=km", scale = "medium", returnclass = c("sf", "sv") )
crs |
a string with the projection. Default is the Mollweide projection with units in kilometers. |
scale |
The scale of map to return. Please see the help of 'ne_countries' function from the 'rnaturalearth' package. |
returnclass |
A string determining the class of the spatial object to return. Please see the help of 'ne_countries' function from the 'rnaturalearth' package. |
The land and ocean maps are obtained with the 'rnaturalearth' package.