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 ORCID iD [aut, cre, cph] (Finn Lindgren continued development of the main code), Fabian E. Bachl [aut, cph] (Fabian Bachl wrote the main code), David L. Borchers [ctb, dtc, cph] (David Borchers wrote code for Gorilla data import and sampling, multiplot tool), Daniel Simpson [ctb, cph] (Daniel Simpson wrote the basic LGCP sampling method), Lindesay Scott-Howard [ctb, dtc, cph] (Lindesay Scott-Howard provided MRSea data import code), Seaton Andy [ctb] (Andy Seaton provided testing, bugfixes, and vignettes), Suen Man Ho [ctb, cph] (Man Ho Suen contributed features for aggregated responses and vignette updates), Roudier Pierre [ctb, cph] (Pierre Roudier contributed general quantile summaries), Meehan Tim [ctb, cph] (Tim Meehan contributed the SVC vignette and robins data), Reddy Peddinenikalva Niharika [ctb, cph] (Niharika Peddinenikalva contributed the LGCP residuals vignette), Perepolkin Dmytro [ctb, cph] (Dmytro Perepolkin contributed the ZIP/ZAP vignette)
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:


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 bru_input.bru_comp_list()

lh_data

A list of data object, one for each likelihood in lhoods that is used to determine the mapper(s). If NULL, the data is or inputs are used instead.

components

A bru_comp_list object

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 bru_comp_list().

Value

An object of class bru_comp_list.

Functions

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

as_bru_comp_list()


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

A result object from a bru() or lgcp() call

predictor

A formula describing the prediction of a 1D LGCP via predict().

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 ⁠[0,1]⁠

...

arguments passed on to predict.bru()

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 bm_aggregate and bm_logsumexp, specifies if the blockwise sums should be normalised by the blockwise weight sums or not:

  • FALSE: (default) Straight weighted sum, no rescaling.

  • TRUE: Divide by the sum of the weight values within each block. This is useful for integration averages, when the given weights are plain integration weights. If the weights are NULL or all ones, this is the same as dividing by the number of entries in each block.

n_block

Predetermined number of output blocks. If NULL, overrides the maximum block index in the inputs. The priority order is input$n_block, the mapper definition n_block, then max(input$block).

type

character; if non-NULL, overrides the rescale argument, and constructs an aggregation mapper of the given type instead. Supported values are "sum", "average", "logsumexp", and "logaverageexp".

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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)

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 bru_mapper objects

hidden

logical, set to TRUE to flag that the mapper is to be used as a first level input mapper for INLA::f() in a model that requires making only the first mapper visible to INLA::f() and INLA::inla.stack(), such as for "bym2" models, as activated by the inla_f argument to ibm_n, ibm_values, and ibm_jacobian. Set to FALSE to always access the full mapper, e.g. for rgeneric models

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

multi

logical; If TRUE (or positive), recurse one level into sub-mappers

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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 ⁠[.bm_collect⁠, whether to extract an individual mapper when i identifies a single element. If FALSE, a list of sub-mappers is returned (suitable e.g. for creating a new bm_collect object). Default: TRUE

value

a character vector of the same length as the number of sub-mappers in the mapper

Value

Methods (by generic)

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 bru_mapper.

...

Arguments passed on to other methods

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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 bru_input.bru_input()

factor_mapping

character; selects the type of factor mapping.

  • 'contrast' for leaving out the first factor level.

  • 'full' for keeping all levels.

indexed

logical; if TRUE, the ibm_values() method will return an integer vector instead of the factor levels. This is needed e.g. for group and replicate mappers, since INLA::f() doesn't accept factor values. Default: FALSE, which works for the main input mappers. The default mapper constructions will set it the required setting.

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

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 fmesher object to map, supported by fmesher::fm_basis⁠(mesh, input)⁠ and fmesher::fm_dof(mesh).

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

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 bm_harmonics, specifies the maximum cos/sin order. (Default 1)

scaling

For bm_harmonics, specifies an optional vector of scaling factors of length intercept + order, or a common single scalar.

intercept

logical; For bm_harmonics, if TRUE, the first basis function is a constant. (Default TRUE)

interval

numeric length-2 vector specifying a domain interval. Default c(0, 1).

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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 bm_index

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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 bru_mapper.

...

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

bm_list object from which to extract element(s)

...

Objects to be combined.

i

indices specifying elements to extract

mapper

A mapper S3 object, inheriting from bru_mapper.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

Value

A bm_list object

Methods (by generic)

Functions

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 bm_aggregate and bm_logsumexp, specifies if the blockwise sums should be normalised by the blockwise weight sums or not:

  • FALSE: (default) Straight weighted sum, no rescaling.

  • TRUE: Divide by the sum of the weight values within each block. This is useful for integration averages, when the given weights are plain integration weights. If the weights are NULL or all ones, this is the same as dividing by the number of entries in each block.

n_block

Predetermined number of output blocks. If NULL, overrides the maximum block index in the inputs. The priority order is input$n_block, the mapper definition n_block, then max(input$block).

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

log

logical; control log output. Default TRUE, see the ibm_eval() details for logsumexp mappers.

sub_lin

Internal, optional pre-computed sub-mapper information

Methods (by generic)

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 lower.tail and log.p arguments, like stats::qnorm().

pfun

A CDF, supporting lower.tail and log.p arguments, like stats::pnorm(). Only needed and used when xor(mapper[["inverse"]], reverse) is TRUE in a method call. Default NULL

dfun

A pdf, supporting log argument, like stats::dnorm(). If NULL (default), uses finite differences on qfun or pfun instead.

dqfun

A function evaluating the reciprocal of the derivative of qfun. If NULL (default), uses dfun(qfun(...),...) or finite differences on qfun or pfun instead.

...

Arguments passed on to other methods

inverse

logical; If FALSE (default), bm_marginal() defines a mapping from standard Normal to a specified distribution. If TRUE, it defines a mapping from the specified distribution to a standard Normal.

mapper

A mapper S3 object, inheriting from bru_mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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 bm_marginal evaluation. Default FALSE. When TRUE, reverses the direction of the mapping, see details for marginal mappers.

Methods (by generic)

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 bru_mapper.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

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 bru_mapper, typically fm_mesh_2d or fm_mesh_1d

B

a square or tall basis conversion matrix

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

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 bru_mapper objects

mapper

A mapper S3 object, inheriting from bru_mapper.

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

multi

logical; If TRUE (or positive), recurse one level into sub-mappers

...

Arguments passed on to other methods

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

sub_A

Internal; precomputed Jacobian matrices.

jacobian

For ibm_eval() methods, an optional pre-computed Jacobian, typically supplied by internal methods that already have the Jacobian.

pre_A

[Deprecated] in favour of jacobian.

x

object from which to extract element(s)

i

indices specifying element(s) to extract

drop

logical; For ⁠[.bm_multi⁠, whether to extract an individual mapper when i identifies a single element. If FALSE, a list of sub-mappers is returned (suitable e.g. for creating a new bm_multi object). Default: TRUE

value

a character vector of up to the same length as the number of mappers in the multi-mapper x

Value

Methods (by generic)

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 bru_mapper objects

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

n_state

integer giving the length of the state vector for mappers that have state dependent output size.

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

Methods (by generic)

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 bm_sum() of mappers.

interleaved

logical; if TRUE, the repeated mapping columns are interleaved; ⁠(x1[1], x2[1], ..., x1[2], x2[2], ...)⁠. If FALSE (default), the repeated mapping columns are contiguous, ⁠(x1[1], x1[2], ..., x2[1], x2[2], ...)⁠, and the Jacobian is a cbind() of the Jacobians of the repeated mappers.

If n_rep is a vector, interleaved should either be a single logical, or a vector of the same length. Each element applies to the corresponding n_rep repetition specification.

...

Arguments passed on to other methods

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

multi

logical; If TRUE (or positive), recurse one level into sub-mappers

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)

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 TRUE, the state vector indexing is interleaved. Default is FALSE, for blockwise indexing.

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

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 bm_scale(), an optional bru_mapper to be scaled. For ⁠ibm_*⁠ methods, a bm_scale mapper object.

...

Arguments passed on to other methods

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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)

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 bru_mapper.

