diff --git a/DESCRIPTION b/DESCRIPTION index 9c74bccce..0ce47e1a4 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,18 +1,23 @@ Package: inlabru Type: Package Title: Spatial Inference using Integrated Nested Laplace Approximation -Version: 2.2.7 +Version: 2.2.8 Authors@R: c( - person("Finn", "Lindgren", email = "finn.lindgren@gmail.com", role = c("aut", "cre"), + person("Finn", "Lindgren", email = "finn.lindgren@gmail.com", + role = c("aut", "cre", "cph"), comment = c(ORCID = "0000-0002-5833-2011", "Finn Lindgren continued development of the main code")), - person("Fabian E.", "Bachl", email = "bachlfab@gmail.com", role = c("aut"), + person("Fabian E.", "Bachl", email = "bachlfab@gmail.com", + role = c("aut", "cph"), comment = "Fabian Bachl wrote the main code"), - person("David L.", "Borchers", email = "dlb@st-andrews.ac.uk", role = c("ctb", "dtc"), + person("David L.", "Borchers", email = "dlb@st-andrews.ac.uk", + role = c("ctb", "dtc", "cph"), comment = "David Borchers wrote code for Gorilla data import and sampling, multiplot tool"), - person("Daniel", "Simpson", email = "dp.simpson@gmail.com", role = c("ctb"), + person("Daniel", "Simpson", email = "dp.simpson@gmail.com", + role = c("ctb", "cph"), comment = "Daniel Simpson wrote the basic LGCP sampling method"), - person("Lindesay", "Scott-Howard", email = "lass@st-andrews.ac.uk", role = c("ctb", "dtc"), + person("Lindesay", "Scott-Howard", email = "lass@st-andrews.ac.uk", + role = c("ctb", "dtc", "cph"), comment = "Lindesay Scott-Howard provided MRSea data import code"), person("Seaton", "Andy", email = "andy.e.seaton@gmail.com", role = c("ctb"), comment = "Andy Seaton provided testing and bugfixes") @@ -31,8 +36,8 @@ Encoding: UTF-8 Depends: ggplot2, methods, - R (>= 3.3), - sp, + R (>= 3.5), + sp (>= 1.4-2), stats Imports: Matrix, diff --git a/NAMESPACE b/NAMESPACE index 4945131cd..d9c7a6fe7 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -100,6 +100,7 @@ export(bincount) export(bru) export(bru_call_options) export(bru_compute_linearisation) +export(bru_fill_missing) export(bru_info) export(bru_int_polygon) export(bru_log) @@ -196,6 +197,7 @@ export(multiplot) export(pixels) export(plotsample) export(point2count) +export(row_kron) export(sample.lgcp) export(sline) export(spatial.to.ppp) diff --git a/NEWS.md b/NEWS.md index d09c58e00..371510032 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,22 @@ +# inlabru 2.2.8 + +* Add `_eval` suffix feature for `generate.bru` and `predict.bru`, that + provides a general evaluator function for each component, allowing evaluation + of e.g. nonlinear effects of spatial covariates as a function of the covariate + value instead of the by the spatial evaluator used in the component definition. + For example, with `components = ~ covar(spatial_grid_df, model = "rw1")`, the + prediction expression can have `~ covar_eval(covariate)`, where `covariate` + is a data column in the prediction data object. + + For components with `group` and `replicate` features, these also need to be + provided to the `_eval` function, with + `..._eval(..., group = ..., replicate = ...)` + + This feature is built on top of the `_latent` suffix feature, that gives + direct access to the latent state variables of a component, so in order to + use `_eval` in the model predictor itself, you must use + `like(..., allow_latent = TRUE)` in the model definition. + # inlabru 2.2.7 * Add support for `ngroup` and `nrep` in component definitions diff --git a/R/bru.gof.R b/R/bru.gof.R index cbd57ff72..67f4e9feb 100644 --- a/R/bru.gof.R +++ b/R/bru.gof.R @@ -13,13 +13,13 @@ #' @aliases bincount #' @export #' @importFrom graphics hist -#' @param result A result object from a [bru] or [lgcp] call -#' @param predictor A formula describing the prediction of a 1D LGCP via [predict]. +#' @param result A result object from a [bru()] or [lgcp()] call +#' @param predictor A formula describing the prediction of a 1D LGCP via [predict()]. #' @param observations A vector of observed values #' @param breaks A vector of bin boundaries #' @param nint Number of integration points per bin. Increase this if the bins are wide and #' @param probs numeric vector of probabilities with values in `[0,1]` -#' @param \dots arguments passed on to [predict.bru] +#' @param \dots arguments passed on to [predict.bru()] #' @return An `data.frame` with a ggplot attribute `ggp` #' #' @examples diff --git a/R/bru.inference.R b/R/bru.inference.R index f5ed433b3..2766e7aab 100644 --- a/R/bru.inference.R +++ b/R/bru.inference.R @@ -272,9 +272,9 @@ bru_info.bru <- function(object, ...) { #' #' @author Fabian E. Bachl \email{bachlfab@@gmail.com} #' -#' @param components A [formula]-like specification of latent components. +#' @param components A `formula`-like specification of latent components. #' Also used to define a default linear additive predictor. See -#' [component] for details. +#' [component()] for details. #' @param ... Likelihoods, each constructed by a calling [like()], or named #' parameters that can be passed to a single [like()] call. #' @param options A [bru_options] options object or a list of options passed @@ -428,14 +428,14 @@ parse_inclusion <- function(thenames, include = NULL, exclude = NULL) { -#' Likelihood construction for usage with [bru] +#' Likelihood construction for usage with [bru()] #' #' @aliases like #' @export #' #' @author Fabian E. Bachl \email{bachlfab@@gmail.com} #' -#' @param formula a [formula] where the right hand side is a general R +#' @param formula a `formula` where the right hand side is a general R #' expression defines the predictor used in the model. #' @param family A string identifying a valid `INLA::inla` likelihood family. #' The default is @@ -467,13 +467,17 @@ parse_inclusion <- function(thenames, include = NULL, exclude = NULL) { #' any components from the inclusion list) #' @param allow_latent logical. If `TRUE`, the latent state of each component is #' 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. #' @param allow_combine logical; If `TRUE`, the predictor expression may #' involve several rows of the input data to influence the same row. #' (TODO: review what's needed to allow the result to also be of a different size) #' @param options A [bru_options] options object or a list of options passed #' on to [bru_options()] #' -#' @return A likelihood configuration which can be used to parameterize [bru]. +#' @return A likelihood configuration which can be used to parameterize [bru()]. #' #' @example inst/examples/like.R @@ -764,7 +768,7 @@ joint_stackmaker <- function(model, lhoods, state) { #' approximation of the posterior. #' @param E Single numeric used rescale all integration weights by a fixed factor #' @param options See [bru_options_set()] -#' @return An [bru] object +#' @return An [bru()] object #' @examples #' #' \donttest{ @@ -871,7 +875,7 @@ expand_to_dataframe <- function(x, data = NULL) { # #' Prediction from fitted bru model #' -#' Takes a fitted `bru` object produced by the function [bru]() and produces +#' 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 @@ -888,12 +892,17 @@ expand_to_dataframe <- function(x, data = NULL) { #' #' @aliases predict.bru #' @export -#' @param object An object obtained by calling [bru] or [lgcp]. +#' @param object An object obtained by calling [bru()] or [lgcp()]. #' @param data A data.frame or SpatialPointsDataFrame of covariates needed for #' the prediction. #' @param formula A formula defining an R expression to evaluate for each generated #' sample. If `NULL`, the latent and hyperparameter states are generated -#' as named list elements. +#' as named list elements. In addition to the component names (that give the effect +#' of each component evaluated for the input data), the suffix `_latent` can be used +#' to directly access the latent state for a component, and the suffix `_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 defined with `field(coordinates, ...)`. #' @param 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. @@ -1029,7 +1038,7 @@ predict.bru <- function(object, #' Sampling based on bru posteriors #' #' @description -#' Takes a fitted `bru` object produced by the function [bru]() and produces +#' 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 @@ -1038,12 +1047,17 @@ predict.bru <- function(object, #' @aliases generate.bru #' @export #' @family sample generators -#' @param object A `bru` object obtained by calling [bru]. +#' @param object A `bru` object obtained by calling [bru()]. #' @param data A data.frame or SpatialPointsDataFrame of covariates needed for #' sampling. #' @param formula A formula defining an R expression to evaluate for each generated #' sample. If `NULL`, the latent and hyperparameter states are returned -#' as named list elements. +#' as named list elements. In addition to the component names (that give the effect +#' of each component evaluated for the input data), the suffix `_latent` can be used +#' to directly access the latent state for a component, and the suffix `_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 defined with `field(coordinates, ...)`. #' @param 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. diff --git a/R/deltaIC.R b/R/deltaIC.R index e18cef9c2..ef80edcc0 100644 --- a/R/deltaIC.R +++ b/R/deltaIC.R @@ -3,7 +3,8 @@ #' @description #' Calculates DIC and WAIC differences and produces an ordered summary. #' -#' @param ... Comma-separated objects inheriting from class `inla` and obtained from a run of [inla][INLA::inla], [bru] or [lgcp] +#' @param ... Comma-separated objects inheriting from class `inla` and obtained +#' from a run of `INLA::inla()`, [bru()] or [lgcp()] #' @param criterion If 'DIC', plots DIC differences; If 'WAIC', plots WAIC differences. #' #' @return A data frame with each row containing the model name, DIC, WAIC, deltaDIC, and diff --git a/R/effect.R b/R/effect.R index ee4cb8680..37cb7d708 100644 --- a/R/effect.R +++ b/R/effect.R @@ -98,7 +98,7 @@ ibm_amatrix <- function(mapper, input, ...) { #' #' @description #' -#' Similar to `glm()`, `gam()` and `inla()`, [bru] models can be constructed via +#' 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 @@ -116,9 +116,9 @@ ibm_amatrix <- function(mapper, input, ...) { #' #' @details #' -#' [bru] will understand formulae describing fixed effect models just like the other methods. For instance, the +#' [bru()] will understand formulae describing fixed effect models just like the other methods. For instance, the #' formula `y ~ x` will fit 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 response `y` with respect to the likelihood family stated when calling [bru()]. Mathematically, #' the linear predictor \eqn{\eta} would be written down as #' #' \deqn{\eta = \beta * x + c,} @@ -152,7 +152,7 @@ ibm_amatrix <- function(mapper, input, ...) { #' \itemize{\item{`components = y ~ psi(x, model = "linear")`.}} #' #' Being able to discriminate between \eqn{x} and \eqn{\psi} is relevant because of two functionalities -#' bru offers. The formula parameters of both, [bru] and the prediction method [predict.bru] +#' 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 #' an analytical combination of the covariate \eqn{x} and the intercept using #' @@ -1666,7 +1666,7 @@ ibm_amatrix.bru_mapper_multi <- function(mapper, input, multi = 0L, ...) { # Combine the matrices (A1, A2, A3) -> rowkron(A3, rowkron(A2, A1)) A_ <- A[[1]] for (k in seq_len(length(mapper[["mappers"]]) - 1)) { - A_ <- INLA::inla.row.kron(A[[k + 1]], A_) + A_ <- row_kron(A[[k + 1]], A_) } return(A_) } diff --git a/R/environment.R b/R/environment.R index 4159cd104..cf15b1f82 100644 --- a/R/environment.R +++ b/R/environment.R @@ -155,7 +155,7 @@ bru_log_message <- function(..., domain = NULL, appendLF = TRUE, #' to run inference.} #' \item{bru_max_iter}{maximum number of inla iterations} #' \item{bru_initial}{An `inla` object returned from previous calls of -#' `INLA::inla`, [bru] or [lgcp], or a list of named vectors of starting +#' `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.} #' \item{bru_int_args}{List of arguments passed all the way to the @@ -334,7 +334,7 @@ bru_options_deprecated <- function(args) { } -#' Additional [bru] options +#' Additional bru options #' #' Construct a `bru_options` object including the default and global options, #' and converting deprecated option names. diff --git a/R/ggplot.R b/R/ggplot.R index b4c6f401f..2687d47ba 100644 --- a/R/ggplot.R +++ b/R/ggplot.R @@ -93,7 +93,7 @@ gg <- function(data, ...) { #' @name gm #' @export #' @param data an object for which to generate a geom. -#' @param ... Arguments passed on to [gg]. +#' @param ... Arguments passed on to [gg()]. #' @return The form of the value returned by gm depends on the class of its argument. See the documentation of the particular methods for details of what is produced by that method. #' @family geomes for inla and inlabru predictions #' @family geomes for spatial data @@ -156,8 +156,8 @@ gg.matrix <- function(data, mapping = NULL, ...) { #' @name gg.data.frame #' @export #' @import ggplot2 -#' @param ... Arguments passed on to [gg.prediction]. -#' @return Concatenation of a [geom_line] value and optionally a [geom_ribbon] value. +#' @param ... Arguments passed on to [gg.prediction()]. +#' @return Concatenation of a `geom_line` value and optionally a `geom_ribbon` value. #' @family geomes for inla and inlabru predictions #' @example inst/examples/gg.prediction.R @@ -171,11 +171,11 @@ gg.data.frame <- function(...) { #' @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 +#' [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 agains the row number of the varriable in the prediction -#' data frame (x-axis) using [geom_line]. In addition, a [geom_ribbon] is used to show +#' data frame (x-axis) using `geom_line`. In addition, a `geom_ribbon` is used to show #' the confidence interval. #' #' Note: `gg.prediction` also understands the format of INLA-style posterior summaries, e.g. @@ -186,13 +186,13 @@ gg.data.frame <- function(...) { #' @export #' @import ggplot2 #' @importFrom utils modifyList -#' @param data A prediction object, usually the result of a [predict.bru] call. -#' @param mapping a set of aesthetic mappings created by [aes] or [aes_]. These are passed on to [geom_line]. +#' @param data A prediction object, usually the result of a [predict.bru()] call. +#' @param mapping a set of aesthetic mappings created by `aes` or `aes_`. These are passed on to [geom_line]. #' @param ribbon If TRUE, plot a ribbon around the line based on the upper and lower 2.5 percent quantiles. #' @param alpha The ribbons numeric alpha level in `[0,1]`. #' @param bar If TRUE plot boxplot-style summary for each variable. -#' @param \dots Arguments passed on to [geom_line]. -#' @return Concatenation of a [geom_line] value and optionally a [geom_ribbon] value. +#' @param \dots Arguments passed on to `geom_line`. +#' @return Concatenation of a `geom_line` value and optionally a `geom_ribbon` value. #' @family geomes for inla and inlabru predictions #' @example inst/examples/gg.prediction.R @@ -745,7 +745,7 @@ gg.RasterLayer <- function(data, mapping = aes_string(x = "x", y = "y", fill = " geom_tile(data = df, mapping = mapping, ...) } -#' Plot method for posterior marginals estimated by [bru] +#' Plot method for posterior marginals estimated by bru #' #' @description #' diff --git a/R/inla.R b/R/inla.R index a52a98e76..977148066 100644 --- a/R/inla.R +++ b/R/inla.R @@ -39,8 +39,8 @@ bru_standardise_names <- function(x) { #' #' @aliases predict.inla #' @export -#' @param object A `bru` object obtained by calling [bru] or [lgcp]. -#' @param ... Arguments passed on to [predict.bru]. +#' @param object A `bru` object obtained by calling [bru()] or [lgcp()]. +#' @param ... Arguments passed on to [predict.bru()]. #' @return A `prediction` object. #' @seealso [predict.inla()] #' @keywords internal diff --git a/R/inlabru.R b/R/inlabru.R index 0922bca65..0f5b80eb3 100644 --- a/R/inlabru.R +++ b/R/inlabru.R @@ -4,14 +4,24 @@ #' #' @details #' -#' `inlabru` facilitates Bayesian spatial modeling using integrated nested Laplace approximations. It -#' is heavily based on R-inla () but adds additional modeling abilities. -#' Tutorials and more information can be found at . +#' `inlabru` facilitates Bayesian spatial modelling using integrated nested +#' Laplace approximations. It is heavily based on R-inla +#' () but adds additional modelling abilities and simplified +#' syntax for (in particular) spatial models. +#' Tutorials and more information can be found at +#' and . +#' The iterative method used for non-linear predictors is documented in the +#' `method` vignette. #' -#' The main function for inference using inlabru is [bru]. For point process inference [lgcp] is -#' a good starting point. The package comes with multiple real world data sets, namely [gorillas], +#' The main function for inference using inlabru is [bru()]. For point process inference [lgcp()] is +#' a good starting point. +#' The general model specification details is documented in [component()] and [like()]. +#' Posterior quantities beyond the basic summaries can be calculated with +#' a `predict()` method, documented in [predict.bru()]. +#' +#' The package comes with multiple real world data sets, namely [gorillas], #' [mexdolphin], [seals]. 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 +#' 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]. #' #' @aliases inlabru @@ -20,5 +30,6 @@ #' @import methods #' @importFrom Matrix diag #' @author Fabian E. Bachl \email{bachlfab@@gmail.com} +#' and Finn Lindgren \email{finn.lindgren@@gmail.com} #' @name inlabru NULL diff --git a/R/model.R b/R/model.R index 65dba3c0e..f65389344 100644 --- a/R/model.R +++ b/R/model.R @@ -107,7 +107,7 @@ bru_model <- function(components, lhoods) { #' Evaluate or sample from a posterior result given a model and locations #' #' @export -#' @param model An [bru] model +#' @param model A [bru] model #' @param state list of lists, as generated by [evaluate_state()] #' @param data A `list`, `data.frame`, or `Spatial*DataFrame`, with coordinates #' and covariates needed to evaluate the predictor. @@ -437,6 +437,56 @@ evaluate_predictor <- function(model, )) names(state_names) <- names(state[[1]]) + # Construct _eval function names + eval_names <- as.list(expand_labels( + intersect(names(state[[1]]), names(model$effects)), + intersect(names(state[[1]]), names(model$effects)), + suffix = "_eval" + )) + names(eval_names) <- intersect(names(state[[1]]), names(model$effects)) + + eval_fun_factory <- + function(.comp, .envir, .enclos) { + .is_offset <- .comp$main$type %in% c("offset") + .mapper <- .comp$mapper + .label <- paste0(.comp$label, "_latent") + eval_fun <- function(main, group = NULL, replicate = NULL, .state = NULL) { + if (is.null(group)) { + group <- rep(1, NROW(main)) + } + if (is.null(replicate)) { + replicate <- rep(1, NROW(main)) + } + .A <- ibm_amatrix( + .mapper, + input = list( + main = main, + group = group, + replicate = replicate + ) + ) + if (.is_offset) { + .values <- .A + } else { + if (is.null(.state)) { + .state <- eval(parse(text = .label), + envir = .envir, + enclos = .enclos) + } + .values <- .A %*% .state + } + + as.matrix(.values) + } + eval_fun + } + for (nm in names(eval_names)) { + assign(eval_names[[nm]], + eval_fun_factory(model$effects[[nm]], .envir = envir, .enclos = enclos), + envir = envir + ) + } + # Remove problematic objects: problems <- c(".Random.seed") remove(list = intersect(names(envir), problems), envir = envir) diff --git a/R/utils.R b/R/utils.R index 66cddd8ca..b5b905afc 100644 --- a/R/utils.R +++ b/R/utils.R @@ -175,20 +175,45 @@ eval_SpatialDF <- function(data, where, layer = NULL, selector = NULL) { } -# Fill in missing values in Spatial grids -# @param data A SpatialPointsDataFrame, SpatialPixelsDataFrame, or a -# SpatialGridDataFrame containg data to use for filling -# @param where A, matrix, data.frame, or SpatialPoints or -# SpatialPointsDataFrame, containing the locations of the evaluated values -# @param values A vector of values to be filled in where `is.na(values)` is -# `FALSE` -# @param layer,selector Specifies what data column or columns from which to -# extract data, see [component()] for details. -# @param batch_size -# @export +#' Fill in missing values in Spatial grids +#' +#' Computes nearest-available-value imputation for missing values in space +#' +#' @param data A SpatialPointsDataFrame, SpatialPixelsDataFrame, or a +#' SpatialGridDataFrame containg data to use for filling +#' @param where A, matrix, data.frame, or SpatialPoints or +#' SpatialPointsDataFrame, containing the locations of the evaluated values +#' @param values A vector of values to be filled in where `is.na(values)` is +#' `TRUE` +#' @param layer,selector Specifies what data column or columns from which to +#' extract data, see [component()] for details. +#' @param batch_size Size of nearest-neighbour calculation blocks, to limit the +#' memory and computational complexity. +#' @return An infilled vector of values +#' @export +#' @examples +#' \dontrun{ +#' 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) +#' +#' } +#' } bru_fill_missing <- function(data, where, values, layer = NULL, selector = NULL, - batch_size = 1000) { + batch_size = 500) { stopifnot(inherits( data, c( @@ -205,8 +230,8 @@ bru_fill_missing <- function(data, where, values, stop(msg) } if (inherits(where, "Spatial")) { - data_crs <- INLA::inla.sp_get_crs(data) - where_crs <- INLA::inla.sp_get_crs(where) + data_crs <- fm_sp_get_crs(data) + where_crs <- fm_sp_get_crs(where) if (!fm_identical_CRS(data_crs, where_crs)) { warning("'data' and 'where' for spatial infilling have different CRS") } @@ -216,7 +241,7 @@ bru_fill_missing <- function(data, where, values, where_crs <- sp::CRS(NA_character_) where_coord <- where } - + if (!is.null(selector)) { selection <- where[[selector]] selector_notok <- is.na(selection) @@ -247,26 +272,25 @@ bru_fill_missing <- function(data, where, values, } return(values) } - + notok <- is.na(values) ok <- which(!notok) notok <- which(notok) data_notok <- is.na(data[[layer]]) data_ok <- which(!data_notok) data_notok <- which(data_notok) - - batch_size <- 200 + for (batch in seq_len(ceiling(length(notok) / batch_size))) { subset <- notok[seq((batch - 1) * batch_size, - min(length(notok), batch * batch_size), - by = 1 + min(length(notok), batch * batch_size), + by = 1 )] dst <- rgeos::gDistance( sp::SpatialPoints(data[data_ok, , drop = FALSE], proj4string = data_crs), sp::SpatialPoints(where_coord[subset, , drop = FALSE], proj4string = where_crs), byid = TRUE ) - + nn <- apply(dst, MARGIN = 1, function(row) which.min(row)[[1]]) values[subset] <- data[[layer]][data_ok[nn]] } @@ -275,7 +299,6 @@ bru_fill_missing <- function(data, where, values, - # Resave data resave_package_data <- function() { name_list <- c("gorillas", "mexdolphin", "mrsea", @@ -315,3 +338,100 @@ resave_package_data <- function() { browser() } } + + +#' Row-wise Kronecker products +#' +#' Takes two Matrices and computes the row-wise Kronecker product. Optionally +#' applies row-wise weights and/or applies an additional 0/1 row-wise Kronecker +#' matrix product. +#' +#' @param M1 A matrix that can be transformed into a sparse Matrix. +#' @param M2 A matrix that can be transformed into a sparse Matrix. +#' @param 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` +#' @param n.repl The maximum replicate index, in the sense used in +#' `INLA::inla.spde.make.A()`. +#' @param weights Optional scaling weights to be applied row-wise to the +#' resulting matrix. +#' @return A `Matrix::sparseMatrix` object. +#' @author Finn Lindgren \email{finn.lindgren@@gmail.com} +#' @export row_kron +row_kron <- function(M1, M2, repl = NULL, n.repl = NULL, weights = NULL) { + M1 <- as(as(as(M1, "CsparseMatrix"), "dgCMatrix"), "dgTMatrix") + M2 <- as(as(as(M2, "CsparseMatrix"), "dgCMatrix"), "dgTMatrix") + n <- nrow(M1) + if (is.null(repl)) { + repl <- rep(1L, n) + } + if (is.null(n.repl)) { + n.repl <- max(repl) + } + if (is.null(weights)) { + weights <- rep(1, n) + } else if (length(weights) == 1L) { + weights <- rep(weights[1], n) + } + + ## TODO: Check robustness for all-zero rows. + ## TODO: Maybe move big sparseMatrix call outside the loop. + ## TODO: Automatically choose M1 or M2 for looping. + + n1 <- (as.vector(Matrix::sparseMatrix( + i = 1L + M1@i, j = rep(1L, length(M1@i)), + x = 1L, dims = c(n, 1) + ))) + n2 <- (as.vector(Matrix::sparseMatrix( + i = 1L + M2@i, j = rep(1L, length(M2@i)), + x = 1L, dims = c(n, 1) + ))) + + M <- (Matrix::sparseMatrix( + i = integer(0), j = integer(0), x = numeric(0), + dims = c(n, ncol(M2) * ncol(M1) * n.repl) + )) + n1 <- n1[1L + M1@i] + for (k in unique(n1)) { + sub <- which(n1 == k) + n.sub <- length(sub) + + i.sub <- 1L + M1@i[sub] + j.sub <- 1L + M1@j[sub] + o1 <- order(i.sub, j.sub) + jj <- rep(seq_len(k), times = n.sub / k) + i.sub <- i.sub[o1] + j.sub <- (Matrix::sparseMatrix( + i = i.sub, + j = jj, + x = j.sub[o1], + dims = c(n, k) + )) + x.sub <- (Matrix::sparseMatrix( + i = i.sub, + j = jj, + x = weights[i.sub] * M1@x[sub][o1], + dims = c(n, k) + )) + sub2 <- which(is.element(1L + M2@i, i.sub)) + + if (length(sub2) > 0) { + i <- 1L + M2@i[sub2] + ii <- rep(i, times = k) + repl.i <- repl[ii] + + M <- (M + + Matrix::sparseMatrix( + i = ii, + j = (1L + rep(M2@j[sub2], times = k) + + ncol(M2) * (as.vector(j.sub[i, ]) - 1L) + + ncol(M2) * ncol(M1) * (repl.i - 1L)), + x = (rep(M2@x[sub2], times = k) * + as.vector(x.sub[i, ])), + dims = c(n, ncol(M2) * ncol(M1) * n.repl) + )) + } + } + + return(M) +} diff --git a/README.Rmd b/README.Rmd index a83d7d188..abf5fd439 100644 --- a/README.Rmd +++ b/README.Rmd @@ -29,7 +29,8 @@ Fabian E. Bachl, Finn Lindgren, David L. Borchers, and Janine B. Illian (2019), spatial modelling from ecological survey data, Methods in Ecology and Evolution, British Ecological Society, 10, 760--766, [doi:10.1111/2041-210X.13168](https://doi.org/10.1111/2041-210X.13168), and `citation("inlabru")`. -The [inlabru.org](http://inlabru.org) website has links to old tutorials with code examples for versions up to 2.1.13. Updated version of these tutorials, as well as new examples, can currently be found under Articles on the [https://inlabru-org.github.io/inlabru/](https://inlabru-org.github.io/inlabru/) website. +The [inlabru.org](http://inlabru.org) website has links to old tutorials with code examples for versions up to 2.1.13. +For later versions, updated versions of these tutorials, as well as new examples, can be found at [https://inlabru-org.github.io/inlabru/articles/](https://inlabru-org.github.io/inlabru/articles/) ## Installation diff --git a/README.md b/README.md index 788a20f64..c4c888873 100644 --- a/README.md +++ b/README.md @@ -28,9 +28,9 @@ Methods in Ecology and Evolution, British Ecological Society, 10, and `citation("inlabru")`. The [inlabru.org](http://inlabru.org) website has links to old tutorials -with code examples for versions up to 2.1.13. Updated version of these -tutorials, as well as new examples, can currently be found under -Articles on the website. +with code examples for versions up to 2.1.13. For later versions, +updated versions of these tutorials, as well as new examples, can be +found at ## Installation @@ -70,12 +70,12 @@ library(inlabru) #> Loading required package: sp library(INLA) #> Loading required package: Matrix -#> Loading required package: parallel #> Loading required package: foreach -#> This is INLA_21.01.26 built 2021-02-16 18:31:08 UTC. +#> Loading required package: parallel +#> This is INLA_21.02.23 built 2021-02-23 20:58:45 UTC. #> - See www.r-inla.org/contact-us for how to get help. #> - To enable PARDISO sparse library; see inla.pardiso() -#> - Save 274Mb of storage running 'inla.prune()' +#> - Save 273.9Mb of storage running 'inla.prune()' library(ggplot2) # Load the data diff --git a/cran-comments.md b/cran-comments.md index 856641e52..962b3589c 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -1,19 +1,14 @@ ## Test environments -* ubuntu 18.04 (local), R release (3.5.1) -* ubuntu 18.04 (local), R devel (2018-07-11) -* ubuntu 18.04 (local), R 3.4.4 -* ubuntu 14.04 (on travis-ci), R 3.5.0 -* TODO: win-builder (devel and release) - -On the local installs, --run-donttest was activated to also test -long running examples and tests, with INLA 18.07.12 installed. +* local R installation, R 4.0.3 +* windows (on github actions), R 4.0.4 +* macOS (on github actions), R 4.0.4 +* ubuntu 20.04 (on github actions), R 4.0.4 +* ubuntu 20.04 (on github actions), R 4.0.3 +* ubuntu 20.04 (on github actions), R devel +* win-builder (devel) ## R CMD check results -0 errors | 0 warnings | 0 notes +0 errors | 0 warnings | 1 note -This is a bugfix release. - - * Corrected INLA repository URL - * Namespace corrections and documentation updates - * Computational method robustification +* This is a new release. diff --git a/man/bincount.Rd b/man/bincount.Rd index 7962fc438..25f865218 100644 --- a/man/bincount.Rd +++ b/man/bincount.Rd @@ -15,9 +15,9 @@ bincount( ) } \arguments{ -\item{result}{A result object from a \link{bru} or \link{lgcp} call} +\item{result}{A result object from a \code{\link[=bru]{bru()}} or \code{\link[=lgcp]{lgcp()}} call} -\item{predictor}{A formula describing the prediction of a 1D LGCP via \link{predict}.} +\item{predictor}{A formula describing the prediction of a 1D LGCP via \code{\link[=predict]{predict()}}.} \item{observations}{A vector of observed values} @@ -27,7 +27,7 @@ bincount( \item{probs}{numeric vector of probabilities with values in \verb{[0,1]}} -\item{\dots}{arguments passed on to \link{predict.bru}} +\item{\dots}{arguments passed on to \code{\link[=predict.bru]{predict.bru()}}} } \value{ An \code{data.frame} with a ggplot attribute \code{ggp} diff --git a/man/bru.Rd b/man/bru.Rd index 9ef0a3bf4..8731df51f 100644 --- a/man/bru.Rd +++ b/man/bru.Rd @@ -10,9 +10,9 @@ bru(components = ~Intercept(1), ..., options = list()) bru_rerun(result, options = list()) } \arguments{ -\item{components}{A \link{formula}-like specification of latent components. +\item{components}{A \code{formula}-like specification of latent components. Also used to define a default linear additive predictor. See -\link{component} for details.} +\code{\link[=component]{component()}} for details.} \item{...}{Likelihoods, each constructed by a calling \code{\link[=like]{like()}}, or named parameters that can be passed to a single \code{\link[=like]{like()}} call.} diff --git a/man/bru_call_options.Rd b/man/bru_call_options.Rd index 2ae1d8278..fe1dbe2bd 100644 --- a/man/bru_call_options.Rd +++ b/man/bru_call_options.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/environment.R \name{bru_call_options} \alias{bru_call_options} -\title{Additional \link{bru} options} +\title{Additional bru options} \usage{ bru_call_options(...) } diff --git a/man/bru_fill_missing.Rd b/man/bru_fill_missing.Rd new file mode 100644 index 000000000..0172d82df --- /dev/null +++ b/man/bru_fill_missing.Rd @@ -0,0 +1,58 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/utils.R +\name{bru_fill_missing} +\alias{bru_fill_missing} +\title{Fill in missing values in Spatial grids} +\usage{ +bru_fill_missing( + data, + where, + values, + layer = NULL, + selector = NULL, + batch_size = 500 +) +} +\arguments{ +\item{data}{A SpatialPointsDataFrame, SpatialPixelsDataFrame, or a +SpatialGridDataFrame containg data to use for filling} + +\item{where}{A, matrix, data.frame, or SpatialPoints or +SpatialPointsDataFrame, containing the locations of the evaluated values} + +\item{values}{A vector of values to be filled in where \code{is.na(values)} is +\code{TRUE}} + +\item{layer, selector}{Specifies what data column or columns from which to +extract data, see \code{\link[=component]{component()}} for details.} + +\item{batch_size}{Size of nearest-neighbour calculation blocks, to limit the +memory and computational complexity.} +} +\value{ +An infilled vector of values +} +\description{ +Computes nearest-available-value imputation for missing values in space +} +\examples{ +\dontrun{ +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) + +} +} +} diff --git a/man/bru_options.Rd b/man/bru_options.Rd index 8a17f7046..bcba36335 100644 --- a/man/bru_options.Rd +++ b/man/bru_options.Rd @@ -101,7 +101,7 @@ log messages of verbosity \eqn{\le} are stored. Default: Inf, to store all messa to run inference.} \item{bru_max_iter}{maximum number of inla iterations} \item{bru_initial}{An \code{inla} object returned from previous calls of -\code{INLA::inla}, \link{bru} or \link{lgcp}, or a list of named vectors of starting +\code{INLA::inla}, \code{\link[=bru]{bru()}} or \code{\link[=lgcp]{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.} \item{bru_int_args}{List of arguments passed all the way to the diff --git a/man/component.Rd b/man/component.Rd index d828e3634..42fc480e8 100644 --- a/man/component.Rd +++ b/man/component.Rd @@ -99,7 +99,7 @@ Likely doesn't work at the moment, and I've found no examples that use it.} \item{envir_extra}{TODO: check/fix this parameter.} } \description{ -Similar to \code{glm()}, \code{gam()} and \code{inla()}, \link{bru} models can be constructed via +Similar to \code{glm()}, \code{gam()} and \code{inla()}, \code{\link[=bru]{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 \code{INLA::inla}, \code{bru} components offer additional functionality which facilitates modelling, and @@ -116,9 +116,9 @@ formula expression that can be interpreted by the \code{\link[=component_list.fo method, called inside \code{\link[=bru]{bru()}}. } \details{ -\link{bru} will understand formulae describing fixed effect models just like the other methods. For instance, the +\code{\link[=bru]{bru()}} will understand formulae describing fixed effect models just like the other methods. For instance, the formula \code{y ~ x} will fit the linear combination of an effect named \code{x} and an intercept to -the response \code{y} with respect to the likelihood family stated when calling \link{bru}. Mathematically, +the response \code{y} with respect to the likelihood family stated when calling \code{\link[=bru]{bru()}}. Mathematically, the linear predictor \eqn{\eta} would be written down as \deqn{\eta = \beta * x + c,} @@ -162,7 +162,7 @@ with an arbitrary name that we wish to assign to the effect, e.g. \itemize{\item{\code{components = y ~ psi(x, model = "linear")}.}} Being able to discriminate between \eqn{x} and \eqn{\psi} is relevant because of two functionalities -bru offers. The formula parameters of both, \link{bru} and the prediction method \link{predict.bru} +bru offers. The formula parameters of both, \code{\link[=bru]{bru()}} and the prediction method \link{predict.bru} are interpreted in the mathematical sense. For instance, \code{predict} may be used to analyze the an analytical combination of the covariate \eqn{x} and the intercept using diff --git a/man/deltaIC.Rd b/man/deltaIC.Rd index 611abfbc7..5970fd773 100644 --- a/man/deltaIC.Rd +++ b/man/deltaIC.Rd @@ -7,7 +7,8 @@ deltaIC(..., criterion = "DIC") } \arguments{ -\item{...}{Comma-separated objects inheriting from class \code{inla} and obtained from a run of \link[INLA:inla]{inla}, \link{bru} or \link{lgcp}} +\item{...}{Comma-separated objects inheriting from class \code{inla} and obtained +from a run of \code{INLA::inla()}, \code{\link[=bru]{bru()}} or \code{\link[=lgcp]{lgcp()}}} \item{criterion}{If 'DIC', plots DIC differences; If 'WAIC', plots WAIC differences.} } diff --git a/man/evaluate_model.Rd b/man/evaluate_model.Rd index 8b546bb1d..7337b27d0 100644 --- a/man/evaluate_model.Rd +++ b/man/evaluate_model.Rd @@ -29,7 +29,7 @@ evaluate_state( ) } \arguments{ -\item{model}{An \link{bru} model} +\item{model}{A \link{bru} model} \item{state}{list of lists, as generated by \code{\link[=evaluate_state]{evaluate_state()}}} diff --git a/man/figures/README-example-1.png b/man/figures/README-example-1.png index fab01a5a3..585330c83 100644 Binary files a/man/figures/README-example-1.png and b/man/figures/README-example-1.png differ diff --git a/man/generate.Rd b/man/generate.Rd index fffc79aaa..49537d869 100644 --- a/man/generate.Rd +++ b/man/generate.Rd @@ -20,7 +20,7 @@ generate(object, ...) ) } \arguments{ -\item{object}{A \code{bru} object obtained by calling \link{bru}.} +\item{object}{A \code{bru} object obtained by calling \code{\link[=bru]{bru()}}.} \item{...}{additional, unused arguments.} @@ -29,7 +29,12 @@ sampling.} \item{formula}{A formula defining an R expression to evaluate for each generated sample. If \code{NULL}, the latent and hyperparameter states are returned -as named list elements.} +as named list elements. In addition to the component names (that give the effect +of each component evaluated for the input data), the suffix \verb{_latent} can be used +to directly access the latent state for a component, and the suffix \verb{_eval} +can be used to evaluate a component at other input values than the expressions +defined in the component definition itself, e.g. \code{field_eval(cbind(x,y))} for a +component defined with \code{field(coordinates, ...)}.} \item{n.samples}{Integer setting the number of samples to draw in order to calculate the posterior statistics. @@ -61,7 +66,7 @@ List of generated samples Generic function for sampling for fitted models. The function invokes particular methods which depend on the class of the first argument. -Takes a fitted \code{bru} object produced by the function \url{bru} and produces +Takes a fitted \code{bru} object produced by the function \code{\link[=bru]{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 diff --git a/man/gg.data.frame.Rd b/man/gg.data.frame.Rd index 543a2ded9..95b1587e5 100644 --- a/man/gg.data.frame.Rd +++ b/man/gg.data.frame.Rd @@ -7,10 +7,10 @@ \method{gg}{data.frame}(...) } \arguments{ -\item{...}{Arguments passed on to \link{gg.prediction}.} +\item{...}{Arguments passed on to \code{\link[=gg.prediction]{gg.prediction()}}.} } \value{ -Concatenation of a \link{geom_line} value and optionally a \link{geom_ribbon} value. +Concatenation of a \code{geom_line} value and optionally a \code{geom_ribbon} value. } \description{ This geom constructor will simply call \link{gg.prediction} for the data provided. diff --git a/man/gg.prediction.Rd b/man/gg.prediction.Rd index ee5b7083b..fe9790dfb 100644 --- a/man/gg.prediction.Rd +++ b/man/gg.prediction.Rd @@ -7,9 +7,9 @@ \method{gg}{prediction}(data, mapping = NULL, ribbon = TRUE, alpha = 0.3, bar = FALSE, ...) } \arguments{ -\item{data}{A prediction object, usually the result of a \link{predict.bru} call.} +\item{data}{A prediction object, usually the result of a \code{\link[=predict.bru]{predict.bru()}} call.} -\item{mapping}{a set of aesthetic mappings created by \link{aes} or \link{aes_}. These are passed on to \link{geom_line}.} +\item{mapping}{a set of aesthetic mappings created by \code{aes} or \code{aes_}. These are passed on to \link{geom_line}.} \item{ribbon}{If TRUE, plot a ribbon around the line based on the upper and lower 2.5 percent quantiles.} @@ -17,18 +17,18 @@ \item{bar}{If TRUE plot boxplot-style summary for each variable.} -\item{\dots}{Arguments passed on to \link{geom_line}.} +\item{\dots}{Arguments passed on to \code{geom_line}.} } \value{ -Concatenation of a \link{geom_line} value and optionally a \link{geom_ribbon} value. +Concatenation of a \code{geom_line} value and optionally a \code{geom_ribbon} value. } \description{ This geom serves to visualize \code{prediction} objects which usually results from a call to -\link{predict.bru}. Predictions objects provide summary statistics (mean, median, sd, ...) for +\code{\link[=predict.bru]{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 \code{bar = TRUE}), a boxplot-style geom is constructed to show the statistics. For multivariate predictions the mean of each variable (y-axis) is plotted agains the row number of the varriable in the prediction -data frame (x-axis) using \link{geom_line}. In addition, a \link{geom_ribbon} is used to show +data frame (x-axis) using \code{geom_line}. In addition, a \code{geom_ribbon} is used to show the confidence interval. Note: \code{gg.prediction} also understands the format of INLA-style posterior summaries, e.g. diff --git a/man/gm.Rd b/man/gm.Rd index 5e9cd5558..21a0abc88 100644 --- a/man/gm.Rd +++ b/man/gm.Rd @@ -9,7 +9,7 @@ gm(data, ...) \arguments{ \item{data}{an object for which to generate a geom.} -\item{...}{Arguments passed on to \link{gg}.} +\item{...}{Arguments passed on to \code{\link[=gg]{gg()}}.} } \value{ The form of the value returned by gm depends on the class of its argument. See the documentation of the particular methods for details of what is produced by that method. diff --git a/man/inlabru.Rd b/man/inlabru.Rd index 4a7886d24..53ed13c17 100644 --- a/man/inlabru.Rd +++ b/man/inlabru.Rd @@ -7,16 +7,27 @@ Convenient model fitting using (iterated) INLA. } \details{ -\code{inlabru} facilitates Bayesian spatial modeling using integrated nested Laplace approximations. It -is heavily based on R-inla (\url{https://www.r-inla.org}) but adds additional modeling abilities. -Tutorials and more information can be found at \url{http://www.inlabru.org/}. +\code{inlabru} facilitates Bayesian spatial modelling using integrated nested +Laplace approximations. It is heavily based on R-inla +(\url{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 +\url{https://inlabru-org.github.io/inlabru/} and \url{http://www.inlabru.org/}. +The iterative method used for non-linear predictors is documented in the +\code{method} vignette. -The main function for inference using inlabru is \link{bru}. For point process inference \link{lgcp} is -a good starting point. The package comes with multiple real world data sets, namely \link{gorillas}, +The main function for inference using inlabru is \code{\link[=bru]{bru()}}. For point process inference \code{\link[=lgcp]{lgcp()}} is +a good starting point. +The general model specification details is documented in \code{\link[=component]{component()}} and \code{\link[=like]{like()}}. +Posterior quantities beyond the basic summaries can be calculated with +a \code{predict()} method, documented in \code{\link[=predict.bru]{predict.bru()}}. + +The package comes with multiple real world data sets, namely \link{gorillas}, \link{mexdolphin}, \link{seals}. Plotting these data sets is straight forward using inlabru's extensions -to \code{ggplot2}, e.g. the \link{gg} function. For educational purposes some simulated data sets are available +to \code{ggplot2}, e.g. the \code{\link[=gg]{gg()}} function. For educational purposes some simulated data sets are available as well, e.g. \link{Poisson1_1D}, \link{Poisson2_1D}, \link{Poisson2_1D} and \link{toygroups}. } \author{ Fabian E. Bachl \email{bachlfab@gmail.com} +and Finn Lindgren \email{finn.lindgren@gmail.com} } diff --git a/man/lgcp.Rd b/man/lgcp.Rd index bcb7d42a8..340bb5c8d 100644 --- a/man/lgcp.Rd +++ b/man/lgcp.Rd @@ -37,7 +37,7 @@ approximation of the posterior.} \item{options}{See \code{\link[=bru_options_set]{bru_options_set()}}} } \value{ -An \link{bru} object +An \code{\link[=bru]{bru()}} object } \description{ This function performs inference on a LGCP observed via points residing diff --git a/man/like.Rd b/man/like.Rd index aa240f274..a59b8b531 100644 --- a/man/like.Rd +++ b/man/like.Rd @@ -6,7 +6,7 @@ \alias{like_list.list} \alias{like_list.bru_like} \alias{[.bru_like_list} -\title{Likelihood construction for usage with \link{bru}} +\title{Likelihood construction for usage with \code{\link[=bru]{bru()}}} \usage{ like( formula = . ~ ., @@ -34,7 +34,7 @@ like_list(...) \method{[}{bru_like_list}(x, i) } \arguments{ -\item{formula}{a \link{formula} where the right hand side is a general R +\item{formula}{a \code{formula} where the right hand side is a general R expression defines the predictor used in the model.} \item{family}{A string identifying a valid \code{INLA::inla} likelihood family. @@ -76,7 +76,11 @@ as determined by the \code{include} parameter; Default: NULL (do not remove any components from the inclusion list)} \item{allow_latent}{logical. If \code{TRUE}, the latent state of each component is -directly available to the predictor expression, with a \verb{_latent} suffix.} +directly available to the predictor expression, with a \verb{_latent} suffix. +This also makes evaluator functions with suffix \verb{_eval} available, taking +parameters \code{main}, \code{group}, and \code{replicate}, taking values for where to +evaluate the component effect that are different than those defined in the +component definition itself.} \item{allow_combine}{logical; If \code{TRUE}, the predictor expression may involve several rows of the input data to influence the same row. @@ -96,10 +100,10 @@ on to \code{\link[=bru_options]{bru_options()}}} \item{i}{indices specifying elements to extract} } \value{ -A likelihood configuration which can be used to parameterize \link{bru}. +A likelihood configuration which can be used to parameterize \code{\link[=bru]{bru()}}. } \description{ -Likelihood construction for usage with \link{bru} +Likelihood construction for usage with \code{\link[=bru]{bru()}} } \details{ \itemize{ diff --git a/man/plot.bru.Rd b/man/plot.bru.Rd index b05315fc2..5f8ae0fc9 100644 --- a/man/plot.bru.Rd +++ b/man/plot.bru.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/ggplot.R \name{plot.bru} \alias{plot.bru} -\title{Plot method for posterior marginals estimated by \link{bru}} +\title{Plot method for posterior marginals estimated by bru} \usage{ \method{plot}{bru}(x, ...) } diff --git a/man/predict.bru.Rd b/man/predict.bru.Rd index 7a1bb7b2f..531335d1f 100644 --- a/man/predict.bru.Rd +++ b/man/predict.bru.Rd @@ -18,14 +18,19 @@ ) } \arguments{ -\item{object}{An object obtained by calling \link{bru} or \link{lgcp}.} +\item{object}{An object obtained by calling \code{\link[=bru]{bru()}} or \code{\link[=lgcp]{lgcp()}}.} \item{data}{A data.frame or SpatialPointsDataFrame of covariates needed for the prediction.} \item{formula}{A formula defining an R expression to evaluate for each generated sample. If \code{NULL}, the latent and hyperparameter states are generated -as named list elements.} +as named list elements. In addition to the component names (that give the effect +of each component evaluated for the input data), the suffix \verb{_latent} can be used +to directly access the latent state for a component, and the suffix \verb{_eval} +can be used to evaluate a component at other input values than the expressions +defined in the component definition itself, e.g. \code{field_eval(cbind(x,y))} for a +component defined with \code{field(coordinates, ...)}.} \item{n.samples}{Integer setting the number of samples to draw in order to calculate the posterior statistics. The default is rather low but provides @@ -57,7 +62,7 @@ a data.frame or Spatial* object with predicted mean values and other summary statistics attached. } \description{ -Takes a fitted \code{bru} object produced by the function \url{bru} and produces +Takes a fitted \code{bru} object produced by the function \code{\link[=bru]{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 diff --git a/man/row_kron.Rd b/man/row_kron.Rd new file mode 100644 index 000000000..5cba2948f --- /dev/null +++ b/man/row_kron.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/utils.R +\name{row_kron} +\alias{row_kron} +\title{Row-wise Kronecker products} +\usage{ +row_kron(M1, M2, repl = NULL, n.repl = NULL, weights = NULL) +} +\arguments{ +\item{M1}{A matrix that can be transformed into a sparse Matrix.} + +\item{M2}{A matrix that can be transformed into a sparse Matrix.} + +\item{repl}{An optional index vector. For each entry, specifies which +replicate the row belongs to, in the sense used in +\code{INLA::inla.spde.make.A}} + +\item{n.repl}{The maximum replicate index, in the sense used in +\code{INLA::inla.spde.make.A()}.} + +\item{weights}{Optional scaling weights to be applied row-wise to the +resulting matrix.} +} +\value{ +A \code{Matrix::sparseMatrix} object. +} +\description{ +Takes two Matrices and computes the row-wise Kronecker product. Optionally +applies row-wise weights and/or applies an additional 0/1 row-wise Kronecker +matrix product. +} +\author{ +Finn Lindgren \email{finn.lindgren@gmail.com} +} diff --git a/tests/testthat/test_component.R b/tests/testthat/test_component.R index c33e29117..68f9d826f 100644 --- a/tests/testthat/test_component.R +++ b/tests/testthat/test_component.R @@ -80,6 +80,9 @@ test_that("Component construction: offset", { test_that("Component construction: default mesh/mapping construction", { + skip_on_cran() + local_bru_safe_inla() + lik <- like("gaussian", formula = y ~ ., data = data.frame(x = c(1, 1.5, 2, 3, 4), y = 11:15), diff --git a/tests/testthat/test_latent_spde2D.R b/tests/testthat/test_latent_spde2D.R index badcc2d06..2b77d2656 100644 --- a/tests/testthat/test_latent_spde2D.R +++ b/tests/testthat/test_latent_spde2D.R @@ -194,7 +194,7 @@ test_that("Latent models: SPDE with group parameter (spatiotemporal)", { # Check SPDE expect_equal( data_$fit$summary.random$mySmooth$mean[c(1, 250, 550)], - c(-0.1739665, 0.9392643, 2.2423229), + c(-0.1618776, 0.7721959, 2.0314753), tolerance = midtol ) expect_equal( diff --git a/tests/testthat/test_predict.R b/tests/testthat/test_predict.R index aa48b5dda..c7b308eba 100644 --- a/tests/testthat/test_predict.R +++ b/tests/testthat/test_predict.R @@ -79,4 +79,25 @@ test_that("bru: factor component", { expect_equal(is.matrix(xipost), TRUE) expect_equal(rownames(xipost), c("Intercept", "x")) + + + # Evaluate effect with _eval feature + + xpost4 <- predict( + fit, + data = NULL, + formula = ~ z_eval((1:10)/2), + n.samples = 5, + seed = 12345L + ) + + xpost4 <- predict( + fit, + data = NULL, + formula = ~ x_eval(1:10), + n.samples = 5, + seed = 12345L + ) + + })