Type: | Package |
Title: | Bayesian Latent Gaussian Modelling using INLA and Extensions |
Version: | 2.13.0 |
URL: | http://www.inlabru.org, https://inlabru-org.github.io/inlabru/, https://github.com/inlabru-org/inlabru |
BugReports: | https://github.com/inlabru-org/inlabru/issues |
Description: | Facilitates spatial and general latent Gaussian modeling using integrated nested Laplace approximation via the INLA package (https://www.r-inla.org). Additionally, extends the GAM-like model class to more general nonlinear predictor expressions, and implements a log Gaussian Cox process likelihood for modeling univariate and spatial point processes based on ecological survey data. Model components are specified with general inputs and mapping methods to the latent variables, and the predictors are specified via general R expressions, with separate expressions for each observation likelihood model in multi-likelihood models. A prediction method based on fast Monte Carlo sampling allows posterior prediction of general expressions of the latent variables. Ecology-focused introduction in Bachl, Lindgren, Borchers, and Illian (2019) <doi:10.1111/2041-210X.13168>. |
License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
Additional_repositories: | https://inla.r-inla-download.org/R/testing |
RoxygenNote: | 7.3.2 |
Encoding: | UTF-8 |
Depends: | fmesher (≥ 0.4.0), methods, R (≥ 3.6), stats |
Imports: | dplyr, lifecycle, magrittr, MatrixModels, Matrix, plyr, rlang, sf, tibble, utils, withr |
Suggests: | covr, ggplot2, graphics, INLA (≥ 23.01.31), knitr, maps, mgcv, patchwork, raster, RColorBrewer, rgl, rmarkdown, scales, scoringRules, shiny, sn, sp (≥ 2.1), spatstat.geom, spatstat.data, sphereplot, splancs, terra, tidyterra, testthat (≥ 3.2.0), tidyr, DiagrammeR |
Enhances: | stars |
Config/testthat/parallel: | true |
Config/testthat/edition: | 3 |
Collate: | '0_inlabru_envir.R' 'bru.gof.R' 'bru.inference.R' 'bru_conversion.R' 'bru_index.R' 'bru_input.R' 'bru_sp.R' 'data.Poisson1_1D.R' 'data.Poisson2_1D.R' 'data.Poisson3_1D.R' 'data.gorillas.R' 'data.mexdolphin.R' 'data.mrsea.R' 'data.robins_subset.R' 'data.shrimp.R' 'data.toygroups.R' 'data.toypoints.R' 'deltaIC.R' 'deprecated.R' 'effect.R' 'environment.R' 'fmesher.R' 'ggplot.R' 'inla.R' 'inlabru-package.R' 'local_testthat.R' 'mappers.R' 'mapper_collect.R' 'mapper_repeat.R' 'mapper_sum.R' 'model.R' 'nlinla.R' 'plotsample.R' 'rgl.R' 'sampling.R' 'spatstat.R' 'spde.R' 'stack.R' 'track_plotting.R' 'transformation.R' 'used.R' 'utils.R' |
VignetteBuilder: | knitr |
BuildVignettes: | true |
LazyData: | true |
LazyDataCompression: | xz |
NeedsCompilation: | no |
Packaged: | 2025-07-09 20:33:47 UTC; flindgre |
Author: | Finn Lindgren |
Maintainer: | Finn Lindgren <finn.lindgren@gmail.com> |
Repository: | CRAN |
Date/Publication: | 2025-07-09 21:20:02 UTC |
inlabru
Description
Convenient model fitting using (iterated) INLA.
Details
inlabru
facilitates Bayesian spatial modelling using integrated nested
Laplace approximations. It is heavily based on R-inla
(https://www.r-inla.org) but adds additional modelling abilities and
simplified syntax for (in particular) spatial models.
Tutorials and more information can be found at
https://inlabru-org.github.io/inlabru/ and http://www.inlabru.org/.
The iterative method used for non-linear predictors is documented in the
method
vignette.
The main function for inference using inlabru is bru()
.
The general model specification details is documented in bru_comp()
and bru_obs()
.
Posterior quantities beyond the basic summaries can be calculated with
a predict()
method, documented in predict.bru()
.
For point process inference lgcp()
can be used as a shortcut to
bru(..., bru_obs(model="cp", ...))
.
The package comes with multiple real world data sets, namely gorillas,
gorillas_sf, mexdolphin_sf. Plotting these data
sets is straight forward using inlabru's extensions
to ggplot2
, e.g. the gg()
function. For educational purposes some
simulated data sets are available as well, e.g. Poisson1_1D,
Poisson2_1D, Poisson2_1D and toygroups.
Author(s)
Fabian E. Bachl bachlfab@gmail.com and Finn Lindgren finn.lindgren@gmail.com
See Also
Useful links:
Report bugs at https://github.com/inlabru-org/inlabru/issues
1-Dimensional Homogeneous Poisson example.
Description
Point data and count data, together with intensity function and expected counts for a homogeneous 1-dimensional Poisson process example.
Usage
data(Poisson1_1D)
Format
The data contain the following R
objects:
lambda1_1D
A function defining the intensity function of a nonhomogeneous Poisson process. Note that this function is only defined on the interval (0,55).
E_nc1
The expected counts of the gridded data.
pts1
The locations of the observed points (a data frame with one column, named
x
).countdata1
A data frame with three columns, containing the count data:
x
The grid cell midpoint.
count
The number of detections in the cell.
exposure
The width of the cell.
Examples
if (require("ggplot2", quietly = TRUE)) {
data(Poisson1_1D)
ggplot(countdata1) +
geom_point(data = countdata1, aes(x = x, y = count), col = "blue") +
ylim(0, max(countdata1$count)) +
geom_point(data = pts1, aes(x = x), y = 0.2, shape = "|", cex = 4) +
geom_point(
data = countdata1, aes(x = x), y = 0, shape = "+",
col = "blue", cex = 4
) +
xlab(expression(bold(s))) +
ylab("count")
}
1-Dimensional NonHomogeneous Poisson example.
Description
Point data and count data, together with intensity function and expected counts for a unimodal nonhomogeneous 1-dimensional Poisson process example.
Usage
data(Poisson2_1D)
Format
The data contain the following R
objects:
lambda2_1D
:A function defining the intensity function of a nonhomogeneous Poisson process. Note that this function is only defined on the interval (0,55).
cov2_1D
:A function that gives what we will call a 'habitat suitability' covariate in 1D space.
E_nc2
The expected counts of the gridded data.
pts2
The locations of the observed points (a data frame with one column, named
x
).countdata2
A data frame with three columns, containing the count data:
x
The grid cell midpoint.
count
The number of detections in the cell.
exposure
The width of the cell.
Examples
if (require("ggplot2", quietly = TRUE)) {
data(Poisson2_1D)
p1 <- ggplot(countdata2) +
geom_point(data = countdata2, aes(x = x, y = count), col = "blue") +
ylim(0, max(countdata2$count, E_nc2)) +
geom_point(
data = countdata2, aes(x = x), y = 0, shape = "+",
col = "blue", cex = 4
) +
geom_point(
data = data.frame(x = countdata2$x, y = E_nc2), aes(x = x),
y = E_nc2, shape = "_", cex = 5
) +
xlab(expression(bold(s))) +
ylab("count")
ss <- seq(0, 55, length.out = 200)
lambda <- lambda2_1D(ss)
p2 <- ggplot() +
geom_line(
data = data.frame(x = ss, y = lambda),
aes(x = x, y = y), col = "blue"
) +
ylim(0, max(lambda)) +
geom_point(data = pts2, aes(x = x), y = 0.2, shape = "|", cex = 4) +
xlab(expression(bold(s))) +
ylab(expression(lambda(bold(s))))
multiplot(p1, p2, cols = 1)
}
1-Dimensional NonHomogeneous Poisson example.
Description
Point data and count data, together with intensity function and expected counts for a multimodal nonhomogeneous 1-dimensional Poisson process example. Counts are given for two different gridded data interval widths.
Usage
data(Poisson3_1D)
Format
The data contain the following R
objects:
lambda3_1D
A function defining the intensity function of a nonhomogeneous Poisson process. Note that this function is only defined on the interval (0,55).
E_nc3a
The expected counts of gridded data for the wider bins (10 bins).
E_nc3b
The expected counts of gridded data for the wider bins (20 bins).
pts3
The locations of the observed points (a data frame with one column, named
x
).countdata3a
A data frame with three columns, containing the count data for the 10-interval case:
countdata3b
A data frame with three columns, containing the count data for the 20-interval case:
x
The grid cell midpoint.
count
The number of detections in the cell.
exposure
The width of the cell.
Examples
if (require("ggplot2", quietly = TRUE)) {
data(Poisson3_1D)
# first the plots for the 10-bin case:
p1a <- ggplot(countdata3a) +
geom_point(data = countdata3a, aes(x = x, y = count), col = "blue") +
ylim(0, max(countdata3a$count, E_nc3a)) +
geom_point(
data = countdata3a, aes(x = x), y = 0, shape = "+",
col = "blue", cex = 4
) +
geom_point(
data = data.frame(x = countdata3a$x, y = E_nc3a),
aes(x = x), y = E_nc3a, shape = "_", cex = 5
) +
xlab(expression(bold(s))) +
ylab("count")
ss <- seq(0, 55, length.out = 200)
lambda <- lambda3_1D(ss)
p2a <- ggplot() +
geom_line(
data = data.frame(x = ss, y = lambda), aes(x = x, y = y),
col = "blue"
) +
ylim(0, max(lambda)) +
geom_point(data = pts3, aes(x = x), y = 0.2, shape = "|", cex = 4) +
xlab(expression(bold(s))) +
ylab(expression(lambda(bold(s))))
multiplot(p1a, p2a, cols = 1)
# Then the plots for the 20-bin case:
p1a <- ggplot(countdata3b) +
geom_point(data = countdata3b, aes(x = x, y = count), col = "blue") +
ylim(0, max(countdata3b$count, E_nc3b)) +
geom_point(
data = countdata3b, aes(x = x), y = 0, shape = "+",
col = "blue", cex = 4
) +
geom_point(
data = data.frame(x = countdata3b$x, y = E_nc3b),
aes(x = x), y = E_nc3b, shape = "_", cex = 5
) +
xlab(expression(bold(s))) +
ylab("count")
ss <- seq(0, 55, length.out = 200)
lambda <- lambda3_1D(ss)
p2a <- ggplot() +
geom_line(
data = data.frame(x = ss, y = lambda), aes(x = x, y = y),
col = "blue"
) +
ylim(0, max(lambda)) +
geom_point(data = pts3, aes(x = x), y = 0.2, shape = "|", cex = 4) +
xlab(expression(bold(s))) +
ylab(expression(lambda(bold(s))))
multiplot(p1a, p2a, cols = 1)
}
Add component input/latent mappers
Description
Add missing mappers between input data and latent variables, based on likelihood data
Equip component(s) with mappers for subcomponents that do not
have predefined mappers. When needed, the data in lhoods
is used to
determine the appropriate mapper(s).
Usage
add_mappers(...)
## S3 method for class 'bru_comp'
add_mappers(component, lhoods, inputs = NULL, lh_data = NULL, ...)
## S3 method for class 'bru_comp_list'
add_mappers(components, lhoods, inputs = NULL, lh_data = NULL, ...)
Arguments
... |
Parameters passed on to other methods |
component |
A component object |
lhoods |
A bru_obs_list object |
inputs |
A precomputed list of inputs, as returned by
|
lh_data |
A list of data object, one for each likelihood in |
components |
A |
Value
A component
object with completed mapper information
Examples
## Not run:
if (interactive() && bru_safe_inla()) {
}
## End(Not run)
Conversion methods for bru_comp
and bru_comp_list
objects
Description
Methods for converting to bru_comp
and bru_comp_list
objects.
Usage
as_bru_comp(x, ...)
as_bru_comp_list(x, ...)
## S3 method for class 'bru_comp'
as_bru_comp(x, ...)
## S3 method for class 'bru_comp_list'
as_bru_comp_list(x, ...)
## S3 method for class 'bru_comp'
as_bru_comp_list(x, ...)
## S3 method for class 'bru'
as_bru_comp_list(x, ...)
## S3 method for class 'list'
as_bru_comp_list(x, ...)
## S3 method for class 'formula'
as_bru_comp_list(x, ...)
Arguments
x |
An object to convert to bru_comp or bru_comp_list |
... |
Additional arguments passed on to |
Value
An object of class bru_comp_list.
Functions
-
as_bru_comp_list(bru)
: Extract the component list from abru()
object.
See Also
as_bru_obs()
, as_bru_obs_list()
Methods for mapper extraction
Description
Extract a mapper from another object
Usage
as_bru_mapper(x)
## S3 method for class 'bru_mapper'
as_bru_mapper(x)
## S3 method for class 'bru_comp'
as_bru_mapper(x)
## S3 method for class 'bru_subcomp'
as_bru_mapper(x)
Arguments
x |
Object to convert/extract |
Value
A bru_mapper
object
Examples
# Extract a mapper from a `bru_subcomp` object
as_bru_mapper(bru_comp("x", x, mapper = bm_index(4))$main)
Conversion methods for bru_obs
and bru_obs_list
objects
Description
Methods for converting to bru_obs
and bru_obs_list
objects.
Usage
as_bru_obs(x, ...)
as_bru_obs_list(x, ...)
## S3 method for class 'bru_obs'
as_bru_obs(x, ...)
## S3 method for class 'bru_obs'
as_bru_obs_list(x, ...)
## S3 method for class 'list'
as_bru_obs_list(x, ...)
## S3 method for class 'bru_obs_list'
as_bru_obs_list(x, ...)
## S3 method for class 'bru'
as_bru_obs_list(x, ...)
Arguments
x |
An object to convert to bru_obs or bru_obs_list |
... |
Additional arguments passed to sub-methods. |
Value
An object of class bru_obs or bru_obs_list.
See Also
1D LGCP bin count simulation and comparison with data
Description
A common procedure of analyzing the distribution of 1D points is to chose a binning and plot the data's histogram with respect to this binning. This function compares the counts that the histogram calculates to simulations from a 1D log Gaussian Cox process conditioned on the number of data samples. For each bin this results in a median number of counts as well as a confidence interval. If the LGCP is a plausible model for the observed points then most of the histogram counts (number of points within a bin) should be within the confidence intervals. Note that a proper comparison is a multiple testing problem which the function does not solve for you.
Usage
bincount(
result,
predictor,
observations,
breaks,
nint = 20,
probs = c(0.025, 0.5, 0.975),
...
)
Arguments
result |
|
predictor |
A formula describing the prediction of a 1D LGCP via
|
observations |
A vector of observed values |
breaks |
A vector of bin boundaries |
nint |
Number of integration intervals per bin. Increase this if the bins are wide and the LGCP is not smooth. |
probs |
numeric vector of probabilities with values in |
... |
arguments passed on to |
Value
An data.frame
with a ggplot attribute ggp
Examples
## Not run:
if (require(ggplot2) && require(fmesher) && bru_safe_inla()) {
# Load a point pattern
data(Poisson2_1D)
# Take a look at the point (and frequency) data
ggplot(pts2) +
geom_histogram(
aes(x = x),
binwidth = 55 / 20,
boundary = 0,
fill = NA,
color = "black"
) +
geom_point(aes(x), y = 0, pch = "|", cex = 4) +
coord_fixed(ratio = 1)
# Fit an LGCP model
x <- seq(0, 55, length.out = 50)
mesh1D <- fm_mesh_1d(x, boundary = "free")
matern <- INLA::inla.spde2.pcmatern(mesh1D,
prior.range = c(1, 0.01),
prior.sigma = c(1, 0.01),
constr = TRUE
)
mdl <- x ~ spde1D(x, model = matern) + Intercept(1)
fit.spde <- lgcp(mdl, pts2, domain = list(x = mesh1D))
# Calculate bin statistics
bc <- bincount(
result = fit.spde,
observations = pts2,
breaks = seq(0, max(pts2), length.out = 12),
predictor = x ~ exp(spde1D + Intercept)
)
# Plot them!
attributes(bc)$ggp
}
## End(Not run)
Mapper for aggregation
Description
Constructs a mapper that aggregates elements of the input state, so it can be used e.g. for weighted summation or integration over blocks of values.
Usage
bm_aggregate(rescale = FALSE, n_block = NULL, type = NULL)
bru_mapper_aggregate(...)
## S3 method for class 'bm_aggregate'
ibm_n(mapper, ..., input = NULL, state = NULL, n_state = NULL)
## S3 method for class 'bm_aggregate'
ibm_n_output(mapper, input = NULL, ...)
## S3 method for class 'bm_aggregate'
ibm_values(mapper, ..., state = NULL, n_state = NULL)
## S3 method for class 'bm_aggregate'
ibm_jacobian(mapper, input, state = NULL, ...)
## S3 method for class 'bm_aggregate'
ibm_eval(mapper, input, state = NULL, ..., sub_lin = NULL)
Arguments
rescale |
logical; For
|
n_block |
Predetermined number of output blocks. If |
type |
character; if non-NULL, overrides the |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
n_state |
integer giving the length of the state vector for mappers that have state dependent output size. |
sub_lin |
Internal, optional pre-computed sub-mapper information |
Methods (by generic)
-
ibm_jacobian(bm_aggregate)
:input
should be a list with elementsblock
andweights
.block
should be a vector of the same length as thestate
, orNULL
, withNULL
equivalent to all-1. Ifweights
isNULL
, it's interpreted as all-1.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_aggregate()
ibm_eval2(m, list(block = c(1, 2, 1, 2), weights = 1:4), 11:14)
ibm_eval2(m, list(block = c(1, 2, 1, 2), weights = 1:4, n_block = 3), 11:14)
Mapper for concatenated variables
Description
Constructs a concatenated collection mapping
Usage
bm_collect(mappers, hidden = FALSE)
bru_mapper_collect(...)
## S3 method for class 'bm_collect'
ibm_n(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_collect'
ibm_n_output(mapper, input, state = NULL, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_collect'
ibm_values(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_collect'
ibm_is_linear(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_collect'
ibm_jacobian(
mapper,
input,
state = NULL,
inla_f = FALSE,
multi = FALSE,
...,
sub_lin = NULL
)
## S3 method for class 'bm_collect'
ibm_eval(
mapper,
input,
state,
inla_f = FALSE,
multi = FALSE,
...,
sub_lin = NULL
)
## S3 method for class 'bm_collect'
ibm_linear(mapper, input, state, inla_f = FALSE, ...)
## S3 method for class 'bm_collect'
ibm_invalid_output(mapper, input, state, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_collect'
x[i, drop = TRUE]
## S3 method for class 'bru_mapper_collect'
x[i, drop = TRUE]
## S3 method for class 'bm_collect'
ibm_names(mapper)
## S3 replacement method for class 'bm_collect'
ibm_names(mapper) <- value
## S3 replacement method for class 'bru_mapper_collect'
ibm_names(mapper) <- value
Arguments
mappers |
A list of |
| |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
inla_f |
logical; when |
multi |
logical;
If |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
sub_lin |
Internal, optional pre-computed sub-mapper information |
x |
object from which to extract element(s) |
i |
indices specifying element(s) to extract |
drop |
logical;
For |
value |
a character vector of the same length as the number of sub-mappers in the mapper |
Value
-
[
-indexing abm_collect
extracts a subsetbm_collect
object (for dropFALSE
) or an individual sub-mapper (for dropTRUE
, andi
identifies a single element)
The
names()
method forbm_collect
returns the names from the sub-mappers list
Methods (by generic)
-
ibm_jacobian(bm_collect)
: Accepts a list with named entries, or a list with unnamed but ordered elements. The names must match the sub-mappers, seeibm_names.bm_collect()
. Each list element should take a format accepted by the corresponding sub-mapper. In case each element is a vector, the input can be given as a data.frame with named columns, a matrix with named columns, or a matrix with unnamed but ordered columns. Wheninla_f=TRUE
andhidden=TRUE
in the mapper definition, the input format should instead match that of the first, non-hidden, sub-mapper. -
ibm_invalid_output(bm_collect)
: Accepts a list with named entries, or a list with unnamed but ordered elements. The names must match the sub-mappers, seeibm_names.bm_collect()
. Each list element should take a format accepted by the corresponding sub-mapper. In case each element is a vector, the input can be given as a data.frame with named columns, a matrix with named columns, or a matrix with unnamed but ordered columns.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
(m <- bm_collect(list(
a = bm_index(2),
b = bm_index(3)
), hidden = FALSE))
ibm_eval2(m, list(a = c(1, 2), b = c(1, 3, 2)), 1:5)
Constant mapper
Description
Create a constant mapper
Usage
bm_const()
bru_mapper_const()
## S3 method for class 'bm_const'
ibm_n(mapper, ...)
## S3 method for class 'bm_const'
ibm_values(mapper, ...)
## S3 method for class 'bm_const'
ibm_jacobian(mapper, input, ...)
## S3 method for class 'bm_const'
ibm_eval(mapper, input, state = NULL, ...)
Arguments
mapper |
A mapper S3 object, inheriting from |
... |
Arguments passed on to other methods |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_const()
ibm_eval2(m, input = 1:4)
Mapper for factor variables
Description
Create a factor mapper
Usage
bm_factor(values, factor_mapping, indexed = FALSE)
bru_mapper_factor(...)
## S3 method for class 'bm_factor'
ibm_n(mapper, ...)
## S3 method for class 'bm_factor'
ibm_values(mapper, ...)
## S3 method for class 'bm_factor'
ibm_jacobian(mapper, input, ...)
Arguments
values |
Input values calculated by |
factor_mapping |
character; selects the type of factor mapping.
|
indexed |
logical; if |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_factor(factor(c("a", "b")), "full")
ibm_eval2(m, input = c("b", "a", "a", "b"), state = c(1, 3))
m <- bm_factor(factor(c("a", "b")), "contrast")
ibm_eval2(m, input = factor(c("b", "a", "a", "b")), state = 2)
Mapper for general fmesher
function space objects
Description
Creates a mapper for general fmesher
function space objects.
Usage
bm_fmesher(mesh)
bru_mapper_fmesher(...)
## S3 method for class 'bm_fmesher'
ibm_n(mapper, ...)
## S3 method for class 'bm_fmesher'
ibm_values(mapper, ...)
## S3 method for class 'bm_fmesher'
ibm_jacobian(mapper, input, ...)
Arguments
mesh |
An |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
Details
Handles indexed mapping for all fmesher
classes that support
fm_dof()
and fm_basis()
methods. For non-indexed mapping of
fm_mesh_1d
objects, use bru_mapper(mesh, indexed = FALSE)
which
invokes the bru_mapper.fm_mesh_1d()
method.
Value
A bm_fmesher
object.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_fmesher(fmesher::fmexample$mesh)
ibm_n(m)
ibm_eval(m, as.matrix(expand.grid(-2:2, -2:2)), seq_len(ibm_n(m)))
Mapper for cos/sin functions
Description
Constructs a mapper for cos
/sin
functions of orders 1 (if
intercept
is TRUE
, otherwise 0) through order
. The total number of
basis functions is intercept + 2 * order
.
Optionally, each order can be given a non-unit scaling, via the scaling
vector, of length intercept + order
. This can be used to
give an effective spectral prior. For example, let
scaling = 1 / (1 + (0:4)^2) x <- seq(0, 1, length.out = 11) bmh1 = bm_harmonics(order = 4, interval = c(0, 1)) u1 <- ibm_eval( bmh1, input = x, state = rnorm(9, sd = rep(scaling, c(1, 2, 2, 2, 2))) )
Then, with
bmh2 = bm_harmonics(order = 4, scaling = scaling) u2 = ibm_eval(bmh2, input = x, state = rnorm(9))
the stochastic properties of u1
and u2
will be the same, with
scaling^2
determining the variance for each frequency contribution.
The period for the first order harmonics is shifted and scaled to match
interval
.
Usage
bm_harmonics(order = 1, scaling = 1, intercept = TRUE, interval = c(0, 1))
bru_mapper_harmonics(...)
## S3 method for class 'bm_harmonics'
ibm_n(mapper, inla_f = FALSE, ...)
## S3 method for class 'bm_harmonics'
ibm_jacobian(mapper, input, state = NULL, inla_f = FALSE, ...)
Arguments
order |
For |
scaling |
For |
intercept |
logical; For |
interval |
numeric length-2 vector specifying a domain interval.
Default |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
inla_f |
logical; when |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_harmonics(2)
ibm_eval2(m, input = c(0, pi / 4, pi / 2, 3 * pi / 4), 1:5)
Mapper for indexed variables
Description
Create a an indexing mapper
Usage
bm_index(n = 1L, ...)
bru_mapper_index(...)
## S3 method for class 'bm_index'
ibm_invalid_output(mapper, input, state, ...)
## S3 method for class 'bm_index'
ibm_jacobian(mapper, input, state, ...)
Arguments
n |
Size of a model for |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_index(4)
ibm_eval(m, -2:6, 1:4)
Mapper for a linear effect
Description
Create a mapper for linear effects
Usage
bm_linear()
bru_mapper_linear()
## S3 method for class 'bm_linear'
ibm_n(mapper, ...)
## S3 method for class 'bm_linear'
ibm_values(mapper, ...)
## S3 method for class 'bm_linear'
ibm_jacobian(mapper, input, ...)
Arguments
mapper |
A mapper S3 object, inheriting from |
... |
Arguments passed on to other methods |
input |
Data input for the mapper. |
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_linear()
ibm_eval(m, input = 1:4, state = 2)
Methods for mapper lists
Description
bru_mapper
lists can be combined into bm_list
lists.
Usage
as_bm_list(x)
## S3 method for class 'list'
as_bm_list(x)
## S3 method for class 'bm_list'
as_bm_list(x)
## S3 method for class 'bru_comp_list'
as_bm_list(x)
## S3 method for class 'bru_mapper'
c(...)
## S3 method for class 'bm_list'
c(...)
## S3 method for class 'bm_list'
x[i]
## S3 method for class 'bm_list'
ibm_linear(mapper, input, state = NULL, ...)
## S3 method for class 'bm_list'
ibm_simplify(mapper, input = NULL, state = NULL, ...)
Arguments
x |
|
... |
Objects to be combined. |
i |
indices specifying elements to extract |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
Value
A bm_list
object
Methods (by generic)
-
c(bm_list)
: The...
arguments should bebm_list
objects. -
[
: Extract sub-list
Functions
-
c(bru_mapper)
: The...
arguments should bebru_mapper
objects.
Examples
m <- c(A = bm_const(), B = bm_scale())
str(m)
str(m[2])
Mapper for log-sum-exp aggregation
Description
Constructs a mapper
that aggregates elements of exp(state)
, with optional non-negative
weighting, and then takes the log()
, so it can be used e.g.
for v_k=\log[\sum_{i\in I_k} w_i \exp(u_i)]
and v_k=\log[\sum_{i\in I_k} w_i \exp(u_i) / \sum_{i\in I_k} w_i]
calculations. Relies on the input handling methods for
bm_aggregate
, but also allows the weights to be supplied on a
logarithmic scale as log_weights
. To avoid numerical overflow, it uses the
common method of internally shifting the state blockwise;
v_k=s_k+\log[\sum_{i\in I_k} \exp(u_i + \log(w_i)- s_k)]
,
where s_k=\max_{i\in I_k} u_i + \log(w_i)
is the
shift for block k
.
Usage
bm_logsumexp(rescale = FALSE, n_block = NULL)
bru_mapper_logsumexp(...)
## S3 method for class 'bm_logsumexp'
ibm_jacobian(mapper, input, state = NULL, ...)
## S3 method for class 'bm_logsumexp'
ibm_eval(mapper, input, state = NULL, log = TRUE, ..., sub_lin = NULL)
Arguments
rescale |
logical; For
|
n_block |
Predetermined number of output blocks. If |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
log |
logical; control |
sub_lin |
Internal, optional pre-computed sub-mapper information |
Methods (by generic)
-
ibm_jacobian(bm_logsumexp)
:input
should be a list with elementsblock
andweights
.block
should be a vector of the same length as thestate
, orNULL
, withNULL
equivalent to all-1. Ifweights
isNULL
, it's interpreted as all-1. -
ibm_eval(bm_logsumexp)
: Whenlog
isTRUE
(default),ibm_eval()
forlogsumexp
returns the log-sum-weight-exp value. IfFALSE
, thesum-weight-exp
value is returned.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_logsumexp()
ibm_eval2(m, list(block = c(1, 2, 1, 2), weights = 1:4), 11:14)
ibm_eval2(m, list(block = c(1, 2, 1, 2), weights = 1:4, n_block = 3), 11:14)
Mapper for marginal distribution transformation
Description
Constructs a mapper that transforms the marginal distribution state
from
\textrm{N}(0,1)
to the distribution of a given (continuous)
quantile function. The ...
arguments are used as parameter arguments to
qfun
, pfun
, dfun
, and dqfun
.
Usage
bm_marginal(qfun, pfun = NULL, dfun = NULL, dqfun = NULL, ..., inverse = FALSE)
bru_mapper_marginal(...)
## S3 method for class 'bm_marginal'
ibm_n(mapper, ..., state = NULL, n_state = NULL)
## S3 method for class 'bm_marginal'
ibm_n_output(mapper, input, state = NULL, ..., n_state = NULL)
## S3 method for class 'bm_marginal'
ibm_values(mapper, ..., state = NULL, n_state = NULL)
## S3 method for class 'bm_marginal'
ibm_jacobian(mapper, input, state = NULL, ..., reverse = FALSE)
## S3 method for class 'bm_marginal'
ibm_eval(mapper, input, state = NULL, ..., reverse = FALSE)
Arguments
qfun |
A quantile function, supporting |
pfun |
A CDF, supporting |
dfun |
A pdf, supporting |
dqfun |
A function evaluating the reciprocal of the derivative of
|
... |
Arguments passed on to other methods |
inverse |
logical; If |
mapper |
A mapper S3 object, inheriting from |
state |
A vector of latent state values for the mapping,
of length |
n_state |
integer giving the length of the state vector for mappers that have state dependent output size. |
input |
Data input for the mapper. |
reverse |
logical; control |
Methods (by generic)
-
ibm_jacobian(bm_marginal)
: Non-NULLinput
values are interpreted as a parameter list forqfun
, overriding that of the mapper itself. -
ibm_eval(bm_marginal)
: Whenxor(mapper[["inverse"]], reverse)
isFALSE
,ibm_eval()
formarginal
returnsqfun(pnorm(x), param)
, evaluated in a numerically stable way. Otherwise, evaluates the inverseqnorm(pfun(x, param))
instead.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_marginal(qexp, pexp, rate = 1 / 8)
(val <- ibm_eval(m, state = -5:5))
ibm_eval(m, state = val, reverse = TRUE)
m <- bm_marginal(qexp, pexp, dexp, rate = 1 / 8)
ibm_eval2(m, state = -3:3)
Mapper for matrix multiplication
Description
Create a matrix mapper, for a given number of columns
Usage
bm_matrix(labels)
bru_mapper_matrix(...)
## S3 method for class 'bm_matrix'
ibm_n(mapper, ...)
## S3 method for class 'bm_matrix'
ibm_values(mapper, ...)
## S3 method for class 'bm_matrix'
ibm_jacobian(mapper, input, state = NULL, inla_f = FALSE, ...)
Arguments
labels |
Column labels for matrix mappings; Can be factor, character, or a single integer specifying the number of columns for integer column indexing. |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
inla_f |
logical; when |
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_matrix(labels = c("a", "b"))
ibm_values(m)
ibm_eval2(m, input = matrix(1:6, 3, 2), state = 2:3)
m <- bm_matrix(labels = 2L)
ibm_values(m)
ibm_eval2(m, input = matrix(1:6, 3, 2), state = 2:3)
Mapper for basis conversion
Description
Creates a mapper for handling basis conversions
Usage
bm_mesh_B(mesh, B)
bru_mapper_mesh_B(...)
## S3 method for class 'bm_mesh_B'
ibm_n(mapper, ...)
## S3 method for class 'bm_mesh_B'
ibm_values(mapper, ...)
## S3 method for class 'bm_mesh_B'
ibm_jacobian(mapper, input, ...)
Arguments
mesh |
object supported by |
B |
a square or tall basis conversion matrix |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
The values for which to produce a mapping matrix |
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Mapper for tensor product domains
Description
Constructs a row-wise Kronecker product mapping of linear/affine mappers. Any offset in sub-mappers is added into a combined offset. Only linear/affine sub-mappers are allowed.
Usage
bm_multi(mappers)
bru_mapper_multi(mappers)
## S3 method for class 'bm_multi'
ibm_n(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_multi'
ibm_n_output(mapper, input, ...)
## S3 method for class 'bm_multi'
ibm_values(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_multi'
ibm_is_linear(mapper, multi = FALSE, ...)
## S3 method for class 'bm_multi'
ibm_jacobian(
mapper,
input,
state = NULL,
inla_f = FALSE,
multi = FALSE,
...,
sub_A = NULL
)
## S3 method for class 'bm_multi'
ibm_linear(mapper, input, state, inla_f = FALSE, ...)
## S3 method for class 'bm_multi'
ibm_eval(
mapper,
input,
state = NULL,
inla_f = FALSE,
...,
jacobian = NULL,
pre_A = deprecated()
)
## S3 method for class 'bm_multi'
ibm_invalid_output(mapper, input, state, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_multi'
x[i, drop = TRUE]
## S3 method for class 'bru_mapper_multi'
x[i, drop = TRUE]
## S3 method for class 'bm_multi'
ibm_names(mapper)
## S3 replacement method for class 'bm_multi'
ibm_names(mapper) <- value
## S3 replacement method for class 'bru_mapper_multi'
ibm_names(mapper) <- value
Arguments
mappers |
A list of |
mapper |
A mapper S3 object, inheriting from |
inla_f |
logical; when |
multi |
logical;
If |
... |
Arguments passed on to other methods |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
sub_A |
Internal; precomputed Jacobian matrices. |
jacobian |
For |
pre_A |
|
x |
object from which to extract element(s) |
i |
indices specifying element(s) to extract |
drop |
logical;
For |
value |
a character vector of up to the same length as the number of mappers in the multi-mapper x |
Value
-
[
-indexing abm_multi
extracts a subsetbm_multi
object (for dropFALSE
) or an individual sub-mapper (for dropTRUE
, andi
identifies a single element)
Methods (by generic)
-
ibm_jacobian(bm_multi)
: Accepts a list with named entries, or a list with unnamed but ordered elements. The names must match the sub-mappers, seeibm_names.bm_multi()
. Each list element should take a format accepted by the corresponding sub-mapper. In case each element is a vector, the input can be given as a data.frame with named columns, a matrix with named columns, or a matrix with unnamed but ordered columns. -
ibm_invalid_output(bm_multi)
: Accepts a list with named entries, or a list with unnamed but ordered elements. The names must match the sub-mappers, seeibm_names.bm_multi()
. Each list element should take a format accepted by the corresponding sub-mapper. In case each element is a vector, the input can be given as a data.frame with named columns, a matrix with named columns, or a matrix with unnamed but ordered columns. -
ibm_names(bm_multi)
: Returns the names from the sub-mappers list
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
(m <- bm_multi(list(a = bm_index(2), b = bm_index(3))))
ibm_eval2(m, list(a = c(1, 2, 1), b = c(1, 3, 2)), 1:6)
Mapper for linking several mappers in sequence
Description
Create a pipe mapper, where mappers
is a list of mappers,
and the evaluated output of each mapper is handed as the state to the next
mapper.
The input
format for the ibm_eval
and ibm_jacobian
methods is
a list of inputs, one for each mapper.
Usage
bm_pipe(mappers)
bru_mapper_pipe(...)
## S3 method for class 'bm_pipe'
ibm_n(mapper, ..., input = NULL, state = NULL)
## S3 method for class 'bm_pipe'
ibm_n_output(mapper, input, state = NULL, ..., n_state = NULL)
## S3 method for class 'bm_pipe'
ibm_values(mapper, ...)
## S3 method for class 'bm_pipe'
ibm_jacobian(mapper, input, state = NULL, ...)
## S3 method for class 'bm_pipe'
ibm_eval(mapper, input, state = NULL, ...)
## S3 method for class 'bm_pipe'
ibm_eval2(mapper, input, state = NULL, ...)
## S3 method for class 'bm_pipe'
ibm_simplify(
mapper,
input = NULL,
state = NULL,
inla_f = FALSE,
...,
n_state = NULL
)
Arguments
mappers |
A list of |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
n_state |
integer giving the length of the state vector for mappers that have state dependent output size. |
inla_f |
logical; when |
Methods (by generic)
-
ibm_simplify(bm_pipe)
: Constructs a simplifiedpipe
mapper. For fully linear pipes, callsibm_linear()
. For partially non-linear pipes, replaces each sequence of linear mappers with a singlebm_taylor()
mapper, while keeping the full list of original mapper names, allowing the originalinput
structure to be used also with the simplified mappers, since thetaylor
mappers are not dependent on inputs.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_pipe(list(
scale = bm_scale(),
shift = bm_shift()
))
ibm_eval2(m, input = list(scale = 2, shift = 1:4), state = 1:4)
Mapper for repeating a mapper
Description
Defines a repeated-space mapper that sums the contributions for
each copy. The ibm_n()
method returns ibm_n(mapper) * n_rep
, and
ibm_values()
returns seq_len(ibm_n(mapper))
.
Usage
bm_repeat(mapper, n_rep, interleaved = FALSE)
bru_mapper_repeat(...)
## S3 method for class 'bm_repeat'
ibm_n(mapper, ...)
## S3 method for class 'bm_repeat'
ibm_n_output(mapper, ...)
## S3 method for class 'bm_repeat'
ibm_values(mapper, ...)
## S3 method for class 'bm_repeat'
ibm_jacobian(
mapper,
input,
state = NULL,
inla_f = FALSE,
multi = FALSE,
...,
sub_lin = NULL
)
## S3 method for class 'bm_repeat'
ibm_eval(mapper, input, state, multi = FALSE, ..., sub_lin = NULL)
## S3 method for class 'bm_repeat'
ibm_linear(mapper, input, state, ...)
## S3 method for class 'bm_repeat'
ibm_invalid_output(mapper, input, state, ...)
Arguments
mapper |
The mapper to be repeated. |
n_rep |
The number of times to repeat the mapper. If a vector, the
non-interleaved repeats are combined into a single repeat mapping,
and combined with interleaved repeats via a |
interleaved |
logical; if If |
... |
Arguments passed on to other methods |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
inla_f |
logical; when |
multi |
logical;
If |
sub_lin |
Internal, optional pre-computed sub-mapper information |
Value
A bm_repeat
or bm_sum
object, or the original
input mapper
.
Methods (by generic)
-
ibm_jacobian(bm_repeat)
: The input should take the format of the repeated submapper. -
ibm_invalid_output(bm_repeat)
: Passes on the input to the corresponding method.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
(m0 <- bm_index(3))
(m <- bm_repeat(m0, 5))
ibm_n(m)
ibm_values(m)
ibm_jacobian(m, 1:3)
ibm_eval(m, 1:3, seq_len(ibm_n(m)))
# Interleaving and grouping
(m <- bm_repeat(m0, c(2, 1, 2), c(TRUE, FALSE, FALSE)))
ibm_n(m)
ibm_values(m)
ibm_jacobian(m, 1:3)
ibm_eval(m, 1:3, seq_len(ibm_n(m)))
Re-indexing matrix for repeated mappers
Description
Helper methods for regular and interleaved state vector indexing, meant for use in bm_repeat mappers.
Usage
bm_repeat_indexing(n_map, n_rep, interleaved = FALSE)
bm_repeat_indexing_matrix(n_map, n_rep)
Arguments
n_map |
The block mapper size |
n_rep |
The number of times the block is repeated |
interleaved |
logical; if |
Value
bm_repeat_indexing
: Returns a list with a vector of offsets,
offsets
, and a vector of relative index values, index
; block k
indexing is given by offsets[k] + index
.
bm_repeat_indexing_matrix
: A sparseMatrix
object.
Functions
-
bm_repeat_indexing()
: Construct the offsets and within-block index vectors for a repeated mapper, with or without interleaving. -
bm_repeat_indexing_matrix()
: Creates a sparse matrixA
such thatz <- A %*% x
constructs a blockwise versionz = c(x1, x2, ..., xn)
of an interleaved state vectorx = c(x1[1], x2[1], ..., x1[2], x2[2], ...)
. Each block is of sizen_map
, and there aren_rep
blocks. The reverse operation, taking a blockwisez = c(x1, x2, ..., xn)
to an interleaved vector isx <- Matrix::t(A) %*% z
.
Examples
(idx <- bm_repeat_indexing(3, 2, FALSE))
(idx <- bm_repeat_indexing(3, 2, TRUE))
(A <- bm_repeat_indexing_matrix(3, 2))
(x_interleaved <- 1:6)
(x_blockwise <- as.vector(A %*% x_interleaved))
(x_recovered <- as.vector(Matrix::t(A) %*% x_blockwise))
Mapper for element-wise scaling
Description
Create a standalone
scaling mapper that can be used as part of a bm_pipe
.
If mapper
is non-null, the bm_scale()
constructor
returns
bm_pipe(list(mapper = mapper, scale = bm_scale()))
Usage
bm_scale(mapper = NULL)
bru_mapper_scale(...)
## S3 method for class 'bm_scale'
ibm_n(mapper, ..., state = NULL, n_state = NULL)
## S3 method for class 'bm_scale'
ibm_n_output(mapper, input, state = NULL, ..., n_state = NULL)
## S3 method for class 'bm_scale'
ibm_values(mapper, ..., state = NULL, n_state = NULL)
## S3 method for class 'bm_scale'
ibm_jacobian(mapper, input, state = NULL, ..., sub_lin = NULL)
## S3 method for class 'bm_scale'
ibm_eval(mapper, input, state = NULL, ..., sub_lin = NULL)
Arguments
mapper |
For |
... |
Arguments passed on to other methods |
state |
A vector of latent state values for the mapping,
of length |
n_state |
integer giving the length of the state vector for mappers that have state dependent output size. |
input |
Data input for the mapper. |
sub_lin |
Internal, optional pre-computed sub-mapper information |
Methods (by generic)
-
ibm_jacobian(bm_scale)
:input
NULL values are interpreted as no scaling.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_scale()
ibm_eval2(m, c(1, 2, 1, 2), 1:4)
Mapper for element-wise shifting
Description
Create a standalone
shift mapper that can be used as part of a bm_pipe
.
If mapper
is non-null, the bm_shift()
constructor
returns
bm_pipe(list(mapper = mapper, shift = bm_shift()))
Usage
bm_shift(mapper = NULL)
bru_mapper_shift(...)
## S3 method for class 'bm_shift'
ibm_n(mapper, ..., state = NULL, n_state = NULL)
## S3 method for class 'bm_shift'
ibm_n_output(mapper, input, state = NULL, ..., n_state = NULL)
## S3 method for class 'bm_shift'
ibm_values(mapper, ..., state = NULL, n_state = NULL)
## S3 method for class 'bm_shift'
ibm_jacobian(mapper, input, state = NULL, ..., sub_lin = NULL)
## S3 method for class 'bm_shift'
ibm_eval(mapper, input, state = NULL, ..., sub_lin = NULL)
Arguments
mapper |
A mapper S3 object, inheriting from |
... |
Arguments passed on to other methods |
state |
A vector of latent state values for the mapping,
of length |
n_state |
integer giving the length of the state vector for mappers that have state dependent output size. |
input |
Data input for the mapper. |
sub_lin |
Internal, optional pre-computed sub-mapper information |
Methods (by generic)
-
ibm_jacobian(bm_shift)
:input
NULL values are interpreted as no shift.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_shift()
ibm_eval2(m, c(1, 2, 1, 2), 1:4)
Mapper for adding multiple mappers
Description
Defines a mapper that adds the effects of each submapper.
The ibm_n()
method returns the sum of ibm_n(mappers[[k]])
, and
ibm_values()
returns seq_len(ibm_n(mapper))
.
Usage
bm_sum(mappers, single_input = FALSE)
bru_mapper_sum(...)
## S3 method for class 'bm_sum'
ibm_n(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_sum'
ibm_n_output(mapper, input, state = NULL, ...)
## S3 method for class 'bm_sum'
ibm_values(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_sum'
ibm_is_linear(mapper, multi = FALSE, ...)
## S3 method for class 'bm_sum'
ibm_jacobian(
mapper,
input,
state = NULL,
inla_f = FALSE,
multi = FALSE,
...,
sub_lin = NULL
)
## S3 method for class 'bm_sum'
ibm_eval(mapper, input, state, multi = FALSE, ..., sub_lin = NULL)
## S3 method for class 'bm_sum'
ibm_linear(mapper, input, state, ...)
## S3 method for class 'bm_sum'
ibm_invalid_output(mapper, input, state, multi = FALSE, ...)
## S3 method for class 'bm_sum'
x[i, drop = TRUE]
## S3 method for class 'bru_mapper_sum'
x[i, drop = TRUE]
## S3 method for class 'bm_sum'
ibm_names(mapper)
## S3 replacement method for class 'bm_sum'
ibm_names(mapper) <- value
## S3 replacement method for class 'bru_mapper_sum'
ibm_names(mapper) <- value
Arguments
mappers |
A list of |
single_input |
logical. If |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
inla_f |
logical; when |
multi |
logical;
If |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
sub_lin |
Internal, optional pre-computed sub-mapper information |
x |
object from which to extract element(s) |
i |
indices specifying element(s) to extract |
drop |
logical;
For |
value |
a character vector of the same length as the number of sub-mappers in the mapper |
Value
A bm_sum
object.
-
[
-indexing abm_sum
extracts a subsetbm_sum
object (for dropFALSE
) or an individual sub-mapper (for dropTRUE
, andi
identifies a single element)
The
names()
method forbm_sum
returns the names from the sub-mappers list
Methods (by generic)
-
ibm_jacobian(bm_sum)
: Accepts a list with named entries, or a list with unnamed but ordered elements. The names must match the sub-mappers, seeibm_names.bm_sum()
. Each list element should take a format accepted by the corresponding sub-mapper. In case each element is a vector, the input can be given as a data.frame with named columns, a matrix with named columns, or a matrix with unnamed but ordered columns. -
ibm_invalid_output(bm_sum)
: Accepts a list with named entries, or a list with unnamed but ordered elements. The names must match the sub-mappers, seeibm_names.bm_sum()
. Each list element should take a format accepted by the corresponding sub-mapper. In case each element is a vector, the input can be given as a data.frame with named columns, a matrix with named columns, or a matrix with unnamed but ordered columns.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
(m <- bm_sum(list(a = bm_index(3), b = bm_index(2))))
ibm_n(m)
ibm_values(m)
ibm_jacobian(m, list(a = 1:3, b = c(1, 1, 2)))
ibm_eval(
m,
list(a = 1:3, b = c(1, 1, 2)),
seq_len(ibm_n(m))
)
Mapper for linear Taylor approximations
Description
Provides a pre-computed affine mapping,
internally used to represent and evaluate linearisation information.
The state0
information indicates for which state the offset
was
evaluated;
The affine mapper output is defined as
effect(state) = offset + jacobian %*% (state - state0)
Usage
bm_taylor(offset = NULL, jacobian = NULL, state0 = NULL, values_mapper = NULL)
bru_mapper_taylor(...)
## S3 method for class 'bm_taylor'
ibm_n(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_taylor'
ibm_n_output(mapper, input, ...)
## S3 method for class 'bm_taylor'
ibm_values(mapper, inla_f = FALSE, multi = FALSE, ...)
## S3 method for class 'bm_taylor'
ibm_jacobian(mapper, ..., multi = FALSE)
## S3 method for class 'bm_taylor'
ibm_eval(mapper, input = NULL, state = NULL, ...)
Arguments
offset |
For |
jacobian |
For |
state0 |
For |
values_mapper |
mapper object to be used for |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
inla_f |
logical; when |
multi |
logical;
If |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
Methods (by generic)
-
ibm_eval(bm_taylor)
: Evaluates linearised mapper information at the givenstate
. Theinput
argument is ignored, so that the usual argument orderibm_eval(mapper, input, state)
syntax can be used, but alsoibm_eval(mapper, state = state)
. For a mapper with a named jacobian list, thestate
argument must also be a named list. Ifstate
isNULL
, all-zero is assumed.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bm_taylor(
offset = rep(2, 3),
jacobian = matrix(1:6, 3, 2),
state0 = c(1, 2)
)
ibm_eval2(m, state = 2:3)
Convenient model fitting using (iterated) INLA
Description
This method is a wrapper for INLA::inla
and provides
multiple enhancements.
-
Easy usage of spatial covariates and automatic construction of inla projection matrices for (spatial) SPDE models. This feature is accessible via the
components
parameter. Practical examples on how to use spatial data by means of the components parameter can also be found by looking at the lgcp function's documentation. -
Constructing multiple likelihoods is straight forward. See like for more information on how to provide additional likelihoods to
bru
using the...
parameter list. -
Support for non-linear predictors. See example below.
-
Log Gaussian Cox process (LGCP) inference is available by using the
cp
family or (even easier) by using the lgcp function.
Usage
bru(components = ~Intercept(1), ..., options = list(), .envir = parent.frame())
bru_rerun(result, options = list())
## S3 method for class 'bru'
print(x, ...)
Arguments
components |
A |
... |
Obervation models, each constructed by a calling |
options |
A bru_options options object or a list of options passed
on to |
.envir |
Environment for component evaluation (for when a non-formula specification is used) |
result |
A previous estimation object of class |
x |
A |
Value
bru returns an object of class "bru". A bru
object inherits
from INLA::inla
(see the inla documentation for its properties) and
adds additional information stored in the bru_info
field.
Methods (by generic)
-
print(bru)
: Print a summary of abru
object.
Functions
-
bru_rerun()
: Continue the optimisation from a previously computed estimate. The estimationoptions
list can be given new values to override the original settings.To rerun with a subset of the data (e.g. for cross validation or prior sampling), use
bru_set_missing()
to set all or part of the response data toNA
before callingbru_rerun()
.
Author(s)
Fabian E. Bachl bachlfab@gmail.com
Examples
if (bru_safe_inla()) {
# Simulate some covariates x and observations y
input.df <- data.frame(x = cos(1:10))
input.df <- within(input.df, {
y <- 5 + 2 * x + rnorm(10, mean = 0, sd = 0.1)
})
# Fit a Gaussian likelihood model
fit <- bru(y ~ x + Intercept(1), family = "gaussian", data = input.df)
# Obtain summary
fit$summary.fixed
}
if (bru_safe_inla()) {
# Alternatively, we can use the bru_obs() function to construct the likelihood:
lik <- bru_obs(family = "gaussian",
formula = y ~ x + Intercept,
data = input.df)
fit <- bru(~ x + Intercept(1), lik)
fit$summary.fixed
}
# An important addition to the INLA methodology is bru's ability to use
# non-linear predictors. Such a predictor can be formulated via bru_obs()'s
# \code{formula} parameter. The z(1) notation is needed to ensure that
# the z component should be interpreted as single latent variable and not
# a covariate:
if (bru_safe_inla()) {
z <- 2
input.df <- within(input.df, {
y <- 5 + exp(z) * x + rnorm(10, mean = 0, sd = 0.1)
})
lik <- bru_obs(
family = "gaussian", data = input.df,
formula = y ~ exp(z) * x + Intercept
)
fit <- bru(~ z(1) + Intercept(1), lik)
# Check the result (z posterior should be around 2)
fit$summary.fixed
}
Additional bru options
Description
Construct a bru_options
object including the default and global options,
and converting deprecated option names.
Usage
bru_call_options(...)
Arguments
... |
Options passed on to |
Value
A bru_options
object
Author(s)
Finn Lindgren finn.lindgren@gmail.com
Examples
opts <- bru_call_options()
# Print them:
opts
Latent model component construction
Description
Similar to glm()
, gam()
and inla()
, bru()
models can be constructed
via a formula-like syntax, where each latent effect is specified. However, in
addition to the parts of the syntax compatible with INLA::inla
, bru
components offer additional functionality which facilitates modelling, and
the predictor expression can be specified separately, allowing more complex
and non-linear predictors to be defined. The formula syntax is just a way to
allow all model components to be defined in a single line of code, but the
definitions can optionally be split up into separate component definitions.
See Details for more information.
The bru_comp
methods all rely on the bru_comp.character()
method, that defines a model component with a given label/name. The user
usually doesn't need to call these methods directly, but can instead supply a
formula expression that can be interpreted by the
bru_comp_list.formula()
method, called inside bru()
.
Usage
bru_comp(...)
bru_component(...)
## S3 method for class 'character'
bru_comp(
object,
main = NULL,
weights = NULL,
...,
model = NULL,
mapper = NULL,
main_layer = NULL,
main_selector = NULL,
n = NULL,
values = NULL,
season.length = NULL,
nrow = NULL,
ncol = NULL,
copy = NULL,
weights_layer = NULL,
weights_selector = NULL,
group = 1L,
group_mapper = NULL,
group_layer = NULL,
group_selector = NULL,
ngroup = NULL,
control.group = NULL,
replicate = 1L,
replicate_mapper = NULL,
replicate_layer = NULL,
replicate_selector = NULL,
nrep = NULL,
marginal = NULL,
A.msk = deprecated(),
.envir = parent.frame(),
envir_extra = NULL
)
Arguments
... |
Parameters passed on to other methods |
object |
A character label for the component |
main |
|
weights , weights_layer , weights_selector |
Optional specification of effect scaling weights.
Same syntax as for |
model |
Either one of "const" (same as "offset"), "factor_full",
"factor_contrast", "linear",
"fixed", or a model name or
object accepted by INLA's |
mapper |
Information about how to do the mapping from the values evaluated in |
main_layer , main_selector |
The The |
n |
The number of latent variables in the model. Should be auto-detected
for most or all models. Default: NULL, for auto-detection. Models with
matrix input for |
values |
Specifies for what covariate/index values INLA should build the latent model. Normally generated internally based on the mapping details. (Default: NULL, for auto-determination) |
season.length |
Passed on to |
nrow , ncol |
Number of rows and columns for |
copy |
character; label of other component that this component should
be a copy of. If the |
group , group_mapper , group_layer , group_selector , ngroup |
Optional specification of kronecker/group model indexing. |
control.group |
|
replicate , replicate_mapper , replicate_layer , replicate_selector , nrep |
Optional specification of indices for an independent
replication model. Same syntax as for |
marginal |
May specify a |
A.msk |
|
.envir |
Evaluation environment |
envir_extra |
TODO: check/fix this parameter. |
Details
As shorthand, bru()
will understand basic additive formulae describing
fixed effect models. For instance, the components specification y ~ x
will
define the linear combination of an effect named x
and an intercept to the
response y
with respect to the likelihood family stated when calling
bru()
. Mathematically, the linear predictor \eta
would be
written as
\eta = \beta x + c,
where:
c
is the intercept
x
is a covariate
\beta
is a latent variable associated with
x
and\psi = \beta x
is called the effect of
x
A problem that arises when using this kind of R formula is that it does not
clearly reflect the mathematical
formula. For instance, when providing the formula to inla, the resulting
object will refer to the random
effect \psi = \beta * x
as x
.
Hence, it is not clear when x
refers to the covariate
or the effect of the covariate.
The bru_comp.character
method is inlabru's equivalent to
INLA
's f()
function but adds functionality that is unique to inlabru.
Deprecated parameters:
map: Use
main
instead.mesh: Use
mapper
instead.
Functions
-
bru_component()
: Backwards compatibility alias forbru_comp()
Naming random effects
In INLA, the f()
notation is used to define more complex models, but
a simple linear effect model can also be expressed as
formula = y ~ f(x, model = "linear")
,
where f()
is the inla specific function to set up random effects of all
kinds. The underlying predictor would again be \eta = \beta * x + c
but
the result of fitting the model would state x
as the random effect's name.
bru allows rewriting this formula in order to explicitly state the name of
the random effect and the name of the associated covariate. This is achieved
by replacing f
with an arbitrary name that we wish to assign to the effect,
e.g.
components = y ~ psi(x, model = "linear")
.
Being able to discriminate between x
and \psi
is relevant because
of two functionalities bru offers. The formula parameters of both bru()
and
the prediction method predict.bru are interpreted in the mathematical
sense. For instance, predict
may be used to analyze the analytical
combination of the covariate x
and the intercept using
predict(fit, data.frame(x=2)), ~ exp(psi + Intercept)
.
which corresponds to the mathematical expression e β + c.
On the other hand, predict may be used to only look at a transformation of
the latent variable \beta_\psi
predict(fit, NULL, ~ exp(psi_latent))
.
which corresponds to the mathematical expression e β.
Author(s)
Fabian E. Bachl bachlfab@gmail.com and Finn Lindgren Finn.Lindgren@gmail.com
See Also
bru_input()
, summary.bru_comp()
Other component constructors:
bru_comp_list()
Examples
# As an example, let us create a linear component. Here, the component is
# called "myLinearEffectOfX" while the covariate the component acts on is
# called "x". Note that a list of components is returned because the
# formula may define multiple components
cmp <- bru_comp_list(~ myLinearEffectOfX(main = x, model = "linear"))
summary(cmp)
# Equivalent shortcuts:
cmp <- bru_comp_list(~ myLinearEffectOfX(x, model = "linear"))
cmp <- bru_comp_list(~ myLinearEffectOfX(x))
# Individual component
cmp <- bru_comp("myLinearEffectOfX", main = x, model = "linear")
summary(cmp)
if (bru_safe_inla()) {
# As an example, let us create a linear component. Here, the component is
# called "myEffectOfX" while the covariate the component acts on is called
# "x":
cmp <- bru_comp("myEffectOfX", main = x, model = "linear")
summary(cmp)
# A more complicated component:
cmp <- bru_comp("myEffectOfX",
main = x,
model = INLA::inla.spde2.matern(fm_mesh_1d(1:10))
)
# Compound fixed effect component, where x and z are in the input data.
# The formula will be passed on to MatrixModels::model.Matrix:
cmp <- bru_comp("eff", ~ -1 + x:z, model = "fixed")
summary(cmp)
}
Evaluate component values in predictor expressions
Description
In predictor expressions, name_eval(...)
can be used to evaluate
the effect of a component called "name".
Usage
bru_comp_eval(
main,
group = NULL,
replicate = NULL,
weights = NULL,
.state = NULL
)
Arguments
main , group , replicate , weights |
Specification of where to evaluate a
component. The four inputs are passed on to the joint list(mapper = list( main = main, group = group, replicate = replicate), scale = weights) NOTE: If you have model component with the same name as a data variable you
want to supply as input to |
.state |
The internal component state. Normally supplied automatically by the internal methods for evaluating inlabru predictor expressions. |
Value
A vector of values for a component
Examples
if (bru_safe_inla() &&
require("sf", quietly = TRUE) &&
requireNamespace("sn", quietly = TRUE)) {
mesh <- fmesher::fm_mesh_2d_inla(
cbind(0, 0),
offset = 2,
max.edge = 2.5
)
spde <- INLA::inla.spde2.pcmatern(
mesh,
prior.range = c(1, NA),
prior.sigma = c(0.2, NA)
)
set.seed(12345L)
data <- sf::st_as_sf(
data.frame(
x = runif(50),
y = runif(50),
z = rnorm(50)
),
coords = c("x", "y")
)
fit <- bru(
z ~ -1 + field(geometry, model = spde),
family = "gaussian", data = data,
options = list(control.inla = list(int.strategy = "eb"))
)
pred <- generate(
fit,
newdata = data.frame(A = 0.5, B = 0.5),
formula = ~ field_eval(cbind(A, B)),
n.samples = 1L
)
}
Methods for inlabru component lists
Description
Constructor methods for inlabru component lists. Syntax details are given in
bru_comp()
.
Usage
bru_comp_list(object, lhoods = NULL, .envir = parent.frame(), ...)
## S3 method for class 'formula'
bru_comp_list(object, lhoods = NULL, .envir = parent.frame(), ...)
## S3 method for class 'list'
bru_comp_list(
object,
lhoods = NULL,
.envir = parent.frame(),
inputs = NULL,
...
)
## S3 method for class 'bru_comp_list'
c(...)
## S3 method for class 'bru_comp'
c(...)
## S3 method for class 'bru_comp_list'
x[i]
Arguments
object |
The object to operate on |
lhoods |
A bru_obs_list object |
.envir |
An evaluation environment for non-formula input |
... |
Parameters passed on to other methods. Also see Details. |
inputs |
A tree-like list of component input evaluations,
from |
x |
|
i |
indices specifying elements to extract |
Methods (by class)
-
bru_comp_list(formula)
: Convert a component formula into abru_comp_list
object -
bru_comp_list(list)
: Combine a list of components and/or component formulas into abru_comp_list
object
Methods (by generic)
-
c(bru_comp_list)
: The...
arguments should bebru_comp_list
objects. The environment from the first argument will be applied to the resultingbru_comp_list
.
Functions
-
c(bru_comp)
: The...
arguments should becomponent
objects frombru_comp()
. The environment from the first argument will be applied to the resultingbru_comp_list
.
Author(s)
Fabian E. Bachl bachlfab@gmail.com and Finn Lindgren finn.lindgren@gmail.com
See Also
Other component constructors:
bru_comp()
Other component constructors:
bru_comp()
Examples
# As an example, let us create a linear component. Here, the component is
# called "myLinearEffectOfX" while the covariate the component acts on is
# called "x". Note that a list of components is returned because the
# formula may define multiple components
eff <- bru_comp_list(~ myLinearEffectOfX(main = x, model = "linear"))
summary(eff[[1]])
# Equivalent shortcuts:
eff <- bru_comp_list(~ myLinearEffectOfX(x, model = "linear"))
eff <- bru_comp_list(~ myLinearEffectOfX(x))
# Individual component
eff <- bru_comp("myLinearEffectOfX", main = x, model = "linear")
Compute inlabru model linearisation information
Description
Compute inlabru model linearisation information
Usage
bru_compute_linearisation(...)
## S3 method for class 'bru_comp'
bru_compute_linearisation(
cmp,
model,
lhood_expr,
data,
data_extra,
input,
state,
comp_simple,
effects,
pred0,
used,
allow_combine,
eps,
n_pred = NULL,
...
)
## S3 method for class 'bru_obs'
bru_compute_linearisation(
lhood,
model,
data,
input,
state,
comp_simple,
eps,
...
)
## S3 method for class 'bru_obs_list'
bru_compute_linearisation(
lhoods,
model,
input,
state,
comp_simple,
eps = 1e-05,
...
)
## S3 method for class 'bru_model'
bru_compute_linearisation(model, lhoods, input, state, comp_simple, ...)
Arguments
... |
Parameters passed on to other methods |
cmp |
A bru_comp object |
model |
A |
lhood_expr |
A predictor expression |
data |
Input data |
data_extra |
Additional data for the predictor |
input |
Precomputed component inputs from |
state |
The state information, as a list of named vectors |
comp_simple |
Component evaluation information |
effects |
|
pred0 |
Precomputed predictor for the given state |
used |
A |
allow_combine |
logical; If |
eps |
The finite difference step size |
n_pred |
The length of the predictor expression. If not |
lhood |
A |
lhoods |
A |
Plot inlabru convergence diagnostics
Description
Draws four panels of convergence diagnostics for an iterated INLA method estimation
Usage
bru_convergence_plot(x, from = 1, to = NULL, type = NULL)
Arguments
x |
a bru object, typically a result from |
from , to |
integer values for the range of iterations to plot.
Default |
type |
|
Details
Requires the "dplyr", "ggplot2", "magrittr", and "patchwork" packages to be installed.
Value
A ggplot object with four panels of convergence diagnostics:
-
Tracks
: Mode and linearisation values for each effect -
Mode - Lin
: Difference between mode and linearisation values for each effect -
|Change| / sd
: Absolute change in mode and linearisation values divided by the standard deviation for each effect -
Change & sd
: Absolute change in mode and linearisation values and standard deviation for each effect
For multidimensional components, only the overall average, maximum, and minimum values are shown.
See Also
Examples
## Not run:
fit <- bru(...)
bru_convergence_plot(fit)
## End(Not run)
Get access to the internal environment
Description
Get access to the internal environment
Usage
bru_env_get()
Details
The environment is defined in 0_inlabru_envir.R
which is loaded
first.
Evaluate expressions in data contexts
Description
Evaluate an expression in a series of data contexts, also making the objects directly available as names surrounded by ".", stopping when the expression evaluation completes with no error.
This is an internal inlabru method, not intended for general use.
Usage
bru_eval_in_data_context(
input,
data = NULL,
default = NULL,
.envir = parent.frame()
)
Arguments
input |
An expression to be evaluated |
data |
list of data objects in priority order. Named elements will
be available as |
default |
Value used if the expression is evaluated as NULL. Default NULL |
.envir |
The evaluation environment |
Value
The result of expression evaluation
Examples
# The A values come from the 'data' element, and the B values come from
# the 'response_data' element, as that is listed first.
bru_eval_in_data_context(
quote(
list(A = .data.$x, B = x)
),
list(
response_data = tibble::tibble(x = 1:5),
data = tibble::tibble(x = 1:10)
)
)
# Both A and B come from the 'data' element, as 'x' is found there,
# terminating the evaluation attempt.
bru_eval_in_data_context(
quote(
list(A = .data.$x, B = x)
),
list(
data = tibble::tibble(x = 1:10),
response_data = tibble::tibble(x = 1:5)
)
)
Fill in missing values in Spatial grids
Description
Computes nearest-available-value imputation for missing values in space
Usage
bru_fill_missing(
data,
where,
values,
layer = NULL,
selector = NULL,
batch_size = deprecated()
)
Arguments
data |
A SpatialPointsDataFrame, SpatialPixelsDataFrame, SpatialGridDataFrame, SpatRaster, Raster, or sf object containing data to use for filling |
where |
A, matrix, data.frame, or SpatialPoints or SpatialPointsDataFrame, or sf object, containing the locations of the evaluated values |
values |
A vector of values to be filled in where |
layer , selector |
Specifies what data column or columns from which to
extract data, see |
batch_size |
|
Value
An infilled vector of values
Examples
## Not run:
if (bru_safe_inla()) {
points <-
sp::SpatialPointsDataFrame(
matrix(1:6, 3, 2),
data = data.frame(val = c(NA, NA, NA))
)
input_coord <- expand.grid(x = 0:7, y = 0:7)
input <-
sp::SpatialPixelsDataFrame(
input_coord,
data = data.frame(val = as.vector(input_coord$y))
)
points$val <- bru_fill_missing(input, points, points$val)
print(points)
# To fill in missing values in a grid:
print(input$val[c(3, 30)])
input$val[c(3, 30)] <- NA # Introduce missing values
input$val <- bru_fill_missing(input, input, input$val)
print(input$val[c(3, 30)])
}
## End(Not run)
Convert components to R code
Description
Convert components to R code
Usage
bru_formula_to_bru_obs_code(components, add = "")
Arguments
components |
A formula describing latent model components. |
Author(s)
Fabian E. Bachl bachlfab@gmail.com
Extract mapper information from INLA model component objects
Description
The component definitions will automatically attempt to extract mapper
information from any model object by calling the generic bru_get_mapper
.
Any class method implementation should return a bru_mapper object suitable
for the given latent model.
Usage
bru_get_mapper(model, ...)
## S3 method for class 'inla.spde'
bru_get_mapper(model, ...)
## S3 method for class 'inla.rgeneric'
bru_get_mapper(model, ...)
bru_get_mapper_safely(model, ...)
Arguments
model |
A model component object |
... |
Arguments passed on to other methods |
Value
A bru_mapper object defined by the model component
Methods (by class)
-
bru_get_mapper(inla.spde)
: Extract an indexed mapper for themodel$mesh
object contained in the model object, which is assumed to be of a class supporting relevantfmesher
methods. -
bru_get_mapper(inla.rgeneric)
: Returns the mapper given by a call tomodel$f$rgeneric$definition("mapper")
. To support this for your owninla.rgeneric
models, add a"mapper"
option to thecmd
argument of your rgeneric definition function. You will need to store the mapper in your object as well. Alternative, define your model using a subclass and define a correspondingbru_get_mapper.subclass
method that should return the correspondingbru_mapper
object.
Functions
-
bru_get_mapper_safely()
: Tries to call thebru_get_mapper
, and returnsNULL
if it fails (e.g. due to no available class method). If the call succeeds and returns non-NULL
, it checks that the object inherits from thebru_mapper
class, and gives an error if it does not.
See Also
bru_mapper for mapper constructor methods, and the individual mappers for specific implementation details.
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
if (bru_safe_inla()) {
library(INLA)
mesh <- fmesher::fm_rcdt_2d_inla(globe = 2)
spde <- inla.spde2.pcmatern(mesh,
prior.range = c(1, 0.5),
prior.sigma = c(1, 0.5)
)
mapper <- bru_get_mapper(spde)
ibm_n(mapper)
}
Extract predictor or component index information
Description
Extract the index vector for a
bru_obs()
predictor,
or the whole or a subset of a full bru()
predictor.
Usage
bru_index(object, ...)
## S3 method for class 'bru_obs'
bru_index(object, what = NULL, ...)
## S3 method for class 'bru'
bru_index(object, tag = NULL, what = NULL, ...)
## S3 method for class 'bru_comp'
bru_index(object, inla_f, ...)
## S3 method for class 'bru_comp_list'
bru_index(object, inla_f, ...)
## S3 method for class 'bru_model'
bru_index(object, used, ...)
index_eval(...)
Arguments
object |
A component. |
... |
Arguments passed on to sub-methods. |
what |
|
tag |
|
inla_f |
logical; when |
used |
A |
Value
-
bru_index(bru_obs)
: Aninteger
vector.
-
bru_index(bru)
: Aninteger
vector.
-
bru_index(bru_comp)
: A list of indices into the latent variables compatible with the component mapper.
-
bru_index(bru_comp_list)
: A list of list of indices into the latent variables compatible with each component mapper.
-
bru_index(bru_model)
: A named list ofidx_full
andidx_inla
, named list of indices, andinla_subset
, andinla_subset
, a named list of logical subset specifications for extracting theINLA::f()
compatible index subsets.
Methods (by class)
-
bru_index(bru_obs)
: Extract the index vector for the predictor vector for abru_obs()
sub-model. The indices are relative to the sub-model, and need to be appropriately offset to be used in the full model predictor. -
bru_index(bru)
: Extract the index vector for "APredictor" for one or more specified observationbru_obs()
sub-models. Accepts any combination oftag
andwhat
. -
bru_index(bru_model)
: Compute all index values for abru_model()
object. Computes the index value matrices for included components according to theused
argument.
Functions
Author(s)
Fabian E. Bachl bachlfab@gmail.com, Finn Lindgren finn.lindgren@gmail.com
Examples
fit <- bru(
~ 0 + x,
bru_obs(
y ~ .,
data = data.frame(x = 1:3, y = 1:3 + rnorm(3)),
tag = "A"
),
bru_obs(
y ~ .,
data = data.frame(x = 1:4, y = c(NA, NA, 3:4) + rnorm(4)),
tag = "B"
)
)
bru_index(fit)
bru_index(fit, "A")
bru_index(fit, "B")
bru_index(fit, c("B", "A"))
bru_index(fit, what = "missing")
Methods for bru_info objects
Description
The bru_info
class is used to store metadata about bru
models.
Usage
bru_info(...)
## S3 method for class 'character'
bru_info(method, ..., inlabru_version = NULL, INLA_version = NULL)
## S3 method for class 'bru'
bru_info(object, ...)
## S3 method for class 'bru_info'
summary(object, verbose = TRUE, ...)
## S3 method for class 'summary_bru_info'
print(x, ...)
## S3 method for class 'bru_info'
print(x, ...)
Arguments
... |
Arguments passed on to other |
method |
character; The type of estimation method used |
inlabru_version |
character; inlabru package version. Default: NULL, for automatically detecting the version |
INLA_version |
character; INLA package version. Default: NULL, for automatically detecting the version |
object |
Object to operate on |
verbose |
logical; If |
x |
An object to be printed |
Methods (by class)
-
bru_info(character)
: Create abru_info
object -
bru_info(bru)
: Extract thebru_info
object from an estimatedbru()
result object. The default print method show information about model components and observation models.
Backwards compatibility to handle mexpand for INLA <= 24.06.02
Description
Expand observation vectors/matrices in stacks into to a multicolumn matrix for multiple likelihoods
Usage
bru_inla.stack.mexpand(
...,
old.names = "BRU.response",
new.name = "BRU.response"
)
Arguments
... |
List of stacks that contain vector observations (existing multilikelihood observation matrices are also permitted) |
old.names |
A vector of strings with the names of the observation vector/matrix for each stack. If a single string, this is assumed for all the stacks. (default "BRU.response") |
new.name |
The name to be used for the expanded observation matrix, possibly the same as an old name. (default "BRU.response") |
Value
a list of modified stacks with multicolumn observations
Author(s)
Fabian E. Bachl f.e.bachl@bath.ac.uk and Finn Lindgren finn.lindgren@gmail.com
Join stacks intended to be run with different likelihoods
Description
Helper functions for multi-likelihood models
Usage
bru_inla.stack.mjoin(
...,
compress = TRUE,
remove.unused = TRUE,
old.names = "BRU.response",
new.name = "BRU.response"
)
Arguments
... |
List of stacks that contain vector observations (existing multi-likelihood observation matrices are also permitted) |
compress |
If |
remove.unused |
If |
old.names |
A vector of strings with the names of the observation vector/matrix for each stack. If a single string, this is assumed for all the stacks. (default "BRU.response") |
new.name |
The name to be used for the expanded observation matrix, possibly the same as an old name. (default "BRU.response") |
Obtain component inputs
Description
Obtain component inputs
Usage
bru_input(...)
## Default S3 method:
bru_input(input, label = NULL, layer = NULL, selector = NULL, ...)
## S3 method for class 'bru_comp'
bru_input(component, data, ...)
## S3 method for class 'bru_model'
bru_input(model, lhoods, ...)
## S3 method for class 'bru_comp_list'
bru_input(components, data, ...)
## S3 method for class 'bru_obs_list'
bru_input(lhoods, components, ...)
## S3 method for class 'bru_input'
bru_input(input, data, env = NULL, null.on.fail = FALSE, ...)
input_eval(...)
evaluate_inputs(...)
Arguments
... |
Passed on to sub-methods. |
component |
A bru_comp object. |
data |
A |
lhoods |
A bru_obs_list object |
components |
Value
-
bru_input(bru_comp)
: A list of mapper input values, formatted for the full component mapper (of type bm_pipe)
Methods (by class)
-
bru_input(default)
: Create abru_input
object. -
bru_input(bru_obs_list)
: Computes the component inputs for included components for each model likelihood -
bru_input(bru_input)
: Attempts to evaluate a component input (e.g.main
,group
,replicate
, orweight
), and process the results:If
eval()
failed, return NULL or map everything to 1 (see thenull.on.fail
argument). This should normally not happen, unless the component use logic is incorrect, (e.g. viaused
orinclude
/exclude
) leading to missing columns for a certain likelihood in a multi-bru_obs()
model.If we obtain a function, apply the function to the data object
If we obtain an object supported by
eval_spatial()
, extract the values of that data frame at the point locationsElse we obtain a vector and return as-is. This happens when input references a column of the data points, or some other complete expression
Functions
-
evaluate_inputs()
:since version
2.12.0.9023
. Usebru_input()
instead. Computes the component inputs for included components for each observation model.
Simple covariates and the input parameters
It is not unusual for a random effect act on a transformation of a covariate.
In other frameworks this would mean that the transformed covariate would have
to be calculated in advance and added to the data frame that is usually
provided via the data
parameter. inlabru provides the option to do this
transformation automatically. For instance, one might be interested in the
effect of a covariate x^2
. In inla and other frameworks this would
require to add a column xsquared
to the input data frame and use the
formula
formula = y ~ f(xsquared, model = "linear")
,
In inlabru this can be achieved in several ways of using the main
parameter
(map
in version 2.1.13 and earlier), which does not need to be named.
components = y ~ psi(x^2, model = "linear")
components = y ~ psi(main = x^2, model = "linear")
components = y ~ psi(mySquareFun(x), model = "linear")
,components = y ~ psi(myOtherSquareFun, model = "linear")
,
In the first example inlabru will interpret the map parameter as an
expression to be evaluated within the data provided. Since x
is a known
covariate it will know how to calculate it. The second example is an
expression as well but it uses a function called mySquareFun
. This function
is defined by user but has to be accessible within the work space when
setting up the components. The third example provides the function
myOtherSquareFun
. In this case, inlabru will call the function as
myOtherSquareFun(.data.)
, where .data.
is the data provided via the
bru_obs()
data
parameter. The function needs to know what parts of the
data to use to construct the needed output. For example,
myOtherSquareFun <- function(data) { data[ ,"x"]^2 }
Spatial Covariates
When fitting spatial models it is common to work with covariates that depend
on space, e.g. sea surface temperature or elevation. Although it is
straightforward to add this data to the input data frame or write a covariate
function like in the previous section there is an even more convenient way in
inlabru. Spatial covariates are often stored as SpatialPixelsDataFrame
,
SpatialPixelsDataFrame
or RasterLayer
objects. These can be provided
directly via the input expressions if they are supported by eval_spatial()
,
and the bru_obs()
data is an sf
or SpatialPointsDataFrame
object.
inlabru
will then automatically evaluate and/or interpolate the covariate
at your data locations when using code like
components = y ~ psi(mySpatialPixels, model = "linear")
For more precise control, use the the layer
and selector
arguments (see
bru_comp()
), or call eval_spatial()
directly, e.g.:
components = y ~ psi(eval_spatial(mySpatialPixels, where = .data.), model = "linear")
Coordinates
A common spatial modelling component when using inla are SPDE models. An
important feature of inlabru is that it will automatically calculate the so
called A-matrix (a component model matrix) which maps SPDE values at the mesh
vertices to values at the data locations. For this purpose, the input can be
set to coordinates
, which is the sp
package function that extracts point
coordinates from the SpatialPointsDataFrame
that was provided as input to
bru_obs()
. The code for this would look as follows:
components = y ~ field(coordinates, model = inla.spde2.matern(...))
Since coordinates
is a function from the sp
package, this results in
evaluation of sp::coordinates(.data.)
, which loses any CRS information
from the data object.
For sf
data with a geometry column (by default named geometry
), use
components = y ~ field(geometry, model = inla.spde2.matern(...))
Since the CRS information is part of the geometry column of the sf
object,
this retains CRS information, so this is more robust, and allows the model
to be built on a different CRS than the observation data.
Author(s)
Fabian E. Bachl bachlfab@gmail.com, Finn Lindgren finn.lindgren@gmail.com
See Also
summary.bru_input()
, bru_comp()
Examples
inp <- bru_input(expression(x), "LABEL")
bru_input(inp, data.frame(x = 1:3))
Check for predictor expression additivity
Description
Checks if a predictor expression is additive or not
Usage
bru_is_additive(x, ...)
## S3 method for class 'data.frame'
bru_is_additive(x, root_id = 0, ..., verbose = FALSE)
## S3 method for class 'character'
bru_is_additive(x, ...)
## S3 method for class 'expression'
bru_is_additive(x, ...)
## S3 method for class 'formula'
bru_is_additive(x, ...)
Arguments
x |
A predictor |
... |
Arguments passed on recursively. |
verbose |
logical; if |
Value
TRUE
if the expression is detected to be additive, FALSE
otherwise.
Access methods for bru_log
objects
Description
Access method for bru_log
objects.
Note: Up to version 2.8.0
, bru_log()
was a deprecated alias for
bru_log_message()
. When running on 2.8.0
or earlier, use bru_log_get()
to access the global log, and cat(fit$bru_iinla$log, sep = "\n")
to print a
stored estimation object log.
After version 2.8.0
, use bru_log()
to access the global log, and
bru_log(fit)
to access a stored estimation log.
Usage
bru_log(x = NULL, verbosity = NULL)
## S3 method for class 'character'
bru_log(x, verbosity = NULL)
## S3 method for class 'bru_log'
bru_log(x, verbosity = NULL)
## S3 method for class 'iinla'
bru_log(x, verbosity = NULL)
## S3 method for class 'bru'
bru_log(x, verbosity = NULL)
## S3 method for class 'bru_log'
format(x, ..., timestamp = TRUE, verbosity = FALSE)
## S3 method for class 'bru_log'
print(x, ..., timestamp = TRUE, verbosity = FALSE)
## S3 method for class 'bru_log'
as.character(x, ...)
## S3 method for class 'bru_log'
x[i]
## S3 method for class 'bru_log'
c(...)
## S3 method for class 'bru_log'
length(x)
Arguments
x |
An object that is, contains, or can be converted to,
a |
verbosity |
integer value for limiting the highest verbosity level being returned. |
... |
further arguments passed to or from other methods. |
timestamp |
If |
i |
indices specifying elements to extract. If |
Value
bru_log
A bru_log
object, containing a
character vector of log messages, and potentially a vector of bookmarks.
Methods (by generic)
-
format(bru_log)
: Format abru_log
object for printing. Ifverbosity
isTRUE
, include the verbosity level of each message. -
print(bru_log)
: Print abru_log
object withcat(x, sep = "\n")
. Ifverbosity
isTRUE
, include the verbosity level of each message. -
as.character(bru_log)
: Convertbru_log
object to a plaincharacter
vector -
[
: Extract a subset of abru_log
object -
c(bru_log)
: Concatenate severalbru_log
orcharacter
objects into abru_log
object. -
length(bru_log)
: Obtain the number of log entries into abru_log
object.
Functions
-
bru_log()
: Extract stored log messages. If non-NULL
, theverbosity
argument determines the maximum verbosity level of the messages to extract.
See Also
Other inlabru log methods:
bru_log_bookmark()
,
bru_log_message()
,
bru_log_new()
,
bru_log_offset()
,
bru_log_reset()
Examples
bru_log(verbosity = 2L)
format(bru_log())
bru_log(verbosity = 2L)
print(bru_log(), timestamp = TRUE, verbosity = TRUE)
Methods for bru_log
bookmarks
Description
Methods for bru_log
bookmarks.
Usage
bru_log_bookmark(bookmark = "", offset = NULL, x = NULL)
bru_log_bookmarks(x = NULL)
Arguments
bookmark |
character; The label for a bookmark with a stored offset. |
offset |
integer; a position offset in the log, with |
x |
A |
Value
bru_log_bookmark()
: Returns the modified bru_log
object if x
is non-NULL.
bru_log_bookmarks()
: Returns the bookmark vector associated with
x
Functions
-
bru_log_bookmark()
: Set a log bookmark. Ifoffset
isNULL
(the default), the bookmark will point to the current end of the log. -
bru_log_bookmarks()
: Return a integer vector with named elements being bookmarks into the globalinlabru
log with associated log position offsets.
See Also
Other inlabru log methods:
bru_log()
,
bru_log_message()
,
bru_log_new()
,
bru_log_offset()
,
bru_log_reset()
Add a log message
Description
Adds a log message.
Usage
bru_log_message(
...,
domain = NULL,
appendLF = TRUE,
verbosity = 1L,
allow_verbose = TRUE,
verbose = NULL,
verbose_store = NULL,
x = NULL
)
bru_log_abort(
msg,
...,
domain = NULL,
appendLF = TRUE,
verbosity = 1L,
allow_verbose = TRUE,
verbose = FALSE,
verbose_store = NULL,
call = rlang::caller_env(),
.frame = rlang::caller_env()
)
bru_log_warn(
msg,
...,
domain = NULL,
appendLF = TRUE,
verbosity = 1L,
allow_verbose = TRUE,
verbose = FALSE,
verbose_store = NULL,
call = rlang::caller_env(),
.frame = rlang::caller_env()
)
Arguments
... |
For |
domain |
Domain for translations, passed on to |
appendLF |
logical; whether to add a newline to the message. Only used for verbose output. |
verbosity |
numeric value describing the verbosity level of the message |
allow_verbose |
Whether to allow verbose output. Must be set to FALSE until the options object has been initialised. |
verbose |
logical, numeric, or |
verbose_store |
Same as |
x |
A |
msg |
character; passed to |
call |
The calling environment. |
.frame |
The throwing context, for when |
Value
bru_log_message
returns invisible(x)
, where x
is the updated bru_log
object, or NULL
.
Functions
-
bru_log_abort()
: Store a log message and throw an error. -
bru_log_warn()
: Store a log message and throw a warning.
See Also
Other inlabru log methods:
bru_log()
,
bru_log_bookmark()
,
bru_log_new()
,
bru_log_offset()
,
bru_log_reset()
Examples
if (interactive()) {
code_runner <- function() {
bru_options_set_local(
# Show messages up to and including level 2 (default 0)
bru_verbose = 2,
# Store messages to an including level 3 (default Inf, storing all)
bru_verbose_store = 3
)
bru_log_bookmark("bookmark 1")
bru_log_message("Test message 1", verbosity = 1)
bru_log_message("Test message 2", verbosity = 2)
bru_log_bookmark("bookmark 2")
bru_log_message("Test message 3", verbosity = 3)
bru_log_message("Test message 4", verbosity = 4)
invisible()
}
message("Run code")
code_runner()
message("Check log from bookmark 1")
print(bru_log()["bookmark 1"])
message("Check log from bookmark 2")
print(bru_log()["bookmark 2"])
}
Create a bru_log
object
Description
Create a bru_log
object, by default empty.
Usage
bru_log_new(x = NULL, bookmarks = NULL)
Arguments
x |
An optional character vector of log messages, or |
bookmarks |
An optional |
See Also
Other inlabru log methods:
bru_log()
,
bru_log_bookmark()
,
bru_log_message()
,
bru_log_offset()
,
bru_log_reset()
Examples
x <- bru_log_new()
x <- bru_log_message("Test message", x = x)
print(x)
Position methods for bru_log
objects
Description
Position methods for bru_log
objects.
Usage
bru_log_offset(x = NULL, bookmark = NULL, offset = NULL)
bru_log_index(x = NULL, i, verbosity = NULL)
Arguments
x |
A |
bookmark |
character; The label for a bookmark with a stored offset. |
offset |
integer; a position offset in the log, with |
i |
indices specifying elements to extract. If |
verbosity |
integer value for limiting the highest verbosity level being returned. |
Functions
-
bru_log_offset()
: Utility function for computing log position offsets. -
bru_log_index()
: Utility function for computing index vectors forbru_log
objects.
See Also
Other inlabru log methods:
bru_log()
,
bru_log_bookmark()
,
bru_log_message()
,
bru_log_new()
,
bru_log_reset()
Clear log contents
Description
Clears the log contents up to
a given offset
or bookmark
. Default: clear the entire log.
When x
is NULL, the global inlabru
log is updated, and invisible(NULL)
is returned. Otherwise the updated object is returned (invisibly).
Usage
bru_log_reset(x = NULL, bookmark = NULL, offset = NULL)
Arguments
x |
A |
bookmark |
character; The label for a bookmark with a stored offset. |
offset |
integer; a position offset in the log, with |
Value
Returns (invisibly) the modified bru_log
object, or NULL
(when
x
is NULL
)
See Also
Other inlabru log methods:
bru_log()
,
bru_log_bookmark()
,
bru_log_message()
,
bru_log_new()
,
bru_log_offset()
Examples
## Not run:
if (interactive()) {
bru_log_reset()
}
## End(Not run)
Build an inla data stack from linearisation information
Description
Combine linearisation for multiple likelihoods
Usage
bru_make_stack(...)
## S3 method for class 'bru_obs'
bru_make_stack(lhood, lin, idx, ..., family_index = 1L)
## S3 method for class 'bru_obs_list'
bru_make_stack(lhoods, lin, idx, ...)
Arguments
... |
Arguments passed on to other methods |
lhood |
A |
lin |
Linearisation information
|
idx |
Output from |
family_index |
integer specifying the family sequence index of the observation model |
lhoods |
A |
Constructors for bru_mapper
objects
Description
Constructors for bru_mapper
objects
Usage
bru_mapper(...)
bru_mapper_define(mapper, new_class = NULL, remove_class = "list", ...)
Arguments
... |
Arguments passed on to sub-methods, or used for special purposes, see details for each function below. |
mapper |
For |
new_class |
If non- |
remove_class |
If non- |
Value
-
bru_mapper()
returns abru_mapper
object
Functions
-
bru_mapper()
: Generic mapper S3 constructor, used for constructing mappers for special objects. See below for details of the default constructorbru_mapper_define()
that can be used to define new mappers in user code. -
bru_mapper_define()
: Adds thenew_class
and"bru_mapper"
class names to the inheritance list for the inputmapper
object, unless the object already inherits from these.To register mapper classes and methods in scripts, use
.S3method()
to register the methods, e.g..S3method("ibm_jacobian", "my_mapper_class", ibm_jacobian.my_mapper_class)
.In packages with
Suggests: inlabru
, add method information for delayed registration, e.g.:#' @rawNamespace S3method(inlabru::bru_get_mapper, inla_rspde) #' @rawNamespace S3method(inlabru::ibm_n, bru_mapper_inla_rspde) #' @rawNamespace S3method(inlabru::ibm_values, bru_mapper_inla_rspde) #' @rawNamespace S3method(inlabru::ibm_jacobian, bru_mapper_inla_rspde)
or before each method, use
@exportS3Method
:#' @exportS3Method inlabru::bru_get_mapper
etc., which semi-automates it.
See Also
bru_mapper_generics for generic methods, the individual mapper pages for special method implementations, and bru_get_mapper for hooks to extract mappers from latent model object class objects.
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
mapper <- bm_index(5)
ibm_jacobian(mapper, input = c(1, 3, 4, 5, 2))
Mapper for fm_mesh_1d
Description
Create mapper for an fm_mesh_1d
object
Usage
## S3 method for class 'fm_mesh_1d'
bru_mapper(mesh, indexed = TRUE, ...)
## S3 method for class 'bm_fm_mesh_1d'
ibm_n(mapper, ...)
## S3 method for class 'bm_fm_mesh_1d'
ibm_values(mapper, ...)
## S3 method for class 'bm_fm_mesh_1d'
ibm_jacobian(mapper, input, ...)
## S3 method for class 'bm_inla_mesh_1d'
ibm_n(mapper, ...)
## S3 method for class 'bm_inla_mesh_1d'
ibm_values(mapper, ...)
## S3 method for class 'bm_inla_mesh_1d'
ibm_jacobian(mapper, input, ...)
Arguments
mesh |
An |
indexed |
logical; If |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
Value
A bm_fm_mesh_1d
or bm_fmesher
object. The the
general bm_fmesher()
mapper handles all indexed fmesher
objects.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_2d()
,
bru_mapper_generics
Examples
m <- bru_mapper(fm_mesh_1d(c(1:3, 5, 7)))
ibm_values(m)
ibm_eval(m, 1:7, 1:5)
m <- bru_mapper(fm_mesh_1d(c(1:3, 5, 7)), indexed = FALSE)
ibm_values(m)
ibm_eval(m, 1:7, 1:5)
m <- bru_mapper(
fm_mesh_1d(c(1:3, 5, 7), degree = 2, boundary = "free"),
indexed = FALSE
)
ibm_values(m)
ibm_eval(m, 1:7, 1:6)
Mapper for fm_mesh_2d
Description
Creates a mapper for 2D fm_mesh_2d
objects. Equivalent
to calling bm_fmesher()
.
Usage
## S3 method for class 'fm_mesh_2d'
bru_mapper(mesh, ...)
## S3 method for class 'bm_fm_mesh_2d'
ibm_n(mapper, ...)
## S3 method for class 'bm_fm_mesh_2d'
ibm_values(mapper, ...)
## S3 method for class 'bm_fm_mesh_2d'
ibm_jacobian(mapper, input, ...)
## S3 method for class 'bm_inla_mesh_2d'
ibm_n(mapper, ...)
## S3 method for class 'bm_inla_mesh_2d'
ibm_values(mapper, ...)
## S3 method for class 'bm_inla_mesh_2d'
ibm_jacobian(mapper, input, ...)
Arguments
mesh |
An |
... |
Arguments passed on to other methods |
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
Value
A bm_fmesher
object. Note: Prior to version 2.12.0.9021
,
this was a bru_mapper_fm_mesh_2d
object. Also see the note for
bru_mapper.fm_mesh_1d()
.
See Also
bru_mapper, bru_mapper_generics
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper_generics
Examples
m <- bru_mapper(fmesher::fmexample$mesh)
ibm_n(m)
ibm_eval(m, as.matrix(expand.grid(-2:2, -2:2)), seq_len(ibm_n(m)))
Generic methods for bru_mapper objects
Description
A bru_mapper
sub-class implementation must provide an
ibm_jacobian()
method. If the model size 'n' and definition
values 'values' are stored in the object itself, default methods are
available (see Details). Otherwise the
ibm_n()
and ibm_values()
methods also need to be provided.
Usage
ibm_n(mapper, inla_f = FALSE, ...)
ibm_n_output(mapper, input, state = NULL, inla_f = FALSE, ...)
ibm_values(mapper, inla_f = FALSE, ...)
ibm_is_linear(mapper, ...)
ibm_jacobian(mapper, input, state = NULL, inla_f = FALSE, ...)
ibm_linear(mapper, input, state = NULL, ...)
ibm_simplify(mapper, input = NULL, state = NULL, ...)
ibm_eval(mapper, input, state = NULL, ...)
ibm_eval2(mapper, input, state = NULL, ...)
ibm_names(mapper)
ibm_names(mapper) <- value
ibm_inla_subset(mapper, ...)
ibm_invalid_output(mapper, input, state, ...)
## Default S3 method:
ibm_n(mapper, inla_f = FALSE, ...)
## Default S3 method:
ibm_n_output(mapper, input, state = NULL, inla_f = FALSE, ...)
## Default S3 method:
ibm_values(mapper, inla_f = FALSE, ...)
## Default S3 method:
ibm_is_linear(mapper, ...)
## Default S3 method:
ibm_jacobian(mapper, input, state = NULL, ...)
## Default S3 method:
ibm_linear(mapper, input, state, ...)
## Default S3 method:
ibm_simplify(mapper, input = NULL, state = NULL, ...)
## Default S3 method:
ibm_eval(mapper, input, state = NULL, ..., jacobian = NULL)
## Default S3 method:
ibm_eval2(mapper, input, state, ...)
## Default S3 method:
ibm_names(mapper, ...)
## Default S3 method:
ibm_inla_subset(mapper, ...)
## Default S3 method:
ibm_invalid_output(mapper, input, state, ...)
Arguments
mapper |
A mapper S3 object, inheriting from |
inla_f |
logical; when |
... |
Arguments passed on to other methods |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
value |
a character vector of the same length as the number of sub-mappers in the mapper |
jacobian |
For |
Functions
-
ibm_n()
: Implementations must return the size of the latent vector being mapped to. -
ibm_n_output()
: Implementations must return an integer denoting the mapper output length. The default implementation returnsNROW(input)
. Mappers such asbm_multi
andbm_collect
, that can acceptlist()
inputs require their own methods implementations. -
ibm_values()
: Wheninla_f=TRUE
, implementations must return a vector that would be interpretable by anINLA::f(..., values = ...)
specification. The exception is the method forbm_multi
, that returns a multi-column data frame ifmulti=TRUE
. -
ibm_is_linear()
: Implementations must returnTRUE
orFALSE
. IfTRUE
(returned by the default method unless the mapper contains anis_linear
variable), users of the mapper may assume the mapper is linear. -
ibm_jacobian()
: Implementations must return a (sparse) matrix of sizeibm_n_output(mapper, input, inla_f)
byibm_n(mapper, inla_f = FALSE)
. Theinla_f=TRUE
argument should only affect the allowed type of input format. -
ibm_linear()
: Implementations must return a bm_taylor object The linearisation information includesoffset
,jacobian
, andstate0
. The state information indicates for which state theoffset
was evaluated, withNULL
meaning all-zero. The linearised mapper output is defined aseffect(input, state) = offset(input, state0) + jacobian(input, state0) %*% (state - state0)
The default method calls
ibm_eval()
andibm_jacobian()
to generate the needed information. -
ibm_simplify()
: Implementations must return a bru_mapper object. The default method returnsibm_linear(...)
for linear mappers, and the originalmapper
for non-linear mappers. -
ibm_eval()
: Implementations must return a vector of lengthibm_n_output(...)
. Theinput
contents must be in a format accepted byibm_jacobian(...)
for the mapper. -
ibm_eval2()
: Implementations must return a list with elementsoffset
andjacobian
. Theinput
contents must be in a format accepted byibm_jacobian(...)
for the mapper. -
ibm_names()
: Implementations must return a character vector of sub-mapper names, orNULL
. Intended for providing information about multi-mappers and mapper collections. -
ibm_names(mapper) <- value
: Set mapper names. -
ibm_inla_subset()
: Implementations must return a logical vector ofTRUE/FALSE
for the subset such that, given the full A matrix and values output,A[, subset, drop = FALSE]
andvalues[subset]
(orvalues[subset, , drop = FALSE]
for data.frame values) are equal to theinla_f = TRUE
version of A and values. The default method uses theibm_values
output to construct the subset indexing. -
ibm_invalid_output()
: Implementations should return a logical vector of lengthibm_n_output(mapper, input, state, ...)
indicating which, if any, output elements ofibm_eval(mapper, input, state, ...)
are known to be invalid. For for multi/collect mappers, a list, when given amulti=TRUE
argument. -
ibm_n(default)
: Returns a non-null element 'n' from the mapper object, and gives an error if it doesn't exist. Ifinla_f=TRUE
, first checks for a 'n_inla' element. -
ibm_n_output(default)
: ReturnsNROW(input)
-
ibm_values(default)
: Returns a non-null element 'values' from the mapper object, andseq_len(ibm_n(mapper))
if it doesn't exist. -
ibm_is_linear(default)
: Returns logicalis_linear
from the mapper object if it exists, and otherwiseTRUE
. -
ibm_jacobian(default)
: Mapper classes must implement their ownibm_jacobian
method. -
ibm_linear(default)
: Callsibm_eval()
andibm_jacobian()
and returns abm_taylor
object. Thestate0
information in the affine mapper indicates for which state theoffset
was evaluated; The affine mapper output is defined aseffect(input, state) = offset(input, state0) + jacobian(input, state0) %*% (state - state0)
-
ibm_simplify(default)
: Callsibm_linear()
for linear mappers, and returns the original mapper for non-linear mappers. -
ibm_eval(default)
: Verifies that the mapper is linear withibm_is_linear()
, and then computes a linear mapping asibm_jacobian(...) %*% state
. Whenstate
isNULL
, a zero vector of lengthibm_n_output(...)
is returned. -
ibm_eval2(default)
: Callsjacobian <- ibm_jacobian(...)
andoffset <- ibm_eval(..., jacobian = jacobian)
and returns a list with elementsoffset
andjacobian
, as needed byibm_linear.default()
and similar methods. Mapper classes can implement their ownibm_eval2
method if joint construction of evaluation and Jacobian is more efficient than separate or sequential construction. -
ibm_names(default)
: ReturnsNULL
-
ibm_inla_subset(default)
: Uses theibm_values
output to construct the inla subset indexing, passing extra arguments such asmulti
on to the methods (this means it supports both regular vector values andmulti=1
data.frame values). -
ibm_invalid_output(default)
: Returns an all-FALSE
logical vector.
See Also
bru_mapper for constructor methods, and bru_get_mapper for hooks to extract mappers from latent model object class objects.
Other mappers:
bm_aggregate()
,
bm_collect()
,
bm_const()
,
bm_factor()
,
bm_fmesher()
,
bm_harmonics()
,
bm_index()
,
bm_linear()
,
bm_logsumexp()
,
bm_marginal()
,
bm_matrix()
,
bm_mesh_B()
,
bm_multi()
,
bm_pipe()
,
bm_repeat()
,
bm_scale()
,
bm_shift()
,
bm_sum()
,
bm_taylor()
,
bru_get_mapper()
,
bru_mapper()
,
bru_mapper.fm_mesh_1d()
,
bru_mapper.fm_mesh_2d()
Examples
# ibm_names
mapper <- bm_multi(list(A = bm_index(2), B = bm_index(2)))
ibm_names(mapper)
ibm_names(mapper) <- c("new", "names")
ibm_names(mapper)
Create an inlabru model object from model components
Description
The inlabru syntax for model formulae is different from what
INLA::inla
considers a valid.
In inla most of the effects are defined by adding an f(...)
expression to
the formula.
In inlabru the f
is replaced by an arbitrary (exceptions: const
and
offset
) string that will determine the label of the effect. See Details for
further information.
Usage
bru_model(components, lhoods, options = list(), .envir = parent.frame())
## S3 method for class 'bru_model'
summary(object, ...)
## S3 method for class 'summary_bru_model'
print(x, ...)
## S3 method for class 'bru_model'
print(x, ...)
Arguments
components |
A bru_comp_list object |
lhoods |
Either a |
options |
A bru_options options object or a list of options passed
on to |
.envir |
The environment in which the components are evaluated. |
object |
Object to operate on |
... |
Arguments passed on to other methods |
x |
An object to be printed |
Details
For instance
y ~ f(myspde, ...)
in INLA is equivalent to
y ~ myspde(...)
in inlabru.
A disadvantage of the inla way is that there is no clear separation between
the name of the covariate and the label of the effect. Furthermore, for some
models like SPDE it is much more natural to use spatial coordinates as
covariates rather than an index into the SPDE vertices. For this purpose
inlabru provides the main
argument. For convenience, the main
argument
can be used like the first argument of the f function, e.g., and is the first
argument of the component definition.
The INLA
model formula
y ~ f(temperature, model = 'linear')
is equivalent to the inlabru
component and formula definition
y ~ temperature(temperature, model = 'linear')
and
y ~ temperature(main = temperature, model = 'linear')
as well as
y ~ temperature(model = 'linear')
which sets main = temperature
.
On the other hand, main
can also be a function mapping, e.g the
sp::coordinates()
function:
y ~ mySPDE(coordinates, ...)
This extracts the coordinates from the data object, and maps it to the latent
field via the information given in the mapper
, which by default is
extracted from the model
object, in the case of spde
model objects.
Morevover, main
can be any expression that evaluates within your data as an
environment.
For instance, if your data has columns 'a' and 'b', you can create a fixed
effect of 'sin(a+b)' by setting map
in the following way:
y ~ myEffect(sin(a+b))
Value
A bru_model object
Mapper methods for model objects
Description
Methods for the ibm_linear()
and ibm_simplify()
methods for
bru model objects and related classes.
Usage
## S3 method for class 'bru_model'
ibm_linear(mapper, input, state = NULL, ...)
## S3 method for class 'bru_comp_list'
ibm_linear(mapper, input, state = NULL, ...)
## S3 method for class 'bru_comp'
ibm_linear(mapper, input, state = NULL, ...)
## S3 method for class 'bru_model'
ibm_simplify(mapper, input = NULL, state = NULL, ...)
## S3 method for class 'bru_comp'
ibm_simplify(mapper, input = NULL, state = NULL, ...)
## S3 method for class 'bru_comp_list'
ibm_simplify(mapper, input = NULL, state = NULL, ...)
Arguments
mapper |
A mapper S3 object, inheriting from |
input |
Data input for the mapper. |
state |
A vector of latent state values for the mapping,
of length |
... |
Arguments passed on to other methods |
Functions
-
ibm_linear(bru_model)
: Returns a list (one element per observation model) of bm_list objects, each with one bm_taylor entry for each included component. -
ibm_simplify(bru_model)
: Returns a list (one element per observation model) of bm_list objects, each with one bru_mapper entry for each included component.
Observation model construction for usage with bru()
Description
Observation model construction for usage with bru()
.
Note: Prior to version 2.12.0
, this function was called like()
, and that
alias will remain for a while until examples etc have been updated and users
made aware of the change. The name change is to avoid issues with namespace
clashes, e.g. with data.table::like()
, and also to signal that the function
defines observation models, not just likelihood functions.
Usage
bru_obs(
formula = . ~ .,
family = "gaussian",
data = NULL,
response_data = NULL,
data_extra = NULL,
E = NULL,
Ntrials = NULL,
weights = NULL,
scale = NULL,
domain = NULL,
samplers = NULL,
ips = NULL,
used = NULL,
allow_combine = NULL,
aggregate = NULL,
aggregate_input = NULL,
control.family = NULL,
tag = NULL,
options = list(),
.envir = parent.frame(),
include = deprecated(),
exclude = deprecated(),
include_latent = deprecated()
)
like(
formula = . ~ .,
family = "gaussian",
data = NULL,
response_data = NULL,
E = NULL,
Ntrials = NULL,
weights = NULL,
scale = NULL,
domain = NULL,
samplers = NULL,
ips = NULL,
used = NULL,
allow_combine = NULL,
control.family = NULL,
tag = NULL,
options = list(),
.envir = parent.frame(),
mesh = deprecated(),
include = deprecated(),
exclude = deprecated(),
include_latent = deprecated()
)
bru_obs_list(...)
## S3 method for class 'list'
bru_obs_list(object, ..., .envir = NULL)
## S3 method for class 'bru_obs_list'
bru_obs_list(..., .envir = NULL)
## S3 method for class 'bru_obs'
c(..., .envir = NULL)
## S3 method for class 'bru_obs_list'
c(..., .envir = NULL)
## S3 method for class 'bru_obs_list'
x[i]
like_list(...)
bru_like_list(...)
Arguments
formula |
a |
family |
A string identifying a valid |
data |
Predictor expression-specific data, as a |
response_data |
Observation/response-specific data for models that need
different size/format for inputs and response variables, as a |
data_extra |
object convertible with |
E |
Exposure/effort parameter for family = 'poisson' passed on to
|
Ntrials |
A vector containing the number of trials for the 'binomial'
likelihood. Default taken from |
weights |
Fixed (optional) weights parameters of the likelihood, so the
log-likelihood For |
scale |
Fixed (optional) scale parameters of the precision for several models, such as Gaussian and student-t response models. |
domain , samplers , ips |
Arguments used for
|
used |
Either |
allow_combine |
logical; If |
aggregate |
character ("none", "sum", "average", "logsumexp", or
"logaverageexp", as defined by |
aggregate_input |
list(block = .data.[[".block"]], weights = .data.[["weight"]], n_block = bru_response_size(.response_data.)) |
control.family |
A optional |
tag |
character; Name that can be used to identify the relevant parts
of INLA predictor vector output, via |
options |
A bru_options options object or a list of options passed
on to |
.envir |
The evaluation environment to use for special arguments ( |
include , exclude , include_latent |
|
mesh |
|
... |
For |
object |
A list of |
x |
|
i |
indices specifying elements to extract |
Value
A likelihood configuration which can be used to parameterise bru()
.
Methods (by generic)
-
c(bru_obs)
: Combine severalbru_obs
objects into abru_obs_list
object
Functions
-
like()
:Legacy
like()
method forinlabru
prior to version2.12.0
. Usebru_obs()
instead. -
bru_obs_list()
: Combinebru_obs
observation model object into abru_obs_list
object -
bru_obs_list(list)
: Combine one or more lists ofbru_obs
observation model objects into abru_obs_list
object -
bru_obs_list(bru_obs_list)
: Combine a list ofbru_obs
observation model objects into abru_obs_list
object -
c(bru_obs_list)
: Combine severalbru_obs_list
objects into abru_obs_list
object -
like_list()
:Backwards compatibility for versions
<= 2.12.0
. For later versions, useas_bru_obs_list()
,bru_obs_list()
, orc()
. -
bru_like_list()
:Backwards compatibility for versions
<= 2.12.0.9017
. For later versions, useas_bru_obs_list()
,bru_obs_list()
orc()
.
Author(s)
Fabian E. Bachl bachlfab@gmail.com
Finn Lindgren finn.lindgren@gmail.com
See Also
bru_response_size()
, bru_used()
, bru_comp()
,
bru_comp_eval()
Examples
if (bru_safe_inla() &&
require(ggplot2, quietly = TRUE)) {
# The 'bru_obs()' (previously 'like()') function's main purpose is to set up
# observation models, both for single- and multi-likelihood models.
# The following example generates some random covariates which are observed
# through two different random effect models with different likelihoods
# Generate the data
set.seed(123)
n1 <- 200
n2 <- 10
x1 <- runif(n1)
x2 <- runif(n2)
z2 <- runif(n2)
y1 <- rnorm(n1, mean = 2 * x1 + 3)
y2 <- rpois(n2, lambda = exp(2 * x2 + z2 + 3))
df1 <- data.frame(y = y1, x = x1)
df2 <- data.frame(y = y2, x = x2, z = z2)
# Single likelihood models and inference using bru are done via
cmp1 <- y ~ -1 + Intercept(1) + x
fit1 <- bru(cmp1, family = "gaussian", data = df1)
summary(fit1)
cmp2 <- y ~ -1 + Intercept(1) + x + z
fit2 <- bru(cmp2, family = "poisson", data = df2)
summary(fit2)
# A joint model has two likelihoods, which are set up using the bru_obs
# function
lik1 <- bru_obs(
"gaussian",
formula = y ~ x + Intercept,
data = df1,
tag = "norm"
)
lik2 <- bru_obs(
"poisson",
formula = y ~ x + z + Intercept,
data = df2,
tag = "pois"
)
# The union of effects of both models gives the components needed to run bru
jcmp <- ~ x + z + Intercept(1)
jfit <- bru(jcmp, lik1, lik2)
bru_index(jfit, "norm")
bru_index(jfit, "pois")
# Compare the estimates
p1 <- ggplot() +
gg(fit1$summary.fixed, bar = TRUE) +
ylim(0, 4) +
ggtitle("Model 1")
p2 <- ggplot() +
gg(fit2$summary.fixed, bar = TRUE) +
ylim(0, 4) +
ggtitle("Model 2")
pj <- ggplot() +
gg(jfit$summary.fixed, bar = TRUE) +
ylim(0, 4) +
ggtitle("Joint model")
multiplot(p1, p2, pj)
}
Utility functions for bru observation model objects
Description
Utility functions for bru observation model objects
Usage
bru_obs_inla_family(x, ...)
## S3 method for class 'bru_obs'
bru_obs_inla_family(x, ...)
## S3 method for class 'bru_obs_list'
bru_obs_inla_family(x, ...)
bru_obs_control_family(x, control.family = NULL, ...)
## S3 method for class 'bru_obs'
bru_obs_control_family(x, control.family = NULL, ...)
## S3 method for class 'bru_obs_list'
bru_obs_control_family(x, control.family = NULL, ...)
Arguments
x |
Object of |
control.family |
list of INLA |
Value
-
bru_obs_inla_family()
returns a string or vector of strings
-
bru_obs_control_family()
returns a list withINLA::control.family
options, or a list of such lists, with one element per observation model
See Also
Create or update an options objects
Description
Create a new options object, or merge information from several objects.
The _get
, _set
, and _reset
functions operate on a global
package options override object. In many cases, setting options in
specific calls to bru()
is recommended instead.
Usage
bru_options(...)
as.bru_options(x = NULL)
bru_options_default()
bru_options_check(options, ignore_null = TRUE)
bru_options_get(name = NULL, include_default = TRUE)
bru_options_set(..., .reset = FALSE)
bru_options_reset()
bru_options_set_local(..., .reset = FALSE, .envir = parent.frame())
Arguments
... |
A collection of named options, optionally including one or more
|
x |
An object to be converted to an |
options |
An |
ignore_null |
Ignore missing or NULL options. |
name |
Either |
include_default |
logical; If |
.reset |
For |
.envir |
The environment in which to set the options.
Default: |
Value
bru_options()
returns a bru_options
object.
For as.bru_options()
, NULL
or no input returns an empty
bru_options
object, a list
is converted via bru_options(...)
,
and bru_options
input is passed through. Other types of input generates
an error.
bru_options_default()
returns an bru_options
object containing
default options.
bru_options_check()
returns a logical
; TRUE
if the object
contains valid options for use by other functions
bru_options_get
returns either an bru_options
object, for
name == NULL
, the contents of single option, if name
is a options name
string, or a named list of option contents, if name
is a list of option
name strings.
bru_options_set()
returns a copy of the global override options,
invisibly (as bru_options_get(include_default = FALSE)
).
Functions
-
as.bru_options()
: Coerces inputs to abru_options
object. -
bru_options_default()
: Returns the default options. -
bru_options_check()
: Checks for valid contents of abru_options
object, and produces warnings for invalid options. -
bru_options_get()
: Used to access global package options. -
bru_options_set()
: Used to set global package options. -
bru_options_reset()
: Clears the global option overrides. -
bru_options_set_local()
: Sets local option overrides, that are automatically reset usingwithr::defer()
.
Valid options
For bru_options
and bru_options_set
, recognised options are:
- bru_verbose
logical or numeric; if
TRUE
, log messages ofverbosity
\le 1
are printed bybru_log_message()
. If numeric, log messages of verbosity\le
bru_verbose
are printed. For line search details, setbru_verbose=2
or3
. Default: 0, to not print any messages- bru_verbose_store
logical or numeric; if
TRUE
, log messages ofverbosity
\le 1
are stored bybru_log_message()
. If numeric, log messages of verbosity\le
are stored. Default: Inf, to store all messages.- bru_run
If TRUE, run inference. Otherwise only return configuration needed to run inference.
- bru_max_iter
maximum number of inla iterations, default 10. Also see the
bru_method$rel_tol
and related options below.- bru_initial
An
inla
object returned from previous calls ofINLA::inla
,bru()
orlgcp()
, or a list of named vectors of starting values for the latent variables. This will be used as a starting point for further improvement of the approximate posterior.- bru_int_args
List of arguments passed all the way to the integration method
ipoints
andint.polygon
for 'cp' family models;- method
"stable" or "direct". For "stable" (default) integration points are aggregated to mesh vertices.
- nsub1
Number of integration points per knot interval in 1D. Default 30.
- nsub2
Number of integration points along a triangle edge for 2D. Default 9.
- nsub
Deprecated parameter that overrides
nsub1
andnsub2
if set. DefaultNULL
.
- bru_method
List of arguments controlling the iterative inlabru method:
- taylor
'pandemic' (default, from version 2.1.15).
- search
Either 'all' (default), to use all available line search methods, or one or more of
- 'finite'
(reduce step size until predictor is finite)
- 'contract'
(decrease step size until trust hypersphere reached)
- 'expand'
(increase step size until no improvement)
- 'optimise'
(fast approximate error norm minimisation)
To disable line search, set to an empty vector. Line search is not available for
taylor="legacy"
.- factor
Numeric,
> 1
determining the line search step scaling multiplier. Default(1 + \sqrt{5})/2
.- rel_tol
Stop the iterations when the largest change in linearisation point (the conditional latent state mode) in relation to the estimated posterior standard deviation is less than
rel_tol
. Default 0.1 (ten percent).- max_step
The largest allowed line search step factor. Factor 1 is the full INLA step. Default is 2.
- line_opt_method
Which method to use for the line search optimisation step. Default "onestep", using a quadratic approximation based on the value and gradient at zero, and the value at the current best step length guess. The method "full" does line optimisation on the full nonlinear predictor; this is slow and intended for debugging purposes only.
- bru_compress_cp
logical; when
TRUE
, compress the\sum_{i=1}^n \eta_i
part of the Poisson process likelihood (family="cp"
) into a single term, withy=n
, and predictormean(eta)
. Default:TRUE
- bru_debug
logical; when
TRUE
, activate temporary debug features for package development. Default:FALSE
inla()
options-
All options not starting with
bru_
are passed on toinla()
, sometimes after altering according to the needs of the inlabru method. Warning: Due to how inlabru currently constructs theinla()
call, themean
,prec
,mean.intercept
, andprec.intercept
settings incontrol.fixed
will have no effect. Until a more elegant alternative has been implemented, use explicitmean.linear
andprec.linear
specifications in eachmodel="linear"
component instead.
See Also
bru_options()
, bru_options_default()
, bru_options_get()
Examples
## Not run:
if (interactive()) {
# Combine global and user options:
options1 <- bru_options(bru_options_get(), bru_verbose = TRUE)
# Create a proto-options object in two equivalent ways:
options2 <- as.bru_options(bru_verbose = TRUE)
options2 <- as.bru_options(list(bru_verbose = TRUE))
# Combine options objects:
options3 <- bru_options(options1, options2)
}
## End(Not run)
## Not run:
if (interactive()) {
bru_options_check(bru_options(bru_max_iter = "text"))
}
## End(Not run)
bru_options_get("bru_verbose")
## Not run:
if (interactive()) {
bru_options_set(
bru_verbose = TRUE,
verbose = TRUE
)
}
## End(Not run)
my_fun <- function(val) {
bru_options_set_local(bru_verbose = val)
bru_options_get("bru_verbose")
}
# Inside the function, the bru_verbose option is changed.
# Outside the function, the bru_verbose option is unchanged.
print(my_fun(TRUE))
print(bru_options_get("bru_verbose"))
print(my_fun(FALSE))
print(bru_options_get("bru_verbose"))
Response size queries
Description
Extract the number of response values from bru
and related objects.
Usage
bru_response_size(object)
## Default S3 method:
bru_response_size(object)
## S3 method for class 'inla.surv'
bru_response_size(object)
## S3 method for class 'bru_obs'
bru_response_size(object)
## S3 method for class 'bru_obs_list'
bru_response_size(object)
## S3 method for class 'bru_info'
bru_response_size(object)
## S3 method for class 'bru'
bru_response_size(object)
Arguments
object |
An object from which to extract response size(s). |
Value
An integer
vector.
Methods (by class)
-
bru_response_size(default)
: Extract the number of observations from an object supportingNROW()
. -
bru_response_size(inla.surv)
: Extract the number of observations from aninla.surv
object. -
bru_response_size(bru_obs)
: Extract the number of observations from abru_obs
object. -
bru_response_size(bru_obs_list)
: Extract the number of observations from abru_obs_list
object, as a vector with one value per observation model. -
bru_response_size(bru_info)
: Extract the number of observations from abru_info
object, as a vector with one value per observation model. -
bru_response_size(bru)
: Extract the number of observations from abru
object, as a vector with one value per observation model.
See Also
Examples
bru_response_size(
bru_obs(y ~ 1, data = data.frame(y = rnorm(10)), family = "gaussian")
)
Load INLA safely for examples and tests
Description
Loads the INLA package with requireNamespace("INLA", quietly = TRUE)
, and
optionally checks and sets the multicore num.threads
INLA option.
Usage
bru_safe_inla(multicore = NULL, quietly = FALSE, minimum_version = "23.1.31")
Arguments
multicore |
logical; if |
quietly |
logical; if |
minimum_version |
character; the minimum required INLA version. Default 23.1.31 (should always match the requirement in the package DESCRIPTION) |
Value
logical; TRUE
if INLA was loaded safely, otherwise FALSE
Examples
## Not run:
if (bru_safe_inla()) {
# Run inla dependent calculations
}
## End(Not run)
Check for potential sp
version compatibility issues
Description
Loads the sp package with requireNamespace("sp", quietly = TRUE)
, and
checks and optionally sets the sp
evolution status flag if rgdal
is
unavailable.
Usage
bru_safe_sp(quietly = FALSE, force = FALSE, minimum_version = "1.4-5")
Arguments
quietly |
logical; if |
force |
logical; If |
minimum_version |
character; the minimum required INLA version. Default 1.4-5 (should always match the requirement in the package DESCRIPTION) |
Value
Returns (invisibly) FALSE
if a potential issue is detected, and
give a message if quietly
is FALSE
. Otherwise returns TRUE
Examples
## Not run:
if (bru_safe_sp() &&
require("sp")) {
# Run sp dependent calculations
}
## End(Not run)
Set missing values in observation models
Description
Set all or parts of the observation model response data
to NA
, for example for use in cross validation (with bru_rerun()
)
or prior sampling (with bru_rerun()
and generate()
).
Usage
bru_set_missing(object, keep = FALSE, ...)
## S3 method for class 'bru'
bru_set_missing(object, keep = FALSE, ...)
## S3 method for class 'bru_obs_list'
bru_set_missing(object, keep = FALSE, ...)
## S3 method for class 'bru_obs'
bru_set_missing(object, keep = FALSE, ...)
Arguments
object |
A |
keep |
For For |
... |
Additional arguments passed on to the |
Details
For bru
and bru_obs_list
,
keep
must be either a single logical, which is expanded to a list,a logical vector, which is converted to a list,
an unnamed list of the same length as the number of observation models, with elements compatible with the
bru_obs
method, ora named list with elements compatible with the
bru_obs
method, and only the namedbro_obs
models are acted upon, i.e. the elements not present in the list are treated askeep = TRUE
.
E.g.: keep = list(b = FALSE)
sets all observations in model b
to missing,
and does not change model a
.
E.g.: keep = list(a = 1:4, b = -(3:5))
keeps only observations 1:4
of
model a
, marking the rest as missing, and sets observations 3:5
of model
b
to missing.
Examples
obs <- c(
A = bru_obs(y_A ~ ., data = data.frame(y_A = 1:6)),
B = bru_obs(y_B ~ ., data = data.frame(y_B = 11:15))
)
bru_response_size(obs)
lapply(
bru_set_missing(obs, keep = FALSE),
function(x) {
x[["response_data"]][["BRU_response"]]
}
)
lapply(
bru_set_missing(obs, keep = list(B = FALSE)),
function(x) {
x[["response_data"]][["BRU_response"]]
}
)
lapply(
bru_set_missing(obs, keep = list(1:4, -(3:5))),
function(x) {
x[["response_data"]][["BRU_response"]]
}
)
Standardise inla hyperparameter names
Description
The inla hyperparameter output uses parameter names that can include whitespace and special characters. This function replaces those characters with underscores.
Usage
bru_standardise_names(x)
Arguments
x |
character vector; names to be standardised |
Value
A character vector with standardised names
Examples
bru_standardise_names("Precision for the Gaussian observations")
Summarise and annotate data
Description
Summarise and annotate data
Usage
bru_summarise(
data,
probs = c(0.025, 0.5, 0.975),
x = NULL,
cbind.only = FALSE,
max_moment = 2
)
Arguments
data |
A list of samples, each either numeric or a |
probs |
A numeric vector of probabilities with values in |
x |
A |
cbind.only |
If TRUE, only |
max_moment |
integer, at least 2. Determines the largest moment
order information to include in the output. If |
Value
A data.frame
or Spatial[Points/Pixels]DataFrame
with summary
statistics, "mean", "sd", paste0("q", probs)
, "mean.mc_std_err",
"sd.mc_std_err"
Examples
bru_summarise(matrix(rexp(10000), 10, 1000), max_moment = 4, probs = NULL)
Extract timing information from fitted bru object
Description
Extracts a data.frame or tibble with information about the Time
(CPU),
System
, and Elapsed
time for each step of a bru()
run.
Usage
bru_timings(object, ...)
## S3 method for class 'bru'
bru_timings(object, ...)
Arguments
object |
A fitted |
... |
unused |
Plot inlabru iteration timings
Description
Draws the time per iteration for preprocessing (including linearisation),
inla()
calls, and
line search. Iteration 0
is the time used for defining the model structure.
Usage
bru_timings_plot(x)
Arguments
x |
a bru object, typically a result from |
Details
Requires the "ggplot2" package to be installed.
Examples
## Not run:
fit <- bru(...)
bru_timings_plot(fit)
## End(Not run)
Transformation tools
Description
Tools for transforming between N(0,1) variables and other distributions in predictor expressions
Usage
bru_forward_transformation(qfun, x, ..., tail.split. = 0)
bru_inverse_transformation(pfun, x, ..., tail.split. = NULL)
Arguments
qfun |
A quantile function object, such as |
x |
Values to be transformed |
... |
Distribution parameters passed on to the |
tail.split. |
For x-values larger than |
pfun |
A CDF function object, such as |
Value
For
bru_forward_transformation
, a numeric vector
For
bru_inverse_transformation
, a numeric vector
Examples
u <- rnorm(5, 0, 1)
y <- bru_forward_transformation(qexp, u, rate = 2)
v <- bru_inverse_transformation(pexp, y, rate = 2)
rbind(u, y, v)
List components used in a model
Description
Create or extract information about which components are used by a model, or
its individual observation models. If a non-NULL labels
argument is
supplied, also calls bru_used_update()
on the bru_used
objects.
Usage
bru_used(x = NULL, ...)
## S3 method for class ''NULL''
bru_used(
x = NULL,
...,
effect = NULL,
effect_exclude = NULL,
latent = NULL,
labels = NULL
)
## S3 method for class 'character'
bru_used(
x,
...,
effect = NULL,
effect_exclude = NULL,
latent = NULL,
labels = NULL
)
## S3 method for class 'expression'
bru_used(
x,
...,
effect = NULL,
effect_exclude = NULL,
latent = NULL,
labels = NULL
)
## S3 method for class 'formula'
bru_used(
x,
...,
effect = NULL,
effect_exclude = NULL,
latent = NULL,
labels = NULL
)
## S3 method for class 'bru'
bru_used(x, ..., join = TRUE)
## S3 method for class 'list'
bru_used(x, ..., join = TRUE)
## S3 method for class 'bru_obs'
bru_used(x, ...)
## S3 method for class 'bru_used'
bru_used(x, labels = NULL, ...)
## S3 method for class 'bru_used'
format(x, ...)
## S3 method for class 'bru_used'
summary(object, ...)
## S3 method for class 'bru_used'
print(x, ...)
Arguments
x |
An object that contains information about used components |
... |
Parameters passed on to the other methods |
effect |
character; components used as effects. When |
effect_exclude |
character; components to specifically exclude from
effect evaluation. When |
latent |
character; components used as |
labels |
character; component labels passed on to
|
join |
Whether to join list output into a single object; Default may depend on the input object class |
Details
The arguments effect
, effect_exclude
, and latent
control what
components and effects are available for use in predictor expressions.
effect
-
Character vector of component labels that are used as effects by the predictor expression; If
NULL
(default), the names are extracted from the formula. exclude
-
Character vector of component labels to be excluded from the effect list even if they have been auto-detected as being necessary. Default is
NULL
; do not remove any components from the inclusion list. include_latent
Character vector. Specifies which latent state variables need to be directly available to the predictor expression, with a
_latent
suffix. This also makes evaluator functions with suffix_eval
available, taking parametersmain
,group
, andreplicate
, taking values for where to evaluate the component effect that are different than those defined in the component definition itself (seebru_comp_eval()
). IfNULL
, the use of_latent
and_eval
in the predictor expression is detected automatically.
Value
A bru_used
object (a list with elements effect
and latent
), or a list of such objects
(for methods with join = FALSE
)
Methods (by class)
-
bru_used(`NULL`)
: Create abru_used
object from effect name character vectors. -
bru_used(character)
: Create abru_used
object from acharacter
representation of an expression. -
bru_used(expression)
: Create abru_used
object from an expression object. -
bru_used(formula)
: Create abru_used
object from a formula (only the right-hand side is used). -
bru_used(bru)
: Extract thebru_used
information for the collection of observation models used in abru
object. -
bru_used(list)
: Extract thebru_used
information for each element of a list, and optionally join into a singlebru_used
object. -
bru_used(bru_obs)
: Extract thebru_used
information for the collection of observation models used in abru
observation modelbru_obs
object. -
bru_used(bru_used)
: Convenience method that takes an existingbru_used
object and callsbru_used_update()
iflabels
is non-NULL.
Methods (by generic)
-
format(bru_used)
: Text formatting method forbru_used
objects. -
summary(bru_used)
: Summary method forbru_used
objects. -
print(bru_used)
: Print method forbru_used
objects.
See Also
Other bru_used:
bru_used_update()
,
bru_used_vars()
Examples
(used <- bru_used(~.))
bru_used(used, labels = c("a", "c"))
(used <- bru_used(~ a + b + c_latent + d_latent))
bru_used(used, labels = c("a", "c"))
(used <- bru_used(expression(a + b + c_latent + d_latent)))
bru_used(used, labels = c("a", "c"))
Update used_component information objects
Description
Merge available component labels information with used components information.
Usage
bru_used_update(x, labels, ...)
## S3 method for class 'bru_obs_list'
bru_used_update(x, labels, ...)
## S3 method for class 'bru_obs'
bru_used_update(x, labels, ...)
## S3 method for class 'bru_used'
bru_used_update(x, labels, ...)
Arguments
x |
Object to be updated |
labels |
character vector of component labels |
... |
Unused |
Value
An updated version of x
See Also
Other bru_used:
bru_used()
,
bru_used_vars()
Extract basic variable names from expression
Description
Extracts the variable names from an R expression by pre- and post-processing
around all.vars()
.
First replaces $
with [[
indexing, so that internal column/variable names
are ignored, then calls all.vars()
.
Usage
bru_used_vars(x, functions = FALSE)
## S3 method for class 'character'
bru_used_vars(x, functions = FALSE)
## S3 method for class 'expression'
bru_used_vars(x, functions = FALSE)
## S3 method for class 'formula'
bru_used_vars(x, functions = FALSE)
Arguments
x |
A |
functions |
logical; if TRUE, include function names |
Value
If successful, a character vector, otherwise NULL
Methods (by class)
-
bru_used_vars(formula)
: Only the right-hand side is used.
See Also
Other bru_used:
bru_used()
,
bru_used_update()
Examples
bru_used_vars(~.)
bru_used_vars(~ a + b + c_latent + d_eval())
bru_used_vars(expression(a + b + c_latent + d_eval()))
bru_used_vars(~., functions = TRUE)
bru_used_vars(~ a + b + c_latent + d_eval(), functions = TRUE)
bru_used_vars(expression(a + b + c_latent + d_eval()), functions = TRUE)
bru_used_vars(a ~ b)
bru_used_vars(expression(a ~ b))
Summarise DIC and WAIC from lgcp
objects.
Description
Calculates DIC and/or WAIC differences and produces an ordered summary.
Usage
deltaIC(..., criterion = "DIC")
Arguments
... |
Comma-separated objects inheriting from class |
criterion |
character vector. If it includes 'DIC', computes DIC differences; If it contains 'WAIC', computes WAIC differences. Default: 'DIC' |
Value
A data frame with each row containing the Model name, DIC and Delta.DIC, and/or WAIC and Delta.WAIC.
Examples
if (bru_safe_inla()) {
# Generate some data
input.df <- data.frame(idx = 1:10, x = cos(1:10))
input.df <- within(
input.df,
y <- rpois(10, 5 + 2 * cos(1:10) + rnorm(10, mean = 0, sd = 0.1))
)
# Fit two models
fit1 <- bru(
y ~ x,
family = "poisson",
data = input.df,
options = list(control.compute = list(dic = TRUE))
)
fit2 <- bru(
y ~ x + rand(idx, model = "iid"),
family = "poisson",
data = input.df,
options = list(control.compute = list(dic = TRUE))
)
# Compare DIC
deltaIC(fit1, fit2)
}
Variance and correlations measures for prediction components
Description
Calculates local and integrated variance and correlation measures as introduced by Yuan et al. (2017).
Usage
devel.cvmeasure(joint, prediction1, prediction2, samplers = NULL, mesh = NULL)
Arguments
joint |
A joint |
prediction1 |
A |
prediction2 |
A |
samplers |
An |
mesh |
The fmesher::fm_mesh_2d for which the prediction was performed (required for cumulative Vmeasure). |
Value
Variance and correlations measures.
References
Y. Yuan, F. E. Bachl, F. Lindgren, D. L. Brochers, J. B. Illian, S. T. Buckland, H. Rue, T. Gerrodette. 2017. Point process models for spatio-temporal distance sampling data from a large-scale survey of blue whales. https://arxiv.org/abs/1604.06013
Examples
if (bru_safe_inla() &&
require("ggplot2", quietly = TRUE) &&
require("patchwork", quietly = TRUE) &&
require("sn", quietly = TRUE) &&
require("terra", quietly = TRUE) &&
require("sf", quietly = TRUE) &&
require("RColorBrewer", quietly = TRUE) &&
require("dplyr", quietly = TRUE) &&
require("magrittr", quietly = TRUE)) {
# Load Gorilla data
gorillas <- gorillas_sf
gorillas$gcov <- gorillas_sf_gcov()
# Use RColorBrewer
# Fit a model with two components:
# 1) A spatial smooth SPDE
# 2) A spatial covariate effect (vegetation)
pcmatern <- INLA::inla.spde2.pcmatern(
gorillas$mesh,
prior.sigma = c(0.1, 0.01),
prior.range = c(0.01, 0.01)
)
cmp <- geometry ~ 0 +
vegetation(gorillas$gcov$vegetation, model = "factor_contrast") +
spde(geometry, model = pcmatern) -
Intercept(1)
fit <- lgcp(
cmp,
gorillas$nests,
samplers = gorillas$boundary,
domain = list(geometry = gorillas$mesh),
options = list(control.inla = list(int.strategy = "eb"))
)
# Predict SPDE and vegetation at a grid covering the domain of interest
pred_loc <- fm_pixels(
gorillas$mesh,
mask = gorillas$boundary,
dims = c(200, 200),
format = "sf"
)
pred <- predict(
fit,
pred_loc,
~ list(
joint = spde + vegetation,
field = spde,
veg = vegetation
)
)
pred_collect <-
rbind(
pred$joint %>% dplyr::mutate(component = "joint"),
pred$field %>% dplyr::mutate(component = "field"),
pred$veg %>% dplyr::mutate(component = "veg")
) %>%
dplyr::mutate(var = sd^2)
# Plot component mean
ggplot(pred_collect) +
geom_tile(aes(geometry = geometry, fill = mean), stat = "sf_coordinates") +
coord_equal() +
facet_wrap(~component, nrow = 1) +
theme(legend.position = "bottom")
# Plot component variance
ggplot(pred_collect) +
geom_tile(aes(geometry = geometry, fill = var), stat = "sf_coordinates") +
coord_equal() +
facet_wrap(~component, nrow = 1) +
theme(legend.position = "bottom")
# Calculate variance and correlation measure
vm <- devel.cvmeasure(pred$joint, pred$field, pred$veg)
# Compute nominal relative variance contributions; note that these can be
# greater than 100%!
vm <- dplyr::mutate(
vm,
var1_rel = if_else(var1 <= 0, NA, var1 / var.joint),
var2_rel = if_else(var2 <= 0, NA, var2 / var.joint)
)
lprange <- range(vm$var.joint, vm$var1, vm$var2)
vm <- tidyr::pivot_longer(vm,
cols = c(var.joint, var1, var2, cov, cor, var1_rel, var2_rel),
names_to = "component",
values_to = "value"
)
# Variance contribution of the components
csc <- scale_fill_gradientn(
colours = brewer.pal(9, "YlOrRd"),
limits = lprange
)
vm_ <- dplyr::filter(vm, component %in% c("var.joint", "var1", "var2"))
ggplot(vm_) +
geom_tile(aes(geometry = geometry, fill = value),
stat = "sf_coordinates"
) +
csc +
coord_equal() +
facet_wrap(~component, nrow = 1) +
theme(legend.position = "bottom")
# Relative variance contribution of the components
# When bo
vm_ <- dplyr::filter(vm, component %in% c("var1_rel", "var2_rel"))
ggplot(vm_) +
geom_tile(aes(geometry = geometry, fill = value),
stat = "sf_coordinates"
) +
scale_fill_gradientn(
colours = brewer.pal(9, "YlOrRd"),
trans = "log"
) +
coord_equal() +
facet_wrap(~component, nrow = 1)
# Where both relative contributions are larger than 1, the posterior
# correlations are strongly negative.
# Covariance and correlation of field and vegetation
vm_cov <- dplyr::filter(vm, component %in% "cov")
vm_cor <- dplyr::filter(vm, component %in% "cor")
(ggplot(vm_cov) +
geom_tile(aes(geometry = geometry, fill = value),
stat = "sf_coordinates"
) +
scale_fill_gradientn(
colours = rev(brewer.pal(9, "RdBu")),
limits = c(-1, 1) * max(abs(vm_cov$value), na.rm = TRUE)
) +
coord_equal() +
theme(legend.position = "bottom") +
ggtitle("Covariances") |
ggplot(vm_cor) +
geom_tile(aes(geometry = geometry, fill = value),
stat = "sf_coordinates"
) +
scale_fill_gradientn(
colours = rev(brewer.pal(9, "RdBu")),
limits = c(-1, 1) * max(abs(vm_cor$value), na.rm = TRUE)
) +
coord_equal() +
theme(legend.position = "bottom") +
ggtitle("Correlations")
)
# Variance and correlation integrated over space
vrt <- fm_vertices(gorillas$mesh, format = "sf")
pred_vrt <- predict(
fit,
vrt,
~ list(
joint = spde + vegetation,
field = spde,
veg = vegetation
)
)
vm.int <- devel.cvmeasure(
pred_vrt$joint,
pred_vrt$field,
pred_vrt$veg,
samplers = fm_int(gorillas$mesh, gorillas$boundary),
mesh = gorillas$mesh
)
vm.int
}
Evaluate spatial covariates
Description
Evaluate spatial covariates
Usage
eval_spatial(data, where, layer = NULL, selector = NULL)
## S3 method for class 'SpatialPolygonsDataFrame'
eval_spatial(data, where, layer = NULL, selector = NULL)
## S3 method for class 'SpatialPixelsDataFrame'
eval_spatial(data, where, layer = NULL, selector = NULL)
## S3 method for class 'SpatialGridDataFrame'
eval_spatial(data, where, layer = NULL, selector = NULL)
## S3 method for class 'sf'
eval_spatial(data, where, layer = NULL, selector = NULL)
## S3 method for class 'SpatRaster'
eval_spatial(data, where, layer = NULL, selector = NULL)
## S3 method for class 'stars'
eval_spatial(data, where, layer = NULL, selector = NULL)
Arguments
data |
Spatial data |
where |
Where to evaluate the data |
layer |
Which |
selector |
The name of a variable in |
Methods (by class)
-
eval_spatial(SpatialPolygonsDataFrame)
: Compatibility wrapper foreval_spatial.sf
-
eval_spatial(sf)
: Supports point-in-polygon information lookup. Other combinations are untested.
Evaluate a component effect
Description
Calculate latent component effects given some data and the state of the component's internal random variables.
Usage
evaluate_effect_single_state(...)
## S3 method for class 'bru_mapper'
evaluate_effect_single_state(component, input, state, ..., label = NULL)
## S3 method for class 'bm_list'
evaluate_effect_single_state(components, input, state, ...)
## S3 method for class 'bru_comp_list'
evaluate_effect_single_state(components, input, state, ...)
Arguments
... |
Optional additional parameters, e.g. |
component |
A bru_mapper, bru_comp, or bm_list. |
input |
Pre-evaluated component input |
state |
Specification of one latent variable state:
|
label |
Option label used for any warning messages, specifying the affected component. |
Value
-
evaluate_effect_single_state.bm_list
: A list of evaluated component effect values
Author(s)
Fabian E. Bachl bachlfab@gmail.com and Finn Lindgren finn.lindgren@gmail.com
Evaluate or sample from a posterior result given a model and locations
Description
Evaluate or sample from a posterior result given a model and locations
Usage
evaluate_model(
model,
state,
data = NULL,
data_extra = NULL,
input = NULL,
comp_simple = NULL,
predictor = NULL,
format = NULL,
used = NULL,
n_pred = NULL,
...
)
evaluate_state(
model,
result,
property = "mode",
n = 1,
seed = 0L,
num.threads = NULL,
internal_hyperpar = FALSE,
...
)
Arguments
model |
A bru model |
state |
list of state lists, as generated by |
data |
A |
data_extra |
Additional data for the predictor evaluation |
input |
Precomputed inputs list for the components |
comp_simple |
Precomputed bm_list of simplified mappers for the components |
predictor |
A formula or an expression to be evaluated given the
posterior or for each sample thereof. The default ( |
format |
character; determines the storage format of predictor output. Available options:
|
used |
A |
n_pred |
integer. If provided, scalar predictor results are expanded to
vectors of length |
... |
Additional arguments passed on to |
result |
|
property |
Property of the model components to obtain value from.
Default: "mode". Other options are "mean", "0.025quant", "0.975quant",
"sd" and "sample". In case of "sample" you will obtain samples from the
posterior (see |
n |
Number of samples to draw. |
seed |
If seed != 0L, the random seed |
num.threads |
Specification of desired number of threads for parallel computations. Default NULL, leaves it up to INLA. When seed != 0, overridden to "1:1" |
internal_hyperpar |
logical; If |
Details
-
evaluate_model
is a wrapper to evaluate model state, A-matrices, effects, and predictor, all in one call.
-
evaluate_state
evaluates model state properties or samples
Evaluate component effects or expressions
Description
Evaluate component effects or expressions, based on a bru model and one or several states of the latent variables and hyperparameters.
Usage
evaluate_predictor(
model,
state,
data,
data_extra,
effects,
predictor,
used = NULL,
format = "auto",
n_pred = NULL
)
Arguments
state |
A list where each element is a list of named latent state
information, as produced by |
data |
A |
data_extra |
Additional data for the predictor evaluation. Variables
with the same name as in |
effects |
A list where each element is list of named evaluated effects,
each computed by |
predictor |
Either a formula or expression |
used |
A |
format |
character; determines the storage format of the output. Available options:
Default: "auto" |
n_pred |
integer. If provided, scalar predictor results are expanded to
vectors of length |
Details
For each component, e.g. "name", the state values are available as
name_latent
, and arbitrary evaluation can be done with name_eval(...)
,
see bru_comp_eval()
.
Value
A list or matrix is returned, as specified by format
Expand labels
Description
Expand labels
Usage
expand_labels(labels, expand, suffix)
Arguments
labels |
character vector; original labels |
expand |
character vector; subset of labels to expand |
suffix |
character; the suffix to add to the labels selected by |
Value
a vector of labels with suffix appended to the selected labels
Extract a summary property from all results of an inla result
Description
Extract a summary property from all results of an inla result
Usage
extract_property(result, property, internal_hyperpar = FALSE)
Arguments
result |
an |
property |
character; "mean", "sd", "mode", or some other column
identifier for inla result |
internal_hyperpar |
logical; if |
Value
named list for each estimated fixed effect coefficient,
random effect vector, and hyperparameter. The hyperparameter names are
standardised with bru_standardise_names()
Summarise component inputs
Description
Summarise component inputs
Usage
## S3 method for class 'bru_input'
format(x, verbose = TRUE, ..., label.override = NULL, type = NULL)
## S3 method for class 'bru_input'
summary(object, verbose = TRUE, ..., label.override = NULL)
## S3 method for class 'bru_input'
print(x, verbose = TRUE, ..., label.override = NULL)
Arguments
x |
Object to be printed |
verbose |
logical; If |
... |
Passed on to other summary methods. |
label.override |
character; If not |
type |
character; if non-NULL, added to the output'; |
object |
Object to be summarised. |
Author(s)
Fabian E. Bachl bachlfab@gmail.com
Finn Lindgren finn.lindgren@gmail.com
See Also
mapper object summaries
Description
mapper object summaries
Usage
## S3 method for class 'bru_mapper'
format(x, ..., prefix = "", initial = prefix, depth = 1)
## S3 method for class 'bm_list'
format(
x,
...,
prefix = "",
initial = prefix,
depth = 1,
collapse = ", ",
labels = TRUE
)
## S3 method for class 'bru_mapper'
summary(object, ..., prefix = "", initial = prefix, depth = 1)
## S3 method for class 'bm_multi'
format(x, ..., prefix = "", initial = prefix, depth = 1)
## S3 method for class 'bm_pipe'
format(x, ..., prefix = "", initial = prefix, depth = 1)
## S3 method for class 'bm_collect'
format(x, ..., prefix = "", initial = prefix, depth = 1)
## S3 method for class 'bm_sum'
format(x, ..., prefix = "", initial = prefix, depth = 1)
## S3 method for class 'bm_repeat'
format(x, ..., prefix = "", initial = prefix, depth = 1)
## S3 method for class 'summary_bru_mapper'
print(x, ..., sep = "\n")
## S3 method for class 'bru_mapper'
print(x, ..., sep = "\n", prefix = "", initial = prefix, depth = 1)
## S3 method for class 'bm_list'
print(
x,
...,
sep = "\n",
prefix = "",
initial = prefix,
depth = 1,
labels = TRUE,
collapse = ", "
)
Arguments
x |
Object to format/print |
... |
Unused arguments |
prefix |
character prefix for each line. Default |
initial |
character prefix for the first line. Default |
depth |
The recursion depth for multi/collection/pipe mappers. Default 1, to only show the collection, and not the contents of the sub-mappers. |
collapse |
character or NULL, as in |
labels |
logical; if TRUE, include mapper names or numerical indices.
Default |
object |
Object to summarise |
sep |
character; separator for printing the summary. |
Examples
mapper <-
bm_pipe(
list(
bm_multi(list(
A = bm_index(2),
B = bm_index(3)
)),
bm_index(2)
)
)
summary(mapper, depth = 2)
mapper <-
bm_repeat(
bm_multi(
list(
A = bm_index(2),
B = bm_index(3)
)
),
3
)
summary(mapper)
summary(mapper, depth = 0)
Generate samples from fitted bru models
Description
Generic function for sampling for fitted models. The function invokes particular methods which depend on the class of the first argument.
Takes a fitted bru
object produced by the function bru()
and produces
samples given a new set of values for the model covariates or the original
values used for the model fit. The samples can be based on any R expression
that is valid given these values/covariates and the joint
posterior of the estimated random effects.
Usage
generate(object, ...)
## S3 method for class 'bru'
generate(
object,
newdata = NULL,
formula = NULL,
n.samples = 100,
seed = 0L,
num.threads = NULL,
used = NULL,
...,
data = deprecated(),
include = deprecated(),
exclude = deprecated()
)
Arguments
object |
A |
... |
additional, unused arguments. |
newdata |
A |
formula |
A formula where the right hand side defines an R expression
to evaluate for each generated sample. If |
n.samples |
Integer setting the number of samples to draw in order to calculate the posterior statistics. The default, 100, is rather low but provides a quick approximate result. |
seed |
Random number generator seed passed on to
|
num.threads |
Specification of desired number of threads for parallel computations. Default NULL, leaves it up to INLA. When seed != 0, overridden to "1:1" |
used |
Either |
data |
|
include , exclude |
|
Details
In addition to the component names (that give the effect of each component
evaluated for the input data), the suffix _latent
variable name can be used
to directly access the latent state for a component, and the suffix function
_eval
can be used to evaluate a component at other input values than the
expressions defined in the component definition itself, e.g.
field_eval(cbind(x, y))
for a component that was defined with
field(coordinates, ...)
(see also bru_comp_eval()
).
For "iid" models with mapper = bm_index(n)
, rnorm()
is used to
generate new realisations for indices greater than n
.
Value
The form of the value returned by generate()
depends on the data
class and prediction formula. Normally, a data.frame is returned, or a list
of data.frames (if the prediction formula generates a list)
List of generated samples
See Also
Examples
if (bru_safe_inla() &&
require("sn", quietly = TRUE)) {
# Generate data for a simple linear model
input.df <- data.frame(x = cos(1:10))
input.df <- within(input.df, y <- 5 + 2 * cos(1:10) + rnorm(10, mean = 0, sd = 0.1))
# Fit the model
fit <- bru(y ~ xeff(main = x, model = "linear"),
family = "gaussian", data = input.df
)
summary(fit)
# Generate samples for some predefined x
df <- data.frame(x = seq(-4, 4, by = 0.1))
smp <- generate(fit, df, ~ xeff + Intercept, n.samples = 10)
# Plot the resulting realizations
plot(df$x, smp[, 1], type = "l")
for (k in 2:ncol(smp)) points(df$x, smp[, k], type = "l")
# We can also draw samples form the joint posterior
df <- data.frame(x = 1)
smp <- generate(fit, df, ~ data.frame(xeff, Intercept), n.samples = 10)
smp[[1]]
# ... and plot them
if (require(ggplot2, quietly = TRUE)) {
plot(do.call(rbind, smp))
}
}
ggplot2 geomes for inlabru related objects
Description
gg is a generic function for generating geomes from various kinds of spatial objects, e.g. Spatial* data, meshes, Raster objects and inla/inlabru predictions. The function invokes particular methods which depend on the class of the first argument.
Usage
gg(data, ...)
Arguments
data |
an object for which to generate a geom. |
... |
Arguments passed on to the geom method. |
Value
The form of the value returned by gg depends on the class of its argument. See the documentation of the particular methods for details of what is produced by that method.
See Also
Other geomes for inla and inlabru predictions:
gg.bru_prediction()
,
gg.data.frame()
,
gg.matrix()
Other geomes for spatial data:
gg.SpatRaster()
,
gg.SpatialGridDataFrame()
,
gg.SpatialLines()
,
gg.SpatialPixels()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPoints()
,
gg.SpatialPolygons()
,
gg.sf()
Other geomes for meshes:
gg.fm_mesh_1d()
,
gg.fm_mesh_2d()
Other geomes for Raster data:
gg.RasterLayer()
Examples
if (require("ggplot2", quietly = TRUE)) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
# Invoke ggplot and add geomes for the Gorilla nests and the survey
# boundary
ggplot() +
gg(gorillas$boundary) +
gg(gorillas$nests)
}
Geom for RasterLayer objects
Description
This function takes a RasterLayer object, converts it into a
SpatialPixelsDataFrame
and uses geom_tile
to plot the data.
Usage
## S3 method for class 'RasterLayer'
gg(
data,
mapping = ggplot2::aes(x = .data[["x"]], y = .data[["y"]], fill = .data[["layer"]]),
...
)
Arguments
data |
A RasterLayer object. |
mapping |
aesthetic mappings created by |
... |
Arguments passed on to |
Details
This function requires the raster
and ggplot2
packages.
Value
An object returned by geom_tile
See Also
Other geomes for Raster data:
gg()
Examples
## Not run:
# Some features require the raster and spatstat.data packages.
if (require("spatstat.data", quietly = TRUE) &&
require("raster", quietly = TRUE) &&
require("ggplot2", quietly = TRUE)) {
# Load Gorilla data
data("gorillas", package = "spatstat.data", envir = environment())
# Convert elevation covariate to RasterLayer
elev <- as(gorillas.extra$elevation, "RasterLayer")
# Plot the elevation
ggplot() +
gg(elev)
}
## End(Not run)
Geom wrapper for SpatRaster objects
Description
Convenience wrapper function for tidyterra::geom_spatraster()
.
Requires the ggplot2
and tidyterra
packages.
Usage
## S3 method for class 'SpatRaster'
gg(data, ...)
Arguments
data |
A SpatRaster object. |
... |
Arguments passed on to |
Value
The output from 'geom_spatraster.
See Also
Other geomes for spatial data:
gg()
,
gg.SpatialGridDataFrame()
,
gg.SpatialLines()
,
gg.SpatialPixels()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPoints()
,
gg.SpatialPolygons()
,
gg.sf()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
require("tidyterra", quietly = TRUE)) {
# Load Gorilla covariates
gcov <- gorillas_sf_gcov()
# Plot the pixel centers
ggplot() +
gg(gcov$elevation)
}
Geom for SpatialGridDataFrame objects
Description
Coerces input SpatialGridDataFrame
to SpatialPixelsDataFrame
and calls
gg.SpatialPixelsDataFrame()
to plot it.
Requires the ggplot2
package.
Usage
## S3 method for class 'SpatialGridDataFrame'
gg(data, ...)
Arguments
data |
A SpatialGridDataFrame object. |
... |
Arguments passed on to |
Value
A geom_tile
value.
See Also
Other geomes for spatial data:
gg()
,
gg.SpatRaster()
,
gg.SpatialLines()
,
gg.SpatialPixels()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPoints()
,
gg.SpatialPolygons()
,
gg.sf()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
bru_safe_sp() &&
require("sp")) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
gcov <- gorillas_sf_gcov()
elev <- terra::as.data.frame(gcov$elevation, xy = TRUE)
elev <- sf::as_Spatial(sf::st_as_sf(elev, coords = c("x", "y")))
# Turn elevation covariate into SpatialGridDataFrame
elev <- sp::SpatialPixelsDataFrame(elev, data = as.data.frame(elev))
# Plot Gorilla elevation covariate provided as SpatialPixelsDataFrame.
# The same syntax applies to SpatialGridDataFrame objects.
ggplot() +
gg(elev)
# Add Gorilla survey boundary and nest sightings
ggplot() +
gg(elev) +
gg(gorillas$boundary, alpha = 0.0, col = "red") +
gg(gorillas$nests)
# Load pantropical dolphin data
mexdolphin <- inlabru::mexdolphin_sp()
# Plot the pantropical survey boundary, ship transects and dolphin sightings
ggplot() +
gg(mexdolphin$ppoly) + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers) + # ship transects as SpatialLines
gg(mexdolphin$points) # dolphin sightings as SpatialPoints
# Change color
ggplot() +
gg(mexdolphin$ppoly, color = "green") + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers, color = "red") + # ship transects as SpatialLines
gg(mexdolphin$points, color = "blue") # dolphin sightings as SpatialPoints
# Visualize data annotations: line width by segment number
names(mexdolphin$samplers) # 'seg' holds the segment number
ggplot() +
gg(mexdolphin$samplers, aes(color = seg))
# Visualize data annotations: point size by dolphin group size
names(mexdolphin$points) # 'size' holds the group size
ggplot() +
gg(mexdolphin$points, aes(size = size))
}
Geom for SpatialLines objects
Description
Extracts start and end points of the lines and calls geom_segment
to plot
lines between them. Requires the ggplot2
package.
Usage
## S3 method for class 'SpatialLines'
gg(data, mapping = NULL, crs = NULL, ...)
Arguments
data |
A |
mapping |
Aesthetic mappings created by ggplot2::aes( x = .data[[sp::coordnames(data)[1]]], y = .data[[sp::coordnames(data)[2]]], xend = .data[[paste0("end.", sp::coordnames(data)[1])]], yend = .data[[paste0("end.", sp::coordnames(data)[2])]]) |
crs |
A |
... |
Arguments passed on to |
Value
A 'geom_segment“ return value.
See Also
Other geomes for spatial data:
gg()
,
gg.SpatRaster()
,
gg.SpatialGridDataFrame()
,
gg.SpatialPixels()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPoints()
,
gg.SpatialPolygons()
,
gg.sf()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
bru_safe_sp() &&
require("sp")) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
gcov <- gorillas_sf_gcov()
elev <- terra::as.data.frame(gcov$elevation, xy = TRUE)
elev <- sf::as_Spatial(sf::st_as_sf(elev, coords = c("x", "y")))
# Turn elevation covariate into SpatialGridDataFrame
elev <- sp::SpatialPixelsDataFrame(elev, data = as.data.frame(elev))
# Plot Gorilla elevation covariate provided as SpatialPixelsDataFrame.
# The same syntax applies to SpatialGridDataFrame objects.
ggplot() +
gg(elev)
# Add Gorilla survey boundary and nest sightings
ggplot() +
gg(elev) +
gg(gorillas$boundary, alpha = 0.0, col = "red") +
gg(gorillas$nests)
# Load pantropical dolphin data
mexdolphin <- inlabru::mexdolphin_sp()
# Plot the pantropical survey boundary, ship transects and dolphin sightings
ggplot() +
gg(mexdolphin$ppoly) + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers) + # ship transects as SpatialLines
gg(mexdolphin$points) # dolphin sightings as SpatialPoints
# Change color
ggplot() +
gg(mexdolphin$ppoly, color = "green") + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers, color = "red") + # ship transects as SpatialLines
gg(mexdolphin$points, color = "blue") # dolphin sightings as SpatialPoints
# Visualize data annotations: line width by segment number
names(mexdolphin$samplers) # 'seg' holds the segment number
ggplot() +
gg(mexdolphin$samplers, aes(color = seg))
# Visualize data annotations: point size by dolphin group size
names(mexdolphin$points) # 'size' holds the group size
ggplot() +
gg(mexdolphin$points, aes(size = size))
}
Geom for SpatialPixels objects
Description
Uses geom_point
to plot the pixel centers.
Requires the ggplot2
package.
Usage
## S3 method for class 'SpatialPixels'
gg(data, ...)
Arguments
data |
A |
... |
Arguments passed on to |
Value
A geom_tile
return value.
See Also
Other geomes for spatial data:
gg()
,
gg.SpatRaster()
,
gg.SpatialGridDataFrame()
,
gg.SpatialLines()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPoints()
,
gg.SpatialPolygons()
,
gg.sf()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
bru_safe_sp()) {
# Load Gorilla data
gcov <- gorillas_sf_gcov()
elev <- terra::as.data.frame(gcov$elevation, xy = TRUE)
pxl <- sf::as_Spatial(sf::st_as_sf(elev, coords = c("x", "y")))
# Turn elevation covariate into SpatialPixels
pxl <- sp::SpatialPixels(pxl)
# Plot the pixel centers
ggplot() +
gg(pxl, size = 0.1)
}
Geom for SpatialPixelsDataFrame objects
Description
Coerces input SpatialPixelsDataFrame to data.frame and uses geom_tile
to
plot it.
Requires the ggplot2
package.
Usage
## S3 method for class 'SpatialPixelsDataFrame'
gg(data, mapping = NULL, crs = NULL, mask = NULL, ...)
Arguments
data |
A SpatialPixelsDataFrame object. |
mapping |
Aesthetic mappings created by ggplot2::aes( x = .data[[sp::coordnames(data)[1]]], y = .data[[sp::coordnames(data)[2]]], fill = .data[[names(data)[[1]]]] ) |
crs |
A |
mask |
A |
... |
Arguments passed on to |
Value
A geom_tile
return value.
See Also
Other geomes for spatial data:
gg()
,
gg.SpatRaster()
,
gg.SpatialGridDataFrame()
,
gg.SpatialLines()
,
gg.SpatialPixels()
,
gg.SpatialPoints()
,
gg.SpatialPolygons()
,
gg.sf()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
bru_safe_sp() &&
require("sp")) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
gcov <- gorillas_sf_gcov()
elev <- terra::as.data.frame(gcov$elevation, xy = TRUE)
elev <- sf::as_Spatial(sf::st_as_sf(elev, coords = c("x", "y")))
# Turn elevation covariate into SpatialGridDataFrame
elev <- sp::SpatialPixelsDataFrame(elev, data = as.data.frame(elev))
# Plot Gorilla elevation covariate provided as SpatialPixelsDataFrame.
# The same syntax applies to SpatialGridDataFrame objects.
ggplot() +
gg(elev)
# Add Gorilla survey boundary and nest sightings
ggplot() +
gg(elev) +
gg(gorillas$boundary, alpha = 0.0, col = "red") +
gg(gorillas$nests)
# Load pantropical dolphin data
mexdolphin <- inlabru::mexdolphin_sp()
# Plot the pantropical survey boundary, ship transects and dolphin sightings
ggplot() +
gg(mexdolphin$ppoly) + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers) + # ship transects as SpatialLines
gg(mexdolphin$points) # dolphin sightings as SpatialPoints
# Change color
ggplot() +
gg(mexdolphin$ppoly, color = "green") + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers, color = "red") + # ship transects as SpatialLines
gg(mexdolphin$points, color = "blue") # dolphin sightings as SpatialPoints
# Visualize data annotations: line width by segment number
names(mexdolphin$samplers) # 'seg' holds the segment number
ggplot() +
gg(mexdolphin$samplers, aes(color = seg))
# Visualize data annotations: point size by dolphin group size
names(mexdolphin$points) # 'size' holds the group size
ggplot() +
gg(mexdolphin$points, aes(size = size))
}
Geom for SpatialPoints objects
Description
This function coerces the SpatialPoints
into a data.frame
and uses
geom_point
to plot the points. Requires the ggplot2
package.
Usage
## S3 method for class 'SpatialPoints'
gg(data, mapping = NULL, crs = NULL, ...)
Arguments
data |
A SpatialPoints object. |
mapping |
Aesthetic mappings created by ggplot2::aes( x = .data[[sp::coordnames(data)[1]]], y = .data[[sp::coordnames(data)[2]]] ) |
crs |
A |
... |
Arguments passed on to |
Value
A geom_point
return value
See Also
Other geomes for spatial data:
gg()
,
gg.SpatRaster()
,
gg.SpatialGridDataFrame()
,
gg.SpatialLines()
,
gg.SpatialPixels()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPolygons()
,
gg.sf()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
bru_safe_sp() &&
require("sp")) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
gcov <- gorillas_sf_gcov()
elev <- terra::as.data.frame(gcov$elevation, xy = TRUE)
elev <- sf::as_Spatial(sf::st_as_sf(elev, coords = c("x", "y")))
# Turn elevation covariate into SpatialGridDataFrame
elev <- sp::SpatialPixelsDataFrame(elev, data = as.data.frame(elev))
# Plot Gorilla elevation covariate provided as SpatialPixelsDataFrame.
# The same syntax applies to SpatialGridDataFrame objects.
ggplot() +
gg(elev)
# Add Gorilla survey boundary and nest sightings
ggplot() +
gg(elev) +
gg(gorillas$boundary, alpha = 0.0, col = "red") +
gg(gorillas$nests)
# Load pantropical dolphin data
mexdolphin <- inlabru::mexdolphin_sp()
# Plot the pantropical survey boundary, ship transects and dolphin sightings
ggplot() +
gg(mexdolphin$ppoly) + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers) + # ship transects as SpatialLines
gg(mexdolphin$points) # dolphin sightings as SpatialPoints
# Change color
ggplot() +
gg(mexdolphin$ppoly, color = "green") + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers, color = "red") + # ship transects as SpatialLines
gg(mexdolphin$points, color = "blue") # dolphin sightings as SpatialPoints
# Visualize data annotations: line width by segment number
names(mexdolphin$samplers) # 'seg' holds the segment number
ggplot() +
gg(mexdolphin$samplers, aes(color = seg))
# Visualize data annotations: point size by dolphin group size
names(mexdolphin$points) # 'size' holds the group size
ggplot() +
gg(mexdolphin$points, aes(size = size))
}
Geom for SpatialPolygons objects
Description
Uses the ggplot2::fortify()
function to turn the SpatialPolygons
objects
into a data.frame
. Then calls geom_polygon
to plot the polygons. Requires
the ggplot2
package.
Usage
## S3 method for class 'SpatialPolygons'
gg(data, mapping = NULL, crs = NULL, ...)
Arguments
data |
A |
mapping |
Aesthetic mappings created by |
crs |
A |
... |
Arguments passed on to |
Details
Up to version 2.10.0
, the ggpolypath
package was used to ensure
proper plotting, since the ggplot2::geom_polygon
function doesn't always
handle geometries with holes properly. After 2.10.0
, the object is
converted to sf
format and passed on to gg.sf()
instead, as ggplot2
version 3.4.4
deprecated the intenrally used ggplot2::fortify()
method
for SpatialPolygons/DataFrame
objects.
Value
A geom_sf
object.
See Also
Other geomes for spatial data:
gg()
,
gg.SpatRaster()
,
gg.SpatialGridDataFrame()
,
gg.SpatialLines()
,
gg.SpatialPixels()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPoints()
,
gg.sf()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
bru_safe_sp() &&
require("sp")) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
gcov <- gorillas_sf_gcov()
elev <- terra::as.data.frame(gcov$elevation, xy = TRUE)
elev <- sf::as_Spatial(sf::st_as_sf(elev, coords = c("x", "y")))
# Turn elevation covariate into SpatialGridDataFrame
elev <- sp::SpatialPixelsDataFrame(elev, data = as.data.frame(elev))
# Plot Gorilla elevation covariate provided as SpatialPixelsDataFrame.
# The same syntax applies to SpatialGridDataFrame objects.
ggplot() +
gg(elev)
# Add Gorilla survey boundary and nest sightings
ggplot() +
gg(elev) +
gg(gorillas$boundary, alpha = 0.0, col = "red") +
gg(gorillas$nests)
# Load pantropical dolphin data
mexdolphin <- inlabru::mexdolphin_sp()
# Plot the pantropical survey boundary, ship transects and dolphin sightings
ggplot() +
gg(mexdolphin$ppoly) + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers) + # ship transects as SpatialLines
gg(mexdolphin$points) # dolphin sightings as SpatialPoints
# Change color
ggplot() +
gg(mexdolphin$ppoly, color = "green") + # survey boundary as SpatialPolygon
gg(mexdolphin$samplers, color = "red") + # ship transects as SpatialLines
gg(mexdolphin$points, color = "blue") # dolphin sightings as SpatialPoints
# Visualize data annotations: line width by segment number
names(mexdolphin$samplers) # 'seg' holds the segment number
ggplot() +
gg(mexdolphin$samplers, aes(color = seg))
# Visualize data annotations: point size by dolphin group size
names(mexdolphin$points) # 'size' holds the group size
ggplot() +
gg(mexdolphin$points, aes(size = size))
}
Geom for predictions
Description
This geom serves to visualize prediction
objects which usually results from
a call to predict.bru()
. Predictions objects provide summary statistics
(mean, median, sd, ...) for one or more random variables. For single
variables (or if requested so by setting bar = TRUE
), a boxplot-style geom
is constructed to show the statistics. For multivariate predictions the mean
of each variable (y-axis) is plotted against the row number of the variable
in the prediction data frame (x-axis) using geom_line
. In addition, a
geom_ribbon
is used to show the confidence interval.
Note: gg.bru_prediction
also understands the format of INLA-style posterior
summaries, e.g. fit$summary.fixed
for an inla object fit
Requires the ggplot2
package.
Usage
## S3 method for class 'bru_prediction'
gg(data, mapping = NULL, ribbon = TRUE, alpha = NULL, bar = FALSE, ...)
## S3 method for class 'prediction'
gg(data, ...)
Arguments
data |
A prediction object, usually the result of a |
mapping |
a set of aesthetic mappings created by |
ribbon |
If TRUE, plot a ribbon around the line based on the smallest
and largest quantiles present in the data, found by matching names starting
with |
alpha |
The ribbons numeric alpha (transparency) level in |
bar |
If TRUE plot boxplot-style summary for each variable. |
... |
Arguments passed on to |
Value
Concatenation of a geom_line
value and optionally a geom_ribbon
value.
See Also
Other geomes for inla and inlabru predictions:
gg()
,
gg.data.frame()
,
gg.matrix()
Examples
if (bru_safe_inla() &&
require(sn, quietly = TRUE) &&
require(ggplot2, quietly = TRUE)) {
# Generate some data
input.df <- data.frame(x = cos(1:10))
input.df <- within(input.df, y <- 5 + 2 * cos(1:10) + rnorm(10, mean = 0, sd = 0.1))
# Fit a model with fixed effect 'x' and intercept 'Intercept'
fit <- bru(y ~ x, family = "gaussian", data = input.df)
# Predict posterior statistics of 'x'
xpost <- predict(fit, NULL, formula = ~x_latent)
# The statistics include mean, standard deviation, the 2.5% quantile, the median,
# the 97.5% quantile, minimum and maximum sample drawn from the posterior as well as
# the coefficient of variation and the variance.
xpost
# For a single variable like 'x' the default plotting method invoked by gg() will
# show these statisics in a fashion similar to a box plot:
ggplot() +
gg(xpost)
# The predict function can also be used to simultaneously estimate posteriors
# of multiple variables:
xipost <- predict(fit,
newdata = NULL,
formula = ~ c(
Intercept = Intercept_latent,
x = x_latent
)
)
xipost
# If we still want a plot in the previous style we have to set the bar parameter to TRUE
p1 <- ggplot() +
gg(xipost, bar = TRUE)
p1
# Note that gg also understands the posterior estimates generated while running INLA
p2 <- ggplot() +
gg(fit$summary.fixed, bar = TRUE)
multiplot(p1, p2)
# By default, if the prediction has more than one row, gg will plot the column 'mean' against
# the row index. This is for instance usefuul for predicting and plotting function
# but not very meaningful given the above example:
ggplot() +
gg(xipost)
# For ease of use we can also type
plot(xipost)
# This type of plot will show a ribbon around the mean, which viszualizes the upper and lower
# quantiles mentioned above (2.5 and 97.5%). Plotting the ribbon can be turned of using the
# \code{ribbon} parameter
ggplot() +
gg(xipost, ribbon = FALSE)
# Much like the other geomes produced by gg we can adjust the plot using ggplot2 style
# commands, for instance
ggplot() +
gg(xipost) +
gg(xipost, mapping = aes(y = median), ribbon = FALSE, color = "red")
}
Geom for data.frame
Description
This geom constructor will simply call gg.bru_prediction()
for the data
provided.
Usage
## S3 method for class 'data.frame'
gg(...)
Arguments
... |
Arguments passed on to |
Details
Requires the ggplot2
package.
Value
Concatenation of a geom_line
value and optionally a geom_ribbon
value.
See Also
Other geomes for inla and inlabru predictions:
gg()
,
gg.bru_prediction()
,
gg.matrix()
Examples
if (bru_safe_inla() &&
require(sn, quietly = TRUE) &&
require(ggplot2, quietly = TRUE)) {
# Generate some data
input.df <- data.frame(x = cos(1:10))
input.df <- within(input.df, y <- 5 + 2 * cos(1:10) + rnorm(10, mean = 0, sd = 0.1))
# Fit a model with fixed effect 'x' and intercept 'Intercept'
fit <- bru(y ~ x, family = "gaussian", data = input.df)
# Predict posterior statistics of 'x'
xpost <- predict(fit, NULL, formula = ~x_latent)
# The statistics include mean, standard deviation, the 2.5% quantile, the median,
# the 97.5% quantile, minimum and maximum sample drawn from the posterior as well as
# the coefficient of variation and the variance.
xpost
# For a single variable like 'x' the default plotting method invoked by gg() will
# show these statisics in a fashion similar to a box plot:
ggplot() +
gg(xpost)
# The predict function can also be used to simultaneously estimate posteriors
# of multiple variables:
xipost <- predict(fit,
newdata = NULL,
formula = ~ c(
Intercept = Intercept_latent,
x = x_latent
)
)
xipost
# If we still want a plot in the previous style we have to set the bar parameter to TRUE
p1 <- ggplot() +
gg(xipost, bar = TRUE)
p1
# Note that gg also understands the posterior estimates generated while running INLA
p2 <- ggplot() +
gg(fit$summary.fixed, bar = TRUE)
multiplot(p1, p2)
# By default, if the prediction has more than one row, gg will plot the column 'mean' against
# the row index. This is for instance usefuul for predicting and plotting function
# but not very meaningful given the above example:
ggplot() +
gg(xipost)
# For ease of use we can also type
plot(xipost)
# This type of plot will show a ribbon around the mean, which viszualizes the upper and lower
# quantiles mentioned above (2.5 and 97.5%). Plotting the ribbon can be turned of using the
# \code{ribbon} parameter
ggplot() +
gg(xipost, ribbon = FALSE)
# Much like the other geomes produced by gg we can adjust the plot using ggplot2 style
# commands, for instance
ggplot() +
gg(xipost) +
gg(xipost, mapping = aes(y = median), ribbon = FALSE, color = "red")
}
Geom for fm_mesh_1d objects
Description
This function generates a geom_point
object showing the knots (vertices)
of a 1D mesh.
Requires the ggplot2
package.
Usage
## S3 method for class 'fm_mesh_1d'
gg(
data,
mapping = ggplot2::aes(.data[["x"]], .data[["y"]]),
y = 0,
shape = 4,
...
)
Arguments
data |
An fmesher::fm_mesh_1d object. |
mapping |
aesthetic mappings created by |
y |
Single or vector numeric defining the y-coordinates of the mesh knots to plot. |
shape |
Shape of the knot markers. |
... |
parameters passed on to |
Value
An object generated by geom_point
.
See Also
Other geomes for meshes:
gg()
,
gg.fm_mesh_2d()
Examples
if (require("fmesher", quietly = TRUE) &&
require("ggplot2", quietly = TRUE)) {
# Create a 1D mesh
mesh <- fm_mesh_1d(seq(0, 10, by = 0.5))
# Plot it
ggplot() +
gg(mesh)
# Plot it using a different shape and size for the mesh nodes
ggplot() +
gg(mesh, shape = "|", size = 5)
}
Geom for fm_mesh_2d objects
Description
This function extracts the graph of an fmesher::fm_mesh_2d object and uses
geom_line
to visualize the graph's edges. Alternatively, if the color
argument is provided, interpolates the colors across for a set of
SpatialPixels covering the mesh area and calls gg.SpatialPixelsDataFrame()
to plot the interpolation.
Requires the ggplot2
package.
Also see the fmesher::geom_fm()
method.
Usage
## S3 method for class 'fm_mesh_2d'
gg(
data,
color = NULL,
alpha = NULL,
edge.color = "grey",
edge.linewidth = 0.25,
interior = TRUE,
int.color = "blue",
int.linewidth = 0.5,
exterior = TRUE,
ext.color = "black",
ext.linewidth = 1,
crs = NULL,
mask = NULL,
nx = 500,
ny = 500,
...
)
Arguments
data |
An |
color |
A vector of scalar values to fill the mesh with colors.
The length of the vector mus correspond to the number of mesh vertices.
The alternative name |
alpha |
A vector of scalar values setting the alpha value of the colors provided. |
edge.color |
Color of the regular mesh edges. |
edge.linewidth |
Line width for the regular mesh edges. Default 0.25 |
interior |
If TRUE, plot the interior boundaries of the mesh. |
int.color |
Color used to plot the interior constraint edges. |
int.linewidth |
Line width for the interior constraint edges. Default 0.5 |
exterior |
If TRUE, plot the exterior boundaries of the mesh. |
ext.color |
Color used to plot the exterior boundary edges. |
ext.linewidth |
Line width for the exterior boundary edges. Default 1 |
crs |
A CRS object supported by |
mask |
A |
nx |
Number of pixels in x direction (when plotting using the color parameter). |
ny |
Number of pixels in y direction (when plotting using the color parameter). |
... |
ignored arguments (S3 generic compatibility). |
Value
geom_line
return values or, if the color argument is used, the
values of gg.SpatialPixelsDataFrame()
.
See Also
Other geomes for meshes:
gg()
,
gg.fm_mesh_1d()
Examples
if (require(fmesher, quietly = TRUE) &&
require(ggplot2, quietly = TRUE)) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
# Plot mesh using default edge colors
ggplot() +
gg(gorillas$mesh)
# Don't show interior and exterior boundaries
ggplot() +
gg(gorillas$mesh, interior = FALSE, exterior = FALSE)
# Change the edge colors
ggplot() +
gg(gorillas$mesh,
edge.color = "green",
int.color = "black",
ext.color = "blue"
)
# Use the x-coordinate of the vertices to colorize the triangles and
# mask the plotted area by the survey boundary, i.e. only plot the inside
xcoord <- gorillas$mesh$loc[, 1]
ggplot() +
gg(gorillas$mesh, color = (xcoord - 580), mask = gorillas$boundary) +
gg(gorillas$boundary, alpha = 0)
}
Geom for matrix
Description
Creates a tile geom for plotting a matrix
Usage
## S3 method for class 'matrix'
gg(data, mapping = NULL, ...)
Arguments
data |
A |
mapping |
a set of aesthetic mappings created by |
... |
Arguments passed on to |
Details
Requires the ggplot2
package.
Value
A geom_tile
with reversed y scale.
See Also
Other geomes for inla and inlabru predictions:
gg()
,
gg.bru_prediction()
,
gg.data.frame()
Examples
if (require("ggplot2", quietly = TRUE)) {
A <- matrix(runif(100), nrow = 10)
ggplot() +
gg(A)
}
Geom helper for sf objects
Description
This function uses geom_sf()
, unless overridden by the geom argument.
Requires the ggplot2
package.
Usage
## S3 method for class 'sf'
gg(data, mapping = NULL, ..., geom = "sf")
Arguments
data |
An |
mapping |
Default mapping is |
... |
Arguments passed on to |
geom |
Either "sf" (default) or "tile". For "tile", uses
|
Value
A ggplot return value
See Also
Other geomes for spatial data:
gg()
,
gg.SpatRaster()
,
gg.SpatialGridDataFrame()
,
gg.SpatialLines()
,
gg.SpatialPixels()
,
gg.SpatialPixelsDataFrame()
,
gg.SpatialPoints()
,
gg.SpatialPolygons()
Examples
if (require("ggplot2", quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
require("tidyterra", quietly = TRUE)) {
# Load Gorilla data
gorillas <- inlabru::gorillas_sf
gorillas$gcov <- gorillas_sf_gcov()
# Plot Gorilla elevation covariate provided as terra::rast.
ggplot() +
gg(gorillas$gcov$elevation)
# Add Gorilla survey boundary and nest sightings
ggplot() +
gg(gorillas$gcov$elevation) +
gg(gorillas$boundary, alpha = 0) +
gg(gorillas$nests)
# Load pantropical dolphin data
mexdolphin <- inlabru::mexdolphin_sf
# Plot the pantropical survey boundary, ship transects and dolphin sightings
ggplot() +
gg(mexdolphin$ppoly, alpha = 0.5) + # survey boundary
gg(mexdolphin$samplers) + # ship transects
gg(mexdolphin$points) # dolphin sightings
# Change color
ggplot() +
gg(mexdolphin$ppoly, color = "green", alpha = 0.5) + # survey boundary
gg(mexdolphin$samplers, color = "red") + # ship transects
gg(mexdolphin$points, color = "blue") # dolphin sightings
# Visualize data annotations: line width by segment number
names(mexdolphin$samplers) # 'seg' holds the segment number
ggplot() +
gg(mexdolphin$samplers, aes(color = seg))
# Visualize data annotations: point size by dolphin group size
names(mexdolphin$points) # 'size' holds the group size
ggplot() +
gg(mexdolphin$points, aes(size = size))
}
Visualize a globe using RGL
Description
Creates a textured sphere and lon/lat coordinate annotations.
This function requires the rgl
and sphereplot
packages.
Usage
globe(
R = 1,
R.grid = 1.05,
specular = "black",
axes = FALSE,
box = FALSE,
xlab = "",
ylab = "",
zlab = ""
)
Arguments
R |
Radius of the globe |
R.grid |
Radius of the annotation sphere. |
specular |
Light color of specular effect. |
axes |
If TRUE, plot x, y and z axes. |
box |
If TRUE, plot a box around the globe. |
xlab , ylab , zlab |
Axes labels |
Value
No value, used for plotting side effect.
See Also
Other inlabru RGL tools:
glplot()
Examples
if (interactive() &&
require("rgl", quietly = TRUE) &&
require("sphereplot", quietly = TRUE) &&
bru_safe_sp() &&
require("sp")) {
# Show the globe
globe()
# Load pantropoical dolphin data
mexdolphin <- inlabru::mexdolphin_sp()
# Add mesh, ship transects and dolphin sightings stored
# as fm_mesh_2d, SpatialLines and SpatialPoints objects, respectively
glplot(mexdolphin$mesh, alpha = 0.2)
glplot(mexdolphin$samplers, lwd = 5)
glplot(mexdolphin$points, size = 10)
}
Render objects using RGL
Description
glplot()
is a generic function for renders various kinds of spatial
objects, i.e. Spatial*
data and fm_mesh_2d
objects. The function invokes
particular methods which depend on the class of the first argument.
Usage
glplot(object, ...)
## S3 method for class 'SpatialPoints'
glplot(object, add = TRUE, color = "red", ...)
## S3 method for class 'SpatialLines'
glplot(object, add = TRUE, ...)
## S3 method for class 'fm_mesh_2d'
glplot(object, add = TRUE, col = NULL, ...)
Arguments
object |
an object used to select a method. |
... |
Parameters passed on to |
add |
If TRUE, add the points to an existing plot. If FALSE, create new plot. |
color |
vector of R color characters. See material3d() for details. |
col |
Color specification. A single named color, a vector of scalar values, or a matrix of RGB values. |
Methods (by class)
-
glplot(SpatialPoints)
: This function will calculate the cartesian coordinates of the points provided and use points3d() in order to render them. -
glplot(SpatialLines)
: This function will calculate a cartesian representation of the lines provided and uselines3d()
in order to render them. -
glplot(fm_mesh_2d)
: This function transforms the mesh to 3D cartesian coordinates and usesfmesher::plot_rgl()
to plot the result.
See Also
Other inlabru RGL tools:
globe()
Other inlabru RGL tools:
globe()
Other inlabru RGL tools:
globe()
Other inlabru RGL tools:
globe()
Examples
if (interactive() &&
require("rgl", quietly = TRUE) &&
require("sphereplot", quietly = TRUE) &&
bru_safe_sp() &&
require("sp")) {
# Show the globe
globe()
# Load pantropoical dolphin data
mexdolphin <- inlabru::mexdolphin_sp()
# Add mesh, ship transects and dolphin sightings stored
# as fm_mesh_2d, SpatialLines and SpatialPoints objects, respectively
glplot(mexdolphin$mesh, alpha = 0.2)
glplot(mexdolphin$samplers, lwd = 5)
glplot(mexdolphin$points, size = 10)
}
Deprecated alias for sp version of the gorillas dataset
Description
Deprecated dataset name for the sp
version
of gorillas_sf. Use gorillas_sp()
instead.
See Also
Gorilla nesting sites in sf format
Description
This is the gorillas
dataset from the package spatstat.data
,
reformatted as point process data for use with inlabru
.
Usage
gorillas_sf
data(gorillas_sf, package = "inlabru")
gorillas_sf_gcov()
gorillas_sp()
Format
The data are a list that contains these elements:
nests
:An
sf
object containing the locations of the gorilla nests.boundary
:An
sf
object defining the boundary of the region that was searched for the nests.mesh
:An
fm_mesh_2d
object containing a mesh that can be used with functionlgcp
to fit a LGCP to the nest data.gcov_file
:The in-package filename of a
terra::SpatRaster
object, with one layer for each of these spatial covariates:aspect
Compass direction of the terrain slope. Categorical, with levels N, NE, E, SE, S, SW, W and NW, which are coded as integers 1 to 8.
elevation
Digital elevation of terrain, in metres.
heat
Heat Load Index at each point on the surface (Beer's aspect), discretised. Categorical with values Warmest (Beer's aspect between 0 and 0.999), Moderate (Beer's aspect between 1 and 1.999), Coolest (Beer's aspect equals 2). These are coded as integers 1, 2 and 3, in that order.
slopangle
Terrain slope, in degrees.
slopetype
Type of slope. Categorical, with values Valley, Toe (toe slope), Flat, Midslope, Upper and Ridge. These are coded as integers 1 to 6.
vegetation
Vegetation type: a categorical variable with 6 levels coded as integers 1 to 6 (in order of increasing expected habitat suitability)
waterdist
Euclidean distance from nearest water body, in metres.
Loading of the covariates can be done with
gorillas_sf_gcov()
orgorillas_sf$gcov <- terra::rast( system.file(gorillas_sf$gcov_file, package = "inlabru") )
plotsample
Plot sample of gorilla nests, sampling 9x9 over the region, with 60\
counts
An
sf
object with elementscount
,exposure
, andgeometry
, holding the point geometry for the centre of each plot, the count in each plot and the area of each plot.plots
An
sf
object withMULTIPOLYGON
objects defining the individual plot boundaries and an all-onesweight
column.nests
An
sf
giving the locations of each detected nests,group
("minor" or "major"),season
("dry" or "rainy"), anddate
(inDate
format).
Functions
-
gorillas_sf_gcov()
: Access thegorillas_sf
covariates data as aterra::rast()
object. -
gorillas_sp()
: Access thegorillas_sf
data insp
format. The covariate data is added asgcov
, a list ofsp::SpatialPixelsDataFrame
objects. Requires thesp
,sf
, andterra
packages to be installed.
Source
Library spatstat.data
.
References
Funwi-Gabga, N. (2008) A pastoralist survey and fire impact assessment in the Kagwene Gorilla Sanctuary, Cameroon. M.Sc. thesis, Geology and Environmental Science, University of Buea, Cameroon.
Funwi-Gabga, N. and Mateu, J. (2012) Understanding the nesting spatial behaviour of gorillas in the Kagwene Sanctuary, Cameroon. Stochastic Environmental Research and Risk Assessment 26 (6), 793-811.
Examples
if (interactive() &&
require(ggplot2, quietly = TRUE) &&
requireNamespace("terra", quietly = TRUE) &&
requireNamespace("tidyterra", quietly = TRUE)) {
# plot all the nests, mesh and boundary
ggplot() +
gg(gorillas_sf$mesh) +
geom_sf(
data = gorillas_sf$boundary,
alpha = 0.1, fill = "blue"
) +
geom_sf(data = gorillas_sf$nests)
# Plot the elevation covariate
gorillas_sf$gcov <- gorillas_sf_gcov()
ggplot() +
tidyterra::geom_spatraster(data = gorillas_sf$gcov$elevation)
# Plot the plot sample
ggplot() +
geom_sf(data = gorillas_sf$plotsample$plots) +
geom_sf(data = gorillas_sf$plotsample$nests)
}
if (interactive() &&
requireNamespace("terra", quietly = TRUE)) {
gorillas_sf$gcov <- gorillas_sf_gcov()
}
Iterated INLA
Description
This is an internal wrapper for iterated runs of INLA::inla
.
For nonlinear models, a linearisation is done with
bru_compute_linearisation
, with a line search method between each
iteration. The INLA::inla.stack
information is setup by bru_make_stack()
.
Usage
iinla(model, lhoods, inputs = NULL, initial = NULL, options)
Arguments
model |
A bru_model object |
lhoods |
A list of likelihood objects from |
inputs |
Optional pre-computed list of per-likelihood component
evaluations, from |
initial |
A previous |
options |
A |
Value
An iinla
object that inherits from INLA::inla
, with an
added field bru_iinla
with elements
- log
The diagnostic log messages produced by the run
- states
The list of linearisation points, one for each inla run
- inla_stack
The
inla.stack
object from the final inla run- track
A list of convergence tracking vectors
If an inla run is aborted by an error, the returned object also contains
an element error
with the error object.
Obtain inla index subset information
Description
Subsets for INLA::f()
compatible indexing
Usage
inla_subset_eval(...)
## S3 method for class 'bru_comp_list'
inla_subset_eval(components, ...)
Arguments
... |
Passed on to submethods. |
components |
A component list. |
Author(s)
Finn Lindgren finn.lindgren@gmail.com
Deprecated functions in inlabru
Description
Some of these functions may stil attempt to do their job, but will be removed in a future version.
Usage
gmap(...)
gm(...)
row_kron(M1, M2, repl = NULL, n.repl = NULL, weights = NULL)
Arguments
... |
Usually passed on to other methods |
M1 |
A matrix that can be transformed into a sparse Matrix. |
M2 |
A matrix that can be transformed into a sparse Matrix. |
repl |
An optional index vector. For each entry, specifies which
replicate the row belongs to, in the sense used in
|
n.repl |
The maximum replicate index, in the sense used in
|
weights |
Optional scaling weights to be applied row-wise to the resulting matrix. |
Functions
-
gmap()
: Plot a map using extent of a spatial objectThis function is deprecated as
ggmap
isn't supported.Used
ggmap::get_map()
to query map services like Google Maps for a region centered around the spatial object provided. Then callsggmap()
to plot the map.This function required the
ggmap
package. -
gm()
:This function is deprecated as
ggmap
isn't supported.ggplot geom for spatial data
gm is a wrapper for the gg method. It will take the first argument and transform its coordinate system to latitude and longitude. Thereafter, gg is called using the transformed data and the arguments provided via
...
. gm is intended to replace gg whenever the data is supposed to be plotted over a spatial map generated by gmap, which only works if the coordinate system is latitude/longitude. -
row_kron()
: Row-wise Kronecker productsin favour of
fmesher::fm_row_kron()
.Takes two Matrices and computes the row-wise Kronecker product. Optionally applies row-wise weights and/or applies an additional 0/1 row-wise Kronecker matrix product.
Returns a
Matrix::sparseMatrix
object.
Author(s)
Finn Lindgren finn.lindgren@gmail.com
Log Gaussian Cox process (LGCP) inference using INLA
Description
This function performs inference on a LGCP observed via points residing possibly multiple dimensions. These dimensions are defined via the left hand side of the formula provided via the model parameter. The left hand side determines the intensity function that is assumed to drive the LGCP. This may include effects that lead to a thinning (filtering) of the point process. By default, the log intensity is assumed to be a linear combination of the effects defined by the formula's RHS.
More sophisticated models, e.g. non-linear thinning, can be achieved by using the predictor argument. The latter requires multiple runs of INLA for improving the required approximation of the predictor. In many applications the LGCP is only observed through subsets of the dimensions the process is living in. For example, spatial point realizations may only be known in sub-areas of the modelled space. These observed subsets of the LGCP domain are called samplers and can be provided via the respective parameter. If samplers is NULL it is assumed that all of the LGCP's dimensions have been observed completely.
Usage
lgcp(
components,
data,
domain = NULL,
samplers = NULL,
ips = NULL,
formula = . ~ .,
...,
options = list(),
.envir = parent.frame()
)
Arguments
components |
A |
data |
Predictor expression-specific data, as a |
domain , samplers , ips |
Arguments used for
|
formula |
a |
... |
Further arguments passed on to |
options |
A bru_options options object or a list of options passed
on to |
.envir |
The evaluation environment to use for special arguments ( |
Value
An bru()
object
Examples
if (bru_safe_inla() &&
require(ggplot2, quietly = TRUE) &&
require(fmesher, quietly = TRUE) &&
require(sn, quietly = TRUE)) {
# Load the Gorilla data
data <- gorillas_sf
# Plot the Gorilla nests, the mesh and the survey boundary
ggplot() +
geom_fm(data = data$mesh) +
gg(data$boundary, fill = "blue", alpha = 0.2) +
gg(data$nests, col = "red", alpha = 0.2)
# Define SPDE prior
matern <- INLA::inla.spde2.pcmatern(
data$mesh,
prior.sigma = c(0.1, 0.01),
prior.range = c(0.1, 0.01)
)
# Define domain of the LGCP as well as the model components (spatial SPDE
# effect and Intercept)
cmp <- geometry ~ field(geometry, model = matern) + Intercept(1)
# Fit the model (with int.strategy="eb" to make the example take less time)
fit <- lgcp(cmp, data$nests,
samplers = data$boundary,
domain = list(geometry = data$mesh),
options = list(control.inla = list(int.strategy = "eb"))
)
# Predict the spatial intensity surface
lambda <- predict(
fit,
fm_pixels(data$mesh, mask = data$boundary),
~ exp(field + Intercept)
)
# Plot the intensity
ggplot() +
gg(lambda, geom = "tile") +
geom_fm(data = data$mesh, alpha = 0, linewidth = 0.05) +
gg(data$nests, col = "red", alpha = 0.2)
}
Unit test helpers
Description
Local helper functions for package unit tests
Usage
local_bru_testthat_assign(x, values, envir = parent.frame())
local_bru_testthat_tolerances(
tolerances = c(1e-04, 0.01, 0.1),
envir = parent.frame()
)
local_bru_options_set(..., .reset = FALSE, envir = parent.frame())
local_basic_intercept_testdata()
local_basic_fixed_effect_testdata()
local_bru_safe_inla(multicore = FALSE, quietly = TRUE, envir = parent.frame())
local_bru_testthat_setup(envir = parent.frame())
Arguments
x |
character; Name of variable to assign to |
values |
the object to assign to |
envir |
environment for exit handlers |
tolerances |
numeric vector of length 3; |
.reset |
For |
multicore |
logical; if |
quietly |
logical; if |
Value
local_bru_options_set()
returns a copy of the global override
options (not including the defaults), invisibly.
Functions
-
local_bru_testthat_assign()
: Assign local variable. Useful for easy cleanup of global workspace withwithr::deferred_run()
when running tests interactively. -
local_bru_testthat_tolerances()
: Assign test tolerances Assign local tolerance variables. Useful for easy cleanup of global workspace withwithr::deferred_run()
when running tests interactively. -
local_bru_options_set()
: Wrapper forbru_options_set_local()
, to locally override the global package options. -
local_bru_safe_inla()
: Tests should set num.threads = "1:1" to ensure within-system repeatability by callinglocal_bru_safe_inla()
; see alsobru_safe_inla()
-
local_bru_testthat_setup()
: Initialise environment for tests. Assigns tolerance variables. To be called either at the top of a testfile, or inside tests. Does not calllocal_bru_safe_inla()
, since that may invoke a skip and should be called inside each test that relies on INLA.
See Also
bru_options_set_local()
, bru_options_default()
,
bru_options_get()
Make hierarchical mesh basis functions
Description
Make hierarchical mesh basis functions
Usage
make_hierarchical_mesh_basis(mesh, forward = TRUE)
inla.spde2.pcmatern_B(mesh, ..., B)
Functions
Matern correlation or covariance function approximate credible bands.
Description
Evaluate the covariance function for an inla.spde object. Calculates the posterior distribution of the range, log(range), variance, or log(variance) parameter of a model's SPDE component. Can also calculate Matern correlation or covariance function.
Usage
materncov.bands(
manifold,
dist,
log.range,
log.variance = NULL,
alpha = 2,
quantile = 0.95,
n = 64,
S1.L = NULL
)
Arguments
manifold |
Either "R1", "S1", "R2", or "S2", from
|
dist |
A vector of distances at which to calculate the covariances/correlations |
log.range |
A scalar or a list (mean, sd), such as produced by
|
log.variance |
Either |
alpha |
The SPDE operator order. Default 2. |
quantile |
The target credible probability. Default 0.95. |
n |
The number of parameter combinations to use for the approximation. Default 64. |
S1.L |
For |
Details
Uses a Gaussian assumption for the internal model parameters, and finds a
region in parameter space with approximately quantile
probability.
Value
A list with estimated covariance or correlation (when log.variance
is NULL
) functions:
lower |
An approximate lower bound for the |
median |
The function for for the approximate median parameters quantile |
upper |
An approximate upper bound for the |
Author(s)
Finn Lindgren Finn.Lindgren@ed.ac.uk
Deprecated alias for sp version of the mexdolphin dataset
Description
Deprecated dataset name for the sp
version
of mexdolphin_sf. Use mexdolphin_sp()
instead.
See Also
Pan-tropical spotted dolphins in the Gulf of Mexico
Description
This a version of the mexdolphins
dataset from the package
dsm
, reformatted as point process data for use with inlabru
, with the
parts stored in sf
format. The data are from a combination of several
NOAA shipboard surveys conducted on pan-tropical spotted dolphins in the
Gulf of Mexico. 47 observations of groups of dolphins were detected. The
group size was recorded, as well as the Beaufort sea state at the time of
the observation. Transect width is 16 km, i.e. maximal detection distance 8
km (transect half-width 8 km).
Usage
mexdolphin_sf
mexdolphin_sp()
Format
A list of objects:
points
:An
sf
object containing the locations of detected dolphin groups, with their size as an attribute.samplers
:An
sf
object containing the transect lines that were surveyed.mesh
:An
fm_mesh_2d
object containing a Delaunay triangulation mesh (a type of discretization of continuous space) covering the survey region.ppoly
:An
sf
object defining the boundary of the survey region.simulated
:A
sf
object containing the locations of a simulated population of dolphin groups. The population was simulated from ainlabru
model fitted to the actual survey data. Note that the simulated data do not have any associated size information.
Functions
-
mexdolphin_sp()
: Convertmexdolphin_sf
tosp
format. Replaces the oldmexdolphin
dataset.
Source
Library dsm
.
References
Halpin, P.N., A.J. Read, E. Fujioka, B.D. Best, B. Donnelly, L.J. Hazen, C. Kot, K. Urian, E. LaBrecque, A. Dimatteo, J. Cleary, C. Good, L.B. Crowder, and K.D. Hyrenbach. 2009. OBIS-SEAMAP: The world data center for marine mammal, sea bird, and sea turtle distributions. Oceanography 22(2):104-115
NOAA Southeast Fisheries Science Center. 1996. Report of a Cetacean Survey of Oceanic and Selected Continental Shelf Waters of the Northern Gulf of Mexico aboard NOAA Ship Oregon II (Cruise 220)
Examples
if (require("ggplot2", quietly = TRUE)) {
data(mexdolphin_sf, package = "inlabru", envir = environment())
ggplot() +
gg(mexdolphin_sf$mesh) +
gg(mexdolphin_sf$ppoly, color = "blue", alpha = 0, linewidth = 1) +
gg(mexdolphin_sf$samplers) +
gg(mexdolphin_sf$points, aes(size = size), color = "red") +
scale_size_area()
ggplot() +
gg(mexdolphin_sf$mesh,
color = mexdolphin_sf$lambda,
mask = mexdolphin_sf$ppoly
)
}
if (require("ggplot2", quietly = TRUE) &&
require("sp", quietly = TRUE)) {
mexdolphin <- mexdolphin_sp()
ggplot() +
gg(mexdolphin$mesh) +
gg(mexdolphin$ppoly, color = "blue") +
gg(mexdolphin$samplers) +
gg(mexdolphin$points, aes(size = size), color = "red") +
scale_size_area() +
coord_equal()
ggplot() +
gg(mexdolphin$mesh,
col = mexdolphin$lambda,
mask = mexdolphin$ppoly
) +
coord_equal()
}
Marine renewables strategic environmental assessment
Description
Data imported from package MRSea, see https://www.creem.st-andrews.ac.uk/software/
Usage
mrsea
Format
A list of objects:
points
A
sf
object containing the locations of XXXXX.samplers
A
sf
object containing the transect lines that were surveyed.mesh
An
fm_mesh_2d
object containing a Delaunay triangulation mesh (a type of discretization of continuous space) covering the survey region.boundary
An
sf
object defining the boundary polygon of the survey region.covar
An
sf
containing sea depth estimates.
Source
Library MRSea
.
References
NONE YET
Examples
if (require(ggplot2, quietly = TRUE)) {
ggplot() +
geom_fm(data = mrsea$mesh) +
gg(mrsea$samplers) +
gg(mrsea$points) +
gg(mrsea$boundary)
}
Multiple ggplots on a page.
Description
in favour of the
patchwork
package;
see the example below.
Renders multiple ggplots on a single page.
Usage
multiplot(..., plotlist = NULL, cols = 1, layout = NULL)
Arguments
... |
Comma-separated |
plotlist |
A list of |
cols |
Number of columns of plots on the page. |
layout |
A matrix specifying the layout. If present, |
Author(s)
David L. Borchers dlb@st-andrews.ac.uk
Source
http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/
Examples
if (require("ggplot2", quietly = TRUE)) {
df <- data.frame(x = 1:10, y = cos(1:10), z = sin(1:10))
pl1 <- ggplot(data = df) +
geom_line(mapping = aes(x, y), color = "red")
pl2 <- ggplot(data = df) +
geom_line(mapping = aes(x, z), color = "blue")
pl3 <- ggplot(data = df) +
geom_path(mapping = aes(y, z), color = "magenta")
multiplot(
pl1, pl2, pl3,
layout = rbind(c(1, 2), c(3, 3))
)
if (require("patchwork")) {
(pl1 + pl2) / pl3
}
}
Parse inclusion of component labels in a predictor expression
Description
Parse inclusion of component labels in a predictor expression
Usage
parse_inclusion(thenames, include = NULL, exclude = NULL)
Arguments
thenames |
Set of labels to restrict |
include |
Character vector of component labels that are needed by the predictor expression; Default: NULL (include all components that are not explicitly excluded) |
exclude |
Character vector of component labels that are not used by the
predictor expression. The exclusion list is applied to the list
as determined by the |
Plot method for posterior marginals estimated by bru
Description
From version 2.11.0
, plot.bru(x, ...)
calls plot.inla(x, ...)
from the INLA
package, unless the first argument after x
is a
character
, in which case the pre-2.11.0
behaviour is used, calling
plotmarginal.inla(x, ...)
instead.
Requires the ggplot2
package.
Usage
## S3 method for class 'bru'
plot(x, ...)
plotmarginal.inla(
result,
varname = NULL,
index = NULL,
link = function(x) {
x
},
add = FALSE,
ggp = TRUE,
lwd = 3,
...
)
Arguments
x |
a fitted |
... |
Options passed on to other methods. |
result |
an |
varname |
character; name of the variable to plot |
index |
integer; index of the random effect to plot |
link |
function; link function to apply to the variable |
add |
logical; if |
ggp |
logical; unused |
lwd |
numeric; line width |
Examples
## Not run:
if (require("ggplot2", quietly = TRUE)) {
# Generate some data and fit a simple model
input.df <- data.frame(x = cos(1:10))
input.df <- within(
input.df,
y <- 5 + 2 * x + rnorm(length(x), mean = 0, sd = 0.1)
)
fit <- bru(y ~ x, family = "gaussian", data = input.df)
summary(fit)
# Plot the posterior density of the model's x-effect
plot(fit, "x")
}
## End(Not run)
Plot prediction using ggplot2
Description
Generates a base ggplot2 using ggplot()
and adds a geom for input x
using
gg.
Requires the ggplot2
package.
Usage
## S3 method for class 'bru_prediction'
plot(x, y = NULL, ...)
## S3 method for class 'prediction'
plot(x, y = NULL, ...)
Arguments
x |
a prediction object. |
y |
Ignored argument but required for S3 compatibility. |
... |
Arguments passed on to |
Value
an object of class gg
Examples
if (bru_safe_inla() &&
require(sn, quietly = TRUE) &&
require(ggplot2, quietly = TRUE)) {
# Generate some data
input.df <- data.frame(x = cos(1:10))
input.df <- within(input.df, y <- 5 + 2 * cos(1:10) + rnorm(10, mean = 0, sd = 0.1))
# Fit a model with fixed effect 'x' and intercept 'Intercept'
fit <- bru(y ~ x, family = "gaussian", data = input.df)
# Predict posterior statistics of 'x'
xpost <- predict(fit, NULL, formula = ~x_latent)
# The statistics include mean, standard deviation, the 2.5% quantile, the median,
# the 97.5% quantile, minimum and maximum sample drawn from the posterior as well as
# the coefficient of variation and the variance.
xpost
# For a single variable like 'x' the default plotting method invoked by gg() will
# show these statisics in a fashion similar to a box plot:
ggplot() +
gg(xpost)
# The predict function can also be used to simultaneously estimate posteriors
# of multiple variables:
xipost <- predict(fit,
newdata = NULL,
formula = ~ c(
Intercept = Intercept_latent,
x = x_latent
)
)
xipost
# If we still want a plot in the previous style we have to set the bar parameter to TRUE
p1 <- ggplot() +
gg(xipost, bar = TRUE)
p1
# Note that gg also understands the posterior estimates generated while running INLA
p2 <- ggplot() +
gg(fit$summary.fixed, bar = TRUE)
multiplot(p1, p2)
# By default, if the prediction has more than one row, gg will plot the column 'mean' against
# the row index. This is for instance usefuul for predicting and plotting function
# but not very meaningful given the above example:
ggplot() +
gg(xipost)
# For ease of use we can also type
plot(xipost)
# This type of plot will show a ribbon around the mean, which viszualizes the upper and lower
# quantiles mentioned above (2.5 and 97.5%). Plotting the ribbon can be turned of using the
# \code{ribbon} parameter
ggplot() +
gg(xipost, ribbon = FALSE)
# Much like the other geomes produced by gg we can adjust the plot using ggplot2 style
# commands, for instance
ggplot() +
gg(xipost) +
gg(xipost, mapping = aes(y = median), ribbon = FALSE, color = "red")
}
Create a plot sample.
Description
Creates a plot sample on a regular grid with a random start location.
Usage
plotsample(spdf, boundary, x.ppn = 0.25, y.ppn = 0.25, nx = 5, ny = 5)
Arguments
spdf |
A |
boundary |
A |
x.ppn |
The proportion of the x=axis that is to be included in the plots. |
y.ppn |
The proportion of the y=axis that is to be included in the plots. |
nx |
The number of plots in the x-dimension. |
ny |
The number of plots in the y-dimension. |
Value
A list with three components:
plots
A
SpatialPolygonsDataFrame
object containing the plots that were sampled.dets
A
SpatialPointsDataFrame
object containing the locations of the points within the plots.counts
A
dataframe
containing the following columnsx
The x-coordinates of the centres of the plots within the boundary.
y
The y-coordinates of the centres of the plots within the boundary.
n
The numbers of points in each plot.
area
The areas of the plots within the boundary
.
Examples
# Some features require the raster package
if (bru_safe_sp() &&
require("sp") &&
require("raster", quietly = TRUE) &&
require("ggplot2", quietly = TRUE) &&
require("terra", quietly = TRUE) &&
require("sf", quietly = TRUE)) {
gorillas <- gorillas_sp()
plotpts <- plotsample(gorillas$nests, gorillas$boundary,
x.ppn = 0.4, y.ppn = 0.4, nx = 5, ny = 5
)
ggplot() +
gg(plotpts$plots) +
gg(plotpts$dets, pch = "+", cex = 2) +
gg(gorillas$boundary)
}
Convert a plot sample of points into one of counts.
Description
Converts a plot sample with locations of each point within each plot, into a plot sample with only the count within each plot.
Usage
point2count(plots, dets)
Arguments
plots |
A |
dets |
A |
Value
A SpatialPolygonsDataFrame
with counts in each plot contained in
slot @data$n
.
Examples
# Some features require the raster package
if (bru_safe_sp() &&
require("sp") &&
require("raster", quietly = TRUE) &&
require("ggplot2", quietly = TRUE) &&
require("terra", quietly = TRUE) &&
require("sf", quietly = TRUE)) {
gorillas <- gorillas_sp()
plotpts <- plotsample(gorillas$nests, gorillas$boundary,
x.ppn = 0.4, y.ppn = 0.4, nx = 5, ny = 5
)
p1 <- ggplot() +
gg(plotpts$plots) +
gg(plotpts$dets) +
gg(gorillas$boundary)
countdata <- point2count(plotpts$plots, plotpts$dets)
x <- sp::coordinates(countdata)[, 1]
y <- sp::coordinates(countdata)[, 2]
count <- countdata@data$n
p2 <- ggplot() +
gg(gorillas$boundary) +
gg(plotpts$plots) +
geom_text(aes(label = count, x = x, y = y))
multiplot(p1, p2, cols = 2)
}
Prediction from fitted bru model
Description
Takes a fitted bru
object produced by the function bru()
and produces
predictions given a new set of values for the model covariates or the
original values used for the model fit. The predictions can be based on any
R expression that is valid given these values/covariates and the joint
posterior of the estimated random effects.
Usage
## S3 method for class 'bru'
predict(
object,
newdata = NULL,
formula = NULL,
n.samples = 100,
seed = 0L,
probs = c(0.025, 0.5, 0.975),
num.threads = NULL,
used = NULL,
drop = FALSE,
...,
data = deprecated(),
include = deprecated(),
exclude = deprecated()
)
Arguments
object |
|
newdata |
A |
formula |
A formula where the right hand side defines an R expression
to evaluate for each generated sample. If |
n.samples |
Integer setting the number of samples to draw in order to calculate the posterior statistics. The default is rather low but provides a quick approximate result. |
seed |
Random number generator seed passed on to |
probs |
A numeric vector of probabilities with values in |
num.threads |
Specification of desired number of threads for parallel computations. Default NULL, leaves it up to INLA. When seed != 0, overridden to "1:1" |
used |
Either |
drop |
logical; If |
... |
Additional arguments passed on to |
data |
|
include , exclude |
|
Details
Mean value predictions are accompanied by the standard errors, upper and lower 2.5% quantiles, the median, variance, coefficient of variation as well as the variance and minimum and maximum sample value drawn in course of estimating the statistics.
Internally, this method calls generate.bru()
in order to draw samples from
the model.
In addition to the component names (that give the effect of each component
evaluated for the input data), the suffix _latent
variable name can be used
to directly access the latent state for a component, and the suffix function
_eval
can be used to evaluate a component at other input values than the
expressions defined in the component definition itself, e.g.
field_eval(cbind(x, y))
for a component that was defined with
field(coordinates, ...)
(see also bru_comp_eval()
).
For "iid" models with mapper = bm_index(n)
, rnorm()
is used to
generate new realisations for indices greater than n
.
Value
a data.frame
, sf
, or Spatial*
object with predicted mean values
and other summary statistics attached. Non-S4 object outputs have the class
"bru_prediction" added at the front of the class list.
Examples
if (bru_safe_inla() &&
require("sn", quietly = TRUE) &&
require("ggplot2", quietly = TRUE) &&
require("terra", quietly = TRUE) &&
require("sf", quietly = TRUE)) {
# Load the Gorilla data
gorillas <- gorillas_sf
# Plot the Gorilla nests, the mesh and the survey boundary
ggplot() +
gg(gorillas$mesh) +
gg(gorillas$nests) +
gg(gorillas$boundary, alpha = 0.1)
# Define SPDE prior
matern <- INLA::inla.spde2.pcmatern(
gorillas$mesh,
prior.sigma = c(0.1, 0.01),
prior.range = c(0.01, 0.01)
)
# Define domain of the LGCP as well as the model components (spatial SPDE effect and Intercept)
cmp <- geometry ~ field(geometry, model = matern) + Intercept(1)
# Fit the model, with "eb" instead of full Bayes
fit <- lgcp(
cmp,
data = gorillas$nests,
samplers = gorillas$boundary,
domain = list(geometry = gorillas$mesh),
options = list(control.inla = list(int.strategy = "eb"))
)
# Once we obtain a fitted model the predict function can serve various purposes.
# The most basic one is to determine posterior statistics of a univariate
# random variable in the model, e.g. the intercept
icpt <- predict(fit, NULL, ~ c(Intercept = Intercept_latent))
plot(icpt)
# The formula argument can take any expression that is valid within the model, for
# instance a non-linear transformation of a random variable
exp.icpt <- predict(fit, NULL, ~ c(
"Intercept" = Intercept_latent,
"exp(Intercept)" = exp(Intercept_latent)
))
plot(exp.icpt, bar = TRUE)
# The intercept is special in the sense that it does not depend on other variables
# or covariates. However, this is not true for the smooth spatial effects 'field'.
# In order to predict 'field' we have to define where (in space) to predict. For
# this purpose, the second argument of the predict function can take \code{data.frame}
# objects as well as Spatial objects. For instance, we might want to predict
# 'field' at the locations of the mesh vertices. Using
vrt <- fm_vertices(gorillas$mesh, format = "sf")
# we obtain these vertices as a SpatialPointsDataFrame
ggplot() +
gg(gorillas$mesh) +
gg(vrt, color = "red")
# Predicting 'mySmooth' at these locations works as follows
field <- predict(fit, vrt, ~field)
# Note that just like the input also the output will be a sf object with
# points and that the predicted statistics are simply added as columns
class(field)
head(vrt)
head(field)
# Plotting the mean, for instance, at the mesh node is straight forward
ggplot() +
gg(gorillas$mesh) +
gg(field, aes(color = mean), size = 2)
# However, we are often interested in a spatial field and thus a linear interpolation,
# which can be achieved by using the gg mechanism for meshes
ggplot() +
gg(gorillas$mesh, color = field$mean)
# Alternatively, we can predict the spatial field at a grid of locations, e.g. a
# sf object with a grid of points covering the relevant part of mesh
pxl <- fm_pixels(gorillas$mesh, format = "sf", mask = gorillas$boundary)
field2 <- predict(fit, pxl, ~field)
# This will give us a sf with the columns we are looking for
head(field2)
ggplot() +
gg(gorillas$boundary) +
gg(data = field2, geom = "tile")
}
Summarise components
Description
Summarise components
Usage
## S3 method for class 'summary_bru_input'
print(x, ...)
## S3 method for class 'bru_comp'
summary(object, ..., depth = Inf, verbose = TRUE)
## S3 method for class 'bru_comp_list'
summary(object, verbose = TRUE, ...)
## S3 method for class 'bru_comp'
print(x, ...)
## S3 method for class 'bru_comp_list'
print(x, ...)
## S3 method for class 'bru_subcomp'
format(x, verbose = TRUE, ..., label.override = NULL)
## S3 method for class 'bru_subcomp'
summary(object, verbose = TRUE, ..., label.override = NULL)
## S3 method for class 'bru_subcomp'
print(x, verbose = TRUE, ..., label.override = NULL)
## S3 method for class 'summary_component'
print(x, ...)
## S3 method for class 'summary_bru_comp_list'
print(x, ...)
## S3 method for class 'summary_bru_subcomp'
print(x, ...)
Arguments
x |
A summary object to be printed. |
... |
Passed on to other summary methods. |
object |
Object to be summarised. |
depth |
The depth of which to expand the component mapper.
Default |
verbose |
logical; If |
label.override |
character; If not |
Author(s)
Fabian E. Bachl bachlfab@gmail.com
Finn Lindgren finn.lindgren@gmail.com
See Also
bru_comp()
, summary.bru_input()
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
- fmesher
robins_subset
Description
This is the robins_subset
dataset, which is a subset of the
full robins data set used to demonstrate a spatially varying trend
coefficient model in Meehan et al. 2019. The dataset includes American
Robin counts, along with time, location, and effort information, from
Audubon Christimas Bird Counts (CBC) conducted in six US states between
1987 and 2016.
Usage
robins_subset
Format
The data are a data.frame with variables
circle
:-
Four-letter code of the CBC circle.
bcr
:-
Numeric code for the bird conservation region encompassing the count circle.
state
:-
US state encompassing the count circle.
year
:-
calendar year the count was conducted.
std_yr
:-
transformed year, with 2016 = 0.
count
:-
number of robins recorded.
log_hrs
:-
the natural log of party hours.
lon
:-
longitude of the count circle centroid.
lat
:-
latitude of the count circle centroid.
obs
:-
unique record identifier.
Source
https://github.com/tmeeha/inlaSVCBC
References
Meehan, T.D., Michel, N.L., and Rue, H. 2019. Spatial modeling of Audubon Christmas Bird Counts reveals fine-scale patterns and drivers of relative abundance trends. Ecosphere, 10(4), p.e02707.
Examples
if (require(ggplot2, quietly = TRUE)) {
data(robins_subset, package = "inlabru") # get the data
# plot the counts for one year of data
ggplot(robins_subset[robins_subset$std_yr == 0, ]) +
geom_point(aes(lon, lat, colour = count + 1)) +
scale_colour_gradient(low = "blue", high = "red", trans = "log")
}
Sample from an inhomogeneous Poisson process
Description
This function provides point samples from one- and two-dimensional
inhomogeneous Poisson processes. The log intensity has to be provided via its
values at the nodes of an fm_mesh_1d
or fm_mesh_2d
object. In between
mesh nodes the log intensity is assumed to be linear.
Usage
sample.lgcp(
mesh,
loglambda,
strategy = NULL,
R = NULL,
samplers = NULL,
ignore.CRS = FALSE
)
Arguments
mesh |
An fmesher::fm_mesh_1d or fmesher::fm_mesh_2d object |
loglambda |
vector or matrix; A vector of log intensities at the mesh
vertices (for higher order basis functions, e.g. for |
strategy |
Only relevant for 2D meshes. One of |
R |
Numerical value only applicable to spherical and geographical
meshes. It is interpreted as |
samplers |
A |
ignore.CRS |
logical; if |
Details
For 2D processes on a sphere the R
parameter can be used to adjust to
sphere's radius implied by the mesh. If the intensity is very high the
standard strategy
"spherical" can cause memory issues. Using the
"sliced-spherical" strategy can help in this case.
For crs-less meshes on R2: Lambda is interpreted in the raw coordinate system. Output has an NA CRS.
For crs-less meshes on S2: Lambda with raw units, after scaling the mesh to radius
R
, if specified. Output is given on the same domain as the mesh, with an NA CRS.For crs meshes on R2: Lambda is interpreted as per km^2, after scaling the globe to the Earth radius 6371 km, or
R
, if specified. Output given in the same CRS as the mesh.For crs meshes on S2: Lambda is interpreted as per km^2, after scaling the globe to the Earth radius 6371 km, or
R
, if specified. Output given in the same CRS as the mesh.
Value
A data.frame
(1D case),
SpatialPoints (2D flat and 3D spherical surface cases)
SpatialPointsDataFrame (2D/3D surface cases with multiple samples).
For multiple samples, the data.frame
output has a
column 'sample'
giving the index for each sample.
object of point locations.
Author(s)
Daniel Simpson dp.simpson@gmail.com (base rectangle and spherical algorithms), Fabian E. Bachl bachlfab@gmail.com (inclusion in inlabru, sliced spherical sampling), Finn Lindgren finn.lindgren@gmail.com (extended CRS support, triangulated sampling)
Examples
# The INLA package is required
if (bru_safe_inla() &&
bru_safe_sp() &&
require("sp")) {
vertices <- seq(0, 3, by = 0.1)
mesh <- fm_mesh_1d(vertices)
loglambda <- 5 - 0.5 * vertices
pts <- sample.lgcp(mesh, loglambda)
pts$y <- 0
plot(vertices, exp(loglambda), type = "l", ylim = c(0, 150))
points(pts, pch = "|")
}
# The INLA package is required
if (bru_safe_inla() &&
require(ggplot2, quietly = TRUE) &&
bru_safe_sp() &&
require("sp") &&
require("terra", quietly = TRUE) &&
require("sf", quietly = TRUE)) {
gorillas <- gorillas_sp()
pts <- sample.lgcp(gorillas$mesh,
loglambda = 1.5,
samplers = gorillas$boundary
)
ggplot() +
gg(gorillas$mesh) +
gg(pts)
}
Blue and red shrimp in the Western Mediterranean Sea
Description
Blue and red shrimp in the Western Mediterranean Sea.
Usage
data(shrimp)
Format
A list of objects:
hauls
:An
sf
object containing haul locationsmesh
:An
fm_mesh_2d
object containing a Delaunay triangulation mesh (a type of discretization of continuous space) covering the haul locations.
catch
Catch in Kg.
landing
Landing in Kg.
depth
Mean depth (in metres) of the fishery haul.
Source
Pennino, Maria Grazia. Personal communication.
References
Pennino, M. G., Paradinas, I., Munoz, F., Illian, J.,Quilez-Lopez, A., Bellido, J.M., Conesa, D. Accounting for preferential sampling in species distribution models. Ecology and Evolution, 9(1), p653-663, 2019 doi:10.1002/ece3.4789
Examples
if (require(ggplot2, quietly = TRUE)) {
data(shrimp, package = "inlabru", envir = environment())
ggplot() +
geom_fm(data = shrimp$mesh) +
gg(shrimp$hauls, aes(col = catch)) +
coord_sf(datum = fm_crs(shrimp$hauls))
}
Convert data frame to SpatialLinesDataFrame
Description
A line in 2D space is defined by a start and an end point, each associated
with 2D coordinates. This function takes a data.frame
as input and assumes
that each row defines a line in space. In order to do so, the data frame must
have at least four columns and the start.cols
and end.cols
parameters
must be used to point out the names of the columns that define the start and
end coordinates of the line. The data is then converted to a
SpatialLinesDataFrame
DF
. If a coordinate reference system crs
is
provided it is attached to DF
. If also to.crs
is provided, the coordinate
system of DF
is transformed accordingly. Additional columns of the input
data, e.g. covariates, are retained and attached to DF
.
Usage
sline(
data,
start.cols,
end.cols,
crs = fm_crs(),
to.crs = NULL,
format = c("sp", "sf")
)
Arguments
data |
A data.frame |
start.cols |
Character array pointing out the columns of |
end.cols |
Character array pointing out the columns of |
crs |
Coordinate reference system of the original |
to.crs |
Coordinate reference system for the output. |
format |
Format of the output object. Either |
Value
sp::SpatialLinesDataFrame
or sf::sf
Examples
# Create a data frame defining three lines
lns <- data.frame(
xs = c(1, 2, 3), ys = c(1, 1, 1), # start points
xe = c(2, 3, 4), ye = c(2, 2, 2)
) # end points
# Conversion to sf without CRS
spl <- sline(lns,
start.cols = c("xs", "ys"),
end.cols = c("xe", "ye"),
format = "sf"
)
if (require(ggplot2, quietly = TRUE)) {
# Plot the lines
ggplot() +
gg(spl)
}
Convert SpatialPoints and boundary polygon to spatstat ppp object
Description
Spatstat point pattern objects consist of points and an observation windows.
This function uses a SpatialPoints
object and a SpatialPolygon
object to
generate the points and the window. Lastly, the ppp()
function is called to
create the ppp
object.
Usage
spatial.to.ppp(points, samplers)
Arguments
points |
A |
samplers |
A |
Value
A spatstat spatstat
ppp
object
Examples
if (require("spatstat.geom") &&
bru_safe_sp() &&
require("sp") &&
require("terra", quietly = TRUE) &&
require("sf", quietly = TRUE)) {
# Load Gorilla data
gorillas <- gorillas_sp()
# Use nest locations and survey boundary to create a spatstat ppp object
gp <- spatial.to.ppp(gorillas$nests, gorillas$boundary)
class(gp)
# Plot it
plot(gp)
}
Posteriors of SPDE hyper parameters and Matern correlation or covariance function.
Description
Calculate posterior distribution of the range, log(range), variance, or
log(variance) parameter of a model's SPDE component. Can also plot Matern
correlation or covariance function. inla.spde.result
.
Usage
spde.posterior(result, name, what = "range", quantile = 0.95)
Arguments
result |
An object inheriting from |
name |
Character stating the name of the SPDE effect, see
|
what |
One of "range", "log.range", "variance", "log.variance", "matern.correlation" or "matern.covariance". |
quantile |
The target credible probability. Default 0.95. |
Value
A prediction
object.
Author(s)
Finn Lindgren Finn.Lindgren@ed.ac.uk
Examples
if (bru_safe_inla() && require(ggplot2, quietly = TRUE)) {
# Load 1D Poisson process data
data(Poisson2_1D, package = "inlabru")
# Take a look at the point (and frequency) data
ggplot(pts2) +
geom_histogram(aes(x = x), binwidth = 55 / 20, boundary = 0, fill = NA, color = "black") +
geom_point(aes(x), y = 0, pch = "|", cex = 4) +
coord_fixed(ratio = 1)
# Fit an LGCP model with and SPDE component
x <- seq(0, 55, length.out = 20)
mesh1D <- fm_mesh_1d(x, boundary = "free")
mdl <- x ~ spde1D(x, model = INLA::inla.spde2.matern(mesh1D, constr = TRUE)) + Intercept(1)
fit <- lgcp(mdl, data = pts2, domain = list(x = mesh1D))
# Calculate and plot the posterior range
range <- spde.posterior(fit, "spde1D", "range")
plot(range)
# Calculate and plot the posterior log range
lrange <- spde.posterior(fit, "spde1D", "log.range")
plot(lrange)
# Calculate and plot the posterior variance
variance <- spde.posterior(fit, "spde1D", "variance")
plot(variance)
# Calculate and plot the posterior log variance
lvariance <- spde.posterior(fit, "spde1D", "log.variance")
plot(lvariance)
# Calculate and plot the posterior Matern correlation
matcor <- spde.posterior(fit, "spde1D", "matern.correlation")
plot(matcor)
# Calculate and plot the posterior Matern covariance
matcov <- spde.posterior(fit, "spde1D", "matern.covariance")
plot(matcov)
}
Convert a data.frame of boundary points into a SpatialPolgonsDataFrame
Description
A polygon can be described as a sequence of points defining the polygon's
boundary. When given such a sequence (anti clockwise!) this function creates
a SpatialPolygonsDataFrame
or sf
holding the polygon decribed. By
default, the first two columns of data
are assumed to define the x and y
coordinates of the points. This behaviour can be changed using the cols
parameter, which points out the names of the columns holding the coordinates.
The coordinate reference system of the resulting spatial polygon can be set
via the crs
parameter. Posterior conversion to a different CRS is supported
using the to.crs
parameter.
Usage
spoly(
data,
cols = colnames(data)[1:2],
crs = fm_crs(),
to.crs = NULL,
format = c("sp", "sf")
)
Arguments
data |
A data.frame of points describing the boundary of the polygon (unique points, no holes) |
cols |
Column names of the x and y coordinates within the data |
crs |
Coordinate reference system of the points |
to.crs |
Coordinate reference system for the |
format |
Format of the output object. Either "sp" (default) or "sf" |
Value
sp::SpatialPolygonsDataFrame
or sf::sf
Examples
# Create data frame of boundary points (anti clockwise!)
pts <- data.frame(
x = c(1, 2, 1.7, 1.3),
y = c(1, 1, 2, 2)
)
# Convert to sf
pol <- spoly(pts, format = "sf")
if (require(ggplot2, quietly = TRUE)) {
# Plot it!
ggplot() +
gg(pol)
}
Summary for an inlabru fit
Description
Takes a fitted bru
object produced by bru()
or lgcp()
and creates
various summaries from it.
Usage
## S3 method for class 'bru'
summary(object, verbose = FALSE, ...)
## S3 method for class 'summary_bru'
print(x, ...)
Arguments
object |
|
verbose |
logical; If |
... |
arguments passed on to component summary functions, see
|
x |
An object to be printed |
Examples
if (bru_safe_inla()) {
# Simulate some covariates x and observations y
input.df <- data.frame(x = cos(1:10))
input.df <- within(input.df, {
y <- 5 + 2 * x + rnorm(10, mean = 0, sd = 0.1)
})
# Fit a Gaussian likelihood model
fit <- bru(y ~ x + Intercept(1), family = "gaussian", data = input.df)
# Obtain summary
fit$summary.fixed
}
if (bru_safe_inla()) {
# Alternatively, we can use the bru_obs() function to construct the likelihood:
lik <- bru_obs(family = "gaussian",
formula = y ~ x + Intercept,
data = input.df)
fit <- bru(~ x + Intercept(1), lik)
fit$summary.fixed
}
# An important addition to the INLA methodology is bru's ability to use
# non-linear predictors. Such a predictor can be formulated via bru_obs()'s
# \code{formula} parameter. The z(1) notation is needed to ensure that
# the z component should be interpreted as single latent variable and not
# a covariate:
if (bru_safe_inla()) {
z <- 2
input.df <- within(input.df, {
y <- 5 + exp(z) * x + rnorm(10, mean = 0, sd = 0.1)
})
lik <- bru_obs(
family = "gaussian", data = input.df,
formula = y ~ exp(z) * x + Intercept
)
fit <- bru(~ z(1) + Intercept(1), lik)
# Check the result (z posterior should be around 2)
fit$summary.fixed
}
Summary and print methods for observation models
Description
Summary and print methods for observation models
Usage
## S3 method for class 'bru_obs'
summary(object, verbose = TRUE, ...)
## S3 method for class 'bru_obs_list'
summary(object, verbose = TRUE, ...)
## S3 method for class 'summary_bru_obs'
print(x, ...)
## S3 method for class 'summary_bru_obs_list'
print(x, ...)
## S3 method for class 'bru_obs'
print(x, ...)
## S3 method for class 'bru_obs_list'
print(x, ...)
Arguments
object |
Object to operate on |
verbose |
logical; If |
... |
Arguments passed on to other |
x |
Object to be printed |
See Also
Examples
obs <- bru_obs(y ~ ., data = data.frame(y = rnorm(10)))
summary(obs)
print(obs)
Print inlabru options
Description
Print inlabru options
Usage
## S3 method for class 'bru_options'
summary(
object,
legend = TRUE,
include_global = TRUE,
include_default = TRUE,
...
)
## S3 method for class 'summary_bru_options'
print(x, ...)
Arguments
object |
A bru_options object to be summarised |
legend |
logical; If |
include_global |
logical; If |
include_default |
logical; If |
... |
Further parameters, currently ignored |
x |
A |
Examples
if (interactive()) {
options <- bru_options(verbose = TRUE)
# Don't print options only set in default:
print(options, include_default = FALSE)
# Only include options set in the object:
print(options, include_default = FALSE, include_global = FALSE)
}
Simulated 1D animal group locations and group sizes
Description
This data set serves to teach the concept of modelling species that gather in groups and where the grouping behaviour depends on space.
Usage
data(toygroups)
Format
The data are a list that contains these elements:
groups
:A
data.frame
of group locationsx
and sizesize
df.size
:IGNORE THIS
df.intensity
:A
data.frame
with Poisson process intensityd.lambda
at locationsx
df.rate
:A
data.frame
the locationsx
and associatedrate
which parameterized the exponential distribution from which the group sizes were drawn.
Examples
if (require(ggplot2, quietly = TRUE)) {
# Load the data
data("toygroups", package = "inlabru")
# The data set is a simulation of animal groups residing in a 1D space. Their
# locations in x-space are sampled from a Cox process with intensity
ggplot(toygroups$df.intensity) +
geom_line(aes(x = x, y = g.lambda))
# Adding the simulated group locations to this plot we obtain
ggplot(toygroups$df.intensity) +
geom_line(aes(x = x, y = g.lambda)) +
geom_point(data = toygroups$groups, aes(x, y = 0), pch = "|")
# Each group has a size mark attached to it.
# These group sizes are sampled from an exponential distribution
# for which the rate parameter depends on the x-coordinate
ggplot(toygroups$groups) +
geom_point(aes(x = x, y = size))
ggplot(toygroups$df.rate) +
geom_line(aes(x, rate))
}
Simulated 2D point process data
Description
This data set serves as an example for basic inlabru.
Usage
data(toypoints)
Format
The data are a list that contains these elements:
points
An
sf
object of point locations and andz
measurementsmesh
An
fm_mesh_2d
objectboundary
An
sf
polygon denting the region of interestpred_locs
A
sf
object with prediction point locations
Examples
if (require("ggplot2")) {
ggplot() +
fmesher::geom_fm(data = toypoints$mesh, alpha = 0) +
geom_sf(data = toypoints$boundary, fill = "blue", alpha = 0.1) +
geom_sf(data = toypoints$points, aes(color = z)) +
scale_color_viridis_c()
}