...

Arguments passed on to other methods

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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)

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 bru_mapper objects.

single_input

logical. If TRUE, the input is passed to all sub-mappers. Otherwise, the input should be a list, data.frame, or matrix. If the mappers list has named entries, the input can reference their corresponding sub-mapper using its name.

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

multi

logical; If TRUE (or positive), recurse one level into sub-mappers

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

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 ⁠[.bm_sum⁠, whether to extract an individual mapper when i identifies a single element. If FALSE, a list of sub-mappers is returned (suitable e.g. for creating a new bm_sum object). Default: TRUE

value

a character vector of the same length as the number of sub-mappers in the mapper

Value

A bm_sum object.

Methods (by generic)

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 bm_taylor, an offset vector giving the value of the linearisation at state0. May be NULL, interpreted as an all-zero vector of length determined by a non-null Jacobian.

jacobian

For bm_taylor(), the Jacobian matrix, evaluated at state0, or, a named list of such matrices. May be NULL or an empty list, for a constant mapping.

state0

For bm_taylor, the reference state for the linearisation, or a list of such states matching the jacobian list. NULL is interpreted as 0.

values_mapper

mapper object to be used for ibm_n and ibm_values for inla_f=TRUE (experimental, currently unused)

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

multi

logical; If TRUE (or positive), recurse one level into sub-mappers

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

Methods (by generic)

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.

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 formula-like specification of latent components. Also used to define a default linear additive predictor. See bru_comp() for details.

...

Obervation models, each constructed by a calling bru_obs(), or named parameters that can be passed to a single bru_obs() call. Note that all the arguments will be evaluated before calling bru_obs() in order to detect if they are like objects. This means that special arguments that need to be evaluated in the context of response_data or data (such as Ntrials) may will only work that way in direct calls to bru_obs().

options

A bru_options options object or a list of options passed on to bru_options()

.envir

Environment for component evaluation (for when a non-formula specification is used)

result

A previous estimation object of class bru

x

A bru object to be printed

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)

Functions

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 as.bru_options()

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

main takes an R expression that evaluates to where the latent variables should be evaluated (coordinates, indices, continuous scalar (for rw2 etc)). Arguments starting with weights, group, replicate behave similarly to main, but for the corresponding features of INLA::f().

weights, weights_layer, weights_selector

Optional specification of effect scaling weights. Same syntax as for main.

model

Either one of "const" (same as "offset"), "factor_full", "factor_contrast", "linear", "fixed", or a model name or object accepted by INLA's f function. If set to NULL, then "linear" is used for vector inputs, and "fixed" for matrix input (converted internally to an iid model with fixed precision)

mapper

Information about how to do the mapping from the values evaluated in main, and to the latent variables. Auto-detects spde model objects in model and extracts the mesh object to use as the mapper, and auto-generates mappers for indexed models. (Default: NULL, for auto-determination)

main_layer, main_selector

The ⁠_layer⁠ input should evaluate to a numeric index or character name or vector of which layer/variable to extract from a covariate data object given in main. (Default: NULL if ⁠_selector⁠ is given. Otherwise the effect component name, if it exists in the covariate object, and otherwise the first column of the covariate data frame)

