) but adds additional modelling abilities and
10 | #' simplified syntax for (in particular) spatial models.
11 | #' Tutorials and more information can be found at
12 | #' and .
13 | #' The iterative method used for non-linear predictors is documented in the
14 | #' `method` vignette.
15 | #'
16 | #' The main function for inference using inlabru is [bru()].
17 | #' The general model specification details is documented in [bru_comp()]
18 | #' and [bru_obs()].
19 | #' Posterior quantities beyond the basic summaries can be calculated with
20 | #' a `predict()` method, documented in [predict.bru()].
21 | #' For point process inference [lgcp()] can be used as a shortcut to
22 | #' `bru(..., bru_obs(model="cp", ...))`.
23 | #'
24 | #' The package comes with multiple real world data sets, namely [gorillas],
25 | #' [gorillas_sf], [mexdolphin_sf]. Plotting these data
26 | #' sets is straight forward using inlabru's extensions
27 | #' to `ggplot2`, e.g. the [gg()] function. For educational purposes some
28 | #' simulated data sets are available as well, e.g. [Poisson1_1D],
29 | #' [Poisson2_1D], [Poisson2_1D] and [toygroups].
30 | #'
31 | #' @aliases inlabru
32 | #' @import stats
33 | #' @import methods
34 | #' @importFrom Matrix diag
35 | #' @import fmesher
36 | #' @importFrom glue glue
37 | #' @importFrom glue glue_data
38 | #' @importFrom glue glue_collapse
39 | #' @author Fabian E. Bachl \email{bachlfab@@gmail.com}
40 | #' and Finn Lindgren \email{finn.lindgren@@gmail.com}
41 | "_PACKAGE"
42 |
43 | ## usethis namespace: start
44 | #' @importFrom lifecycle deprecated
45 | ## usethis namespace: end
46 | NULL
47 |
--------------------------------------------------------------------------------
/man/bru_used_vars.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/used.R
3 | \name{bru_used_vars}
4 | \alias{bru_used_vars}
5 | \alias{bru_used_vars.character}
6 | \alias{bru_used_vars.expression}
7 | \alias{bru_used_vars.quosure}
8 | \alias{bru_used_vars.formula}
9 | \title{Extract basic variable names from expression}
10 | \usage{
11 | bru_used_vars(x, functions = FALSE)
12 |
13 | \method{bru_used_vars}{character}(x, functions = FALSE)
14 |
15 | \method{bru_used_vars}{expression}(x, functions = FALSE)
16 |
17 | \method{bru_used_vars}{quosure}(x, functions = FALSE)
18 |
19 | \method{bru_used_vars}{formula}(x, functions = FALSE)
20 | }
21 | \arguments{
22 | \item{x}{A \code{formula}, \code{expression}, or \code{character}}
23 |
24 | \item{functions}{logical; if TRUE, include function names}
25 | }
26 | \value{
27 | If successful, a character vector, otherwise \code{NULL}
28 | }
29 | \description{
30 | Extracts the variable names from an R expression by pre- and post-processing
31 | around \code{\link[=all.vars]{all.vars()}}.
32 | First replaces \code{$} with \code{[[} indexing, so that internal column/variable names
33 | are ignored, then calls \code{all.vars()}.
34 | }
35 | \section{Methods (by class)}{
36 | \itemize{
37 | \item \code{bru_used_vars(formula)}: Only the right-hand side is used.
38 |
39 | }}
40 | \examples{
41 | bru_used_vars(~.)
42 | bru_used_vars(~ a + b + c_latent + d_eval())
43 | bru_used_vars(expression(a + b + c_latent + d_eval()))
44 |
45 | bru_used_vars(~., functions = TRUE)
46 | bru_used_vars(~ a + b + c_latent + d_eval(), functions = TRUE)
47 | bru_used_vars(expression(a + b + c_latent + d_eval()), functions = TRUE)
48 |
49 | bru_used_vars(a ~ b)
50 | bru_used_vars(expression(a ~ b))
51 |
52 | }
53 | \seealso{
54 | Other bru_used:
55 | \code{\link{bru_used}()},
56 | \code{\link{bru_used_update}()},
57 | \code{\link{new_bru_used}()}
58 | }
59 | \concept{bru_used}
60 | \keyword{internal}
61 |
--------------------------------------------------------------------------------
/man/bm_matrix.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/mappers.R
3 | \name{bm_matrix}
4 | \alias{bm_matrix}
5 | \alias{bru_mapper_matrix}
6 | \title{Mapper for matrix multiplication}
7 | \usage{
8 | bm_matrix(labels)
9 |
10 | bru_mapper_matrix(...)
11 | }
12 | \arguments{
13 | \item{labels}{Column labels for matrix mappings; Can be factor, character, or
14 | a single integer specifying the number of columns for integer column
15 | indexing.}
16 |
17 | \item{\dots}{Arguments passed on to \code{\link[=bm_matrix]{bm_matrix()}}}
18 | }
19 | \description{
20 | Create a matrix mapper, for a given number of columns
21 | }
22 | \examples{
23 | m <- bm_matrix(labels = c("a", "b"))
24 | ibm_values(m)
25 | ibm_eval2(m, input = matrix(1:6, 3, 2), state = 2:3)
26 |
27 | m <- bm_matrix(labels = 2L)
28 | ibm_values(m)
29 | ibm_eval2(m, input = matrix(1:6, 3, 2), state = 2:3)
30 |
31 | }
32 | \seealso{
33 | \link{bru_mapper}, \link{bru_mapper_generics}
34 |
35 | Other mappers:
36 | \code{\link{bm_aggregate}()},
37 | \code{\link{bm_collect}()},
38 | \code{\link{bm_const}()},
39 | \code{\link{bm_factor}()},
40 | \code{\link{bm_fm_mesh_1d}},
41 | \code{\link{bm_fmesher}()},
42 | \code{\link{bm_harmonics}()},
43 | \code{\link{bm_index}()},
44 | \code{\link{bm_linear}()},
45 | \code{\link{bm_logitaverage}()},
46 | \code{\link{bm_logsumexp}()},
47 | \code{\link{bm_marginal}()},
48 | \code{\link{bm_multi}()},
49 | \code{\link{bm_pipe}()},
50 | \code{\link{bm_reparam}()},
51 | \code{\link{bm_repeat}()},
52 | \code{\link{bm_scale}()},
53 | \code{\link{bm_shift}()},
54 | \code{\link{bm_sum}()},
55 | \code{\link{bm_taylor}()},
56 | \code{\link{bru_get_mapper}()},
57 | \code{\link{bru_mapper}()}
58 |
59 | Other specific \link{bm_matrix} method implementations:
60 | \code{\link{ibm_jacobian}()},
61 | \code{\link{ibm_n}()},
62 | \code{\link{ibm_values}()}
63 | }
64 | \concept{mappers}
65 | \concept{specific \link{bm_matrix} method implementations}
66 |
--------------------------------------------------------------------------------
/vignettes/articles.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Articles list"
3 | output: rmarkdown::html_vignette
4 | vignette: >
5 | %\VignetteIndexEntry{Articles list}
6 | %\VignetteEngine{knitr::rmarkdown}
7 | %\VignetteEncoding{UTF-8}
8 | ---
9 |
10 | ```{r, include = FALSE}
11 | knitr::opts_chunk$set(
12 | collapse = TRUE,
13 | comment = "#>"
14 | )
15 | ```
16 |
17 | ```{r setup, echo=FALSE,include=FALSE}
18 | ```
19 |
20 | ## Package vignettes
21 |
22 | These package vignettes are available in the R package and on
23 | [`https://inlabru-org.github.io/inlabru/`](https://inlabru-org.github.io/inlabru/)
24 |
25 | ```{r, echo=FALSE,results="asis"}
26 | files <- list.files(".", "\\.Rmd$")
27 | for (file in files) {
28 | lines <- readLines(file, n = 10)
29 | title_idx <- grep("^title: ", lines)
30 | if (length(title_idx) > 0) {
31 | title <- sub("^title: ", "", lines[title_idx[1]])
32 | title <- sub('^"', "", title)
33 | title <- sub('"$', "", title)
34 | cat("* [",
35 | title,
36 | "](https://inlabru-org.github.io/inlabru/articles/",
37 | sub("\\.Rmd", ".html", file),
38 | ")\n",
39 | sep = ""
40 | )
41 | }
42 | }
43 | ```
44 |
45 | ## Package examples
46 |
47 | These potentially long running examples/tutorials are available on
48 | [`https://inlabru-org.github.io/inlabru/`](https://inlabru-org.github.io/inlabru/)
49 |
50 | ```{r, echo=FALSE,results="asis"}
51 | files <- list.files("articles", "\\.Rmd$")
52 | for (file in file.path("articles", files)) {
53 | lines <- readLines(file, n = 10)
54 | title_idx <- grep("^title: ", lines)
55 | if (length(title_idx) > 0) {
56 | title <- sub("^title: ", "", lines[title_idx[1]])
57 | title <- sub('^"', "", title)
58 | title <- sub('"$', "", title)
59 | cat("* [",
60 | title,
61 | "](https://inlabru-org.github.io/inlabru/articles/",
62 | sub("\\.Rmd", ".html", basename(file)),
63 | ")\n",
64 | sep = ""
65 | )
66 | }
67 | }
68 | ```
69 |
70 |
--------------------------------------------------------------------------------
/man/as_bru_comp.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/bru_conversion.R
3 | \name{as_bru_comp}
4 | \alias{as_bru_comp}
5 | \alias{as_bru_comp_list}
6 | \alias{as_bru_comp.bru_comp}
7 | \alias{as_bru_comp_list.bru_comp_list}
8 | \alias{as_bru_comp_list.bru_comp}
9 | \alias{as_bru_comp_list.bru}
10 | \alias{as_bru_comp_list.bru_info}
11 | \alias{as_bru_comp_list.bru_model}
12 | \alias{as_bru_comp_list.list}
13 | \alias{as_bru_comp_list.formula}
14 | \title{Conversion methods for \code{bru_comp} and \code{bru_comp_list} objects}
15 | \usage{
16 | as_bru_comp(x, ...)
17 |
18 | as_bru_comp_list(x, ...)
19 |
20 | \method{as_bru_comp}{bru_comp}(x, ...)
21 |
22 | \method{as_bru_comp_list}{bru_comp_list}(x, ...)
23 |
24 | \method{as_bru_comp_list}{bru_comp}(x, ...)
25 |
26 | \method{as_bru_comp_list}{bru}(x, ...)
27 |
28 | \method{as_bru_comp_list}{bru_info}(x, ...)
29 |
30 | \method{as_bru_comp_list}{bru_model}(x, ...)
31 |
32 | \method{as_bru_comp_list}{list}(x, ...)
33 |
34 | \method{as_bru_comp_list}{formula}(x, ...)
35 | }
36 | \arguments{
37 | \item{x}{An object to convert to \link{bru_comp} or \link{bru_comp_list}}
38 |
39 | \item{\dots}{Additional arguments passed on to \code{\link[=bru_comp_list]{bru_comp_list()}}.}
40 | }
41 | \value{
42 | An object of class \link{bru_comp_list}.
43 | }
44 | \description{
45 | Methods for converting to \code{bru_comp} and \code{bru_comp_list}
46 | objects.
47 | }
48 | \section{Functions}{
49 | \itemize{
50 | \item \code{as_bru_comp_list(bru)}: Extract the component list from a \code{\link[=bru]{bru()}} object.
51 |
52 | \item \code{as_bru_comp_list(bru_info)}: Extract the component list from a \code{\link[=bru_info]{bru_info()}}
53 | object.
54 |
55 | \item \code{as_bru_comp_list(bru_model)}: Extract the component list from a \code{\link[=bru_model]{bru_model()}}
56 | object.
57 |
58 | }}
59 | \seealso{
60 | \code{\link[=as_bru_obs]{as_bru_obs()}}, \code{\link[=as_bru_obs_list]{as_bru_obs_list()}}
61 | }
62 |
--------------------------------------------------------------------------------
/man/spoly.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/bru_sp.R
3 | \name{spoly}
4 | \alias{spoly}
5 | \title{Convert a data.frame of boundary points into a SpatialPolgonsDataFrame}
6 | \usage{
7 | spoly(
8 | data,
9 | cols = colnames(data)[1:2],
10 | crs = fm_crs(),
11 | to.crs = NULL,
12 | format = c("sp", "sf")
13 | )
14 | }
15 | \arguments{
16 | \item{data}{A data.frame of points describing the boundary of the polygon
17 | (unique points, no holes)}
18 |
19 | \item{cols}{Column names of the x and y coordinates within the data}
20 |
21 | \item{crs}{Coordinate reference system of the points}
22 |
23 | \item{to.crs}{Coordinate reference system for the \code{SpatialLines}/\code{sf} ouput.}
24 |
25 | \item{format}{Format of the output object. Either "sp" (default) or "sf"}
26 | }
27 | \value{
28 | \code{sp::SpatialPolygonsDataFrame} or \link[sf:sf]{sf::sf}
29 | }
30 | \description{
31 | A polygon can be described as a sequence of points defining the polygon's
32 | boundary. When given such a sequence (anti clockwise!) this function creates
33 | a \code{SpatialPolygonsDataFrame} or \code{sf} holding the polygon decribed. By
34 | default, the first two columns of \code{data} are assumed to define the x and y
35 | coordinates of the points. This behaviour can be changed using the \code{cols}
36 | parameter, which points out the names of the columns holding the coordinates.
37 | The coordinate reference system of the resulting spatial polygon can be set
38 | via the \code{crs} parameter. Posterior conversion to a different CRS is supported
39 | using the \code{to.crs} parameter.
40 | }
41 | \examples{
42 | \donttest{
43 | # Create data frame of boundary points (anti clockwise!)
44 | pts <- data.frame(
45 | x = c(1, 2, 1.7, 1.3),
46 | y = c(1, 1, 2, 2)
47 | )
48 |
49 | # Convert to sf
50 | pol <- spoly(pts, format = "sf")
51 |
52 | if (require(ggplot2, quietly = TRUE)) {
53 | # Plot it!
54 | ggplot() +
55 | gg(pol)
56 | }
57 | }
58 |
59 | }
60 | \keyword{internal}
61 |
--------------------------------------------------------------------------------
/man/toygroups.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/data.toygroups.R
3 | \docType{data}
4 | \name{toygroups}
5 | \alias{toygroups}
6 | \title{Simulated 1D animal group locations and group sizes}
7 | \format{
8 | The data are a list that contains these elements:
9 | \describe{
10 | \item{\code{groups}:}{ A \code{data.frame} of group locations \code{x} and size \code{size}}
11 | \item{\code{df.size}:}{ IGNORE THIS }
12 | \item{\code{df.intensity}:}{ A \code{data.frame} with Poisson process
13 | intensity \code{d.lambda} at locations \code{x}}
14 | \item{\code{df.rate}:}{ A \code{data.frame} the locations \code{x} and associated \code{rate}
15 | which parameterized the exponential distribution from which the group
16 | sizes were drawn.}
17 | }
18 | }
19 | \usage{
20 | data(toygroups)
21 | }
22 | \description{
23 | This data set serves to teach the concept of modelling species that gather in
24 | groups and where the grouping behaviour depends on space.
25 | }
26 | \examples{
27 | \donttest{
28 | if (require(ggplot2, quietly = TRUE)) {
29 | # Load the data
30 |
31 | data("toygroups", package = "inlabru")
32 |
33 | # The data set is a simulation of animal groups residing in a 1D space. Their
34 | # locations in x-space are sampled from a Cox process with intensity
35 |
36 | ggplot(toygroups$df.intensity) +
37 | geom_line(aes(x = x, y = g.lambda))
38 |
39 | # Adding the simulated group locations to this plot we obtain
40 |
41 | ggplot(toygroups$df.intensity) +
42 | geom_line(aes(x = x, y = g.lambda)) +
43 | geom_point(data = toygroups$groups, aes(x, y = 0), pch = "|")
44 |
45 | # Each group has a size mark attached to it.
46 | # These group sizes are sampled from an exponential distribution
47 | # for which the rate parameter depends on the x-coordinate
48 |
49 | ggplot(toygroups$groups) +
50 | geom_point(aes(x = x, y = size))
51 |
52 | ggplot(toygroups$df.rate) +
53 | geom_line(aes(x, rate))
54 | }
55 | }
56 | }
57 | \keyword{datasets}
58 |
--------------------------------------------------------------------------------
/man/ibm_input.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/bru_input.R
3 | \name{ibm_input}
4 | \alias{ibm_input}
5 | \alias{ibm_input_set}
6 | \alias{ibm_input_new}
7 | \alias{ibm_input_available}
8 | \alias{ibm_input_get}
9 | \alias{bm_autodetect}
10 | \title{Interface between \code{bru_input} and \code{bru_mapper}}
11 | \usage{
12 | ibm_input_set(mapper, input)
13 |
14 | ibm_input_new(mapper, ...)
15 |
16 | ibm_input_available(mapper)
17 |
18 | ibm_input_get(mapper)
19 |
20 | bm_autodetect()
21 | }
22 | \arguments{
23 | \item{mapper}{A \code{bru_mapper} object.}
24 |
25 | \item{input}{A \code{bru_input} object, or \code{NULL} to remove any existing input.
26 | Alternatively, an existing \code{bru_mapper} object with or without associated
27 | input can be provided, in which case the input from that mapper
28 | is copied.}
29 |
30 | \item{\dots}{Passed on to \code{\link[=new_bru_input]{new_bru_input()}}.}
31 | }
32 | \description{
33 | Associate \link{bru_input} objects with \link{bru_mapper} objects.
34 | }
35 | \section{Functions}{
36 | \itemize{
37 | \item \code{ibm_input_set()}: Add an existing \code{bru_input} to a \code{bru_mapper}.
38 |
39 | \item \code{ibm_input_new()}: Create and add a \code{bru_input} to a \code{bru_mapper}.
40 |
41 | \item \code{ibm_input_available()}: Check if a \code{bru_input} is associated with a
42 | \code{bru_mapper}.
43 |
44 | \item \code{ibm_input_get()}: Get the \code{bru_input} associated with a \code{bru_mapper}.
45 |
46 | \item \code{bm_autodetect()}: Create a \code{bru_mapper} placeholder object of class
47 | \code{bm_autodetect}. The main purpose of this class is to attach \link{bru_input}
48 | information to it, which is later used to determine a suitable 'real'
49 | mapper type.
50 |
51 | }}
52 | \examples{
53 | (m <- bm_autodetect())
54 | ibm_input_available(m)
55 | (m <- ibm_input_new(m, cos(x)))
56 | ibm_input_available(m)
57 | ibm_input_set(bm_linear(), m)
58 |
59 | }
60 | \seealso{
61 | \code{\link[=bru_input]{bru_input()}}
62 | }
63 |
--------------------------------------------------------------------------------
/misc/apmaker.R:
--------------------------------------------------------------------------------
1 | # https://github.com/inlabru-org/inlabru/issues/125
2 |
3 | # TODO 20220126should not be a S3 but local function and function name should be clearer
4 | # bru_log_list function ---------------------------------------------------------
5 | # How does sf deal with secondary geometry columns?
6 | # TODO ####
7 | # TODO have to deal with the multidomain samplers
8 | # https://r-spatial.github.io/sf/articles/sf6.html
9 | # TODO #### extra domains we assign the sampler for them
10 | # TODO can use local helper function (with S3 Usemethod() maybe)
11 |
12 | # @param start_with The message starts with
13 | # @param end_with The message ends with
14 | # @verbosity Default: 2
15 | # @ verbose_store Default: T
16 | bru_log_list <- function(x, attr_names = "sf_column", start_with = NULL, end_with = NULL) {
17 | for (i in seq_along(x)) {
18 | bru_log_message(
19 | paste0(
20 | start_with,
21 | i,
22 | " is/are ",
23 | attr(x[[i]], attr_names),
24 | end_with,
25 | ".\n"
26 | ),
27 | verbosity = 2, verbose_store = T
28 | )
29 | }
30 | }
31 |
32 | # devtools::load_all()
33 | # data(mrsea, package = "inlabru")
34 | # domain = list(coordinates = mrsea$mesh,
35 | # season = seq_len(4))
36 | # samplers <- mrsea$samplers
37 | # samplers <- list(season = samplers$season, samplers)
38 | # debugonce(inlabru:::apmaker)
39 | # apmaker(samplers=samplers, domain=domain, response="coordinate")
40 |
41 | # TODO Extend S3 method with names_list???
42 | # https://stackoverflow.com/questions/18513607/how-to-extend-s3-method-from-another-package-without-loading-the-package
43 | # to deal with samplers names in a dataframe 20230126
44 | # 1) do I need the names of the list or the names within the list(s)?
45 | # 2) Does column names mean sth here?
46 | # 3) What to do with NULL cases, aka unamed list?
47 | # @name names
48 | # @export names_list
49 | # @title Names within list(s)
50 | #
51 | names_list <- function(x) {
52 | lapply(x, function(y) {
53 | names(y)
54 | })
55 | }
56 |
--------------------------------------------------------------------------------
/man/gg.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/ggplot.R
3 | \name{gg}
4 | \alias{gg}
5 | \title{ggplot2 geomes for inlabru related objects}
6 | \usage{
7 | gg(data, ...)
8 | }
9 | \arguments{
10 | \item{data}{an object for which to generate a geom.}
11 |
12 | \item{\dots}{Arguments passed on to the geom method.}
13 | }
14 | \value{
15 | The form of the value returned by gg depends on the class of its
16 | argument. See the documentation of the particular methods for details of
17 | what is produced by that method.
18 | }
19 | \description{
20 | gg is a generic function for generating geomes from various kinds of spatial
21 | objects, e.g. Spatial* data, meshes, Raster objects and inla/inlabru
22 | predictions. The function invokes particular methods which depend on the
23 | \link{class} of the first argument.
24 | }
25 | \examples{
26 | if (require("ggplot2", quietly = TRUE)) {
27 | # Load Gorilla data
28 |
29 | gorillas <- inlabru::gorillas_sf
30 |
31 | # Invoke ggplot and add geomes for the Gorilla nests and the survey
32 | # boundary
33 |
34 | ggplot() +
35 | gg(gorillas$boundary) +
36 | gg(gorillas$nests)
37 | }
38 | }
39 | \seealso{
40 | Other geomes for inla and inlabru predictions:
41 | \code{\link{gg.bru_prediction}()},
42 | \code{\link{gg.data.frame}()},
43 | \code{\link{gg.matrix}()}
44 |
45 | Other geomes for spatial data:
46 | \code{\link{gg.SpatRaster}()},
47 | \code{\link{gg.SpatialGridDataFrame}()},
48 | \code{\link{gg.SpatialLines}()},
49 | \code{\link{gg.SpatialPixels}()},
50 | \code{\link{gg.SpatialPixelsDataFrame}()},
51 | \code{\link{gg.SpatialPoints}()},
52 | \code{\link{gg.SpatialPolygons}()},
53 | \code{\link{gg.sf}()}
54 |
55 | Other geomes for meshes:
56 | \code{\link{gg.fm_mesh_1d}()},
57 | \code{\link{gg.fm_mesh_2d}()}
58 |
59 | Other geomes for Raster data:
60 | \code{\link{gg.RasterLayer}()}
61 | }
62 | \concept{geomes for Raster data}
63 | \concept{geomes for inla and inlabru predictions}
64 | \concept{geomes for meshes}
65 | \concept{geomes for spatial data}
66 |
--------------------------------------------------------------------------------
/tests/testthat/test-utils.R:
--------------------------------------------------------------------------------
1 | test_that("Missing data infilling", {
2 | skip_on_cran()
3 | local_bru_safe_inla()
4 | skip_if_not(bru_safe_sp())
5 | skip_if_not_installed("terra")
6 |
7 | points <-
8 | sp::SpatialPointsDataFrame(
9 | matrix(1:6, 3, 2),
10 | data = data.frame(val = c(NA, NA, NA))
11 | )
12 | input_coord <- expand.grid(x = 0:6, y = 0:7)
13 | input_data <- data.frame(val = as.vector(input_coord$y))
14 | input <-
15 | sp::SpatialPixelsDataFrame(
16 | input_coord,
17 | data = input_data
18 | )
19 |
20 | val0 <- bru_fill_missing(input, points, points$val)
21 |
22 | input <-
23 | sp::SpatialPointsDataFrame(
24 | input_coord,
25 | data = input_data
26 | )
27 | val2 <- bru_fill_missing(input, points, points$val)
28 |
29 | expect_equal(val2, val0)
30 |
31 | input <- sp::SpatialGrid(sp::GridTopology(c(0, 0), c(1, 1), c(7, 8)))
32 | input_data <- data.frame(val = as.vector(sp::coordinates(input)[, 2]))
33 | input <-
34 | sp::SpatialGridDataFrame(
35 | input,
36 | data = input_data
37 | )
38 | val2 <- bru_fill_missing(input, points, points$val)
39 |
40 | expect_equal(val2, val0)
41 | })
42 |
43 |
44 | test_that("Laplace distribution", {
45 | q <- -5:5
46 | rate <- 2
47 | p <- plaplace(q, rate = rate)
48 |
49 | expect_equal(plaplace(q, rate = rate, lower.tail = TRUE), p)
50 | expect_equal(plaplace(-q, rate = rate, lower.tail = FALSE), p)
51 | expect_equal(
52 | plaplace(q, rate = rate, lower.tail = TRUE, log.p = TRUE),
53 | log(p)
54 | )
55 | expect_equal(
56 | plaplace(-q, rate = rate, lower.tail = FALSE, log.p = TRUE),
57 | log(p)
58 | )
59 | expect_equal(qlaplace(p, rate = rate, lower.tail = TRUE), q)
60 | expect_equal(qlaplace(p, rate = rate, lower.tail = FALSE), -q)
61 | expect_equal(
62 | qlaplace(log(p), rate = rate, lower.tail = TRUE, log.p = TRUE),
63 | q
64 | )
65 | expect_equal(
66 | qlaplace(log(p), rate = rate, lower.tail = FALSE, log.p = TRUE),
67 | -q
68 | )
69 | })
70 |
--------------------------------------------------------------------------------
/man/bru_convergence_plot.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/track_plotting.R
3 | \name{bru_convergence_plot}
4 | \alias{bru_convergence_plot}
5 | \title{Plot inlabru convergence diagnostics}
6 | \usage{
7 | bru_convergence_plot(x, from = 1, to = NULL, type = NULL)
8 | }
9 | \arguments{
10 | \item{x}{a \link{bru} object, typically a result from \code{\link[=bru]{bru()}} for a nonlinear
11 | predictor model}
12 |
13 | \item{from, to}{integer values for the range of iterations to plot.
14 | Default \code{from = 1} (start from the first iteration) and \code{to = NULL} (end at
15 | the last iteration).
16 | Set \code{from = 0} to include the initial linearisation point in the track plot.}
17 |
18 | \item{type}{\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} character; "bru" (default)
19 | for iterative nonlinear inlabru convergence diagnostics plots, or "inla"
20 | for INLA optimiser trace plots.}
21 | }
22 | \value{
23 | A ggplot object with four panels of convergence diagnostics:
24 | \itemize{
25 | \item \code{Tracks}: Mode and linearisation values for each effect
26 | \item \code{Mode - Lin}: Difference between mode and linearisation values for each
27 | effect
28 | \item \verb{|Change| / sd}: Absolute change in mode and linearisation values
29 | divided by the standard deviation for each effect
30 | \item \code{Change & sd}: Absolute change in mode and linearisation values
31 | and standard deviation for each effect
32 | }
33 |
34 | For multidimensional components, only the overall average, maximum, and
35 | minimum values are shown.
36 | }
37 | \description{
38 | Draws four panels of convergence diagnostics for an iterated INLA method
39 | estimation
40 | }
41 | \details{
42 | Requires the "dplyr", "ggplot2", and "patchwork"
43 | packages to be installed.
44 | }
45 | \examples{
46 | \dontrun{
47 | fit <- bru(...)
48 | bru_convergence_plot(fit)
49 | }
50 | }
51 | \seealso{
52 | \code{\link[=bru]{bru()}}
53 | }
54 |
--------------------------------------------------------------------------------
/man/bru_model_mapper_methods.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/model.R
3 | \name{bru_model_mapper_methods}
4 | \alias{bru_model_mapper_methods}
5 | \alias{ibm_linear.bru_model}
6 | \alias{ibm_linear.bru_comp_list}
7 | \alias{ibm_simplify.bru_model}
8 | \alias{ibm_simplify.bru_comp}
9 | \alias{ibm_simplify.bru_comp_list}
10 | \alias{ibm_linear.bm_list}
11 | \alias{ibm_simplify.bm_list}
12 | \title{Mapper methods for model objects}
13 | \usage{
14 | \method{ibm_linear}{bru_model}(mapper, input, state = NULL, ...)
15 |
16 | \method{ibm_linear}{bru_comp_list}(mapper, input, state = NULL, ...)
17 |
18 | \method{ibm_simplify}{bru_model}(mapper, input = NULL, state = NULL, ...)
19 |
20 | \method{ibm_simplify}{bru_comp}(mapper, input = NULL, state = NULL, ...)
21 |
22 | \method{ibm_simplify}{bru_comp_list}(mapper, input = NULL, state = NULL, ...)
23 |
24 | \method{ibm_linear}{bm_list}(mapper, input, state = NULL, ...)
25 |
26 | \method{ibm_simplify}{bm_list}(mapper, input = NULL, state = NULL, ...)
27 | }
28 | \arguments{
29 | \item{mapper}{A mapper S3 object, inheriting from \code{bru_mapper}.}
30 |
31 | \item{input}{Data input for the mapper.}
32 |
33 | \item{state}{A vector of latent state values for the mapping,
34 | of length \code{ibm_n(mapper, inla_f = FALSE)}}
35 |
36 | \item{...}{Arguments passed on to other methods}
37 | }
38 | \description{
39 | Methods for the \code{ibm_linear()} and \code{ibm_simplify()} methods for
40 | \link{bru} model objects and related classes.
41 | }
42 | \section{Functions}{
43 | \itemize{
44 | \item \code{ibm_linear(bru_model)}: Returns a list (one element per
45 | observation model) of \link{bm_list} objects, each with one \link{bm_taylor}
46 | entry for each included component.
47 |
48 | \item \code{ibm_simplify(bru_model)}: Returns a list (one element per
49 | observation model) of \link{bm_list} objects, each with one \link{bru_mapper}
50 | entry for each included component.
51 |
52 | }}
53 | \concept{specific \link{bm_list} mapper method implementations}
54 | \concept{specific \link{bru_comp_list} mapper method implementations}
55 |
--------------------------------------------------------------------------------
/man/bm_pipe.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/mappers.R
3 | \name{bm_pipe}
4 | \alias{bm_pipe}
5 | \alias{bru_mapper_pipe}
6 | \title{Mapper for linking several mappers in sequence}
7 | \usage{
8 | bm_pipe(mappers)
9 |
10 | bru_mapper_pipe(...)
11 | }
12 | \arguments{
13 | \item{mappers}{A list of \code{bru_mapper} objects}
14 |
15 | \item{\dots}{Arguments passed on to \code{\link[=bm_pipe]{bm_pipe()}}}
16 | }
17 | \description{
18 | Create a pipe mapper, where \code{mappers} is a list of mappers,
19 | and the evaluated output of each mapper is handed as the state to the next
20 | mapper.
21 | The \code{input} format for the \code{ibm_eval} and \code{ibm_jacobian} methods is
22 | a list of inputs, one for each mapper.
23 | }
24 | \examples{
25 | m <- bm_pipe(list(
26 | scale = bm_scale(),
27 | shift = bm_shift()
28 | ))
29 | ibm_eval2(m, input = list(scale = 2, shift = 1:4), state = 1:4)
30 |
31 | }
32 | \seealso{
33 | \link{bru_mapper}, \link{bru_mapper_generics}
34 |
35 | Other mappers:
36 | \code{\link{bm_aggregate}()},
37 | \code{\link{bm_collect}()},
38 | \code{\link{bm_const}()},
39 | \code{\link{bm_factor}()},
40 | \code{\link{bm_fm_mesh_1d}},
41 | \code{\link{bm_fmesher}()},
42 | \code{\link{bm_harmonics}()},
43 | \code{\link{bm_index}()},
44 | \code{\link{bm_linear}()},
45 | \code{\link{bm_logitaverage}()},
46 | \code{\link{bm_logsumexp}()},
47 | \code{\link{bm_marginal}()},
48 | \code{\link{bm_matrix}()},
49 | \code{\link{bm_multi}()},
50 | \code{\link{bm_reparam}()},
51 | \code{\link{bm_repeat}()},
52 | \code{\link{bm_scale}()},
53 | \code{\link{bm_shift}()},
54 | \code{\link{bm_sum}()},
55 | \code{\link{bm_taylor}()},
56 | \code{\link{bru_get_mapper}()},
57 | \code{\link{bru_mapper}()}
58 |
59 | Other specific \link{bm_pipe} method implementations:
60 | \code{\link{ibm_eval}()},
61 | \code{\link{ibm_eval2}()},
62 | \code{\link{ibm_jacobian}()},
63 | \code{\link{ibm_n}()},
64 | \code{\link{ibm_n_output}()},
65 | \code{\link{ibm_simplify}()},
66 | \code{\link{ibm_values}()}
67 | }
68 | \concept{mappers}
69 | \concept{specific \link{bm_pipe} method implementations}
70 |
--------------------------------------------------------------------------------
/man/bm_repeat_indexing.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/mapper_repeat.R
3 | \name{bm_repeat_indexing}
4 | \alias{bm_repeat_indexing}
5 | \alias{bm_repeat_indexing_matrix}
6 | \title{Re-indexing matrix for repeated mappers}
7 | \usage{
8 | bm_repeat_indexing(n_map, n_rep, interleaved = FALSE)
9 |
10 | bm_repeat_indexing_matrix(n_map, n_rep)
11 | }
12 | \arguments{
13 | \item{n_map}{The block mapper size}
14 |
15 | \item{n_rep}{The number of times the block is repeated}
16 |
17 | \item{interleaved}{logical; if \code{TRUE}, the state vector indexing is
18 | interleaved. Default is \code{FALSE}, for blockwise indexing.}
19 | }
20 | \value{
21 | \code{bm_repeat_indexing}: Returns a list with a vector of offsets,
22 | \code{offsets}, and a vector of relative index values, \code{index}; block \code{k}
23 | indexing is given by \code{offsets[k] + index}.
24 |
25 | \code{bm_repeat_indexing_matrix}: A \code{sparseMatrix} object.
26 | }
27 | \description{
28 | Helper methods for regular and interleaved state vector
29 | indexing, meant for use in \link{bm_repeat} mappers.
30 | }
31 | \section{Functions}{
32 | \itemize{
33 | \item \code{bm_repeat_indexing()}: Construct the offsets and within-block
34 | index vectors for a repeated mapper, with or without interleaving.
35 |
36 | \item \code{bm_repeat_indexing_matrix()}: Creates a sparse matrix \code{A} such that
37 | \code{z <- A \%*\% x} constructs a blockwise version \code{z = c(x1, x2, ..., xn)} of
38 | an interleaved state vector \code{x = c(x1[1], x2[1], ..., x1[2], x2[2], ...)}.
39 | Each block is of size \code{n_map}, and there are \code{n_rep} blocks. The reverse
40 | operation, taking a blockwise \code{z = c(x1, x2, ..., xn)} to an interleaved
41 | vector is \code{x <- Matrix::t(A) \%*\% z}.
42 |
43 | }}
44 | \examples{
45 | (idx <- bm_repeat_indexing(3, 2, FALSE))
46 | (idx <- bm_repeat_indexing(3, 2, TRUE))
47 | (A <- bm_repeat_indexing_matrix(3, 2))
48 | (x_interleaved <- 1:6)
49 | (x_blockwise <- as.vector(A \%*\% x_interleaved))
50 | (x_recovered <- as.vector(Matrix::t(A) \%*\% x_blockwise))
51 |
52 | }
53 | \keyword{internal}
54 |
--------------------------------------------------------------------------------
/inst/examples/gg.sp.R:
--------------------------------------------------------------------------------
1 | \donttest{
2 | if (require("ggplot2", quietly = TRUE) &&
3 | requireNamespace("terra", quietly = TRUE) &&
4 | bru_safe_sp() &&
5 | require("sp")) {
6 | # Load Gorilla data
7 |
8 | gorillas <- inlabru::gorillas_sf
9 |
10 | gcov <- gorillas_sf_gcov()
11 | elev <- terra::as.data.frame(gcov$elevation, xy = TRUE)
12 | elev <- sf::as_Spatial(sf::st_as_sf(elev, coords = c("x", "y")))
13 |
14 | # Turn elevation covariate into SpatialGridDataFrame
15 | elev <- sp::SpatialPixelsDataFrame(elev, data = as.data.frame(elev))
16 |
17 | # Plot Gorilla elevation covariate provided as SpatialPixelsDataFrame.
18 | # The same syntax applies to SpatialGridDataFrame objects.
19 |
20 | ggplot() +
21 | gg(elev)
22 |
23 | # Add Gorilla survey boundary and nest sightings
24 |
25 | ggplot() +
26 | gg(elev) +
27 | gg(gorillas$boundary, alpha = 0.0, col = "red") +
28 | gg(gorillas$nests)
29 |
30 | # Load pantropical dolphin data
31 |
32 | mexdolphin <- inlabru::mexdolphin_sp()
33 |
34 | # Plot the pantropical survey boundary, ship transects and dolphin sightings
35 |
36 | ggplot() +
37 | gg(mexdolphin$ppoly) + # survey boundary as SpatialPolygon
38 | gg(mexdolphin$samplers) + # ship transects as SpatialLines
39 | gg(mexdolphin$points) # dolphin sightings as SpatialPoints
40 |
41 | # Change color
42 |
43 | ggplot() +
44 | gg(mexdolphin$ppoly, color = "green") + # survey boundary as SpatialPolygon
45 | gg(mexdolphin$samplers, color = "red") + # ship transects as SpatialLines
46 | gg(mexdolphin$points, color = "blue") # dolphin sightings as SpatialPoints
47 |
48 |
49 | # Visualize data annotations: line width by segment number
50 |
51 | names(mexdolphin$samplers) # 'seg' holds the segment number
52 | ggplot() +
53 | gg(mexdolphin$samplers, aes(color = seg))
54 |
55 | # Visualize data annotations: point size by dolphin group size
56 |
57 | names(mexdolphin$points) # 'size' holds the group size
58 | ggplot() +
59 | gg(mexdolphin$points, aes(size = size))
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/inst/examples/bru_obs.R:
--------------------------------------------------------------------------------
1 | \donttest{
2 | if (bru_safe_inla() &&
3 | require(ggplot2, quietly = TRUE)) {
4 |
5 | # The 'bru_obs()' (previously 'like()') function's main purpose is to set up
6 | # observation models, both for single- and multi-likelihood models.
7 | # The following example generates some random covariates which are observed
8 | # through two different random effect models with different likelihoods
9 |
10 | # Generate the data
11 |
12 | set.seed(123)
13 |
14 | n1 <- 200
15 | n2 <- 10
16 |
17 | x1 <- runif(n1)
18 | x2 <- runif(n2)
19 | z2 <- runif(n2)
20 |
21 | y1 <- rnorm(n1, mean = 2 * x1 + 3)
22 | y2 <- rpois(n2, lambda = exp(2 * x2 + z2 + 3))
23 |
24 | df1 <- data.frame(y = y1, x = x1)
25 | df2 <- data.frame(y = y2, x = x2, z = z2)
26 |
27 | # Single likelihood models and inference using bru are done via
28 |
29 | cmp1 <- y ~ -1 + Intercept(1) + x
30 | fit1 <- bru(cmp1, family = "gaussian", data = df1)
31 | summary(fit1)
32 |
33 | cmp2 <- y ~ -1 + Intercept(1) + x + z
34 | fit2 <- bru(cmp2, family = "poisson", data = df2)
35 | summary(fit2)
36 |
37 | # A joint model has two likelihoods, which are set up using the bru_obs
38 | # function
39 |
40 | lik1 <- bru_obs(
41 | "gaussian",
42 | formula = y ~ x + Intercept,
43 | data = df1,
44 | tag = "norm"
45 | )
46 | lik2 <- bru_obs(
47 | "poisson",
48 | formula = y ~ x + z + Intercept,
49 | data = df2,
50 | tag = "pois"
51 | )
52 |
53 | # The union of effects of both models gives the components needed to run bru
54 |
55 | jcmp <- ~ x + z + Intercept(1)
56 | jfit <- bru(jcmp, lik1, lik2)
57 |
58 | bru_index(jfit, "norm")
59 | bru_index(jfit, "pois")
60 |
61 | # Compare the estimates
62 |
63 | p1 <- ggplot() +
64 | gg(fit1$summary.fixed, bar = TRUE) +
65 | ylim(0, 4) +
66 | ggtitle("Model 1")
67 | p2 <- ggplot() +
68 | gg(fit2$summary.fixed, bar = TRUE) +
69 | ylim(0, 4) +
70 | ggtitle("Model 2")
71 | pj <- ggplot() +
72 | gg(jfit$summary.fixed, bar = TRUE) +
73 | ylim(0, 4) +
74 | ggtitle("Joint model")
75 |
76 | multiplot(p1, p2, pj)
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/man/robins_subset.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/data.robins_subset.R
3 | \docType{data}
4 | \name{robins_subset}
5 | \alias{robins_subset}
6 | \title{robins_subset}
7 | \format{
8 | The data are a data.frame with variables
9 | \describe{
10 | \item{\code{circle}:}{
11 | Four-letter code of the CBC circle.
12 | }
13 | \item{\code{bcr}:}{
14 | Numeric code for the bird conservation region encompassing the
15 | count circle.
16 | }
17 | \item{\code{state}:}{
18 | US state encompassing the count circle.
19 | }
20 | \item{\code{year}:}{
21 | calendar year the count was conducted.
22 | }
23 | \item{\code{std_yr}:}{
24 | transformed year, with 2016 = 0.
25 | }
26 | \item{\code{count}:}{
27 | number of robins recorded.
28 | }
29 | \item{\code{log_hrs}:}{
30 | the natural log of party hours.
31 | }
32 | \item{\code{lon}:}{
33 | longitude of the count circle centroid.
34 | }
35 | \item{\code{lat}:}{
36 | latitude of the count circle centroid.
37 | }
38 | \item{\code{obs}:}{
39 | unique record identifier.
40 | }
41 | }
42 | }
43 | \source{
44 | https://github.com/tmeeha/inlaSVCBC
45 | }
46 | \usage{
47 | robins_subset
48 | }
49 | \description{
50 | This is the \code{robins_subset} dataset, which is a subset of the
51 | full robins data set used to demonstrate a spatially varying trend
52 | coefficient model in Meehan et al. 2019. The dataset includes American
53 | Robin counts, along with time, location, and effort information, from
54 | Audubon Christimas Bird Counts (CBC) conducted in six US states between
55 | 1987 and 2016.
56 | }
57 | \examples{
58 | if (require(ggplot2, quietly = TRUE)) {
59 | data(robins_subset, package = "inlabru") # get the data
60 |
61 | # plot the counts for one year of data
62 | ggplot(robins_subset[robins_subset$std_yr == 0, ]) +
63 | geom_point(aes(lon, lat, colour = count + 1)) +
64 | scale_colour_gradient(low = "blue", high = "red", trans = "log")
65 | }
66 | }
67 | \references{
68 | Meehan, T.D., Michel, N.L., and Rue, H. 2019. Spatial modeling of Audubon
69 | Christmas Bird Counts reveals fine-scale patterns and drivers of relative
70 | abundance trends. Ecosphere, 10(4), p.e02707.
71 | }
72 | \keyword{datasets}
73 |
--------------------------------------------------------------------------------
/R/data.robins_subset.R:
--------------------------------------------------------------------------------
1 | #' @name robins_subset
2 | #' @title robins_subset
3 | #' @docType data
4 | #' @description This is the `robins_subset` dataset, which is a subset of the
5 | #' full robins data set used to demonstrate a spatially varying trend
6 | #' coefficient model in Meehan et al. 2019. The dataset includes American
7 | #' Robin counts, along with time, location, and effort information, from
8 | #' Audubon Christimas Bird Counts (CBC) conducted in six US states between
9 | #' 1987 and 2016.
10 | #'
11 | #' @format The data are a data.frame with variables
12 | #' \describe{
13 | #' \item{`circle`:}{
14 | #' Four-letter code of the CBC circle.
15 | #' }
16 | #' \item{`bcr`:}{
17 | #' Numeric code for the bird conservation region encompassing the
18 | #' count circle.
19 | #' }
20 | #' \item{`state`:}{
21 | #' US state encompassing the count circle.
22 | #' }
23 | #' \item{`year`:}{
24 | #' calendar year the count was conducted.
25 | #' }
26 | #' \item{`std_yr`:}{
27 | #' transformed year, with 2016 = 0.
28 | #' }
29 | #' \item{`count`:}{
30 | #' number of robins recorded.
31 | #' }
32 | #' \item{`log_hrs`:}{
33 | #' the natural log of party hours.
34 | #' }
35 | #' \item{`lon`:}{
36 | #' longitude of the count circle centroid.
37 | #' }
38 | #' \item{`lat`:}{
39 | #' latitude of the count circle centroid.
40 | #' }
41 | #' \item{`obs`:}{
42 | #' unique record identifier.
43 | #' }
44 | #' }
45 | #' @source
46 | #' https://github.com/tmeeha/inlaSVCBC
47 | #'
48 | #'
49 | #' @references
50 | #' Meehan, T.D., Michel, N.L., and Rue, H. 2019. Spatial modeling of Audubon
51 | #' Christmas Bird Counts reveals fine-scale patterns and drivers of relative
52 | #' abundance trends. Ecosphere, 10(4), p.e02707.
53 | #'
54 | #' @examples
55 | #' if (require(ggplot2, quietly = TRUE)) {
56 | #' data(robins_subset, package = "inlabru") # get the data
57 | #'
58 | #' # plot the counts for one year of data
59 | #' ggplot(robins_subset[robins_subset$std_yr == 0, ]) +
60 | #' geom_point(aes(lon, lat, colour = count + 1)) +
61 | #' scale_colour_gradient(low = "blue", high = "red", trans = "log")
62 | #' }
63 | "robins_subset"
64 |
--------------------------------------------------------------------------------
/man/summary.bru_comp.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/bru_input.R, R/effect.R
3 | \name{print.summary_bru_input}
4 | \alias{print.summary_bru_input}
5 | \alias{summary.bru_comp}
6 | \alias{summary.bru_comp_list}
7 | \alias{print.bru_comp}
8 | \alias{print.bru_comp_list}
9 | \alias{format.bru_subcomp}
10 | \alias{summary.bru_subcomp}
11 | \alias{print.bru_subcomp}
12 | \alias{print.summary_component}
13 | \alias{print.summary_bru_comp_list}
14 | \alias{print.summary_bru_subcomp}
15 | \title{Summarise components}
16 | \usage{
17 | \method{print}{summary_bru_input}(x, ...)
18 |
19 | \method{summary}{bru_comp}(object, ..., depth = Inf, verbose = TRUE)
20 |
21 | \method{summary}{bru_comp_list}(object, verbose = TRUE, ...)
22 |
23 | \method{print}{bru_comp}(x, ...)
24 |
25 | \method{print}{bru_comp_list}(x, ...)
26 |
27 | \method{format}{bru_subcomp}(x, verbose = TRUE, ..., label.override = NULL)
28 |
29 | \method{summary}{bru_subcomp}(object, verbose = TRUE, ..., label.override = NULL)
30 |
31 | \method{print}{bru_subcomp}(x, verbose = TRUE, ..., label.override = NULL)
32 |
33 | \method{print}{summary_component}(x, ...)
34 |
35 | \method{print}{summary_bru_comp_list}(x, ...)
36 |
37 | \method{print}{summary_bru_subcomp}(x, ...)
38 | }
39 | \arguments{
40 | \item{x}{A summary object to be printed.}
41 |
42 | \item{\dots}{Passed on to other summary methods.}
43 |
44 | \item{object}{Object to be summarised.}
45 |
46 | \item{depth}{The depth of which to expand the component mapper.
47 | Default \code{Inf}, to traverse the entire mapper tree.}
48 |
49 | \item{verbose}{logical; If \code{TRUE}, includes more details of the
50 | component definitions. When \code{FALSE}, only show basic component
51 | definition information. Default \code{TRUE}.}
52 |
53 | \item{label.override}{character; If not \code{NULL}, use this label instead of
54 | the object's label.}
55 | }
56 | \description{
57 | Summarise components
58 | }
59 | \seealso{
60 | \code{\link[=bru_comp]{bru_comp()}}, \code{\link[=summary.bru_input]{summary.bru_input()}}
61 | }
62 | \author{
63 | Fabian E. Bachl \email{bachlfab@gmail.com}
64 |
65 | Finn Lindgren \email{finn.lindgren@gmail.com}
66 | }
67 | \keyword{internal}
68 |
--------------------------------------------------------------------------------
/man/inlabru-package.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/inlabru-package.R
3 | \docType{package}
4 | \name{inlabru-package}
5 | \alias{inlabru-package}
6 | \alias{inlabru}
7 | \title{inlabru}
8 | \description{
9 | Convenient model fitting using (iterated) INLA.
10 | }
11 | \details{
12 | \code{inlabru} facilitates Bayesian spatial modelling using integrated nested
13 | Laplace approximations. It is heavily based on R-inla
14 | (\url{https://www.r-inla.org}) but adds additional modelling abilities and
15 | simplified syntax for (in particular) spatial models.
16 | Tutorials and more information can be found at
17 | \url{https://inlabru-org.github.io/inlabru/} and \url{http://www.inlabru.org/}.
18 | The iterative method used for non-linear predictors is documented in the
19 | \code{method} vignette.
20 |
21 | The main function for inference using inlabru is \code{\link[=bru]{bru()}}.
22 | The general model specification details is documented in \code{\link[=bru_comp]{bru_comp()}}
23 | and \code{\link[=bru_obs]{bru_obs()}}.
24 | Posterior quantities beyond the basic summaries can be calculated with
25 | a \code{predict()} method, documented in \code{\link[=predict.bru]{predict.bru()}}.
26 | For point process inference \code{\link[=lgcp]{lgcp()}} can be used as a shortcut to
27 | \code{bru(..., bru_obs(model="cp", ...))}.
28 |
29 | The package comes with multiple real world data sets, namely \link{gorillas},
30 | \link{gorillas_sf}, \link{mexdolphin_sf}. Plotting these data
31 | sets is straight forward using inlabru's extensions
32 | to \code{ggplot2}, e.g. the \code{\link[=gg]{gg()}} function. For educational purposes some
33 | simulated data sets are available as well, e.g. \link{Poisson1_1D},
34 | \link{Poisson2_1D}, \link{Poisson2_1D} and \link{toygroups}.
35 | }
36 | \seealso{
37 | Useful links:
38 | \itemize{
39 | \item \url{http://www.inlabru.org}
40 | \item \url{https://inlabru-org.github.io/inlabru/}
41 | \item \url{https://github.com/inlabru-org/inlabru}
42 | \item Report bugs at \url{https://github.com/inlabru-org/inlabru/issues}
43 | }
44 |
45 | }
46 | \author{
47 | Fabian E. Bachl \email{bachlfab@gmail.com}
48 | and Finn Lindgren \email{finn.lindgren@gmail.com}
49 | }
50 |
--------------------------------------------------------------------------------
/man/plotsample.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/plotsample.R
3 | \name{plotsample}
4 | \alias{plotsample}
5 | \title{Create a plot sample.}
6 | \usage{
7 | plotsample(spdf, boundary, x.ppn = 0.25, y.ppn = 0.25, nx = 5, ny = 5)
8 | }
9 | \arguments{
10 | \item{spdf}{A \code{SpatialPointsDataFrame} defining the points that are to be
11 | sampled by the plot sample.}
12 |
13 | \item{boundary}{A \code{SpatialPolygonsDataFrame} defining the survey boundary
14 | within which the points occur.}
15 |
16 | \item{x.ppn}{The proportion of the x=axis that is to be included in the
17 | plots.}
18 |
19 | \item{y.ppn}{The proportion of the y=axis that is to be included in the
20 | plots.}
21 |
22 | \item{nx}{The number of plots in the x-dimension.}
23 |
24 | \item{ny}{The number of plots in the y-dimension.}
25 | }
26 | \value{
27 | A list with three components:
28 | \describe{
29 | \item{\code{plots}}{A \code{SpatialPolygonsDataFrame} object containing the plots
30 | that were sampled.}
31 | \item{\code{dets}}{A \code{SpatialPointsDataFrame} object containing the locations
32 | of the points within the plots.}
33 | \item{\code{counts}}{A \code{dataframe} containing the following columns
34 | \describe{
35 | \item{\code{x}}{The x-coordinates of the centres of the plots within the
36 | boundary.}
37 | \item{\code{y}}{The y-coordinates of the centres of the plots within the
38 | boundary.}
39 | \item{\code{n}}{The numbers of points in each plot.}
40 | \item{\code{area}}{The areas of the plots within the boundary}
41 | }}
42 | }.
43 | }
44 | \description{
45 | Creates a plot sample on a regular grid with a random start location.
46 | }
47 | \examples{
48 | \donttest{
49 | # Some features require the raster package
50 | if (bru_safe_sp() &&
51 | require("sp") &&
52 | require("raster", quietly = TRUE) &&
53 | require("ggplot2", quietly = TRUE) &&
54 | require("terra", quietly = TRUE) &&
55 | require("sf", quietly = TRUE)) {
56 | gorillas <- gorillas_sp()
57 | plotpts <- plotsample(gorillas$nests, gorillas$boundary,
58 | x.ppn = 0.4, y.ppn = 0.4, nx = 5, ny = 5
59 | )
60 | ggplot() +
61 | gg(plotpts$plots) +
62 | gg(plotpts$dets, pch = "+", cex = 2) +
63 | gg(gorillas$boundary)
64 | }
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/man/bru_fill_missing.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/utils.R
3 | \name{bru_fill_missing}
4 | \alias{bru_fill_missing}
5 | \title{Fill in missing values in Spatial grids}
6 | \usage{
7 | bru_fill_missing(
8 | data,
9 | where,
10 | values,
11 | layer = NULL,
12 | selector = NULL,
13 | batch_size = deprecated()
14 | )
15 | }
16 | \arguments{
17 | \item{data}{A SpatialPointsDataFrame, SpatialPixelsDataFrame,
18 | SpatialGridDataFrame, SpatRaster, Raster, or sf object
19 | containing data to use for filling}
20 |
21 | \item{where}{A, matrix, data.frame, or SpatialPoints or
22 | SpatialPointsDataFrame, or sf object, containing the locations of the
23 | evaluated values}
24 |
25 | \item{values}{A vector of values to be filled in where \code{is.na(values)} is
26 | \code{TRUE}}
27 |
28 | \item{layer, selector}{Specifies what data column or columns from which to
29 | extract data, see \code{\link[=bru_comp]{bru_comp()}} for details.}
30 |
31 | \item{batch_size}{\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#deprecated}{\figure{lifecycle-deprecated.svg}{options: alt='[Deprecated]'}}}{\strong{[Deprecated]}} due to improved
32 | algorithm.
33 | Size of nearest-neighbour calculation blocks, to limit the
34 | memory and computational complexity.}
35 | }
36 | \value{
37 | An infilled vector of values
38 | }
39 | \description{
40 | Computes nearest-available-value imputation for missing values in space
41 | }
42 | \examples{
43 | \dontrun{
44 | if (require("sf", quietly = TRUE)) {
45 | points <-
46 | sf::st_as_sf(
47 | data.frame(
48 | x = 1:3,
49 | y = 4:6,
50 | val = c(NA, NA, NA)
51 | ),
52 | coords = c("x", "y")
53 | )
54 | input_coord <- expand.grid(x = 0:7, y = 0:7)
55 | input <-
56 | sf::st_as_sf(
57 | cbind(input_coord, val = as.vector(input_coord$y)),
58 | coords = c("x", "y")
59 | )
60 | points$val <- bru_fill_missing(input, points, points$val)
61 | print(points)
62 |
63 | # To fill in missing values in a grid:
64 | print(input$val[c(3, 30)])
65 | input$val[c(3, 30)] <- NA # Introduce missing values
66 | input$val <- bru_fill_missing(input, input, input$val)
67 | print(input$val[c(3, 30)])
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/man/sline.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/bru_sp.R
3 | \name{sline}
4 | \alias{sline}
5 | \title{Convert data frame to SpatialLinesDataFrame}
6 | \usage{
7 | sline(
8 | data,
9 | start.cols,
10 | end.cols,
11 | crs = fm_crs(),
12 | to.crs = NULL,
13 | format = c("sp", "sf")
14 | )
15 | }
16 | \arguments{
17 | \item{data}{A data.frame}
18 |
19 | \item{start.cols}{Character array pointing out the columns of \code{data} that
20 | hold the start points of the lines}
21 |
22 | \item{end.cols}{Character array pointing out the columns of \code{data} that hold
23 | the end points of the lines}
24 |
25 | \item{crs}{Coordinate reference system of the original \code{data}}
26 |
27 | \item{to.crs}{Coordinate reference system for the output.}
28 |
29 | \item{format}{Format of the output object. Either \code{"sp"} (default) or \code{"sf"}}
30 | }
31 | \value{
32 | \code{sp::SpatialLinesDataFrame} or \link[sf:sf]{sf::sf}
33 | }
34 | \description{
35 | A line in 2D space is defined by a start and an end point, each associated
36 | with 2D coordinates. This function takes a \code{data.frame} as input and assumes
37 | that each row defines a line in space. In order to do so, the data frame must
38 | have at least four columns and the \code{start.cols} and \code{end.cols} parameters
39 | must be used to point out the names of the columns that define the start and
40 | end coordinates of the line. The data is then converted to a
41 | \code{SpatialLinesDataFrame} \code{DF}. If a coordinate reference system \code{crs} is
42 | provided it is attached to \code{DF}. If also \code{to.crs} is provided, the coordinate
43 | system of \code{DF} is transformed accordingly. Additional columns of the input
44 | data, e.g. covariates, are retained and attached to \code{DF}.
45 | }
46 | \examples{
47 | \donttest{
48 | # Create a data frame defining three lines
49 | lns <- data.frame(
50 | xs = c(1, 2, 3), ys = c(1, 1, 1), # start points
51 | xe = c(2, 3, 4), ye = c(2, 2, 2)
52 | ) # end points
53 |
54 |
55 | # Conversion to sf without CRS
56 | spl <- sline(lns,
57 | start.cols = c("xs", "ys"),
58 | end.cols = c("xe", "ye"),
59 | format = "sf"
60 | )
61 |
62 | if (require(ggplot2, quietly = TRUE)) {
63 | # Plot the lines
64 | ggplot() +
65 | gg(spl)
66 | }
67 | }
68 |
69 | }
70 | \keyword{internal}
71 |
--------------------------------------------------------------------------------
/man/materncov.bands.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/spde.R
3 | \name{materncov.bands}
4 | \alias{materncov.bands}
5 | \title{Matern correlation or covariance function approximate credible bands.}
6 | \usage{
7 | materncov.bands(
8 | manifold,
9 | dist,
10 | log.range,
11 | log.variance = NULL,
12 | alpha = 2,
13 | quantile = 0.95,
14 | n = 64,
15 | S1.L = NULL
16 | )
17 | }
18 | \arguments{
19 | \item{manifold}{Either "R1", "S1", "R2", or "S2", from
20 | \code{fm_manifold(mesh)}, or an object supported by
21 | \code{\link[fmesher:fm_manifold]{fmesher::fm_manifold()}}.}
22 |
23 | \item{dist}{A vector of distances at which to calculate the
24 | covariances/correlations}
25 |
26 | \item{log.range}{A scalar or a list (mean, sd), such as produced by
27 | \code{inla.spde.result(...)$summary.log.range.nominal[[1]][c("mean","sd")]}}
28 |
29 | \item{log.variance}{Either \code{NULL}, a scalar, or vector of the
30 | same type as for log.range. When \code{NULL}, the correlations
31 | are calculated instead of the covariances.}
32 |
33 | \item{alpha}{The SPDE operator order. Default 2.}
34 |
35 | \item{quantile}{The target credible probability. Default 0.95.}
36 |
37 | \item{n}{The number of parameter combinations to use for the
38 | approximation. Default 64.}
39 |
40 | \item{S1.L}{For \code{manifold} \code{"S1"}, give the length of the
41 | cyclic interval}
42 | }
43 | \value{
44 | A list with estimated covariance or correlation (when \code{log.variance}
45 | is \code{NULL}) functions:
46 | \item{lower}{An approximate lower bound for the \code{quantile} credible region}
47 | \item{median}{The function for for the approximate median parameters
48 | quantile}
49 | \item{upper}{An approximate upper bound for the \code{quantile} credible region}
50 | }
51 | \description{
52 | Evaluate the covariance function for an inla.spde
53 | object. Calculates the posterior distribution of the range,
54 | log(range), variance, or log(variance) parameter of a model's
55 | SPDE component. Can also calculate Matern correlation or covariance
56 | function.
57 | }
58 | \details{
59 | Uses a Gaussian assumption for the internal model parameters, and finds a
60 | region in parameter space with approximately \code{quantile} probability.
61 | }
62 | \author{
63 | Finn Lindgren \email{Finn.Lindgren@ed.ac.uk}
64 | }
65 | \keyword{internal}
66 |
--------------------------------------------------------------------------------
/misc/mdata_testing.R:
--------------------------------------------------------------------------------
1 | library(INLA)
2 | library(inlabru)
3 | library(tibble)
4 |
5 | dat1 <- tibble(
6 | time_to_event = 1:4,
7 | event_type = rep(c(1, 0), 2),
8 | cure_covar = matrix(1:8, 4, 2)
9 | )
10 | dat2 <- tibble(
11 | time_to_event = 1:3 + 10,
12 | event_type = c(1, 0, 1),
13 | cure_covar = matrix(1:6, 3, 2) + 10
14 | )
15 |
16 | dat1_ <- as_tibble(unclass(with(
17 | dat1,
18 | inla.surv(time = time_to_event, event = event_type, cure = cure_covar)
19 | ))[-7])
20 | dat2_ <- as_tibble(unclass(with(
21 | dat2,
22 | inla.mdata(time_to_event, cure_covar)
23 | )))
24 |
25 | stk1 <- inla.stack(dat1_, A = list(diag(4)), effects=list(Intercept=1))
26 | stk2 <- inla.stack(dat2_, A = list(diag(3)), effects=list(Intercept=1))
27 | inla.stack.LHS(stk1)
28 | inla.stack.RHS(stk1)
29 | inla.stack.LHS(stk2)
30 | inla.stack.RHS(stk2)
31 |
32 | stk <- inla.stack(stk1, stk2)
33 | inla.stack.LHS(stk)
34 | inla.stack.RHS(stk)
35 |
36 |
37 | fit <- inla(formula = list(inla.stack.LHS(stk), inla.stack.LHS(stk)) ~ 0 + Intercept,
38 | family = c("exponentialsurv", "agaussian"),
39 | data = inla.stack.RHS(stk),
40 | control.predictor = list(A = inla.stack.A(stk)),
41 | safe = FALSE)
42 |
43 | fit <- inla(formula = list(inla.stack.LHS(stk1), inla.stack.LHS(stk2)) ~ 0 + Intercept,
44 | family = c("exponentialsurv", "agaussian"),
45 | data = inla.stack.RHS(stk),
46 | control.predictor = list(A = inla.stack.A(stk)),
47 | safe = FALSE)
48 |
49 |
50 | fitb1 <- bru(
51 | components = ~ 0 + Intercept(1),
52 | bru_obs(formula = dat1_ ~ .,
53 | family = "exponentialsurv",
54 | response_data = list(dat1_ = dat1_)),
55 | options = list(safe = FALSE)
56 | )
57 | fitb2 <- bru(
58 | components = ~ 0 + Intercept(1),
59 | bru_obs(formula = dat2_ ~ .,
60 | family = "agaussian",
61 | data = dat2),
62 | options = list(safe = FALSE)
63 | )
64 | fitb <- bru(
65 | components = ~ 0 + Intercept(1),
66 | bru_obs(formula = as.data.frame(unclass(inla.surv(time = time_to_event, event = event_type, cure = cure_covar))[-7]) ~ .,
67 | family = "exponentialsurv",
68 | data = dat1),
69 | bru_obs(formula = inla.mdata(time_to_event, cure_covar) ~ .,
70 | family = "agaussian",
71 | data = dat2),
72 | options = list(safe = FALSE)
73 | )
74 |
--------------------------------------------------------------------------------
/tests/testthat/test-bru_sf.R:
--------------------------------------------------------------------------------
1 | test_that("sf gorillas lgcp vignette", {
2 | ## skip("Feature not yet implemented")
3 |
4 | skip_on_cran()
5 | local_bru_safe_inla()
6 | skip_if_not_installed("sf")
7 |
8 | # Code adapted from the lgcp vignette with an additional mesh construction
9 | # step instead of using the mesh provided in the gorillas data.
10 |
11 | # All sp objects in the example are replaced with sf equivalents.
12 |
13 | data(gorillas_sf, package = "inlabru", envir = environment())
14 |
15 | # ## Not needed anymore for this test, but kept for future reference
16 | # # Bug in st_as_sf making check_ring_dir=TRUE have no effect, as
17 | # # st_as_sfc.SpatialPolygons ignores it. To get around it, need to convert to
18 | # # sfc_POLYGON first, and then do a separate st_sfc call, which does use
19 | # # check_ring_dir.
20 | # # No effect:
21 | # b1 <- sf::st_as_sf(gorillas$boundary, check_ring_dir = TRUE)
22 | # # st_sfc gives the proper effect:
23 | # b2 <- b1
24 | # b2$geometry <- sf::st_sfc(sf::st_geometry(b2$geometry),
25 | # check_ring_dir = TRUE)
26 | #
27 | # gorillas_sf$boundary <- b2
28 |
29 | ## Build boundary information:
30 | boundary <- list(
31 | gorillas_sf$boundary,
32 | NULL
33 | )
34 |
35 | ## Build the mesh:
36 | mesh_sf <- fm_mesh_2d_inla(
37 | boundary = boundary,
38 | max.edge = c(0.54, 0.97),
39 | min.angle = c(30, 21),
40 | ## Safeguard against large meshes.
41 | max.n = c(48000, 16000),
42 | ## Don't build a huge mesh!
43 | max.n.strict = c(128000, 128000),
44 | ## Filter away adjacent points.
45 | cutoff = 0.01,
46 | ## Offset for extra boundaries, if needed.
47 | offset = c(0.73, 1.55),
48 | ## Build mesh in this crs:
49 | crs = fm_crs(gorillas_sf$nests)
50 | )
51 |
52 | # library(ggplot2)
53 | # ggplot() +
54 | # gg(mesh_sf) +
55 | # geom_sf(data = gorillas_sf$boundary, alpha = 0.2, fill = "blue")
56 |
57 | matern <- INLA::inla.spde2.pcmatern(mesh_sf,
58 | prior.sigma = c(0.1, 0.01),
59 | prior.range = c(0.1, 0.01)
60 | )
61 |
62 | cmp <- geometry ~ mySmooth(geometry, model = matern) +
63 | Intercept(1)
64 |
65 | expect_no_error(
66 | fit <- lgcp(
67 | cmp,
68 | data = gorillas_sf$nests,
69 | samplers = gorillas_sf$boundary,
70 | domain = list(geometry = mesh_sf)
71 | )
72 | )
73 | })
74 |
--------------------------------------------------------------------------------
/man/bru_comp_eval.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/model.R
3 | \name{bru_comp_eval}
4 | \alias{bru_comp_eval}
5 | \alias{bru_component_eval}
6 | \title{Evaluate component values in predictor expressions}
7 | \usage{
8 | bru_comp_eval(
9 | main,
10 | group = NULL,
11 | replicate = NULL,
12 | weights = NULL,
13 | .state = NULL
14 | )
15 | }
16 | \arguments{
17 | \item{main, group, replicate, weights}{Specification of where to evaluate a
18 | component. The four inputs are passed on to the joint \code{bru_mapper} for the
19 | component, as
20 |
21 | \if{html}{\out{}}\preformatted{list(mapper = list(
22 | main = main,
23 | group = group,
24 | replicate = replicate),
25 | scale = weights)
26 | }\if{html}{\out{
}}
27 |
28 | NOTE: If you have model component with the same name as a data variable you
29 | want to supply as input to \code{name_eval()}, you need to use
30 | \code{.data.[["myvar"]]} to access it. Otherwise, it will try to use the other
31 | component effect as input, which is ill-defined.}
32 |
33 | \item{.state}{The internal component state. Normally supplied automatically
34 | by the internal methods for evaluating inlabru predictor expressions.}
35 | }
36 | \value{
37 | A vector of values for a component
38 | }
39 | \description{
40 | In predictor expressions, \code{name_eval(...)} can be used to evaluate
41 | the effect of a component called "name".
42 | }
43 | \examples{
44 | if (bru_safe_inla() &&
45 | require("sf", quietly = TRUE) &&
46 | requireNamespace("sn", quietly = TRUE)) {
47 | mesh <- fmesher::fm_mesh_2d_inla(
48 | cbind(0, 0),
49 | offset = 2,
50 | max.edge = 2.5
51 | )
52 | spde <- INLA::inla.spde2.pcmatern(
53 | mesh,
54 | prior.range = c(1, NA),
55 | prior.sigma = c(0.2, NA)
56 | )
57 | set.seed(12345L)
58 | data <- sf::st_as_sf(
59 | data.frame(
60 | x = runif(50),
61 | y = runif(50),
62 | z = rnorm(50)
63 | ),
64 | coords = c("x", "y")
65 | )
66 | fit <- bru(
67 | z ~ -1 + field(geometry, model = spde),
68 | family = "gaussian", data = data,
69 | options = list(control.inla = list(int.strategy = "eb"))
70 | )
71 | pred <- generate(
72 | fit,
73 | newdata = data.frame(A = 0.5, B = 0.5),
74 | formula = ~ field_eval(cbind(A, B)),
75 | n.samples = 1L
76 | )
77 | }
78 | }
79 |
--------------------------------------------------------------------------------