The ⁠_selector⁠ value should be a character name of a variable whose contents determines which layer to extract from a covariate for each data point. (Default: NULL)

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 Cmatrix or graph will use the matrix size. An error is given if it realises it can't figure it out by itself.

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 INLA::f() for model "seasonal" (TODO: check if this parameter is still fully handled)

nrow, ncol

Number of rows and columns for model types "rw2d", "rw2diid", and "matern2d". Default is NULL.

copy

character; label of other component that this component should be a copy of. If the fixed = FALSE, a scaling constant is estimated, via a hyperparameter. If fixed = TRUE, the component scaling is fixed, by default to 1; for fixed scaling, it's more efficient to express the scaling in the predictor expression instead of making a copy component.

group, group_mapper, group_layer, group_selector, ngroup

Optional specification of kronecker/group model indexing.

control.group

list of kronecker/group model parameters, currently passed directly on to INLA::f

replicate, replicate_mapper, replicate_layer, replicate_selector, nrep

Optional specification of indices for an independent replication model. Same syntax as for main

marginal

May specify a bm_marginal() mapper, that is applied before scaling by weights.

A.msk

[Deprecated] and has no effect.

.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:

Functions

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

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.

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

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

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 bru_mapper for the component, as

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 name_eval(), you need to use .data.[["myvar"]] to access it. Otherwise, it will try to use the other component effect as input, which is ill-defined.

.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 bru_input.bru_obs_list().

x

bru_comp_list object from which to extract a sub-list

i

indices specifying elements to extract

Methods (by class)

Methods (by generic)

Functions

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 bru_model object

lhood_expr

A predictor expression

data

Input data

data_extra

Additional data for the predictor

input

Precomputed component inputs from bru_input()

state

The state information, as a list of named vectors

comp_simple

Component evaluation information

  • For bru_comp: A bm_taylor object

  • For bru_obs: A bm_list object for the components in the likelihood

  • For bru_obs_list: A list of bm_list objects

effects
  • For bru_comp: Precomputed effect list for all components involved in the likelihood expression

pred0

Precomputed predictor for the given state

used

A bru_used() object for the predictor expression

allow_combine

logical; If TRUE, the predictor expression may involve several rows of the input data to influence the same row.

eps

The finite difference step size

n_pred

The length of the predictor expression. If not NULL, scalar predictor evaluations are expanded to vectors of length n_pred.

lhood

A bru_obs object

lhoods

A bru_obs_list object


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 bru() for a nonlinear predictor model

from, to

integer values for the range of iterations to plot. Default from = 1 (start from the first iteration) and to = NULL (end at the last iteration). Set from = 0 to include the initial linearisation point in the track plot.

type

[Experimental] character; "bru" (default) for iterative nonlinear inlabru convergence diagnostics plots, or "inla" for INLA optimiser trace plots.

Details

Requires the "dplyr", "ggplot2", "magrittr", and "patchwork" packages to be installed.

Value

A ggplot object with four panels of convergence diagnostics:

For multidimensional components, only the overall average, maximum, and minimum values are shown.

See Also

bru()

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 .name. in the evaluation. The input expression is evaluated with each non-NULL data object as envir, in order, until success. If there are no non-NULL data objects, the expression is evaluated in an empty environment, potentially falling back to enclosing environment variables.

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 is.na(values) is TRUE

layer, selector

Specifies what data column or columns from which to extract data, see bru_comp() for details.

batch_size

[Deprecated] due to improved algorithm. Size of nearest-neighbour calculation blocks, to limit the memory and computational complexity.

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)

Functions

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

[Experimental] 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

character or NULL; One of NULL, "all", "observed", and "missing". If NULL (default) or "all", gives the index vector for the full sub-model predictor. If "observed", gives the index vector for the observed part (response is not NA). If "missing", gives the index vector for the missing part (response is NA) of the model.

tag

character or integer; Either a character vector identifying the tags of one or more of the bru_obs() observation models, or an integer vector identifying models by their bru() specification order. If NULL (default) computes indices for all sub-models.

inla_f

logical; when TRUE, must result in values compatible with INLA::f(...) an specification and corresponding INLA::inla.stack(...) constructions.

used

A bru_used() object

Value

Methods (by class)

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 summary methods

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 TRUE, include more details of the component definitions. If FALSE, only show basic component definition information. Default: TRUE

x

An object to be printed

Methods (by class)


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 TRUE, compress the model by removing duplicated rows of effects, replacing the corresponding A-matrix columns with a single column containing the sum.

remove.unused

If TRUE, compress the model by removing rows of effects corresponding to all-zero columns in the A matrix (and removing those columns).

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 data.frame, tibble, sf, list, or ⁠Spatial*⁠ object of covariates and/or point locations.

lhoods

A bru_obs_list object

components

A bru_comp_list.

Value

Methods (by class)

Functions

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

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.

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 expression, formula, or parse information data.frame.

...

Arguments passed on recursively.

verbose

logical; if TRUE, print diagnostic parsing information.

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 bru_log object. If NULL, refers to the global inlabru log.

verbosity

integer value for limiting the highest verbosity level being returned.

...

further arguments passed to or from other methods.

timestamp

If TRUE, include the timestamp of each message. Default TRUE.

i

indices specifying elements to extract. If character, denotes the sequence between bookmark i and the next bookmark (or the end of the log if i is the last bookmark)

Value

bru_log A bru_log object, containing a character vector of log messages, and potentially a vector of bookmarks.

Methods (by generic)

Functions

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 0L pointing at the start of the log. If negative, denotes the point abs(offset) elements from tail of the log. When bookmark is non-NULL, the offset applies a shift (forwards or backwards) to the bookmark list.

x

A bru_log object. If NULL, the global inlabru log is used.

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

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 bru_log_message(), zero or more objects passed on to base::.makeMessage(). For bru_log_abort() and bru_log_warn(), passed on to rlang::abort() and rlang::warn().

domain

Domain for translations, passed on to base::.makeMessage()

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 NULL; local override for verbose output. If NULL, the global option bru_verbose or default value is used. If FALSE, no messages are printed. If TRUE, messages with verbosity \le 1 are printed. If numeric, messages with verbosity \le verbose are printed.

verbose_store

Same as verbose, but controlling what messages are stored in the global log object. Can be controlled via the bru_verbose_store with bru_options_set().

x

A bru_log object. If NULL, refers to the global inlabru log.

msg

character; passed to base::.makeMessage()

call

The calling environment.

.frame

The throwing context, for when .internal is TRUE

Value

bru_log_message returns invisible(x), where x is the updated bru_log object, or NULL.

Functions

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 data.frame with columns message, timestamp, and verbosity.

bookmarks

An optional integer vector of named bookmarks message in x.

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 bru_log object. If NULL, the global inlabru log is used.

bookmark

character; The label for a bookmark with a stored offset.

offset

integer; a position offset in the log, with 0L pointing at the start of the log. If negative, denotes the point abs(offset) elements from tail of the log. When bookmark is non-NULL, the offset applies a shift (forwards or backwards) to the bookmark list.

i

indices specifying elements to extract. If character, denotes the sequence between bookmark i and the next bookmark (or the end of the log if i is the last bookmark)

verbosity

integer value for limiting the highest verbosity level being returned.

Functions

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 bru_log object, or in some cases, and object that can be converted/extracted to a bru_log object. NULL denotes the global inlabru log object.

bookmark

character; The label for a bookmark with a stored offset.

offset

integer; a position offset in the log, with 0L pointing at the start of the log. If negative, denotes the point abs(offset) elements from tail of the log. When bookmark is non-NULL, the offset applies a shift (forwards or backwards) to the bookmark list.

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 bru_obs object

lin

Linearisation information

  • For .bru_obs, a bm_taylor object

  • For .bru_obs_list, a list of bm_taylor objects

idx

Output from bru_index.bru_model()

family_index

integer specifying the family sequence index of the observation model

lhoods

A bru_obs_list object


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 bru_mapper_define, a prototype mapper object, see Details.

new_class

If non-NULL, this is added at the front of the class definition

remove_class

If non-NULL, this class or classes is removed from the class definition before adding the new_class names. Default is "list".

Value

Functions

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 fm_mesh_1d object to use as a mapper

indexed

logical; If TRUE (default), the ibm_values() output will be the integer indexing sequence for the latent variables (needed for spde models). If FALSE, points representative of the basis centres are returned (useful for an interpolator for rw2 models and similar, for fmesher versions ⁠>= 0.3.0.9002⁠).

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

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 fm_mesh_2d object to use as a mapper

...

Arguments passed on to other methods

mapper

A mapper S3 object, inheriting from bru_mapper.

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 bru_mapper.

inla_f

logical; when TRUE for ibm_n() and ibm_values(), the result must be compatible with the INLA::f(...) and corresponding INLA::inla.stack(...) constructions. For ⁠ibm_{eval,jacobian,linear}⁠, the input interpretation may be different. Implementations do not normally need to do anything different, except for mappers of the type needed for hidden multicomponent models such as "bym2", which can be handled by bm_collect.

...

Arguments passed on to other methods

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

value

a character vector of the same length as the number of sub-mappers in the mapper

jacobian

For ibm_eval() methods, an optional pre-computed Jacobian, typically supplied by internal methods that already have the Jacobian.

Functions

See Also

bru_mapper for constructor methods, and bru_get_mapper for hooks to extract mappers from latent model object class objects.

bru_mapper, bru_get_mapper()

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 bru_obs() object, a bru_obs_list() object, or a list of one or more bru_obs() or bru_obs_list() objects, or a list of arguments for a call to bru_obs().

options

A bru_options options object or a list of options passed on to bru_options()

.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 bru_mapper.

input

Data input for the mapper.

state

A vector of latent state values for the mapping, of length ibm_n(mapper, inla_f = FALSE)

...

Arguments passed on to other methods

Functions


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 formula where the right hand side is a general R expression defines the predictor used in the model.

family

A string identifying a valid INLA::inla likelihood family. The default is gaussian with identity link. In addition to the likelihoods provided by inla (see names(INLA::inla.models()$likelihood)) inlabru supports fitting latent Gaussian Cox processes via family = "cp". As an alternative to bru(), the lgcp() function provides a convenient interface to fitting Cox processes.

data

Predictor expression-specific data, as a data.frame, tibble, or sf. Since ⁠2.12.0.9023⁠, deprecated support for SpatialPoints[DataFrame] objects.

response_data

Observation/response-specific data for models that need different size/format for inputs and response variables, as a data.frame, tibble, or sf. Since ⁠2.12.0.9023⁠, deprecated support for SpatialPoints[DataFrame] objects.

data_extra

object convertible with as.list() with additional variables to be made available in predictor evaluations. Variables with the same names as the data object will be ignored, unless accessed via .data_extra.[["name"]] or .data_extra.$name in the formula.

E

Exposure/effort parameter for family = 'poisson' passed on to INLA::inla. Special case if family is 'cp': rescale all integration weights by a scalar E. For sampler specific reweighting/effort, use a weight column in the samplers object instead, see fmesher::fm_int(). Default taken from options$E, normally 1.

Ntrials

A vector containing the number of trials for the 'binomial' likelihood. Default taken from options$Ntrials, normally 1.

weights

Fixed (optional) weights parameters of the likelihood, so the log-likelihood⁠[i]⁠ is changed into weights[i] * log_likelihood[i]. Default value is 1. WARNING: The normalizing constant for the likelihood is NOT recomputed, so ALL marginals (and the marginal likelihood) must be interpreted with great care.

For family = "cp", the weights are applied as sum(weights * eta) in the point location contribution part of the log-likelihood, where eta is the linear predictor, and do not affect the integration part of the likelihood. This can be used to implement approximative methods for point location uncertainty.

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 family="cp" and ⁠aggregate=⁠.

domain

Named list of domain definitions, see fmesher::fm_int().

samplers

Integration domain for family="cp" or subdomains for ⁠aggregate=⁠, see fmesher::fm_int().

ips

Integration points. Defaults to fmesher::fm_int(domain, samplers). If explicitly given, overrides domain and samplers.

used

Either NULL (default) or a bru_used() object. When, NULL, the information about what effects and latent vectors are made available to the predictor evaluation is defined by bru_used(formula), which will include all effects and latent vectors used by the predictor expression.

allow_combine

logical; If TRUE, the predictor expression may involve several rows of the input data to influence the same row. When NULL, defaults to FALSE, unless response_data is non-NULL, or data is a list, or the likelihood construction requires it.

aggregate

character ("none", "sum", "average", "logsumexp", or "logaverageexp", as defined by bm_aggregate(type = aggregate)) or an aggregation bru_mapper object (bm_aggregate() or bm_logsumexp()). Default NULL, interpreted as "none". [Experimental], available from version ⁠2.12.0.9013⁠.

aggregate_input

NULL or an optional input list to the mapper defined by non-NULL aggregate, overriding the default,

list(block = .data.[[".block"]],
     weights = .data.[["weight"]],
     n_block = bru_response_size(.response_data.))

[Experimental], available from version ⁠2.12.0.9013⁠.

control.family

A optional list of INLA::control.family options

tag

character; Name that can be used to identify the relevant parts of INLA predictor vector output, via bru_index().

options

A bru_options options object or a list of options passed on to bru_options()

.envir

The evaluation environment to use for special arguments (E, Ntrials, weights, and scale) if not found in response_data or data. Defaults to the calling environment.

include, exclude, include_latent

[Deprecated], use used instead.

mesh

[Deprecated] Ignored.

...

For bru_obs_list.bru_obs, one or more bru_obs objects

object

A list of bru_obs objects

x

bru_obs_list object from which to extract element(s)

i

indices specifying elements to extract

Value

A likelihood configuration which can be used to parameterise bru().

Methods (by generic)

Functions

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()

summary.bru_obs()

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 bru_obs or bru_obs_list type

control.family

list of INLA control.family options to override

Value

See Also

summary.bru_obs()


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 bru_options objects. Options specified later override the previous options.

x

An object to be converted to an bru_options object.

options

An bru_options object to be checked

ignore_null

Ignore missing or NULL options.

name

Either NULL, or single option name string, or character vector or list with option names, Default: NULL

include_default

logical; If TRUE, the default options are included together with the global override options. Default: TRUE

.reset

For bru_options_set, logical indicating if the global override options list should be emptied before setting the new option(s).

.envir

The environment in which to set the options. Default: parent.frame()

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

Valid options

For bru_options and bru_options_set, recognised options are:

bru_verbose

logical or numeric; if TRUE, log messages of verbosity \le 1 are printed by bru_log_message(). If numeric, log messages of verbosity \lebru_verbose are printed. For line search details, set bru_verbose=2 or 3. Default: 0, to not print any messages

bru_verbose_store

logical or numeric; if TRUE, log messages of verbosity \le 1 are stored by bru_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 of INLA::inla, bru() or lgcp(), 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 and int.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 and nsub2 if set. Default NULL.

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, with y=n, and predictor mean(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 to inla(), sometimes after altering according to the needs of the inlabru method. Warning: Due to how inlabru currently constructs the inla() call, the mean, prec, mean.intercept, and prec.intercept settings in control.fixed will have no effect. Until a more elegant alternative has been implemented, use explicit mean.linear and prec.linear specifications in each model="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)

See Also

like()

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 TRUE, multiple cores are allowed, and the INLA num.threads option is not checked or altered. If FALSE, forces num.threads="1:1". Default: NULL, checks if running in testthat or non-interactively, in which case sets multicore=FALSE, otherwise TRUE.

quietly

logical; if FALSE and multicore is FALSE, prints a message if the num.threads option isn't already "1.1" to alert the user to the change. Default: FALSE.

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 TRUE, prints diagnostic messages. Default FALSE

force

logical; If rgdal is unavailable and evolution status is less that 2L, return FALSE if force is FALSE. If force is TRUE, return TRUE if the package configuration is safe, potentially after forcing the evolution status to 2L. Default FALSE

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 bru, bru_obs or bru_obs_list object

keep

For bru_obs, a single logical or an integer vector; If TRUE, keep all the response data, if FALSE (default), set all of it to NA. An integer vector determines which elements to keep (for positive values) or to set as missing (negative values).

For bru and bru_obs_list, a logical scalar or vector, or a list, see Details.

...

Additional arguments passed on to the bru_obs method. Currently unused.

Details

For bru and bru_obs_list,

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 data.frame

probs

A numeric vector of probabilities with values in ⁠[0, 1]⁠, passed to stats::quantile

x

A data.frame of data columns that should be added to the summary data frame

cbind.only

If TRUE, only cbind the samples and return a matrix where each column is a sample

max_moment

integer, at least 2. Determines the largest moment order information to include in the output. If max_moment > 2, includes "skew" (skewness, E[(x-m)^3/s^3]), and if max_moment > 3, includes "ekurtosis" (excess kurtosis, E[(x-m)^4/s^4] - 3). Default 2. Note that the Monte Carlo variability of the ekurtois estimate may be large.

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 bru object

...

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 bru() for a nonlinear predictor model

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 qexp

x

Values to be transformed

...

Distribution parameters passed on to the qfun and pfun functions

tail.split.

For x-values larger than tail.split., upper quantile calculations are used internally, and for smaller values lower quantile calculations are used. This can avoid lack of accuracy in the distribution tails. If NULL, forward calculations split at 0, and inverse calculations use lower tails only, potentially losing accuracy in the upper tails.

pfun

A CDF function object, such as pexp

Value

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 NULL, auto-detect components to include all components in a predictor expression.

effect_exclude

character; components to specifically exclude from effect evaluation. When NULL, do not specifically exclude any components.

latent

character; components used as ⁠_latent⁠ or ⁠_eval()⁠. When NULL, auto-detect components.

labels

character; component labels passed on to bru_used_update()

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 parameters main, group, and replicate, taking values for where to evaluate the component effect that are different than those defined in the component definition itself (see bru_comp_eval()). If NULL, 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)

Methods (by generic)

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 formula, expression, or character

functions

logical; if TRUE, include function names

Value

If successful, a character vector, otherwise NULL

Methods (by class)

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 inla and obtained from a run of INLA::inla(), bru() or lgcp()

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 prediction of two latent model components.

prediction1

A prediction of the first component.

prediction2

A prediction of the second component.

samplers

An sf or SpatialPolygon object describing the area for which to compute the cumulative variance measure.

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 data layer to extract (as integer or character). May be a vector, specifying a separate layer for each where item.

selector

The name of a variable in where specifying the layer information.

Methods (by class)


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. inla_f. Normally unused.

component

A bru_mapper, bru_comp, or bm_list.

input

Pre-evaluated component input

state

Specification of one latent variable state:

  • evaluate_effect_single_state.bru_mapper: A vector of the latent component state.

  • ⁠evaluate_effect_single_state.*_list⁠: list of named state vectors.

label

Option label used for any warning messages, specifying the affected component.

Value

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 evaluate_state()

data

A list, data.frame, or Spatial*DataFrame, with coordinates and covariates needed to evaluate the predictor.

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 (NULL) returns a data.frame containing the sampled effects. In case of a formula the right hand side is used for evaluation.

format

character; determines the storage format of predictor output. Available options:

  • "auto" If the first evaluated result is a vector or single-column matrix, the "matrix" format is used, otherwise "list".

  • "matrix" A matrix where each column contains the evaluated predictor expression for a state.

  • "list" A list where each element contains the evaluated predictor expression for a state.

used

A bru_used() object, or NULL (default)

n_pred

integer. If provided, scalar predictor results are expanded to vectors of length n_pred.

...

Additional arguments passed on to inla.posterior.sample

result

A bru object from bru() or lgcp()

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 parameter). If result is NULL, all-zero vectors are returned for each component.

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 TRUE, return hyperparameter properties on the internal scale. Currently ignored when property="sample". Default is FALSE.

Details


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 evaluate_state()

data

A list, data.frame, or Spatial*DataFrame, with coordinates and covariates needed to evaluate the model.

data_extra

Additional data for the predictor evaluation. Variables with the same name as in data will be ignored, unless accessed via .data_extra.[["name"]] or .data_extra.$name.

effects

A list where each element is list of named evaluated effects, each computed by evaluate_effect_single_state.bru_comp_list()

predictor

Either a formula or expression

used

A bru_used() object, or NULL (default)

format

character; determines the storage format of the output. Available options:

  • "auto" If the first evaluated result is a vector or single-column matrix, the "matrix" format is used, otherwise "list".

  • "matrix" A matrix where each column contains the evaluated predictor expression for a state.

  • "list" A list where each column contains the evaluated predictor expression for a state.

Default: "auto"

n_pred

integer. If provided, scalar predictor results are expanded to vectors of length n_pred.

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 expand

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 inla result object

property

character; "mean", "sd", "mode", or some other column identifier for inla result ⁠$summary.fixed⁠, ⁠$summary.random$label⁠, and ⁠$summary.hyperpar⁠, or "joint_mode". For "joint_mode", the joint latent mode is extracted, and the joint hyperparameter mode, in the internal scale. For "predictor_sd" the posterior standard deviations of the linear predictor are returned.

internal_hyperpar

logical; if TRUE, use internal scale for hyperparamter properties. Default is FALSE, except when property is "joint_mode" which forces internal_hyperpar=TRUE.

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 TRUE, includes more details of the component definitions. When FALSE, only show basic component definition information. Default TRUE.

...

Passed on to other summary methods.

label.override

character; If not NULL, use this label instead of the object's label.

type

character; if non-NULL, added to the output'; label = type(input).

object

Object to be summarised.

Author(s)

Fabian E. Bachl bachlfab@gmail.com

Finn Lindgren finn.lindgren@gmail.com

See Also

bru_input(), bru_comp()


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 initial=prefix.

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 base::paste().

labels

logical; if TRUE, include mapper names or numerical indices. Default TRUE

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 bru object obtained by calling bru().

...

additional, unused arguments.

newdata

A data.frame or SpatialPointsDataFrame of covariates needed for sampling.

formula

A formula where the right hand side defines an R expression to evaluate for each generated sample. If NULL, the latent and hyperparameter states are returned as named list elements. See Details for more information.

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 INLA::inla.posterior.sample

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 NULL or a bru_used() object. Default, NULL, uses auto-detection of used variables in the formula.

data

[Deprecated] Use newdata instead.

include, exclude

[Deprecated] If auto-detection of used variables fails, use used instead.

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

predict.bru

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 aes. These are passed on to geom_tile.

...

Arguments passed on to geom_tile.

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 geom_spatraster.

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 gg.SpatialPixelsDataFrame().

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 SpatialLines or SpatialLinesDataFrame object.

mapping

Aesthetic mappings created by ggplot2::aes or ggplot2::aes_ used to update the default mapping. The default mapping is

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 CRS object defining the coordinate system to project the data to before plotting.

...

Arguments passed on to ggplot2::geom_segment.

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 sp::SpatialPixels object.

...

Arguments passed on to geom_tile.

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 aes used to update the default mapping. The default mapping is

ggplot2::aes(
  x = .data[[sp::coordnames(data)[1]]],
  y = .data[[sp::coordnames(data)[2]]],
  fill = .data[[names(data)[[1]]]]
)
crs

A sp::CRS object defining the coordinate system to project the data to before plotting.

mask

A sp::SpatialPolygons object defining the region that is plotted.

...

Arguments passed on to geom_tile.

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 aes used to update the default mapping. The default mapping is

ggplot2::aes(
  x = .data[[sp::coordnames(data)[1]]],
  y = .data[[sp::coordnames(data)[2]]]
)
crs

A sp::CRS object defining the coordinate system to project the data to before plotting.

...

Arguments passed on to geom_point.

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 SpatialPolygons or SpatialPolygonsDataFrame object.

mapping

Aesthetic mappings created by aes used to update the default mapping.

crs

A CRS object defining the coordinate system to project the data to before plotting.

...

Arguments passed on to geom_sf. Unless specified by the user, the argument alpha = 0.2 (alpha level for polygon filling) is added.

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 predict.bru() call.

mapping

a set of aesthetic mappings created by aes. These are passed on to geom_line(). If "fill" is present, it is passed to geom_ribbon().

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 q and followed by a numerical value. inla()-style numeric+"quant" names are converted to inlabru style before matching.

alpha

The ribbons numeric alpha (transparency) level in ⁠[0,1]⁠.

bar

If TRUE plot boxplot-style summary for each variable.

...

Arguments passed on to geom_line.

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 gg.bru_prediction().

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 aes. These are passed on to geom_point.

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 geom_point.

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 fm_mesh_2d object.

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 colour is also recognised.

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 fmesher::fm_transform() defining the coordinate system to project the mesh to before plotting.

mask

A SpatialPolygon or sf polygon defining the region that is plotted.

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 matrix object.

mapping

a set of aesthetic mappings created by aes. These are passed on to geom_tile.

...

Arguments passed on to geom_tile.

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 sf object.

mapping

Default mapping is ggplot2::aes(geometry = ...), where the geometry name is obtained from attr(data, "sf_column"). This is merged with the user supplied mapping.

...

Arguments passed on to geom_sf or geom_tile.

geom

Either "sf" (default) or "tile". For "tile", uses geom_tile(..., stat = "sf_coordinates"), intended for converting point data to grid tiles with the fill aesthetic, which is by default set to the first data column.

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 plot_rgl.fm_mesh_2d()

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)

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

gorillas_sf


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 function lgcp 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() or

gorillas_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 elements count, exposure, and geometry, 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 with MULTIPOLYGON objects defining the individual plot boundaries and an all-ones weight column.

nests

An sf giving the locations of each detected nests, group ("minor" or "major"), season ("dry" or "rainy"), and date (in Date format).

Functions

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 bru_obs()

inputs

Optional pre-computed list of per-likelihood component evaluations, from bru_input.bru_obs_list().

initial

A previous bru result or a list of named latent variable initial states (missing elements are set to zero), to be used as starting point, or NULL. If non-null, overrides options$bru_initial

options

A bru_options object.

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 INLA::inla.spde.make.A

n.repl

The maximum replicate index, in the sense used in INLA::inla.spde.make.A().

weights

Optional scaling weights to be applied row-wise to the resulting matrix.

Functions

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 formula-like specification of latent components. Also used to define a default linear additive predictor. See bru_comp() for details.

data

Predictor expression-specific data, as a data.frame, tibble, or sf. Since ⁠2.12.0.9023⁠, deprecated support for SpatialPoints[DataFrame] objects.

domain, samplers, ips

Arguments used for family="cp" and ⁠aggregate=⁠.

domain

Named list of domain definitions, see fmesher::fm_int().

samplers

Integration domain for family="cp" or subdomains for ⁠aggregate=⁠, see fmesher::fm_int().

ips

Integration points. Defaults to fmesher::fm_int(domain, samplers). If explicitly given, overrides domain and samplers.

formula

a formula where the right hand side is a general R expression defines the predictor used in the model.

...

Further arguments passed on to bru_obs(). In particular, optional E, a single numeric used rescale all integration weights by a fixed factor.

options

A bru_options options object or a list of options passed on to bru_options()

.envir

The evaluation environment to use for special arguments (E, Ntrials, weights, and scale) if not found in response_data or data. Defaults to the calling environment.

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 x

envir

environment for exit handlers

tolerances

numeric vector of length 3; ⁠[lowtol, midtol, hitol]⁠

.reset

For local_bru_options_set, logical indicating if the global override options list should be emptied before setting the new option(s).

multicore

logical; if TRUE, multiple cores are allowed, and the INLA num.threads option is not checked or altered. Default: FALSE, multicore not allowed (used for examples and unit tests).

quietly

logical; if TRUE, prints diagnostic messages. A message is always printed if the INLA num.threads option is altered, regardless of the quietly argument. Default: TRUE.

Value

local_bru_options_set() returns a copy of the global override options (not including the defaults), invisibly.

Functions

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 fm_manifold(mesh), or a full fm_mesh_2d or fm_mesh_1d object.

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 inla.spde.result(...)$summary.log.range.nominal[[1]][c("mean","sd")]

log.variance

Either NULL, a scalar, or vector of the same type as for log.range. When NULL, the correlations are calculated instead of the covariances.

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 manifold "S1", give the length of the cyclic interval

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 quantile credible region

median

The function for for the approximate median parameters quantile

upper

An approximate upper bound for the quantile credible region

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

mexdolphin_sf


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 a inlabru model fitted to the actual survey data. Note that the simulated data do not have any associated size information.

Functions

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

[Deprecated] 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 ggplot objects.

plotlist

A list of ggplot objects - an alternative to the comma-separated argument above.

cols

Number of columns of plots on the page.

layout

A matrix specifying the layout. If present, cols is ignored. If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE), then plot 1 will go in the upper left, 2 will go in the upper right, and 3 will go all the way across the bottom.

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 include parameter; Default: NULL (do not remove any components from the inclusion list)


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 bru() model.

...

Options passed on to other methods.

result

an inla or bru result object

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 TRUE, add to an existing plot

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 gg.prediction().

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 SpatialPointsDataFrame defining the points that are to be sampled by the plot sample.

boundary

A SpatialPolygonsDataFrame defining the survey boundary within which the points occur.

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 columns

x

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 SpatialPolygonsDataFrame object containing the plots that were sampled.

dets

A SpatialPointsDataFrame object containing the locations of the points within the plots.

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

An object obtained by calling bru() or lgcp().

newdata

A data.frame or SpatialPointsDataFrame of covariates needed for the prediction.

formula

A formula where the right hand side defines an R expression to evaluate for each generated sample. If NULL, the latent and hyperparameter states are returned as named list elements. See Details for more information.

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 inla.posterior.sample

probs

A numeric vector of probabilities with values in ⁠[0, 1]⁠, passed to stats::quantile

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 NULL or a bru_used() object. Default, NULL, uses auto-detection of used variables in the formula.

drop

logical; If keep=FALSE, newdata is a Spatial*DataFrame, and the prediciton summary has the same number of rows as newdata, then the output is a Spatial*DataFrame object. Default FALSE.

...

Additional arguments passed on to inla.posterior.sample()

data

[Deprecated] Use newdata instead.

include, exclude

[Deprecated] If auto-detection of used variables fails, use used instead.

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 Inf, to traverse the entire mapper tree.

verbose

logical; If TRUE, includes more details of the component definitions. When FALSE, only show basic component definition information. Default TRUE.

label.override

character; If not NULL, use this label instead of the object's label.

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

fm_cprod, fm_crs, fm_int, fm_pixels, fm_sp2segment


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 fm_mesh_1d meshes, loglambda should be given as mesh$m basis function weights rather than the values at the mesh$n vertices) A single scalar is expanded to a vector of the appropriate length. If a matrix is supplied, one process sample for each column is produced.

strategy

Only relevant for 2D meshes. One of 'triangulated', 'rectangle', 'sliced-spherical', 'spherical'. The 'rectangle' method is only valid for CRS-less flat 2D meshes. If NULL or 'auto', the the likely fastest method is chosen; 'rectangle' for flat 2D meshes with no CRS, 'sliced-spherical' for CRS 'longlat' meshes, and 'triangulated' for all other meshes.

R

Numerical value only applicable to spherical and geographical meshes. It is interpreted as R is the equivalent Earth radius, in km, used to scale the lambda intensity. For CRS enabled meshes, the default is 6371. For CRS-less spherical meshes, the default is 1.

samplers

A SpatialPolygonsDataFrame or fm_mesh_2d object. Simulated points that fall outside these polygons are discarded.

ignore.CRS

logical; if TRUE, ignore any CRS information in the mesh. Default FALSE. This affects R and the permitted values for strategy.

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.

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 locations

mesh:

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 data that hold the start points of the lines

end.cols

Character array pointing out the columns of data that hold the end points of the lines

crs

Coordinate reference system of the original data

to.crs

Coordinate reference system for the output.

format

Format of the output object. Either "sp" (default) or "sf"

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 SpatialPoints[DataFrame] object describing the point pattern.

samplers

A SpatialPolygons[DataFrame] object describing the observation window.

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 inla.

name

Character stating the name of the SPDE effect, see names(result$summary.random).

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 SpatialLines/sf ouput.

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

An object obtained from a bru() or lgcp() call

verbose

logical; If TRUE, include more details of the component definitions. If FALSE, only show basic component definition information. Default: FALSE

...

arguments passed on to component summary functions, see summary.bru_comp().

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 TRUE, include more details of the component definitions. If FALSE, only show basic component definition information. Default: TRUE

...

Arguments passed on to other summary methods

x

Object to be printed

See Also

bru_obs()

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 TRUE, include explanatory text, Default: TRUE

include_global

logical; If TRUE, include global override options

include_default

logical; If TRUE, include default options

...

Further parameters, currently ignored

x

A summary_bru_options object to be printed

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 locations x and size size

df.size:

IGNORE THIS

df.intensity:

A data.frame with Poisson process intensity d.lambda at locations x

df.rate:

A data.frame the locations x and associated rate 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 and z measurements

mesh

An fm_mesh_2d object

boundary

An sf polygon denting the region of interest

pred_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()
}