content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' Sample Function for GP-based SVC Model for Given Locations
#'
#' @description Samples SVC data at given locations. The SVCs parameters and the
#' covariance function have to be provided. The sampled model matrix can be
#' provided or it is sampled. The SVCs are sampled according to their given parametrization and at
#' respective observation locations. The error vector is sampled from a nugget
#' effect. Finally, the response vector is computed. Please note that the
#' function is not optimized for sampling large data sets.
#'
#' @param df.pars (\code{data.frame(p, 3)}) \cr
#' Contains the mean and covariance parameters of SVCs. The three columns
#' must have the names \code{"mean"}, \code{"var"}, and \code{"scale"}.
#' @param nugget.sd (\code{numeric(1)}) \cr
#' Standard deviation of the nugget / error term.
#' @param cov.name (\code{character}(1)) \cr
#' Character defining the covariance function, c.f. \code{\link{SVC_mle_control}}.
#' @param locs (\code{numeric(n)} or \code{matrix(n, d)}) \cr
#' The numeric vector or matrix contains the observation locations and
#' therefore defines the number of observations to be \code{n}. For a vector,
#' we assume locations on the real line, i.e., \eqn{d=1}.
#' @param X (\code{NULL} or \code{matrix(n, p)}) \cr
#' If \code{NULL}, the covariates are sampled, where the first column contains
#' only ones to model an intercept and further columns are sampled from a
#' standard normal. If it is provided as a \code{matrix}, then the dimensions
#' must match the number of locations in \code{locs} (\code{n}) and the number of SVCs
#' defined by the number of rows in \code{df.pars} (\code{p}).
#'
#' @return \code{list} \cr
#' Returns a list with the response \code{y}, model matrix
#' \code{X}, a matrix \code{beta} containing the sampled SVC at given
#' locations, a vector \code{eps} containing the error, and a matrix
#' \code{locs} containing the original locations. The \code{true_pars}
#' contains the data frame of covariance parameters that were used to
#' sample the GP-based SVCs. The nugget variance has been added to the
#' original argument of the function with its respective variance, but
#' \code{NA} for \code{"mean"} and \code{"scale"}.
#'
#' @details The parameters of the model can be chosen such that we obtain data
#' from a not full model, i.e., not all covariates are associated with a
#' fixed and a random effect. Using \code{var = 0} for instance yields a
#' constant beta coefficient for respective covariate. Note that in that
#' case the \code{scale} value is neglected.
#'
#' @examples
#' set.seed(123)
#' # SVC parameters
#' (df.pars <- data.frame(
#' var = c(2, 1),
#' scale = c(3, 1),
#' mean = c(1, 2)))
#' # nugget standard deviation
#' tau <- 0.5
#'
#' # sample locations
#' s <- sort(runif(500, min = 0, max = 10))
#' SVCdata <- sample_SVCdata(
#' df.pars = df.pars, nugget.sd = tau, locs = s, cov.name = "mat32"
#' )
#' @importFrom spam rmvnorm cov.exp cov.mat cov.sph cov.wend1 cov.wend2
#' @importFrom stats rnorm
#' @export
sample_SVCdata <- function(
df.pars, nugget.sd, locs,
cov.name = c("exp", "sph", "mat32", "mat52", "wend1", "wend2"),
X = NULL
) {
# transform to matrix for further computations
if (is.vector(locs)) {
locs <- matrix(locs, ncol = 1)
}
# check covariance parameters and locations
stopifnot(
is.data.frame(df.pars),
all(df.pars$var >= 0),
all(df.pars$scale > 0),
nugget.sd > 0,
is.matrix(locs)
)
# dimensions
d <- dim(locs)[2]
n <- dim(locs)[1]
p <- nrow(df.pars)
## build SVC models depending on covariance function, i.e., Sigma_y
D <- as.matrix(dist(locs, diag = TRUE, upper = TRUE))
## covariance functions
cov_fun <- function(theta) {
do.call(
what = MLE.cov.func(cov.name),
args = list(h = D, theta = theta)
)
}
## sample SVCs (including mean effect)
beta <- apply(df.pars, 1, function(x) {
if (x["var"] == 0) {
rep(x["mean"], n)
} else {
spam::rmvnorm(
n = 1,
mu = rep(x["mean"], n),
Sigma = cov_fun(theta = x[c("scale", "var")])
)
}
})
# nugget
eps <- rnorm(n, sd = nugget.sd)
# data
if (is.null(X)) {
X <- cbind(1, matrix(rnorm(n*(p-1)), ncol = p-1))
} else {
stopifnot(
is.matrix(X),
dim(X)[1] == n,
dim(X)[2] == p
)
}
y <- apply(beta*X, 1, sum) + eps
list(
y = y, X = X, beta = beta, eps = eps, locs = locs,
true_pars = rbind(
df.pars,
data.frame(
var = nugget.sd^2,
scale = NA, mean = NA
)
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/example.R
|
#' @title Extact Model Fitted Values
#'
#' @description Method to extract the fitted values from an \code{\link{SVC_mle}} object. This is only possible if \code{save.fitted} was set to \code{TRUE} in the control of the function call
#'
#' @param object \code{\link{SVC_mle}} object
#' @param ... further arguments
#'
#' @return Data frame, fitted values to given data, i.e., the SVC as well as the response and their locations
#'
#' @author Jakob Dambon
#'
#' @importFrom stats fitted
#' @export
fitted.SVC_mle <- function(object, ...) {
stopifnot(!is.null(object$fitted))
return(object$fitted)
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/fitted-SVC_mle.R
|
#' @title Extact the Likelihood
#'
#' @description Method to extract the computed (penalized) log (profile) Likelihood from an \code{\link{SVC_mle}} object.
#'
#' @param object \code{\link{SVC_mle}} object
#' @param ... further arguments
#'
#' @return an object of class \code{logLik} with attributes
#' \itemize{
#' \item \code{"penalized"}, logical, if the likelihood (\code{FALSE}) or some penalized likelihood (\code{TRUE}) was optimized.
#' \item \code{"profileLik"}, logical, if the optimization was done using the profile likelihood (\code{TRUE}) or not.
#' \item \code{"nobs"}, integer of number of observations
#' \item \code{"df"}, integer of how many parameters were estimated. \strong{Note}: This includes only the covariance parameters if the profile likelihood was used.
#' }
#'
#' @author Jakob Dambon
#'
#' @importFrom stats logLik
#' @export
logLik.SVC_mle <- function(object, ...) {
profLik <- object$MLE$call.args$control$profileLik
# we transform from neg2LL to LL
val <- (-1/2) * as.numeric(object$MLE$optim.output$value)
attr(val, "penalized") <- (!is.null(object$MLE$call.args$control$pc.prior))
attr(val, "profileLik") <- profLik
attr(val, "nobs") <- nobs(object)
attr(val, "df") <- object$df$df
class(val) <- "logLik"
val
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/logLik-SVC_mle.R
|
#' @title Extract Number of Unique Locations
#'
#' @description Function to extract the number of unique locations in the data
#' set used in an MLE of the \code{\link{SVC_mle}} object.
#'
#' @param object \code{\link{SVC_mle}} object
#'
#' @return integer with the number of unique locations
#'
#' @author Jakob Dambon
#'
#'
#' @export
nlocs <- function(object) {
nrow(unique(object$MLE$call.args$locs))
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/nlocs.R
|
#' @title Extract Number of Observations
#'
#' @description Method to extract the number of observations used in MLE for an \code{\link{SVC_mle}} object.
#'
#' @param object \code{\link{SVC_mle}} object
#' @param ... further arguments
#'
#' @return an integer of number of observations
#'
#' @author Jakob Dambon
#'
#' @importFrom stats nobs
#' @export
nobs.SVC_mle <- function(object, ...) {
length(object$data$y)
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/nobs-SVC_mle.R
|
# holds objective functions to be optimized, i.e. negative log-likelihood of SVC-Models
#' @importFrom spam chol.spam forwardsolve
n2LL <- function(
x, cov_func, outer.W, y, X, W,
mean.est = NULL,
taper = NULL,
pc.dens = NULL,
Rstruct = NULL,
profile = TRUE
) {
q <- dim(W)[2]
p <- dim(X)[2]
n <- length(y)
# compute covariance matrices
Sigma <- Sigma_y(x[1:(2*q+1)], cov_func, outer.W, taper = taper)
# calculate Cholesky-Decompisition
# powerboost function
# spam pivot check
if (is.spam(Sigma)) {
cholS <- spam::chol.spam(Sigma, Rstruct = Rstruct)
} else {
cholS <- chol(Sigma)
}
## profile LL
mu <- if (profile) {
# compute mu(theta)...
if (is.null(mean.est)) {
# ...using GLS
GLS_chol(cholS, X, y)
} else {
# ...or set by some constant
mean.est
}
} else {
# given directly by objective parameters
x[1 + 2*q + 1:p]
}
res <- y - X %*% mu
## quadratic form of residual, i.e., t(res) %*% Sigma^-1 %*% res
quad_res <- if (is.matrix(cholS)) {
as.numeric(crossprod(solve(t(cholS), res)))
} else {
as.numeric(crossprod(spam::forwardsolve(cholS, res,
transpose = TRUE,
upper.tri = TRUE)))
}
# n2LL as stated in paper Dambon et al. (2020) does not contain the
# summand n*log(2 * pi), but it is needed to compute the actual LL
return(n * log(2 * pi) +
2 * c(determinant(cholS)$modulus) +
quad_res +
pc_penalty(x, q, pc.dens))
}
#
# n2LL <- function(x, cov_func, outer.W, y, X, W,
# taper = NULL, pc.dens = NULL, Rstruct = NULL) {
#
#
# pW <- ncol(W)
# pX <- ncol(X)
# n <- length(y)
#
# # compute covariance matrices
# Sigma <- Sigma_y(x, cov_func, outer.W, taper = taper)
#
#
# if (is.spam(Sigma)) {
# cholS <- spam::chol.spam(Sigma, Rstruct = Rstruct)
# } else {
# cholS <- chol(Sigma)
# }
#
# # calculate Cholesky-Decompisition
# cholS <- spam::chol.spam(Sigma, Rstruct = Rstruct)
#
# # get mu
# mu <- x[1 + 2*pW + 1:pX]
#
# res <- y - X %*% mu
#
#
# quad_res <- if (is.matrix(cholS)) {
# as.numeric(crossprod(solve(t(cholS), res)))
# } else {
# as.numeric(crossprod(spam::forwardsolve(cholS, res,
# transpose = TRUE,
# upper.tri = TRUE)))
# }
#
#
# # n2LL as stated in paper Dambon et al. (2020) does not contain the
# # summand n*log(2 * pi), but it is needed to compute the actual LL
# return(n * log(2 * pi) +
# 2 * c(determinant(cholS)$modulus) +
# quad_res +
# pc_penalty(x, pW, pc.dens))
# }
pc_penalty <- function(x, q, pc.dens) {
if (is.null(pc.dens)) {
return(0)
} else {
cov_vars <- x[1:(2*q)]
pc.priors <- sapply(1:q, function(j) {
pc.dens(cov_vars[2*(j-1) + 1:2])
})
return(sum(pc.priors))
}
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/objective_functions.R
|
#' @title Plotting Residuals of \code{SVC_mle} model
#'
#' @description Method to plot the residuals from an \code{\link{SVC_mle}}
#' object. For this, \code{save.fitted} has to be \code{TRUE} in
#' \code{\link{SVC_mle_control}}.
#'
#' @param x (\code{\link{SVC_mle}})
#' @param which (\code{numeric}) \cr A numeric vector and subset of
#' \code{1:2} indicating which of the 2 plots should be plotted.
#' @param ... further arguments
#'
#' @return a maximum 2 plots
#' \itemize{
#' \item Tukey-Anscombe plot, i.e. residuals vs. fitted
#' \item QQ-plot
#' }
#'
#' @author Jakob Dambon
#'
#' @seealso \code{\link[graphics]{legend}} \link{SVC_mle}
#'
#' @examples
#' #' ## ---- toy example ----
#' ## sample data
#' # setting seed for reproducibility
#' set.seed(123)
#' m <- 7
#' # number of observations
#' n <- m*m
#' # number of SVC
#' p <- 3
#' # sample data
#' y <- rnorm(n)
#' X <- matrix(rnorm(n*p), ncol = p)
#' # locations on a regular m-by-m-grid
#' locs <- expand.grid(seq(0, 1, length.out = m),
#' seq(0, 1, length.out = m))
#'
#' ## preparing for maximum likelihood estimation (MLE)
#' # controls specific to MLE
#' control <- SVC_mle_control(
#' # initial values of optimization
#' init = rep(0.1, 2*p+1),
#' # using profile likelihood
#' profileLik = TRUE
#' )
#'
#' # controls specific to optimization procedure, see help(optim)
#' opt.control <- list(
#' # number of iterations (set to one for demonstration sake)
#' maxit = 1,
#' # tracing information
#' trace = 6
#' )
#'
#' ## starting MLE
#' fit <- SVC_mle(y = y, X = X, locs = locs,
#' control = control,
#' optim.control = opt.control)
#'
#' ## output: convergence code equal to 1, since maxit was only 1
#' summary(fit)
#'
#' ## plot residuals
#' # only QQ-plot
#' plot(fit, which = 2)
#'
#' # two plots next to each other
#' oldpar <- par(mfrow = c(1, 2))
#' plot(fit)
#' par(oldpar)
#'
#' @importFrom stats qqnorm qqline
#' @importFrom graphics plot abline legend
#' @method plot SVC_mle
#' @export
plot.SVC_mle <- function(x, which = 1:2, ...) {
stopifnot(
# residuals needed
!is.null(x$residuals),
# only two kinds of plots supported
all(which %in% 1:2)
)
## Tukey-Anscombe
if (1 %in% which) {
plot(fitted(x)$y.pred,
residuals(x),
main = "Tukey-Anscombe Plot",
xlab = "fitted", ylab = "residuals",
col = "grey")
abline(h = 0)
}
## QQ-plot
if (2 %in% which) {
qqnorm(residuals(x))
qqline(residuals(x))
}
# ## spatial residuals
# if (3 %in% which) {
# loc_x <- fitted(x)$loc_x
# loc_y <- fitted(x)$loc_y
# res <- residuals(x)
# cex.range <- range(sqrt(abs(res)))
#
# plot(loc_x, loc_y,
# type = "p",
# main = "Spatial Residuals Plot",
# xlab = "x locations", ylab = "y locations",
# pch = 1, col = ifelse(res < 0, "blue", "orange"),
# cex = sqrt(abs(res)))
#
# legend(legend.pos,
# legend = c("pos. residuals", "neg. residuals", "min", "max"),
# pch = c(19, 19, 1, 1),
# col = c("orange", "blue", "grey", "grey"),
# pt.cex = c(1, 1, cex.range))
# }
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/plot-SVC_mle.R
|
#' Prediction of SVCs (and response variable)
#'
#' @param object (\code{SVC_mle}) \cr
#' Model obtained from \code{\link{SVC_mle}} function call.
#' @param newlocs (\code{NULL} or \code{matrix(n.new, 2)}) \cr
#' If \code{NULL}, then function uses observed locations of model to estimate
#' SVCs. Otherwise, these are the new locations the SVCs are predicted for.
#' @param newX (\code{NULL} or \code{matrix(n.new, q)}) \cr
#' If provided (together with \code{newW}), the function also returns the
#' predicted response variable.
#' @param newW (\code{NULL} or \code{matrix(n.new, p)}) \cr
#' If provided (together with \code{newX}), the function also returns the
#' predicted response variable.
#' @param newdata (\code{NULL} or \code{data.frame(n.new, p)}) \cr
#' This argument can be used, when the \code{SVC_mle} function has been called
#' with an formula, see examples.
#' @param compute.y.var (\code{logical(1)}) \cr
#' If \code{TRUE} and the response is being estimated, the predictive
#' variance of each estimate will be computed.
#' @param ... further arguments
#'
#' @return The function returns a data frame of \code{n.new} rows and with
#' columns
#' \itemize{
#' \item \code{SVC_1, ..., SVC_p}: the predicted SVC at locations \code{newlocs}.
#' \item \code{y.pred}, if \code{newX} and \code{newW} are provided
#' \item \code{y.var}, if \code{newX} and \code{newW} are provided and
#' \code{compute.y.var} is set to \code{TRUE}.
#' \item \code{loc_x, loc_y}, the locations of the predictions
#' }
#'
#' @seealso \code{\link{SVC_mle}}
#'
#' @author Jakob Dambon
#' @references Dambon, J. A., Sigrist, F., Furrer, R. (2021)
#' \emph{Maximum likelihood estimation of spatially varying coefficient
#' models for large data with an application to real estate price prediction},
#' Spatial Statistics \doi{10.1016/j.spasta.2020.100470}
#'
#' @examples
#' ## ---- toy example ----
#' ## We use the sampled, i.e., one dimensional SVCs
#' str(SVCdata)
#' # sub-sample data to have feasible run time for example
#' set.seed(123)
#' id <- sample(length(SVCdata$locs), 50)
#'
#' ## SVC_mle call with matrix arguments
#' fit_mat <- with(SVCdata, SVC_mle(
#' y[id], X[id, ], locs[id],
#' control = SVC_mle_control(profileLik = TRUE, cov.name = "mat32")))
#'
#' ## SVC_mle call with formula
#' df <- with(SVCdata, data.frame(y = y[id], X = X[id, -1]))
#' fit_form <- SVC_mle(
#' y ~ X, data = df, locs = SVCdata$locs[id],
#' control = SVC_mle_control(profileLik = TRUE, cov.name = "mat32")
#' )
#'
#' ## prediction
#'
#' # predicting SVCs
#' predict(fit_mat, newlocs = 1:2)
#' predict(fit_form, newlocs = 1:2)
#'
#' # predicting SVCs and response providing new covariates
#' predict(
#' fit_mat,
#' newX = matrix(c(1, 1, 3, 4), ncol = 2),
#' newW = matrix(c(1, 1, 3, 4), ncol = 2),
#' newlocs = 1:2
#' )
#' predict(fit_form, newdata = data.frame(X = 3:4), newlocs = 1:2)
#'
#' @import spam
#' @importFrom stats sd model.matrix
#' @export
predict.SVC_mle <- function(
object,
newlocs = NULL,
newX = NULL,
newW = NULL,
newdata = NULL,
compute.y.var = FALSE,
...
) {
# extract parameters
mu <- coef(object)
cov.par <- cov_par(object)
q <- dim(as.matrix(object$MLE$call.args$W))[2]
p <- dim(as.matrix(object$MLE$call.args$X))[2]
n <- length(object$MLE$call.args$y)
locs <- object$MLE$call.args$locs
tapering <- object$MLE$call.args$control$tapering
dist_args <- object$MLE$call.args$control$dist
# define distance matrices
d <- do.call(
own_dist,
c(list(x = locs, taper = tapering), dist_args)
)
# if no new locations are given, predict for training data
if (is.null(newlocs)) {
newlocs <- object$MLE$call.args$locs
d_cross <- d
n.new <- n
} else {
newlocs <- as.matrix(newlocs)
n.new <- nrow(newlocs)
d_cross <- do.call(
own_dist,
c(list(x = newlocs, y = locs, taper = tapering), dist_args)
)
}
# covariance function (not tapered)
raw.cf <- MLE.cov.func(object$MLE$call.args$control$cov.name)
if (is.null(object$MLE$call.args$control$taper)) {
taper <- NULL
# cross-covariance (newlocs and locs)
cf_cross <- function(x) raw.cf(d_cross, x)
} else {
taper <- get_taper(
object$MLE$call.args$control$cov.name, d, tapering
)
taper_cross <- get_taper(
object$MLE$call.args$control$cov.name, d_cross, tapering
)
# cross-covariance (newlocs and locs)
cf_cross <- function(x) raw.cf(d_cross, x)*taper_cross
}
# covariance y
cf <- function(x) raw.cf(d, x)
cov_y <- object$MLE$comp.args$Sigma_final
# cross-covariance beta' y
cov_b_y <- Sigma_b_y(
x = cov.par,
cov.func = cf_cross,
W = as.matrix(object$MLE$call.args$W),
n.new = n.new
)
eff <- cov_b_y %*%
solve(cov_y, object$MLE$call.args$y - object$MLE$call.args$X %*% mu)
eff <- matrix(eff, ncol = q)
# if newdata is given and formula is present in SVC_mle object, extract
# newX and newW (and overwrite provided ones)
if (!is.null(newdata)) {
if (!is.null(object$formula)) {
if (!is.null(newX)) {
warning("Formula and 'newdata' provided: 'newX' argument was overwritten!")
}
if (!is.null(newW)) {
warning("Formula and 'newdata' provided: 'newW' argument was overwritten!")
}
# create covariates
# drop response from fromula
formula <- drop_response(object$formula)
RE_formula <- drop_response(object$RE_formula)
newX <- as.matrix(stats::model.matrix(formula, data = newdata))
newW <- as.matrix(stats::model.matrix(RE_formula, data = newdata))
} else {
warning("Data provided bu object has not been trained by a formula.\n
Cannot compute fixed and random effect covariates.")
}
}
if (!is.null(newX) & !is.null(newW)) {
# Do dimensions for training and prediction data match?
stopifnot(q == ncol(newW), p == ncol(newX))
y.pred <- apply(newW * eff, 1, sum) + newX %*% mu
# computation of standard deviation fro each observation.
if (compute.y.var) {
# Have to compute
#
# var.y = Sigma_ynew - Sigma_ynew_y Sigma_y^-1 Sigma_y_ynew
#
# Sigma_ynew = A
# Sigma_ynew_y = B
# Sigma_y = C
# Sigma_y_ynew = D = t(C)
# Part B:
cov_ynew_y <- Sigma_y_y(
cov.par,
cov.func = cf_cross,
X = object$MLE$call.args$W,
newX = newW
)
# Part A:
d_new <- if (n.new == 1) {
as.matrix(0)
} else {
do.call(
own_dist,
c(list(x = newlocs, taper = tapering), dist_args)
)
}
if (is.null(tapering)) {
outer.newW <- lapply(1:q, function(k) {
(newW[, k]%o%newW[, k]) })
taper_new <- NULL
} else {
taper_new <- get_taper(
object$MLE$call.args$control$cov.name, d_new, tapering
)
outer.newW <- lapply(1:q, function(k) {
(newW[, k]%o%newW[, k]) * taper_new
})
}
# cross-covariance (newlocs and locs)
cf_new <- function(x) raw.cf(d_new, x)
cov_ynew <- Sigma_y(
cov.par,
cf_new,
outer.W = outer.newW,
taper = taper_new
)
# Part C: already calculated with cov_y
# Computation of variance of y
var.y <- diag(cov_ynew) - diag(cov_ynew_y %*% solve(cov_y, t(cov_ynew_y)))
# form out put
out <- as.data.frame(cbind(eff, y.pred, var.y, newlocs))
colnames(out) <- c(paste0("SVC_", 1:ncol(eff)), "y.pred", "y.var", paste0("loc_", 1:ncol(newlocs)))
} else {
out <- as.data.frame(cbind(eff, y.pred, newlocs))
colnames(out) <- c(paste0("SVC_", 1:ncol(eff)), "y.pred", paste0("loc_", 1:ncol(newlocs)))
}
} else {
if (compute.y.var)
warning("Please provide 'newX' and 'newW' to predict y and its variance.")
out <- as.data.frame(cbind(eff, newlocs))
colnames(out) <- c(paste0("SVC_", 1:ncol(eff)), paste0("loc_", 1:ncol(newlocs)))
}
# two ensure that predict calls with formula and matrix are identical
row.names(out) <- as.character(row.names(out))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/predict-SVC_mle.R
|
#' @title Print Method for \code{SVC_mle}
#'
#' @description Method to print an \code{\link{SVC_mle}} object.
#'
#' @param x \code{\link{SVC_mle}} object
#' @param digits (\code{numeric})
#' Number of digits to be plotted.
#' @param ... further arguments
#'
#' @author Jakob Dambon
#'
#' @method print SVC_mle
#' @export
print.SVC_mle <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
cat("Coefficients of fixed effects:\n")
print.default(format(coef(x), digits = digits), print.gap = 2L,
quote = FALSE)
cat("\n\nCovaraiance parameters of the SVC(s):\n")
print.default(format(cov_par(x), digits = digits), print.gap = 2L,
quote = FALSE)
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/print-SVC_mle.R
|
#' @title Extact Model Residuals
#'
#' @description Method to extract the residuals from an \code{\link{SVC_mle}}
#' object. This is only possible if \code{save.fitted} was set to \code{TRUE}.
#'
#' @param object \code{\link{SVC_mle}} object
#' @param ... further arguments
#'
#' @return (\code{numeric(n)})
#' Residuals of model
#'
#' @author Jakob Dambon
#'
#' @importFrom stats residuals resid
#' @export
residuals.SVC_mle <- function(object, ...) {
stopifnot(!is.null(object$residuals))
return(object$residuals)
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/residuals-SVC_mle.R
|
#' @title Summary Method for \code{SVC_mle}
#'
#' @description Method to construct a \code{summary.SVC_mle} object out of a
#' \code{\link{SVC_mle}} object.
#'
#' @param object \code{\link{SVC_mle}} object
#' @param ... further arguments
#'
#' @return object of class \code{summary.SVC_mle} with summarized values of the MLE.
#'
#' @author Jakob Dambon
#'
#' @seealso \code{\link{SVC_mle}}
#'
#' @importFrom stats pchisq pnorm
#' @method summary SVC_mle
#' @export
summary.SVC_mle <- function(object, ...) {
stopifnot(!is.null(object$residuals))
p <- dim(as.matrix(object$data$X))[2]
q <- dim(as.matrix(object$data$W))[2]
se_RE <- object$MLE$comp.args$par_SE$RE$SE
se_FE <- object$MLE$comp.args$par_SE$FE$SE
covpars <- cbind(
Estimate = cov_par(object),
`Std. Error` = se_RE,
`W value` = (cov_par(object)/se_RE)^2,
`Pr(>W)` = pchisq((cov_par(object)/se_RE)^2, df = 1, lower.tail = FALSE)
)
# do not test range and nugget variance
covpars[-(2*(1:q)), 3:4] <- NA
ans <- list(
call = object$call,
pX = p,
pW = q,
nobs = nobs(object),
nlocs = nlocs(object),
resids = resid(object),
y.mean.resid = object$data$y-mean(object$data$y),
coefs = cbind(
Estimate = coef(object),
`Std. Error` = se_FE,
`Z value` = (coef(object)/se_FE),
`Pr(>|Z|)` = 2*pnorm(abs(coef(object)/se_FE), lower.tail = FALSE)
),
covpars = covpars,
cov_fun = switch(
attr(cov_par(object), "cov_fun"),
"exp" = "exponential",
"mat32" = "Matern (nu = 3/2)",
"mat52" = "Matern (nu = 5/2)",
"sph" = "spherical",
"wend1" = "Wendland (kappa = 1)",
"wend2" = "Wendland (kappa = 2)"),
optim.out = object$MLE$optim.output,
logLik = logLik(object),
taper = object$MLE$call.args$control$tapering,
BIC = as.numeric(BIC(object))
)
ans$r.squared <- 1 - sum(ans$resids^2)/sum(ans$y.mean.resid^2)
class(ans) <- "summary.SVC_mle"
ans
}
#' @title Printing Method for \code{summary.SVC_mle}
#'
#' @param x \code{\link{summary.SVC_mle}}
#' @param digits the number of significant digits to use when printing.
#' @param ... further arguments
#'
#'
#' @return The printed output of the summary in the console.
#' @seealso \link{summary.SVC_mle} \link{SVC_mle}
#'
#' @importFrom stats printCoefmat sd
#' @method print summary.SVC_mle
#' @export
print.summary.SVC_mle <- function(x, digits = max(3L, getOption("digits") - 3L),
...) {
cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
cat(paste0("Fitting a GP-based SVC model with ",
x$pX,
" fixed effect(s) and ",
x$pW,
" SVC(s)\n"))
cat(paste0("using ", x$nobs, " observations at ",
x$nlocs, " different locations / coordinates.\n\n"))
cat("Residuals:\n")
print.default(format(summary(x$resids)[-4], digits = digits), print.gap = 2L,
quote = FALSE)
cat(paste0("\nResidual standard error: ",
formatC(sd(x$resids),
digits = digits),
"\nMultiple R-squared: ",
formatC(x$r.squared,
digits = digits),
", BIC: ", formatC(x$BIC,
digits = digits), "\n"))
cat("\n\nCoefficients of fixed effect(s):\n")
stats::printCoefmat(x$coefs, digits = digits,
signif.stars = getOption("show.signif.stars"),
na.print = "NA", ...)
# print.default(format(x$coefs, digits = digits), print.gap = 2L,
# quote = FALSE)
# covpar <- as.data.frame(matrix(x$covpars[-(2*x$pW+1)],
# ncol = 2, byrow = TRUE))
# colnames(covpar) <- c("range", "variance")
# rownames(covpar) <- substr(names(x$covpars)[2*(1:x$pW)],
# 1, nchar(names(x$covpars)[2*(1:x$pW)])-4)
cat("\n\nCovariance parameters of the SVC(s):\n")
stats::printCoefmat(x$covpar, digits = digits,
signif.stars = getOption("show.signif.stars"),
na.print = "NA", ...)
cat(paste0("\nThe covariance parameters were estimated using \n",
x$cov_fun, " covariance functions.\n"))
if(is.null(x$taper)) {
cat("No covariance tapering applied.\n")
} else {
cat(paste0("Covariance tapering range set to: ",
formatC(x$taper, digits = digits), "\n"))
}
cat(paste0(
"\n\nMLE:\nThe MLE terminated after ",
x$optim.out$counts["function"],
" function evaluations with convergence code ",
x$optim.out$convergence,
"\n(0 meaning that the optimization was succesful).\n"
))
cat(paste0(
"The final", if (attr(x$logLik, "penalized")) {" regularized"} else {""} ,
if (attr(x$logLik, "profileLik")) {" profile"} else {""},
" log likelihood value is " ,
formatC(x$logLik,digits = digits), ".\n"
))
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/summary-SVC_mle.R
|
#' @importFrom spam cov.mat
cov.mat32 <- function(h, theta) {
stopifnot(length(theta) == 2L)
# smoothness nu = 3/2
spam::cov.mat(h, theta = c(theta, 3/2))
}
#' @importFrom spam cov.mat
cov.mat52 <- function(h, theta) {
stopifnot(length(theta) == 2L)
# smoothness nu = 5/2
spam::cov.mat(h, theta = c(theta, 5/2))
}
## ---- help function to give back correct covariance function ----
#' @importFrom spam cov.exp cov.sph cov.wend1 cov.wend2
MLE.cov.func <- function(
cov.name = c("exp", "mat32", "mat52", "sph", "wend1", "wend2")
) {
if (is.character(cov.name)) {
cov.func <- get(paste0("cov.", match.arg(cov.name)))
} else if (is.function(cov.name)) {
cov.func <- cov.name
} else {
stop("Cov.name argument neither character, nor covariance function.")
}
return(cov.func)
}
#' GLS Estimate using Cholesky Factor
#'
#' Computes the GLS estimate using the formula:
#' \deqn{\mu_{GLS} = (X^\top \Sigma^{-1} X)^{-1}X^\top \Sigma^{-1} y.}
#' The computation is done depending on the input class of the Cholesky factor
#' \code{R}. It relies on the classical \code{\link[base]{solve}} or on
#' using \code{forwardsolve} and \code{backsolve} functions of package
#' \code{spam}, see \code{\link[spam]{solve}}. This is much faster than
#' computing the inverse of \eqn{\Sigma}, especially since we have to compute
#' the Cholesky decomposition of \eqn{\Sigma} either way.
#'
#' @param R (\code{spam.chol.NgPeyton} or \code{matrix(n, n)}) \cr Cholesky factor of
#' the covariance matrix \eqn{\Sigma}. If covariance tapering and sparse
#' matrices are used, then the input is of class \code{spam.chol.NgPeyton}.
#' Otherwise, \code{R} is the output of a standard \code{\link[base]{chol}},
#' i.e., a simple \code{matrix}
#' @param X (\code{matrix(n, p)}) \cr Data / design matrix.
#' @param y (\code{numeric(n)}) \cr Response vector
#'
#' @return A \code{numeric(p)} vector, i.e., the mean effects.
#' @author Jakob Dambon
#'
#' @export
#'
#' @examples
#' # generate data
#' n <- 10
#' X <- cbind(1, 20+1:n)
#' y <- rnorm(n)
#' A <- matrix(runif(n^2)*2-1, ncol=n)
#' Sigma <- t(A) %*% A
#' # two possibilities
#' ## using standard Cholesky decomposition
#' R_mat <- chol(Sigma); str(R_mat)
#' mu_mat <- GLS_chol(R_mat, X, y)
#' ## using spam
#' R_spam <- chol(spam::as.spam(Sigma)); str(R_spam)
#' mu_spam <- GLS_chol(R_spam, X, y)
#' # should be identical to the following
#' mu <- solve(crossprod(X, solve(Sigma, X))) %*%
#' crossprod(X, solve(Sigma, y))
#' ## check
#' abs(mu - mu_mat)
#' abs(mu - mu_spam)
GLS_chol <- function(R, X, y) UseMethod("GLS_chol")
#' @rdname GLS_chol
#' @importFrom spam forwardsolve backsolve
#' @export
GLS_chol.spam.chol.NgPeyton <- function(R, X, y) {
# (X^T * Sigma^-1 * X)^-1
solve(
crossprod(spam::forwardsolve(R, X))
) %*%
# (X^T * Sigma^-1 * y)
crossprod(X, spam::backsolve(R, spam::forwardsolve(R, y)))
}
#' @rdname GLS_chol
#' @export
GLS_chol.matrix <- function(R, X, y) {
RiX <- solve(t(R), X)
# (X^T * Sigma^-1 * X)^-1
solve(
crossprod(RiX)
) %*%
# (X^T * Sigma^-1 * y)
crossprod(RiX, solve(t(R), y))
}
# Covariance Matrix of GP-based SVC Model
#
# Builds the covariance matrix of \eqn{y} (p. 6, Dambon et al. (2021)
#\doi{10.1016/j.spasta.2020.100470}) for a given set of covariance
# parameters and other, pre-defined objects (like the outer-products,
# covariance function, and, possibly, a taper matrix).
#
# @param x (\code{numeric(2q+1)}) \cr Non negative vector containing
# the covariance parameters in the following order: \eqn{\rho_1, \sigma_1^2,
# ..., \rho_q, \sigma_q^2 , \tau^2}. Note that the odd entries, i.e., the
# ranges and the nugget variance, have to be greater than 0, otherwise the
# covariance matrix is not well-defined (singularities or not-invertible).
# @param cov_func (\code{function}) \cr A covariance function that works on
# the pre-defined distance matrix \code{d}. It takes a numeric vector as an
# input, the first entry being the range, the second being the variance
# (also called partial sill). Usually, it is defined as, e.g.:
# \code{function(pars) spam::cov.exp(d, pars)} or any other covariance function
# defined for two parameters.
# @param outer.W (\code{list(q)}) \cr A list of length \code{q} containing
# the outer products of the random effect covariates in a lower triangular,
# (possibly sparse) matrix. If tapering is applied, the list entries, i.e.,
# the outer products have to be given as \code{\link[spam]{spam}} objects.
# @param taper (\code{NULL} or \code{spam}) \cr If covariance tapering is
# applied, this argument contains the taper matrix, which is a
# \code{\link[spam]{spam}} object. Otherwise, it is \code{NULL}.
#
# @return Returns a positive-definite covariance matrix y, which is needed in
# the MLE. Specifically, a Cholesky Decomposition is applied on the covariance
# matrix.
#
#
# @author Jakob Dambon
# @references Dambon, J. A., Sigrist, F., Furrer, R. (2021)
# \emph{Maximum likelihood estimation of spatially varying coefficient
# models for large data with an application to real estate price prediction},
# Spatial Statistics \doi{10.1016/j.spasta.2020.100470}
#
#
# @examples
# # locations
# locs <- 1:6
# # random effects covariates
# W <- cbind(rep(1, 6), 5:10)
# # distance matrix with and without tapering
# d <- as.matrix(dist(locs))
# # distance matrix with and without tapering
# tap_dist <- 2
# d_tap <- spam::nearest.dist(locs, delta = tap_dist)
# # call without tapering
# (Sy <- varycoef:::Sigma_y(
# x = rep(0.5, 5),
# cov_func = function(x) spam::cov.exp(d, x),
# outer.W = lapply(1:ncol(W), function(k) W[, k] %o% W[, k])
# ))
# str(Sy)
# # call with tapering
# (Sy_tap <- varycoef:::Sigma_y(
# x = rep(0.5, 5),
# cov_func = function(x) spam::cov.exp(d_tap, x),
# outer.W = lapply(1:ncol(W), function(k)
# spam::as.spam((W[, k] %o% W[, k]) * (d_tap<=tap_dist))
# ),
# taper = spam::cov.wend1(d_tap, c(tap_dist, 1, 0))
# ))
# str(Sy_tap)
# # difference between tapered and untapered covariance matrices
# Sy-Sy_tap
Sigma_y <- function(x, cov_func, outer.W, taper = NULL) {
n <- nrow(outer.W[[1]])
q <- length(outer.W)
if (is.null(taper)) {
# with no tapering computations are done on matrix objects
Sigma <- matrix(0, nrow = n, ncol = n)
for (k in 1:q) {
# first argument: range, second argument: variance / sill
Cov <- cov_func(x[2*(k-1) + 1:2])
Sigma <- Sigma + (
Cov * outer.W[[k]]
)
}
nug <- if (n == 1) {
x[2*q+1]
} else {
diag(rep(x[2*q+1], n))
}
return(Sigma + nug)
} else {
# With tapering computations are done on spam objects.
# Specifically, due to their fixed structure and since we are only
# pair-wise adding and multiplying, on the spam entries themselves
stopifnot(
all(sapply(outer.W, is.spam))
)
# construct a sparse matrix with 0 values as future entries
# for k = 1
Sigma <- outer.W[[1]] * cov_func(x[1:2])
# if q > 1, build covariance matrix using components of other GPs
if (q > 1) {
for (k in 2:q) {
Cov <- do.call(cov_func, list(c(x[2*(k-1) + 1:2], 0)))
Sigma <- Sigma + (Cov * outer.W[[k]])
}
}
options(spam.trivalues = TRUE)
nug <- if (n == 1) {
x[2*q+1]
} else {
spam::diag.spam(rep(x[2*q+1], n))
}
# Sigma <- Sigma * taper
# add lower tri. cov-matrices up and mirror them to get full cov-matrix
# due to spam::nearest.dist design
return(spam::lower.tri.spam(Sigma) +
spam::t.spam(Sigma) +
nug)
}
}
Sigma_b_y <- function(x, cov.func, W, n.new) {
n <- nrow(W)
cov <- lapply(1:ncol(W),
function(j) {
# cross-covariances of Sigma_b_y
cov.func(c(x[2*(j-1) + 1:2])) *
matrix(rep(W[, j], each = n.new), ncol = n)
})
# binding to one matrix
Reduce(rbind, cov)
}
Sigma_y_y <- function(x, cov.func, X, newX) {
p <- ncol(X)
Sigma <- matrix(0, ncol = nrow(X), nrow = nrow(newX))
for (j in 1:p) {
Cov <- cov.func(c(x[2*(j-1) + 1:2], 0))
Sigma <- Sigma + (
Cov * (newX[, j] %o% X[, j])
)
}
return(Sigma)
}
#' Check Lower Bound of Covariance Parameters
#'
#' Ensures that the covariance parameters define a positive definite covariance
#' matrix. It takes the vector
#' \eqn{(\rho_1, \sigma^2_1, ..., \rho_q, \sigma^2_q, \tau^2)} and checks if
#' all \eqn{\rho_k>0}, all \eqn{\sigma_k^2>=0}, and \eqn{\tau^2>0}.
#' @param cv (\code{numeric(2*q+1)}) \cr Covariance vector of SVC model.
#' @param q (\code{numeric(1)}) \cr Integer indicating the number of SVCs.
#'
#' @return \code{logical(1)} with \code{TRUE} if all conditions above are
#' fulfilled.
#' @export
#'
#' @examples
#' # first one is true, all other are false
#' check_cov_lower(c(0.1, 0, 0.2, 1, 0.2), q = 2)
#' check_cov_lower(c(0 , 0, 0.2, 1, 0.2), q = 2)
#' check_cov_lower(c(0.1, 0, 0.2, 1, 0 ), q = 2)
#' check_cov_lower(c(0.1, 0, 0.2, -1, 0 ), q = 2)
check_cov_lower <- function(cv, q) {
# check range and nugget variance parameters
l_rp <- all(cv[1+2*(0:q)]>0)
# check SVC variances
l_vp <- all(cv[2*(1:q)] >= 0)
return(l_rp & l_vp)
}
#' Setting of Optimization Bounds and Initial Values
#'
#' Sets bounds and initial values for \code{\link[stats]{optim}} by
#' extracting potentially given values from \code{\link{SVC_mle_control}} and
#' checking them, or calculating them from given data. See Details.
#'
#' @param control (\code{\link{SVC_mle_control}} output, i.e. \code{list})
#' @param p (\code{numeric(1)}) \cr Number of fixed effects
#' @param q (\code{numeric(1)}) \cr Number of SVCs
#' @param id_obj (\code{numeric(2*q+1+q)}) \cr Index vector to identify the
#' arguments of objective function.
#' @param med_dist (\code{numeric(1)}) \cr Median distance between observations
#' @param y_var (\code{numeric(1)}) \cr Variance of response \code{y}
#' @param OLS_mu (\code{numeric(p)}) \cr Coefficient estimates of ordinary
#' least squares (OLS).
#'
#' @details If values are not provided, then they are set in the following way.
#' Let \eqn{d} be the median distance \code{med_dist}, let \eqn{s^2_y} be
#' the variance of the response \code{y_var}, and let \eqn{b_j} be the OLS
#' coefficients of the linear model. The computed values are given in the
#' table below.
#'
#' | Parameter | Lower bound | Initial Value | Upper Bound |
#' | ------------ | -------------:| -----------------:| -------------:|
#' | Range | \eqn{d/1000} | \eqn{d/4} | \eqn{10 d} |
#' | Variance | \eqn{0} | \eqn{s^2_y/(q+1)} | \eqn{10s^2_y} |
#' | Nugget | \eqn{10^{-6}} | \eqn{s^2_y/(q+1)} | \eqn{10s^2_y} |
#' | Mean \eqn{j} | \code{-Inf} | \eqn{b_j} | \code{Inf} |
#' @md
#'
#' @author Jakob Dambon
#'
#' @export
#'
#' @return A \code{list} with three entries: \code{lower}, \code{init},
#' and \code{upper}.
init_bounds_optim <- function(control, p, q, id_obj, med_dist, y_var, OLS_mu) {
# lower bound for optim
if (is.null(control$lower)) {
lower <- if (control$profileLik) {
c(rep(c(med_dist/1000, 0), q), 1e-6)
} else {
c(rep(c(med_dist/1000, 0), q), 1e-6, rep(-Inf, p))
}
} else {
lower <- control$lower
if (length(lower) != length(id_obj)) {
stop("Lower boundary vector has wrong length. Check SVC_mle_control.")
}
if (!check_cov_lower(lower[1:(2*q+1)], q)) {
stop("Lower boundary vector is not greater (or equal) than 0. Call ?check_cov_lower.")
}
}
# upper bound for optim
if (is.null(control$upper)) {
upper <- if (control$profileLik) {
c(rep(c(10*med_dist, 10*y_var), q), 10*y_var)
} else {
c(rep(c(10*med_dist, 10*y_var), q), 10*y_var, rep(Inf, p))
}
} else {
upper <- control$upper
if (length(upper) != length(id_obj)) {
stop("Upper boundary vector has wrong length. Check SVC_mle_control.")
}
if (!check_cov_lower(upper[1:(2*q+1)], q)) {
stop("Upper boundary vector is not greater (or equal) than 0. Call ?check_cov_lower.")
}
if (any(lower>upper)) {
stop("Upper boundary vector smaller than lower boundary.")
}
}
# init
if (is.null(control$init)) {
init <- if (control$profileLik) {
c(rep(c(med_dist/4, y_var/(q+1)), q), y_var/(q+1))
} else {
c(rep(c(med_dist/4, y_var/(q+1)), q), y_var/(q+1), OLS_mu)
}
} else {
init <- control$init
if (length(init) != length(id_obj)) {
stop("Initial vector has wrong length. Check SVC_mle_control.")
}
if (!check_cov_lower(init[1:(2*q+1)], q)) {
stop("Initial value vector is not greater (or equal) than 0. Call ?check_cov_lower.")
}
if (!(all(lower <= init) & all(init <= upper))) {
stop("Initial values do not lie between lower and upper boundarys.")
}
}
return(list(lower = lower, init = init, upper = upper))
}
# Preparation of Parameter Output
#
# Prepares and computes the ML estimates and their respective standard errors.
# @param output_par (\code{numeric}) \cr Found optimal value of
# \code{\link[stats]{optim}}.
# @param Sigma_final (\code{spam} or \code{matrix(n, n)}) \cr Covariance matrix
# Sigma of SVC under final covariance parameters.
# @param Rstruct (\code{NULL} or \code{spam.chol.NgPeyton}) \cr If
# covariance tapering is used, the Cholesky factor has been calculated
# previously and can be used to efficiently update the Cholesky factor of
# \code{Sigma_final}, which is an \code{spam} object.
# @param profileLik (\code{logical(1)}) \cr Indicates if optimization has been
# conducted over full or profile likelihood.
# @param X (\code{matrix(n, p)}) Design matrix
# @param y (\code{numeric(p)}) Response vector
# @param H (\code{NULL} or \code{matrix}) Hessian of MLE
# @param q (\code{numeric(1)}) Number of SVC
#
# @return A \code{list} with two \code{data.frame}. Each contains the estimated
# parameters with their standard errors of the fixed and random effects,
# respectively.
#
#' @importFrom methods is
prep_par_output <- function(output_par, Sigma_final, Rstruct, profileLik,
X, y, H, q) {
p <- dim(as.matrix(X))[2]
# get mean effects depending on likelihood optimization
if (profileLik) {
# calculate Cholesky-Decomposition
if (is.spam(Sigma_final)) {
cholS <- chol(Sigma_final, Rstruct = Rstruct)
} else {
cholS <- chol(Sigma_final)
}
mu <- GLS_chol(cholS, X, y)
} else {
mu <- output_par[2*q+1 + 1:p]
}
# get standard errors of parameters
if (is.null(H)) {
warning("MLE without Hessian. Cannot return standard errors of covariance parameters.")
se_all <- rep(NA_real_, length(output_par))
} else {
# divide by 2 due to (-2)*LL
se_all <- try({sqrt(diag(solve(H/2)))}, silent = TRUE)
# if no convergence, standard errors cannot be extracted
if (methods::is(se_all, "try-error")) {
warning("Could not invert Hessian.")
se_all <- rep(NA_real_, length(output_par))
}
}
# on profile?
if (profileLik) {
se_RE <- se_all
# compute variance covariance matrix for fixed effects
# using GLS properties
Sigma_FE <- solve(crossprod(X, solve(Sigma_final, X)))
se_FE <- sqrt(diag(Sigma_FE))
} else {
se_RE <- se_all[1:(2*q+1)]
se_FE <- se_all[2*q+1 + 1:p]
}
return(list(
RE = data.frame(est = output_par[1:(2*q+1)], SE = se_RE),
FE = data.frame(est = mu, SE = se_FE)
))
}
#
# own_dist <- function(
# locs, newlocs = NULL, taper = NULL, method_list = NULL
# ) {
# if (is.null(taper)) {
# d <- as.matrix(
# do.call(dist,
# c(list(x = locs, diag = TRUE, upper = TRUE), method_list)))
# } else {
# d <- do.call(spam::nearest.dist,
# c(list(x = locs,
# delta = control$tapering),
# control$dist))
# }
# }
# Computes (Cross-) Distances
#
# @param x (\code{matrix}) \cr Matrix containing locations
# @param y (\code{NULL} or \code{matrix}) \cr If \code{NULL}, computes the
# distances between \code{x}. Otherwise, computes cross-distances, i.e.,
# pair-wise distances between rows of \code{x} and \code{y}.
# @param taper (\code{NULL} or \code{numeric(1)}) \cr If \code{NULL}, all
# distances are considered. Otherwise, only distances shorter than
# \code{taper} are used. Hence the output will be a sparse matrix of type
# \code{\link[spam]{spam}}.
# @param ... Further arguments for either \code{\link[stats]{dist}} or
# \code{\link[spam]{nearest.dist}}.
#
# @return A \code{matrix} or \code{spam} object.
#' @importFrom spam nearest.dist
#' @importFrom stats dist
own_dist <- function(x, y = NULL, taper = NULL, ...) {
d <- if (is.null(taper)) {
# without tapering
if (is.null(y)) {
# no cross distances
as.matrix(do.call(
dist,
c(list(x = x, diag = TRUE, upper = TRUE), ...)
))
} else {
# cross distances
as.matrix(do.call(
spam::nearest.dist,
c(list(x = x, y = y, delta = 1e99), ...)
))
}
} else {
# with tapering
if (is.null(y)) {
# no cross distances
do.call(
spam::nearest.dist,
c(list(x = x, delta = taper), ...)
)
} else {
# cross distances
do.call(
spam::nearest.dist,
c(list(x = x, y = y, delta = taper), ...)
)
}
}
# return output
d
}
get_taper <- function(cov.name, d, tapering) {
switch(
cov.name,
"exp" = spam::cov.wend1(d, c(tapering, 1, 0)),
"mat32" = spam::cov.wend1(d, c(tapering, 1, 0)),
"mat52" = spam::cov.wend2(d, c(tapering, 1, 0))
)
}
is.formula <- function(x){
inherits(x,"formula")
}
#' @importFrom stats as.formula
drop_response <- function(formula) {
stopifnot(is.formula(formula))
deparsed_form <- as.character(formula)
if (length(deparsed_form) > 2L) {
return(stats::as.formula(paste(deparsed_form[c(1, 3)], collapse = " ")))
} else {
return(formula)
}
}
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/utils.R
|
#' varycoef: Modeling Spatially Varying Coefficients
#'
#' This package offers functions to estimate and predict Gaussian process-based
#' spatially varying coefficient (SVC) models. Briefly described, one
#' generalizes a linear regression equation such that the coefficients are no
#' longer constant, but have the possibility to vary spatially. This is enabled
#' by modeling the coefficients using Gaussian processes with (currently) either
#' an exponential or spherical covariance function. The advantages of such SVC
#' models are that they are usually quite easy to interpret, yet they offer a
#' very high level of flexibility.
#'
#'
#' @section Estimation and Prediction:
#' The ensemble of the function \code{\link{SVC_mle}} and the method
#' \code{predict} estimates the defined SVC model and gives predictions of the
#' SVC as well as the response for some pre-defined locations. This concept
#' should be rather familiar as it is the same for the classical regression
#' (\code{\link{lm}}) or local polynomial regression (\code{\link{loess}}),
#' to name a couple. As the name suggests, we are using a \emph{maximum
#' likelihood estimation} (MLE) approach in order to estimate the model. The
#' predictor is obtained by the empirical best linear unbiased predictor.
#' to give location-specific predictions. A detailed tutorial with examples is
#' given in a vignette; call \code{vignette("example", package = "varycoef")}.
#' We also refer to the original article Dambon et al. (2021) which lays the
#' methodological foundation of this package.
#'
#'
#' With the before mentioned \code{\link{SVC_mle}} function one gets an object
#' of class \code{\link{SVC_mle}}. And like the method \code{predict} for
#' predictions, there are several more methods in order to diagnose the model,
#' see \code{methods(class = "SVC_mle")}.
#'
#' @section Variable Selection:
#' As of version 0.3.0 of \code{varycoef}, a joint variable selection of both
#' fixed and random effect of the Gaussian process-based SVC model is
#' implemented. It uses a \emph{penalized maximum likelihood estimation} (PMLE)
#' which is implemented via a gradient descent. The estimation of the shrinkage
#' parameter is available using a \emph{model-based optimization} (MBO). Here,
#' we use the framework by Bischl et al. (2017). The methodological foundation
#' of the PMLE is described in Dambon et al. (2022).
#'
#' @examples
#' vignette("manual", package = "varycoef")
#' methods(class = "SVC_mle")
#'
#' @author Jakob Dambon
#'
#' @references Bischl, B., Richter, J., Bossek, J., Horn, D., Thomas, J.,
#' Lang, M. (2017). \emph{mlrMBO: A Modular Framework for Model-Based
#' Optimization of Expensive Black-Box Functions},
#' ArXiv preprint \url{https://arxiv.org/abs/1703.03373}
#'
#' Dambon, J. A., Sigrist, F., Furrer, R. (2021).
#' \emph{Maximum likelihood estimation of spatially varying coefficient
#' models for large data with an application to real estate price prediction},
#' Spatial Statistics 41 100470 \doi{10.1016/j.spasta.2020.100470}
#'
#' Dambon, J. A., Sigrist, F., Furrer, R. (2022).
#' \emph{Joint Variable Selection of both Fixed and Random Effects for
#' Gaussian Process-based Spatially Varying Coefficient Models},
#' International Journal of Geographical Information Science
#' \doi{10.1080/13658816.2022.2097684}
#'
#' @docType package
#' @name varycoef
NULL
|
/scratch/gouwar.j/cran-all/cranData/varycoef/R/varycoef.R
|
## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE, message = FALSE,
fig.width=7, fig.height=4)
library(knitr)
prop_train <- 0.2
## ----install, eval=FALSE------------------------------------------------------
# # install from CRAN
# install.packages("varycoef")
#
# # install from Github (make sure that you installed the package "devtools")
# devtools::install_github("jakobdambon/varycoef")
## ----help and vignettes, warning=FALSE----------------------------------------
# attach package
library(varycoef)
# general package help file
help("varycoef")
# where you find this vignette
vignette("Introduction", package = "varycoef")
## ----synthetic data-----------------------------------------------------------
str(SVCdata)
help(SVCdata)
# number of observations, number of coefficients
n <- nrow(SVCdata$X); p <- ncol(SVCdata$X)
## ----synthetic data train and test--------------------------------------------
# create data frame
df <- with(SVCdata, data.frame(y = y, x = X[, 2], locs = locs))
set.seed(123)
idTrain <- sort(sample(n, n*prop_train))
df_train <- df[idTrain, ]
df_test <- df[-idTrain, ]
## ----synthetic data EDA-------------------------------------------------------
par(mfrow = 1:2)
plot(y ~ x, data = df_train, xlab = "x", ylab = "y",
main = "Scatter Plot of Response and Covariate")
plot(y ~ locs, data = df_train, xlab = "s", ylab = "y",
main = "Scatter Plot of Response and Locations")
par(mfrow = c(1, 1))
## ----synthetic data linear model----------------------------------------------
fit_lm <- lm(y ~ x, data = df_train)
coef(fit_lm)
# residual plots
par(mfrow = 1:2)
plot(x = fitted(fit_lm), y = resid(fit_lm),
xlab = "Fitted Values", ylab = "Residuals",
main = "Residuals vs Fitted")
abline(h = 0, lty = 2, col = "grey")
plot(x = df_train$locs, y = resid(fit_lm), xlab = "Location", ylab = "Residuals",
main = "Residuals vs Locations")
abline(h = 0, lty = 2, col = "grey")
par(mfrow = c(1, 1))
## ----synthetic data svc model-------------------------------------------------
fit_svc <- SVC_mle(y ~ x, data = df_train, locs = df_train$locs)
coef(fit_svc)
## ----methods------------------------------------------------------------------
# summary output
summary(fit_svc)
# fitted output
head(fitted(fit_svc))
# residual plots
par(mfrow = 1:2)
plot(x = fitted(fit_svc)$y.pred, y = resid(fit_svc),
xlab = "Fitted Values", ylab = "Residuals",
main = "Residuals vs Fitted")
abline(h = 0, lty = 2, col = "grey")
plot(x = df_train$locs, y = resid(fit_svc), xlab = "Location", ylab = "Residuals",
main = "Residuals vs Locations")
abline(h = 0, lty = 2, col = "grey")
par(mfrow = c(1, 1))
## ----synthetic data model fit------------------------------------------------
kable(data.frame(
Model = c("linear", "SVC"),
# using method logLik
`log Likelihood` = round(as.numeric(c(logLik(fit_lm), logLik(fit_svc))), 2),
# using method AIC
AIC = round(c(AIC(fit_lm), AIC(fit_svc)), 2),
# using method BIC
BIC = round(c(BIC(fit_lm), BIC(fit_svc)), 2)
))
## ----synthetic data fitted----------------------------------------------------
head(fitted(fit_svc))
## ----synthetic data SVC plot--------------------------------------------------
mat_coef <- cbind(
# constant coefficients from lm
lin1 = coef(fit_lm)[1],
lin2 = coef(fit_lm)[2],
# SVCs
svc1 = coef(fit_svc)[1] + fitted(fit_svc)[, 1],
svc2 = coef(fit_svc)[2] + fitted(fit_svc)[, 2]
)
matplot(
x = df_train$locs,
y = mat_coef, pch = c(1, 2, 1, 2), col = c(1, 1, 2, 2),
xlab = "Location", ylab = "Beta", main = "Estimated Coefficients")
legend("topright", legend = c("Intercept", "covariate x", "linear model", "SVC model"),
pch = c(1, 2, 19, 19), col = c("grey", "grey", "black", "red"))
## ----synthetic data predictive performance------------------------------------
# using method predict with whole data and corresponding locations
df_svc_pred <- predict(fit_svc, newdata = df, newlocs = df$locs)
# combining mean values and deviations
mat_coef_pred <- cbind(
svc1_pred = coef(fit_svc)[1] + df_svc_pred[, 1],
svc2_pred = coef(fit_svc)[2] + df_svc_pred[, 2]
)
# plot
matplot(x = df$locs, y = mat_coef_pred,
xlab = "Location", ylab = "Beta",
main = "Predicted vs Actual Coefficients",
col = c(1, 2), lty = c(1, 1), type = "l")
points(x = df$locs, y = SVCdata$beta[, 1], col = 1, pch = ".")
points(x = df$locs, y = SVCdata$beta[, 2], col = 2, pch = ".")
legend("topright", legend = c("Intercept", "Covariate", "Actual"),
col = c("black", "red", "black"),
pch = c(NA, NA, "."),
lty = c(1, 1, NA))
## ----sample location----------------------------------------------------------
(s_id <- sample(n, 1))
## ----synthetic data RMSE------------------------------------------------------
SE_lm <- (predict(fit_lm, newdata = df) - df$y)^2
# df_svc_pred from above
SE_svc <- (df_svc_pred$y.pred - df$y)^2
kable(data.frame(
model = c("linear", "SVC"),
`in-sample RMSE` = round(sqrt(c(mean(SE_lm[idTrain]), mean(SE_svc[idTrain]))), 3),
`out-of-sample RMSE` = round(sqrt(c(mean(SE_lm[-idTrain]), mean(SE_svc[-idTrain]))), 3)
))
## ----meuse intro--------------------------------------------------------------
library(sp)
# attach sp and load data
data("meuse")
# documentation
help("meuse")
# overview
summary(meuse)
dim(meuse)
## ----meuse data and location of interest--------------------------------------
df_meuse <- meuse[, c("dist", "lime", "elev")]
df_meuse$l_cad <- log(meuse$cadmium)
df_meuse$lime <- as.numeric(as.character(df_meuse$lime))
locs <- as.matrix(meuse[, c("x", "y")])
## ----meuse data spatial plot, echo = FALSE, message=FALSE, warning=FALSE------
# load meuse river outlines
data("meuse.riv")
# create spatial object to create spplot
sp_meuse <- df_meuse
coordinates(sp_meuse) <- ~ locs
# visualize log Cadmium measurements along river
spplot(
sp_meuse, zcol = "l_cad", main = "Meuse River and Log Cadmium Measurements"
) + latticeExtra::layer(panel.lines(meuse.riv))
## ----meuse data pairs---------------------------------------------------------
pairs(df_meuse)
## ----meuse linear model-------------------------------------------------------
fit_lm <- lm(l_cad ~ ., data = df_meuse)
coef(fit_lm)
## ----LM residuals-------------------------------------------------------------
oldpar <- par(mfrow = c(1, 2))
plot(fit_lm, which = 1:2)
par(oldpar)
## ----LM spatial residuals, echo=FALSE-----------------------------------------
# add residuals to spatial object
sp_meuse$res_lm <- resid(fit_lm)
# visualize linear model residuals along river
spplot(sp_meuse, zcol = "res_lm",
main = "Meuse River and Residuals of Linear Model"
) + latticeExtra::layer(panel.lines(meuse.riv))
## ----meuse SVC model, warning=FALSE-------------------------------------------
fit_svc <- SVC_mle(l_cad ~ ., data = df_meuse, locs = locs,
control = SVC_mle_control(
profileLik = TRUE,
parscale = TRUE
))
coef(fit_svc)
## ----meuse fixed effects, echo = FALSE----------------------------------------
kable(t(data.frame(
round(cbind(`linear` = coef(fit_lm), `SVC`= coef(fit_svc)), 3)
)))
## ----varycoef predict locations-----------------------------------------------
# study area
data("meuse.grid")
# prediction
df_svc_pred <- predict(fit_svc, newlocs = as.matrix(meuse.grid[, c("x", "y")]))
colnames(df_svc_pred)[1:4] <- c("Intercept", "dist", "lime", "elev")
head(df_svc_pred)
|
/scratch/gouwar.j/cran-all/cranData/varycoef/inst/doc/Introduction.R
|
---
title: "varycoef: An R Package to Model Spatially Varying Coefficients"
author: "Jakob A. Dambon"
date: "October 2019, Updated: August 2022"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE,
fig.width=7, fig.height=4)
library(knitr)
prop_train <- 0.2
```
## Introduction
With the R package `varycoef` we enable the user to analyze spatial data and in a simple, yet versatile way. The underlying idea are *spatially varying coefficients* (SVC) that extend the linear model
$$ y_i = x_i^{(1)} \beta_1 + ... + x_i^{(p)} \beta_p + \varepsilon_i$$
by allowing the coefficients $\beta_j, j = 1, ..., p$ to vary over space. That is, for a location $s$ we assume the following model:
$$ y_i = x_i^{(1)} \beta_1(s) + ... + x_i^{(p)} \beta_p(s) + \varepsilon_i$$
In particular, we use so-called *Gaussian processes* (GP) to define the spatial structure of the coefficients. Therefore, our models are called *GP-based SVC models*.
In this article, we will show what SVC models are and how to define them. Afterwards, we give a short and illustrative example with synthetic data and show how to apply the methods provided in `varycoef`. Finally, using the well known data set `meuse` from the package `sp`.
### Disclaimer
The analyses and results in this article are meant to introduce the package `varycoef` and **not** to be a rigorous statistical analysis of a data set. As this article should make the usage of `varycoef` as simple as possible, we skip over some of the technical or mathematical details and in some cases abuse notation. For a rigorous definition, please refer to the resources below. Further, the model estimation is performed on rather small data sets to ease computation ($n < 200$). We recommend to apply SVC models, particularly with many coefficients, on larger data sets.
### Further References
Our package evolved over time and we present some highlights:
- In [Dambon et al. (2021a)](https://doi.org/10.1016/j.spasta.2020.100470) we introduce the GP-based SVC model and the methodology on how to estimate them. Further, we provide a comparison on synthetic and real world data with other SVC methodologies.
- In [Dambon et al. (2022a)](https://doi.org/10.1186/s41937-021-00080-2) we present an in-depth analysis of Swiss real estate data using GP-based SVC models.
- In [Dambon et al. (2022b)](https://doi.org/10.1080/13658816.2022.2097684) we introduce a variable selection method. This is not covered by this article.
- For more information on Gaussian processes and their application on spatial data, please refer to chapter 9 of the ["STA330: Modeling Dependent Data" lecture notes](http://user.math.uzh.ch/furrer/download/sta330/script_sta330.pdf) by Reinhard Furrer.
### Preliminaries
Before we start, we want to give some prerequisites that you should know about in order to follow the analysis below. Beside a classical linear regression model, we require the knowledge of:
- spatial data and geostatistics
- Gaussian processes and Gaussian random fields
- covariance functions and how the range and variance parameter influence them
- maximum likelihood estimation
### Set up
The `varycoef` package is available via [CRAN](https://cran.r-project.org/package=varycoef) or [Github](https://github.com/jakobdambon/varycoef). Latter one hosts the most recent version that is released to CRAN on a regular base.
```{r install, eval=FALSE}
# install from CRAN
install.packages("varycoef")
# install from Github (make sure that you installed the package "devtools")
devtools::install_github("jakobdambon/varycoef")
```
### Where to find help?
Within the R package, you can use these resources:
```{r help and vignettes, warning=FALSE}
# attach package
library(varycoef)
# general package help file
help("varycoef")
# where you find this vignette
vignette("Introduction", package = "varycoef")
```
You can find this article on the Github repository, too. We continue to add more material and examples.
## Synthetic Data Example
Let's dive into the analysis of some synthetic data. To ease the visualization, we will work with one-dimensional spatial data, i.e., any location $s$ is from the real line $\mathbb R$. We want to highlight that are package is not restricted to such analysis and that we can analyze spatial data from higher dimensions, i.e., $s \in \mathbb R^d$, where $d \geq 1$.
### Model and Data
As mentioned before, an SVC model extends the linear model by allowing the coefficients to vary over space. Therefore, we can write:
$$ y_i = x_i^{(1)} \beta_1(s) + ... + x_i^{(p)} \beta_p(s) + \varepsilon_i,$$
for some location $s$ where $\beta_j(s)$ indicates the dependence of the $j$th coefficient on the space. The coefficients are defined by Gaussian processes, but we skip over this part for now and take a look at a data set that was sampled using the model above. In `varycoef`, a data set named `SVCdata` is provided:
```{r synthetic data}
str(SVCdata)
help(SVCdata)
# number of observations, number of coefficients
n <- nrow(SVCdata$X); p <- ncol(SVCdata$X)
```
It consists of the response `y`, the model matrix `X`, the locations `locs`, and the usually unknown true coefficients `beta`, error `eps`, and true parameters `true_pars`. The model matrix is of dimension $`r n` \times `r p`$, i.e., we have $`r n`$ observations and $p = `r p`$ coefficients. The first column of `X` is identical to 1 to model the intercept.
We will use `r n*prop_train` observations of the data to train the model and leave the remaining `r n*(1-prop_train)` out as a test sample, i.e.:
```{r synthetic data train and test}
# create data frame
df <- with(SVCdata, data.frame(y = y, x = X[, 2], locs = locs))
set.seed(123)
idTrain <- sort(sample(n, n*prop_train))
df_train <- df[idTrain, ]
df_test <- df[-idTrain, ]
```
### Exploratory Data Analysis
We plot the part of the data that is usually available to us:
```{r synthetic data EDA}
par(mfrow = 1:2)
plot(y ~ x, data = df_train, xlab = "x", ylab = "y",
main = "Scatter Plot of Response and Covariate")
plot(y ~ locs, data = df_train, xlab = "s", ylab = "y",
main = "Scatter Plot of Response and Locations")
par(mfrow = c(1, 1))
```
We note that there is a clear linear dependency between the covariate and the response. However, there is not a clear spatial structure. We estimate a linear model and analyze the residuals thereof.
```{r synthetic data linear model}
fit_lm <- lm(y ~ x, data = df_train)
coef(fit_lm)
# residual plots
par(mfrow = 1:2)
plot(x = fitted(fit_lm), y = resid(fit_lm),
xlab = "Fitted Values", ylab = "Residuals",
main = "Residuals vs Fitted")
abline(h = 0, lty = 2, col = "grey")
plot(x = df_train$locs, y = resid(fit_lm), xlab = "Location", ylab = "Residuals",
main = "Residuals vs Locations")
abline(h = 0, lty = 2, col = "grey")
par(mfrow = c(1, 1))
```
Discarding the spatial information, we observe no structure within the residuals (Figure above, LHS). However, if we plot the residuals against there location, we clearly see some spatial structure. Therefore, we will apply the SVC model next.
### SVC Model
To estimate an SVC model, we can use the `SVC_mle()` function almost like the `lm()` function from above. As the name suggests, we use a *maximum likelihood estimation* (MLE) for estimating the parameters. For now, we only focus on the mean coefficients, which we obtain by the `coef()` method.
```{r synthetic data svc model}
fit_svc <- SVC_mle(y ~ x, data = df_train, locs = df_train$locs)
coef(fit_svc)
```
The only additional argument that we have to provide explicitly when calling `SVC_mle()` are the coordinates, i.e., the observation locations. The output is an object of class `r class(fit_svc)`. We can apply most of the methods that exist for `lm` objects to out output, too. For instance methods of `summary()`, `fitted()`, or `resid()`. We give the `summary()` output but do not go into details for now. Further, use the `fitted()` and `residuals()` methods to analyze the SVC model. Contrary to a `fitted()` method for an `lm` object, the output does not only contain the fitted response, but is a `data.frame` that contains the spatial deviations from the mean named `SVC_1`, `SVC_2`, and so on (see section Model Interpretation below), the response `y.pred`, and the respective locations `loc_1`, `loc_2`, etc. In our case, there is only one column since the locations are from a one-dimensional domain.
```{r methods}
# summary output
summary(fit_svc)
# fitted output
head(fitted(fit_svc))
# residual plots
par(mfrow = 1:2)
plot(x = fitted(fit_svc)$y.pred, y = resid(fit_svc),
xlab = "Fitted Values", ylab = "Residuals",
main = "Residuals vs Fitted")
abline(h = 0, lty = 2, col = "grey")
plot(x = df_train$locs, y = resid(fit_svc), xlab = "Location", ylab = "Residuals",
main = "Residuals vs Locations")
abline(h = 0, lty = 2, col = "grey")
par(mfrow = c(1, 1))
```
Compared to the output and residuals of the linear models, we immediately see that the residuals of the SVC model are smaller in range and do not have a spatial structure. They are both with respect to fitted values and locations distributed around zero and homoscedastic.
### Comparison of Models
We end this synthetic data example by comparing the linear with the SVC model. We already saw some advantages of the SVC model when investigating the residuals. Now, we take a look at the quality of the model fit, the model interpretation, and the predictive performance.
#### Model Fit
We can compare the models by the log likelihood, Akaike's or the Bayesian information criterion (AIC and BIC, respectively). Again, the corresponding methods are available:
```{r synthetic data model fit}
kable(data.frame(
Model = c("linear", "SVC"),
# using method logLik
`log Likelihood` = round(as.numeric(c(logLik(fit_lm), logLik(fit_svc))), 2),
# using method AIC
AIC = round(c(AIC(fit_lm), AIC(fit_svc)), 2),
# using method BIC
BIC = round(c(BIC(fit_lm), BIC(fit_svc)), 2)
))
```
In all four metrics the SVC model outperforms the linear model, i.e., the log likelihood is larger and the two information criteria are smaller.
#### Visualization of Coefficients
While the linear model estimates constant coefficients $\beta_j$, contrary and as the name suggests, the SVC model's coefficients vary over space $\beta_j(s)$. That is why the `fitted()` method does not only return the fitted response, but also the fitted coefficients and at their given locations:
```{r synthetic data fitted}
head(fitted(fit_svc))
```
Therefore, the SVC mentioned above is the sum of the mean value from the method `coef()` which we name $\mu_j$ and the zero-mean spatial deviations from above which we name $\eta_j(s)$, i.e., $\beta_j(s) = \mu_j + \eta_j(s)$. We visualize the coefficients at their respective locations:
```{r synthetic data SVC plot}
mat_coef <- cbind(
# constant coefficients from lm
lin1 = coef(fit_lm)[1],
lin2 = coef(fit_lm)[2],
# SVCs
svc1 = coef(fit_svc)[1] + fitted(fit_svc)[, 1],
svc2 = coef(fit_svc)[2] + fitted(fit_svc)[, 2]
)
matplot(
x = df_train$locs,
y = mat_coef, pch = c(1, 2, 1, 2), col = c(1, 1, 2, 2),
xlab = "Location", ylab = "Beta", main = "Estimated Coefficients")
legend("topright", legend = c("Intercept", "covariate x", "linear model", "SVC model"),
pch = c(1, 2, 19, 19), col = c("grey", "grey", "black", "red"))
```
#### Spatial Prediction
We use the entire data set to compute the in- and out-of-sample rooted mean square error (RMSE) for the response for both the linear and SVC model. Here we rely on the `predict()` methods. Further, we can compare the predicted coefficients with the true coefficients provided in `SVCdata`, something that we usually cannot do.
```{r synthetic data predictive performance}
# using method predict with whole data and corresponding locations
df_svc_pred <- predict(fit_svc, newdata = df, newlocs = df$locs)
# combining mean values and deviations
mat_coef_pred <- cbind(
svc1_pred = coef(fit_svc)[1] + df_svc_pred[, 1],
svc2_pred = coef(fit_svc)[2] + df_svc_pred[, 2]
)
# plot
matplot(x = df$locs, y = mat_coef_pred,
xlab = "Location", ylab = "Beta",
main = "Predicted vs Actual Coefficients",
col = c(1, 2), lty = c(1, 1), type = "l")
points(x = df$locs, y = SVCdata$beta[, 1], col = 1, pch = ".")
points(x = df$locs, y = SVCdata$beta[, 2], col = 2, pch = ".")
legend("topright", legend = c("Intercept", "Covariate", "Actual"),
col = c("black", "red", "black"),
pch = c(NA, NA, "."),
lty = c(1, 1, NA))
```
#### Model Interpretation
The linear model is constant and the same for each location, i.e.:
$$y = \beta_1 + \beta_2\cdot x + \varepsilon = `r round(coef(fit_lm)[1], 2)` + `r round(coef(fit_lm)[2], 2)` \cdot x + \varepsilon$$
Here, the SVC model can be interpreted in a similar way where on average, it is simply the mean coefficient value with some location specific deviation $\eta_j(s)$, i.e.:
$$y = \beta_1(s) + \beta_2(s)\cdot x + \varepsilon = \bigl(`r round(coef(fit_svc)[1], 2)` + \eta_1(s)\bigr) + \bigl(`r round(coef(fit_svc)[2], 2)`+ \eta_2(s) \bigr) \cdot x + \varepsilon$$
Say we are interested in a particular position, like:
```{r sample location}
(s_id <- sample(n, 1))
```
The coordinate is $s_{`r s_id`} = `r round(df$locs[s_id], 2)`$. We can extract the deviations $\eta_j(s)$ and simply add them to the model. We receive the following location specific model.
$$y = \beta_1(s_{`r s_id`}) + \beta_2(s_{`r s_id`})\cdot x + \varepsilon = \bigl(`r round(coef(fit_svc)[1], 2)` `r round(df_svc_pred[s_id, 1], 2)`\bigr) + \bigl(`r round(coef(fit_svc)[2], 2)`+ `r round(df_svc_pred[s_id, 2], 2)`\bigr) \cdot x + \varepsilon = `r round(coef(fit_svc)[1] + df_svc_pred[s_id, 1], 2)` + `r round(coef(fit_svc)[2] + df_svc_pred[s_id, 2], 2)` \cdot x + \varepsilon$$
The remaining comparison of the two model at the given location is as usual. Between the both models we see that the intercept of the linear model is larger and the coefficient of $x$ is smaller than the
SVC model's intercept and coefficient of $x$, respectively.
#### Predictive Performance
Finally, we compare the prediction errors of the model. We compute the rooted mean squared errors (RMSE) for both models and both the training and testing data.
```{r synthetic data RMSE}
SE_lm <- (predict(fit_lm, newdata = df) - df$y)^2
# df_svc_pred from above
SE_svc <- (df_svc_pred$y.pred - df$y)^2
kable(data.frame(
model = c("linear", "SVC"),
`in-sample RMSE` = round(sqrt(c(mean(SE_lm[idTrain]), mean(SE_svc[idTrain]))), 3),
`out-of-sample RMSE` = round(sqrt(c(mean(SE_lm[-idTrain]), mean(SE_svc[-idTrain]))), 3)
))
```
We notice a significant difference in both RMSE between the models. On the training data, i.e., the in-sample RMSE, we observe and improvement by more than 50%. This is quite common since the SVC model has a higher flexibility. Therefore, it is very pleasing to see that even on the testing data, i.e., the out-of-sample RMSE, the SVC model still improves the RMSE by almost 30% compared to the linear model.
## Meuse Data Set Example
We now turn to a real world data set, the `meuse` data from the package `sp`.
```{r meuse intro}
library(sp)
# attach sp and load data
data("meuse")
# documentation
help("meuse")
# overview
summary(meuse)
dim(meuse)
```
Our goal is to model the log `cadmium` measurements using the following independent variables:
- `dist`, i.e. the normalized distance to the river Meuse.
- `lime`, which is a 2-level factor indicating the presence of lime.
- `elev`, i.e. the relative elevation above the local river bed.
This provides us a model with "cheap" covariates and we can regress our variable of interest on them.
```{r meuse data and location of interest}
df_meuse <- meuse[, c("dist", "lime", "elev")]
df_meuse$l_cad <- log(meuse$cadmium)
df_meuse$lime <- as.numeric(as.character(df_meuse$lime))
locs <- as.matrix(meuse[, c("x", "y")])
```
### Exploratory Data Analysis
First, we plot the log Cadmium measurements at their respective locations. The color ranges from yellow (high Cadmium measurements) to black (low Cadmium measurements).
```{r meuse data spatial plot, echo = FALSE, message=FALSE, warning=FALSE}
# load meuse river outlines
data("meuse.riv")
# create spatial object to create spplot
sp_meuse <- df_meuse
coordinates(sp_meuse) <- ~ locs
# visualize log Cadmium measurements along river
spplot(
sp_meuse, zcol = "l_cad", main = "Meuse River and Log Cadmium Measurements"
) + latticeExtra::layer(panel.lines(meuse.riv))
```
Generally, the values for `l_cad` are highest close to the river Meuse. However, there is some spatial structure comparing the center of all observations to the Northern part. Therefore, we expect the `dist` covariate to be an important regressor. Omitting the spatial structure, we can also look at a `pairs` plot.
```{r meuse data pairs}
pairs(df_meuse)
```
Indeed, we note linear relationships between `l_cad` on the one hand and `elev` as well as `dist` on the other hand. Further, when `lime` is equal to 1, i.e., there is lime present in the soil, the Cadmium measurements are higher.
### Linear Model
As a baseline, we start with a linear model:
```{r meuse linear model}
fit_lm <- lm(l_cad ~ ., data = df_meuse)
coef(fit_lm)
```
The residual analysis shows:
```{r LM residuals}
oldpar <- par(mfrow = c(1, 2))
plot(fit_lm, which = 1:2)
par(oldpar)
```
The spatial distribution of the residuals is the following:
```{r LM spatial residuals, echo=FALSE}
# add residuals to spatial object
sp_meuse$res_lm <- resid(fit_lm)
# visualize linear model residuals along river
spplot(sp_meuse, zcol = "res_lm",
main = "Meuse River and Residuals of Linear Model"
) + latticeExtra::layer(panel.lines(meuse.riv))
```
One can observe that there is a spatial structure in the residuals. This motivates us to use an SVC model.
### SVC Model
The call to estimate the SVC model is again quite similar to the `lm()` call from above. However, we specify further arguments for the MLE using the `control` argument. First, we are using an optimization over the profiled likelihood (`profileLik = TRUE`) and second, we apply parameter scaling (`parscale = TRUE`) in the numeric optimization. Please check the corresponding help file `help("SVC_mle_control")` for more details.
```{r meuse SVC model, warning=FALSE}
fit_svc <- SVC_mle(l_cad ~ ., data = df_meuse, locs = locs,
control = SVC_mle_control(
profileLik = TRUE,
parscale = TRUE
))
coef(fit_svc)
```
The obtained mean coefficient values of the linear and SVC model are quite similar, but this does not come as a surprise.
```{r meuse fixed effects, echo = FALSE}
kable(t(data.frame(
round(cbind(`linear` = coef(fit_lm), `SVC`= coef(fit_svc)), 3)
)))
```
### Predictions
Additionally to the `meuse` data the `sp` package also contains another data set called `meuse.grid` that contains a 40 by 40 meter spaced grid of the entire study area along the Meuse river. We can use the locations to predict the SVCs. However, the covariates `elev` and `lime` are missing. Therefore, we cannot predict the response. Again, the fitted SVC values are only the deviations from the mean. We observe that the SVC for `elev` is in fact constant.
```{r varycoef predict locations}
# study area
data("meuse.grid")
# prediction
df_svc_pred <- predict(fit_svc, newlocs = as.matrix(meuse.grid[, c("x", "y")]))
colnames(df_svc_pred)[1:4] <- c("Intercept", "dist", "lime", "elev")
head(df_svc_pred)
```
The attentive reader might have noticed that the `elev` column only contains 0. Therefore, there are no deviations and the respective coefficient is constant and our method is capable to estimate constant coefficients within the MLE. There exists a selection method to not only select the varying coefficients, but to also select the mean value, i.e., the fixed effect. Please refer to Dambon et al. (2022b) for further information.
## Conclusion
SVC models are a powerful tool to analyze spatial data. With the R package `varycoef`, we provide an accessible and easy way to apply GP-based SVC models that is very close to the classical `lm` experience. If you have further questions or issues, please visit our [Github repository](https://github.com/jakobdambon/varycoef).
## References
Dambon, J. A., Sigrist, F., Furrer, R. (2021) **Maximum likelihood estimation of spatially varying coefficient models for large data with an application to real estate price prediction**, Spatial Statistics, 41 (100470). [doi:10.1016/j.spasta.2020.100470 ](https://doi.org/10.1016/j.spasta.2020.100470)
Dambon, J.A., Fahrländer, S.S., Karlen, S. et al. (2022a) **Examining the vintage effect in hedonic pricing using spatially varying coefficients models: a case study of single-family houses in the Canton of Zurich**, Swiss Journal Economics Statistics 158(2). [doi:10.1186/s41937-021-00080-2](https://doi.org/10.1186/s41937-021-00080-2)
Dambon, J. A., Sigrist, F., Furrer, R. (2022b) **Joint variable selection of both fixed and random effects for Gaussian process-based spatially varying coefficient models**, International Journal of Geographical Information Science [doi:10.1080/13658816.2022.2097684](https://doi.org/10.1080/13658816.2022.2097684)
Furrer, R. (2022) **Modeling Dependent Data**, [Lecture notes](http://user.math.uzh.ch/furrer/download/sta330/script_sta330.pdf) accessed on August 15, 2022
|
/scratch/gouwar.j/cran-all/cranData/varycoef/inst/doc/Introduction.Rmd
|
---
title: "varycoef: An R Package to Model Spatially Varying Coefficients"
author: "Jakob A. Dambon"
date: "October 2019, Updated: August 2022"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE,
fig.width=7, fig.height=4)
library(knitr)
prop_train <- 0.2
```
## Introduction
With the R package `varycoef` we enable the user to analyze spatial data and in a simple, yet versatile way. The underlying idea are *spatially varying coefficients* (SVC) that extend the linear model
$$ y_i = x_i^{(1)} \beta_1 + ... + x_i^{(p)} \beta_p + \varepsilon_i$$
by allowing the coefficients $\beta_j, j = 1, ..., p$ to vary over space. That is, for a location $s$ we assume the following model:
$$ y_i = x_i^{(1)} \beta_1(s) + ... + x_i^{(p)} \beta_p(s) + \varepsilon_i$$
In particular, we use so-called *Gaussian processes* (GP) to define the spatial structure of the coefficients. Therefore, our models are called *GP-based SVC models*.
In this article, we will show what SVC models are and how to define them. Afterwards, we give a short and illustrative example with synthetic data and show how to apply the methods provided in `varycoef`. Finally, using the well known data set `meuse` from the package `sp`.
### Disclaimer
The analyses and results in this article are meant to introduce the package `varycoef` and **not** to be a rigorous statistical analysis of a data set. As this article should make the usage of `varycoef` as simple as possible, we skip over some of the technical or mathematical details and in some cases abuse notation. For a rigorous definition, please refer to the resources below. Further, the model estimation is performed on rather small data sets to ease computation ($n < 200$). We recommend to apply SVC models, particularly with many coefficients, on larger data sets.
### Further References
Our package evolved over time and we present some highlights:
- In [Dambon et al. (2021a)](https://doi.org/10.1016/j.spasta.2020.100470) we introduce the GP-based SVC model and the methodology on how to estimate them. Further, we provide a comparison on synthetic and real world data with other SVC methodologies.
- In [Dambon et al. (2022a)](https://doi.org/10.1186/s41937-021-00080-2) we present an in-depth analysis of Swiss real estate data using GP-based SVC models.
- In [Dambon et al. (2022b)](https://doi.org/10.1080/13658816.2022.2097684) we introduce a variable selection method. This is not covered by this article.
- For more information on Gaussian processes and their application on spatial data, please refer to chapter 9 of the ["STA330: Modeling Dependent Data" lecture notes](http://user.math.uzh.ch/furrer/download/sta330/script_sta330.pdf) by Reinhard Furrer.
### Preliminaries
Before we start, we want to give some prerequisites that you should know about in order to follow the analysis below. Beside a classical linear regression model, we require the knowledge of:
- spatial data and geostatistics
- Gaussian processes and Gaussian random fields
- covariance functions and how the range and variance parameter influence them
- maximum likelihood estimation
### Set up
The `varycoef` package is available via [CRAN](https://cran.r-project.org/package=varycoef) or [Github](https://github.com/jakobdambon/varycoef). Latter one hosts the most recent version that is released to CRAN on a regular base.
```{r install, eval=FALSE}
# install from CRAN
install.packages("varycoef")
# install from Github (make sure that you installed the package "devtools")
devtools::install_github("jakobdambon/varycoef")
```
### Where to find help?
Within the R package, you can use these resources:
```{r help and vignettes, warning=FALSE}
# attach package
library(varycoef)
# general package help file
help("varycoef")
# where you find this vignette
vignette("Introduction", package = "varycoef")
```
You can find this article on the Github repository, too. We continue to add more material and examples.
## Synthetic Data Example
Let's dive into the analysis of some synthetic data. To ease the visualization, we will work with one-dimensional spatial data, i.e., any location $s$ is from the real line $\mathbb R$. We want to highlight that are package is not restricted to such analysis and that we can analyze spatial data from higher dimensions, i.e., $s \in \mathbb R^d$, where $d \geq 1$.
### Model and Data
As mentioned before, an SVC model extends the linear model by allowing the coefficients to vary over space. Therefore, we can write:
$$ y_i = x_i^{(1)} \beta_1(s) + ... + x_i^{(p)} \beta_p(s) + \varepsilon_i,$$
for some location $s$ where $\beta_j(s)$ indicates the dependence of the $j$th coefficient on the space. The coefficients are defined by Gaussian processes, but we skip over this part for now and take a look at a data set that was sampled using the model above. In `varycoef`, a data set named `SVCdata` is provided:
```{r synthetic data}
str(SVCdata)
help(SVCdata)
# number of observations, number of coefficients
n <- nrow(SVCdata$X); p <- ncol(SVCdata$X)
```
It consists of the response `y`, the model matrix `X`, the locations `locs`, and the usually unknown true coefficients `beta`, error `eps`, and true parameters `true_pars`. The model matrix is of dimension $`r n` \times `r p`$, i.e., we have $`r n`$ observations and $p = `r p`$ coefficients. The first column of `X` is identical to 1 to model the intercept.
We will use `r n*prop_train` observations of the data to train the model and leave the remaining `r n*(1-prop_train)` out as a test sample, i.e.:
```{r synthetic data train and test}
# create data frame
df <- with(SVCdata, data.frame(y = y, x = X[, 2], locs = locs))
set.seed(123)
idTrain <- sort(sample(n, n*prop_train))
df_train <- df[idTrain, ]
df_test <- df[-idTrain, ]
```
### Exploratory Data Analysis
We plot the part of the data that is usually available to us:
```{r synthetic data EDA}
par(mfrow = 1:2)
plot(y ~ x, data = df_train, xlab = "x", ylab = "y",
main = "Scatter Plot of Response and Covariate")
plot(y ~ locs, data = df_train, xlab = "s", ylab = "y",
main = "Scatter Plot of Response and Locations")
par(mfrow = c(1, 1))
```
We note that there is a clear linear dependency between the covariate and the response. However, there is not a clear spatial structure. We estimate a linear model and analyze the residuals thereof.
```{r synthetic data linear model}
fit_lm <- lm(y ~ x, data = df_train)
coef(fit_lm)
# residual plots
par(mfrow = 1:2)
plot(x = fitted(fit_lm), y = resid(fit_lm),
xlab = "Fitted Values", ylab = "Residuals",
main = "Residuals vs Fitted")
abline(h = 0, lty = 2, col = "grey")
plot(x = df_train$locs, y = resid(fit_lm), xlab = "Location", ylab = "Residuals",
main = "Residuals vs Locations")
abline(h = 0, lty = 2, col = "grey")
par(mfrow = c(1, 1))
```
Discarding the spatial information, we observe no structure within the residuals (Figure above, LHS). However, if we plot the residuals against there location, we clearly see some spatial structure. Therefore, we will apply the SVC model next.
### SVC Model
To estimate an SVC model, we can use the `SVC_mle()` function almost like the `lm()` function from above. As the name suggests, we use a *maximum likelihood estimation* (MLE) for estimating the parameters. For now, we only focus on the mean coefficients, which we obtain by the `coef()` method.
```{r synthetic data svc model}
fit_svc <- SVC_mle(y ~ x, data = df_train, locs = df_train$locs)
coef(fit_svc)
```
The only additional argument that we have to provide explicitly when calling `SVC_mle()` are the coordinates, i.e., the observation locations. The output is an object of class `r class(fit_svc)`. We can apply most of the methods that exist for `lm` objects to out output, too. For instance methods of `summary()`, `fitted()`, or `resid()`. We give the `summary()` output but do not go into details for now. Further, use the `fitted()` and `residuals()` methods to analyze the SVC model. Contrary to a `fitted()` method for an `lm` object, the output does not only contain the fitted response, but is a `data.frame` that contains the spatial deviations from the mean named `SVC_1`, `SVC_2`, and so on (see section Model Interpretation below), the response `y.pred`, and the respective locations `loc_1`, `loc_2`, etc. In our case, there is only one column since the locations are from a one-dimensional domain.
```{r methods}
# summary output
summary(fit_svc)
# fitted output
head(fitted(fit_svc))
# residual plots
par(mfrow = 1:2)
plot(x = fitted(fit_svc)$y.pred, y = resid(fit_svc),
xlab = "Fitted Values", ylab = "Residuals",
main = "Residuals vs Fitted")
abline(h = 0, lty = 2, col = "grey")
plot(x = df_train$locs, y = resid(fit_svc), xlab = "Location", ylab = "Residuals",
main = "Residuals vs Locations")
abline(h = 0, lty = 2, col = "grey")
par(mfrow = c(1, 1))
```
Compared to the output and residuals of the linear models, we immediately see that the residuals of the SVC model are smaller in range and do not have a spatial structure. They are both with respect to fitted values and locations distributed around zero and homoscedastic.
### Comparison of Models
We end this synthetic data example by comparing the linear with the SVC model. We already saw some advantages of the SVC model when investigating the residuals. Now, we take a look at the quality of the model fit, the model interpretation, and the predictive performance.
#### Model Fit
We can compare the models by the log likelihood, Akaike's or the Bayesian information criterion (AIC and BIC, respectively). Again, the corresponding methods are available:
```{r synthetic data model fit}
kable(data.frame(
Model = c("linear", "SVC"),
# using method logLik
`log Likelihood` = round(as.numeric(c(logLik(fit_lm), logLik(fit_svc))), 2),
# using method AIC
AIC = round(c(AIC(fit_lm), AIC(fit_svc)), 2),
# using method BIC
BIC = round(c(BIC(fit_lm), BIC(fit_svc)), 2)
))
```
In all four metrics the SVC model outperforms the linear model, i.e., the log likelihood is larger and the two information criteria are smaller.
#### Visualization of Coefficients
While the linear model estimates constant coefficients $\beta_j$, contrary and as the name suggests, the SVC model's coefficients vary over space $\beta_j(s)$. That is why the `fitted()` method does not only return the fitted response, but also the fitted coefficients and at their given locations:
```{r synthetic data fitted}
head(fitted(fit_svc))
```
Therefore, the SVC mentioned above is the sum of the mean value from the method `coef()` which we name $\mu_j$ and the zero-mean spatial deviations from above which we name $\eta_j(s)$, i.e., $\beta_j(s) = \mu_j + \eta_j(s)$. We visualize the coefficients at their respective locations:
```{r synthetic data SVC plot}
mat_coef <- cbind(
# constant coefficients from lm
lin1 = coef(fit_lm)[1],
lin2 = coef(fit_lm)[2],
# SVCs
svc1 = coef(fit_svc)[1] + fitted(fit_svc)[, 1],
svc2 = coef(fit_svc)[2] + fitted(fit_svc)[, 2]
)
matplot(
x = df_train$locs,
y = mat_coef, pch = c(1, 2, 1, 2), col = c(1, 1, 2, 2),
xlab = "Location", ylab = "Beta", main = "Estimated Coefficients")
legend("topright", legend = c("Intercept", "covariate x", "linear model", "SVC model"),
pch = c(1, 2, 19, 19), col = c("grey", "grey", "black", "red"))
```
#### Spatial Prediction
We use the entire data set to compute the in- and out-of-sample rooted mean square error (RMSE) for the response for both the linear and SVC model. Here we rely on the `predict()` methods. Further, we can compare the predicted coefficients with the true coefficients provided in `SVCdata`, something that we usually cannot do.
```{r synthetic data predictive performance}
# using method predict with whole data and corresponding locations
df_svc_pred <- predict(fit_svc, newdata = df, newlocs = df$locs)
# combining mean values and deviations
mat_coef_pred <- cbind(
svc1_pred = coef(fit_svc)[1] + df_svc_pred[, 1],
svc2_pred = coef(fit_svc)[2] + df_svc_pred[, 2]
)
# plot
matplot(x = df$locs, y = mat_coef_pred,
xlab = "Location", ylab = "Beta",
main = "Predicted vs Actual Coefficients",
col = c(1, 2), lty = c(1, 1), type = "l")
points(x = df$locs, y = SVCdata$beta[, 1], col = 1, pch = ".")
points(x = df$locs, y = SVCdata$beta[, 2], col = 2, pch = ".")
legend("topright", legend = c("Intercept", "Covariate", "Actual"),
col = c("black", "red", "black"),
pch = c(NA, NA, "."),
lty = c(1, 1, NA))
```
#### Model Interpretation
The linear model is constant and the same for each location, i.e.:
$$y = \beta_1 + \beta_2\cdot x + \varepsilon = `r round(coef(fit_lm)[1], 2)` + `r round(coef(fit_lm)[2], 2)` \cdot x + \varepsilon$$
Here, the SVC model can be interpreted in a similar way where on average, it is simply the mean coefficient value with some location specific deviation $\eta_j(s)$, i.e.:
$$y = \beta_1(s) + \beta_2(s)\cdot x + \varepsilon = \bigl(`r round(coef(fit_svc)[1], 2)` + \eta_1(s)\bigr) + \bigl(`r round(coef(fit_svc)[2], 2)`+ \eta_2(s) \bigr) \cdot x + \varepsilon$$
Say we are interested in a particular position, like:
```{r sample location}
(s_id <- sample(n, 1))
```
The coordinate is $s_{`r s_id`} = `r round(df$locs[s_id], 2)`$. We can extract the deviations $\eta_j(s)$ and simply add them to the model. We receive the following location specific model.
$$y = \beta_1(s_{`r s_id`}) + \beta_2(s_{`r s_id`})\cdot x + \varepsilon = \bigl(`r round(coef(fit_svc)[1], 2)` `r round(df_svc_pred[s_id, 1], 2)`\bigr) + \bigl(`r round(coef(fit_svc)[2], 2)`+ `r round(df_svc_pred[s_id, 2], 2)`\bigr) \cdot x + \varepsilon = `r round(coef(fit_svc)[1] + df_svc_pred[s_id, 1], 2)` + `r round(coef(fit_svc)[2] + df_svc_pred[s_id, 2], 2)` \cdot x + \varepsilon$$
The remaining comparison of the two model at the given location is as usual. Between the both models we see that the intercept of the linear model is larger and the coefficient of $x$ is smaller than the
SVC model's intercept and coefficient of $x$, respectively.
#### Predictive Performance
Finally, we compare the prediction errors of the model. We compute the rooted mean squared errors (RMSE) for both models and both the training and testing data.
```{r synthetic data RMSE}
SE_lm <- (predict(fit_lm, newdata = df) - df$y)^2
# df_svc_pred from above
SE_svc <- (df_svc_pred$y.pred - df$y)^2
kable(data.frame(
model = c("linear", "SVC"),
`in-sample RMSE` = round(sqrt(c(mean(SE_lm[idTrain]), mean(SE_svc[idTrain]))), 3),
`out-of-sample RMSE` = round(sqrt(c(mean(SE_lm[-idTrain]), mean(SE_svc[-idTrain]))), 3)
))
```
We notice a significant difference in both RMSE between the models. On the training data, i.e., the in-sample RMSE, we observe and improvement by more than 50%. This is quite common since the SVC model has a higher flexibility. Therefore, it is very pleasing to see that even on the testing data, i.e., the out-of-sample RMSE, the SVC model still improves the RMSE by almost 30% compared to the linear model.
## Meuse Data Set Example
We now turn to a real world data set, the `meuse` data from the package `sp`.
```{r meuse intro}
library(sp)
# attach sp and load data
data("meuse")
# documentation
help("meuse")
# overview
summary(meuse)
dim(meuse)
```
Our goal is to model the log `cadmium` measurements using the following independent variables:
- `dist`, i.e. the normalized distance to the river Meuse.
- `lime`, which is a 2-level factor indicating the presence of lime.
- `elev`, i.e. the relative elevation above the local river bed.
This provides us a model with "cheap" covariates and we can regress our variable of interest on them.
```{r meuse data and location of interest}
df_meuse <- meuse[, c("dist", "lime", "elev")]
df_meuse$l_cad <- log(meuse$cadmium)
df_meuse$lime <- as.numeric(as.character(df_meuse$lime))
locs <- as.matrix(meuse[, c("x", "y")])
```
### Exploratory Data Analysis
First, we plot the log Cadmium measurements at their respective locations. The color ranges from yellow (high Cadmium measurements) to black (low Cadmium measurements).
```{r meuse data spatial plot, echo = FALSE, message=FALSE, warning=FALSE}
# load meuse river outlines
data("meuse.riv")
# create spatial object to create spplot
sp_meuse <- df_meuse
coordinates(sp_meuse) <- ~ locs
# visualize log Cadmium measurements along river
spplot(
sp_meuse, zcol = "l_cad", main = "Meuse River and Log Cadmium Measurements"
) + latticeExtra::layer(panel.lines(meuse.riv))
```
Generally, the values for `l_cad` are highest close to the river Meuse. However, there is some spatial structure comparing the center of all observations to the Northern part. Therefore, we expect the `dist` covariate to be an important regressor. Omitting the spatial structure, we can also look at a `pairs` plot.
```{r meuse data pairs}
pairs(df_meuse)
```
Indeed, we note linear relationships between `l_cad` on the one hand and `elev` as well as `dist` on the other hand. Further, when `lime` is equal to 1, i.e., there is lime present in the soil, the Cadmium measurements are higher.
### Linear Model
As a baseline, we start with a linear model:
```{r meuse linear model}
fit_lm <- lm(l_cad ~ ., data = df_meuse)
coef(fit_lm)
```
The residual analysis shows:
```{r LM residuals}
oldpar <- par(mfrow = c(1, 2))
plot(fit_lm, which = 1:2)
par(oldpar)
```
The spatial distribution of the residuals is the following:
```{r LM spatial residuals, echo=FALSE}
# add residuals to spatial object
sp_meuse$res_lm <- resid(fit_lm)
# visualize linear model residuals along river
spplot(sp_meuse, zcol = "res_lm",
main = "Meuse River and Residuals of Linear Model"
) + latticeExtra::layer(panel.lines(meuse.riv))
```
One can observe that there is a spatial structure in the residuals. This motivates us to use an SVC model.
### SVC Model
The call to estimate the SVC model is again quite similar to the `lm()` call from above. However, we specify further arguments for the MLE using the `control` argument. First, we are using an optimization over the profiled likelihood (`profileLik = TRUE`) and second, we apply parameter scaling (`parscale = TRUE`) in the numeric optimization. Please check the corresponding help file `help("SVC_mle_control")` for more details.
```{r meuse SVC model, warning=FALSE}
fit_svc <- SVC_mle(l_cad ~ ., data = df_meuse, locs = locs,
control = SVC_mle_control(
profileLik = TRUE,
parscale = TRUE
))
coef(fit_svc)
```
The obtained mean coefficient values of the linear and SVC model are quite similar, but this does not come as a surprise.
```{r meuse fixed effects, echo = FALSE}
kable(t(data.frame(
round(cbind(`linear` = coef(fit_lm), `SVC`= coef(fit_svc)), 3)
)))
```
### Predictions
Additionally to the `meuse` data the `sp` package also contains another data set called `meuse.grid` that contains a 40 by 40 meter spaced grid of the entire study area along the Meuse river. We can use the locations to predict the SVCs. However, the covariates `elev` and `lime` are missing. Therefore, we cannot predict the response. Again, the fitted SVC values are only the deviations from the mean. We observe that the SVC for `elev` is in fact constant.
```{r varycoef predict locations}
# study area
data("meuse.grid")
# prediction
df_svc_pred <- predict(fit_svc, newlocs = as.matrix(meuse.grid[, c("x", "y")]))
colnames(df_svc_pred)[1:4] <- c("Intercept", "dist", "lime", "elev")
head(df_svc_pred)
```
The attentive reader might have noticed that the `elev` column only contains 0. Therefore, there are no deviations and the respective coefficient is constant and our method is capable to estimate constant coefficients within the MLE. There exists a selection method to not only select the varying coefficients, but to also select the mean value, i.e., the fixed effect. Please refer to Dambon et al. (2022b) for further information.
## Conclusion
SVC models are a powerful tool to analyze spatial data. With the R package `varycoef`, we provide an accessible and easy way to apply GP-based SVC models that is very close to the classical `lm` experience. If you have further questions or issues, please visit our [Github repository](https://github.com/jakobdambon/varycoef).
## References
Dambon, J. A., Sigrist, F., Furrer, R. (2021) **Maximum likelihood estimation of spatially varying coefficient models for large data with an application to real estate price prediction**, Spatial Statistics, 41 (100470). [doi:10.1016/j.spasta.2020.100470 ](https://doi.org/10.1016/j.spasta.2020.100470)
Dambon, J.A., Fahrländer, S.S., Karlen, S. et al. (2022a) **Examining the vintage effect in hedonic pricing using spatially varying coefficients models: a case study of single-family houses in the Canton of Zurich**, Swiss Journal Economics Statistics 158(2). [doi:10.1186/s41937-021-00080-2](https://doi.org/10.1186/s41937-021-00080-2)
Dambon, J. A., Sigrist, F., Furrer, R. (2022b) **Joint variable selection of both fixed and random effects for Gaussian process-based spatially varying coefficient models**, International Journal of Geographical Information Science [doi:10.1080/13658816.2022.2097684](https://doi.org/10.1080/13658816.2022.2097684)
Furrer, R. (2022) **Modeling Dependent Data**, [Lecture notes](http://user.math.uzh.ch/furrer/download/sta330/script_sta330.pdf) accessed on August 15, 2022
|
/scratch/gouwar.j/cran-all/cranData/varycoef/vignettes/Introduction.Rmd
|
#' Kolmogorov-Smirnov goodness-of-fit test for the Vasicek distribution
#'
#' The function \code{gof_ks} performs Kolmogorov-Smirnov goodness-of-fit
#' test for the Vasicek distribution
#'
#' @param x A numeric vector in the (0, 1) interval that is supposed to
#' follow the Vasicek distribution
#' @param Rho The Rho parameter in the Vasicek distribution
#' @param P The P parameter in the Vasicek distribution
#'
#' @return A list with statistical test result, including ks stat and p-value.
#'
#' @examples
#' x <- vsk_rvs(100, Rho = 0.2, P = 0.1)
#' gof_ks(x, Rho = 0.2, P = 0.1)
gof_ks <- function(x, Rho, P) {
x_ <- sort(x[x > 0 & x < 1 & !is.na(x)])
cdf0 <- stats::ecdf(x_)(x_)
cdf1 <- vsk_cdf(x, Rho = Rho, P = P)
ks <- stats::ks.test(cdf0, cdf1)
return(list(ks = ks$statistic, pvalue = ks$p.value))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/gof_ks.R
|
#' Estimating Vasicek Rho parameter by assuming the know P parameter
#'
#' The function \code{vsk_Rho} estimates Rho parameter in the Vasicek
#' distribution by using maximum likelihood estimator, assuming the
#' known P parameter.
#'
#' @param x A numeric vector in the (0, 1) interval that is supposed to
#' follow the Vasicek distribution
#' @param p A numeric vector in the (0, 1) interval. p has the same length
#' as x. Each value of p can be a constant or varying.
#'
#' @return A scalar representing the Rho parameter in the Vasicek distribution.
#'
#' @examples
#' x <- vsk_rvs(1000, Rho = 0.2, P = 0.1)
#' p <- rep(mean(x), length(x))
#' vsk_Rho(x, p)
#' # 0.2110976
vsk_Rho <- function(x, p) {
x_ <- x[x > 0 & x < 1 & !is.na(x)]
p_ <- p[p > 0 & p < 1 & !is.na(p)]
if (length(x_) != length(p_)) stop("x and p have different lengths!", call. = F)
fn <- function(r_) -sum(log(Reduce(c, lapply(1:length(x),
function(i) vsk_pdf(x_[i], Rho = r_, P = p_[i])))))
r_ <- optimize(fn, c(0, 1))$minimum
return(r_)
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_Rho.R
|
#' Calculating the cumulative distribution function of Vasicek
#'
#' The function \code{vsk_cdf} calculates the cumulative distribution
#' function of Vasicek.
#'
#' @param x A numeric vector in the [0, 1] interval that is supposed to
#' follow the Vasicek distribution
#' @param Rho The Rho parameter in the Vasicek distribution
#' @param P The P parameter in the Vasicek distribution
#'
#' @return A numeric vector with the corresponding cdf.
#'
#' @examples
#' vsk_cdf(c(0.278837772815679, 0.5217229060260343), Rho = 0.2, P = 0.3)
#' # [1] 0.5 0.9
vsk_cdf <- function(x, Rho, P) {
x_ <- x[x >= 0 & x <= 1 & !is.na(x)]
return(pnorm((sqrt(1 - Rho) * qnorm(x_) - qnorm(P)) / sqrt(Rho)))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_cdf.R
|
#' Estimating Vasicek parameters by using direct moment matching
#'
#' The function \code{vsk_mle} estimates parameters in the Vasicek
#' distribution by using direct moment matching.
#'
#' @param x A numeric vector in the (0, 1) interval that is supposed to
#' follow the Vasicek distribution
#'
#' @return A list with Vasicek parameters, namely Rho and P.
#'
#' @examples
#' vsk_dmm(vsk_rvs(1000, Rho = 0.2, P = 0.1))
#' # $Rho
#' # [1] 0.2135844
#' # $P
#' # [1] 0.1025469
vsk_dmm <- function(x) {
x_ <- x[x > 0 & x < 1 & !is.na(x)]
p_ <- mean(x_)
xx <- mean(x_ ^ 2)
mu <- c(0, 0)
fn <- function(r) {
abs(mvtnorm::pmvnorm(mean = mu, sigma = matrix(c(1, r, r, 1), ncol = 2),
lower = rep(-Inf, 2), upper = rep(qnorm(p_), 2)) - xx)
}
r_ <- optimize(fn, c(0, 1))$minimum
return(list(Rho = r_, P = p_))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_dmm.R
|
#' Estimating Vasicek parameters by using indirect moment matching
#'
#' The function \code{vsk_imm} estimates parameters in the Vasicek
#' distribution by using indirect moment matching.
#'
#' @param x A numeric vector in the (0, 1) interval that is supposed to
#' follow the Vasicek distribution
#'
#' @return A list with Vasicek parameters, namely Rho and P.
#'
#' @examples
#' vsk_imm(vsk_rvs(1000, Rho = 0.2, P = 0.1))
#' # $Rho
#' # [1] 0.2110422
#' # $P
#' # [1] 0.1024877
vsk_imm <- function(x) {
x_ <- x[x > 0 & x < 1 & !is.na(x)]
mu <- mean(qnorm(x_))
s2 <- mean((qnorm(x_)) ** 2) - mu * mu
p_ <- pnorm(mu / sqrt(1 + s2))
r_ <- s2 / (1 + s2)
return(list(Rho = r_, P = p_))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_imm.R
|
#' Estimating Vasicek parameters by using maximum likelihood estimator
#'
#' The function \code{vsk_mle} estimates parameters in the Vasicek
#' distribution by using maximum likelihood estimator.
#'
#' @param x A numeric vector in the (0, 1) interval that is supposed to
#' follow the Vasicek distribution
#'
#' @return A list with Vasicek parameters, namely Rho and P.
#'
#' @examples
#' vsk_mle(vsk_rvs(1000, Rho = 0.2, P = 0.1))
#' # $Rho
#' # [1] 0.2110976
#' # $P
#' # [1] 0.1025469
vsk_mle <- function(x) {
x_ <- x[x > 0 & x < 1 & !is.na(x)]
p_ <- mean(x_)
fn <- function(r_) -sum(log(vsk_pdf(x_, Rho = r_, P = p_)))
r_ <- optimize(fn, c(0, 1))$minimum
return(list(Rho = r_, P = p_))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_mle.R
|
#' Calculating the probability density function of Vasicek
#'
#' The function \code{vsk_pdf} calculates the probability density
#' function of Vasicek.
#'
#' @param x A numeric vector in the (0, 1) interval that is supposed to
#' follow the Vasicek distribution
#' @param Rho The Rho parameter in the Vasicek distribution
#' @param P The P parameter in the Vasicek distribution
#'
#' @return A numeric vector with the corresponding pdf.
#'
#' @examples
#' vsk_pdf(c(0.01, 0.02), Rho = 0.2, P = 0.3)
#' # [1] 0.07019659 0.22207564
vsk_pdf <- function(x, Rho, P) {
x_ <- x[x > 0 & x < 1 & !is.na(x)]
return(sqrt((1 - Rho) / Rho) * exp(-1 / (2 * Rho)
* (sqrt(1 - Rho) * qnorm(x_) - qnorm(P)) ^ 2
+ 1 / 2 * (qnorm(x_)) ^ 2))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_pdf.R
|
#' Calculating the percentile point function of Vasicek
#'
#' The function \code{vsk_ppf} calculates the percentile point
#' function of Vasicek.
#'
#' @param Alpha A numeric vector of probabilities
#' @param Rho The Rho parameter in the Vasicek distribution
#' @param P The P parameter in the Vasicek distribution
#'
#' @return A numeric vector with the corresponding ppf.
#'
#' @examples
#' vsk_ppf(c(0.5, 0.9), Rho = 0.2, P = 0.3)
#' # [1] 0.2788378 0.5217229
vsk_ppf <- function(Alpha, Rho, P) {
a_ <- Alpha[Alpha >= 0 & Alpha <= 1 & !is.na(Alpha)]
return(pnorm((qnorm(P) + sqrt(Rho) * qnorm(a_)) / sqrt(1 - Rho)))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_ppf.R
|
#' Estimating Vasicek parameters by using quantile-based estimator
#'
#' The function \code{vsk_qbe} estimates parameters in the Vasicek
#' distribution by using quantile-based estimator. It is not recommended
#' for small sample size.
#'
#' @param x A numeric vector in the (0, 1) interval that is supposed to
#' follow the Vasicek distribution
#'
#' @return A list with Vasicek parameters, namely Rho and P.
#'
#' @examples
#' vsk_qbe(vsk_rvs(1000, Rho = 0.2, P = 0.1))
#' # $Rho
#' # [1] 0.1941091
#' # $P
#' # [1] 0.1019701
vsk_qbe <- function(x) {
x_ <- stats::qnorm(x[x > 0 & x < 1 & !is.na(x)])
mu <- stats::quantile(x_, 0.50, names = FALSE)
s2 <- ((stats::quantile(x_, 0.75, names = FALSE) - mu) / stats::qnorm(0.75)) ^ 2
r_ <- s2 / (1 + s2)
p_ <- pnorm(mu / (sqrt(1 + s2)))
return(list(Rho = r_, P = p_))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_qbe.R
|
#' Generating random numbers for the Vasicek distribution
#'
#' The function \code{vsk_rvs} generates random numbers for the Vasicek
#' distribution.
#'
#' @param n An integer for the number of observations.
#' @param Rho The Rho parameter in the Vasicek distribution. It is in the
#' range of (0, 1).
#' @param P The P parameter in the Vasicek distribution. It is in the
#' range of (0, 1).
#' @param seed An integer that is used as the seed value to generate
#' random numbers.
#'
#' @return A list of random number that follows the Vasicek distribution.
#'
#' @examples
#' vsk_rvs(10, Rho = 0.2, P = 0.1)
vsk_rvs <- function(n, Rho, P, seed = 1) {
set.seed(seed)
rn <- stats::rnorm(n)
rv <- stats::pnorm((stats::qnorm(P) - sqrt(Rho) * rn) / sqrt(1 - Rho))
return(rv)
}
|
/scratch/gouwar.j/cran-all/cranData/vasicek/R/vsk_rvs.R
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
cpp_dvasicekmean <- function(x, alpha, theta, logprob = FALSE) {
.Call('_vasicekreg_cpp_dvasicekmean', PACKAGE = 'vasicekreg', x, alpha, theta, logprob)
}
cpp_pvasicekmean <- function(x, alpha, theta, lowertail = TRUE, logprob = FALSE) {
.Call('_vasicekreg_cpp_pvasicekmean', PACKAGE = 'vasicekreg', x, alpha, theta, lowertail, logprob)
}
cpp_qvasicekmean <- function(x, alpha, theta, lowertail = TRUE, logprob = FALSE) {
.Call('_vasicekreg_cpp_qvasicekmean', PACKAGE = 'vasicekreg', x, alpha, theta, lowertail, logprob)
}
cpp_dvasicekquant <- function(x, mu, theta, tau, logprob = FALSE) {
.Call('_vasicekreg_cpp_dvasicekquant', PACKAGE = 'vasicekreg', x, mu, theta, tau, logprob)
}
cpp_pvasicekquant <- function(x, mu, theta, tau, lowertail = TRUE, logprob = FALSE) {
.Call('_vasicekreg_cpp_pvasicekquant', PACKAGE = 'vasicekreg', x, mu, theta, tau, lowertail, logprob)
}
cpp_qvasicekquant <- function(x, mu, theta, tau, lowertail = TRUE, logprob = FALSE) {
.Call('_vasicekreg_cpp_qvasicekquant', PACKAGE = 'vasicekreg', x, mu, theta, tau, lowertail, logprob)
}
|
/scratch/gouwar.j/cran-all/cranData/vasicekreg/R/RcppExports.R
|
#' @name bodyfat
#' @aliases bodyfat
#'
#' @title Percentage of body fat data set
#'
#' @description The body fat percentage of individuals assisted in a public hospital in Curitiba, Paraná, Brazil.
#'
#' @format A data-frame with 298 observations and 9 columns:
#'
#' \itemize{
#' \item \code{ARMS}: arms fat percentage.
#' \item \code{LEGS}: legs fat percentage.
#' \item \code{BODY}: body fat percentage.
#' \item \code{ANDROID}: android fat percentage.
#' \item \code{GYNECOID}: ginecoid fat percentage.
#' \item \code{AGE}: age of individuals.
#' \item \code{BMI}: body mass index.
#' \item \code{SEX}: 1 for female, 2 for male.
#' \item \code{IPAQ}: 0 for IPAQ = sedentary, 1 for IPAQ = insufficiently active and 2 for IPAQ = active.
#' }
#'
#' @author Josmar Mazucheli \email{[email protected]}
#' @author Bruna Alves \email{[email protected]}
#' @usage data(bodyfat, package = "vasicekreg")
#'
#' @references
#'
#' Mazucheli, J., Leiva, V., Alves, B., and Menezes A. F. B., (2021). A new quantile regression for modeling bounded data under a unit Birnbaum-Saunders distribution with applications in medicine and politics. \emph{Symmetry}, \bold{13}(4) 1--21.
#'
#' Petterle, R. R., Bonat, W. H., Scarpin, C. T., Jonasson, T., and Borba, V. Z. C., (2020). Multivariate quasi-beta regression models for continuous bounded data. \emph{The International Journal of Biostatistics}, 1--15, (preprint).
#'
#' @source \url{http://www.leg.ufpr.br/doku.php/publications:papercompanions:multquasibeta}
#'
#' @examples
#' data(bodyfat, package = "vasicekreg")
#'
#' bodyfat$BMI <- bodyfat$BMI / 100
#' bodyfat$SEX <- as.factor(bodyfat$SEX)
#' bodyfat$IPAQ<- as.factor(bodyfat$IPAQ)
#'
#' library(gamlss)
#'
#' # mean fit
#' fitmean.logit <- gamlss(ARMS ~ AGE + BMI + SEX + IPAQ,
#' data = bodyfat, family = VASIM(mu.link = "logit", sigma.link = "logit"))
#'
#' fitmean.probit <- gamlss(ARMS ~ AGE + BMI + SEX + IPAQ,
#' data = bodyfat, family = VASIM(mu.link = "probit", sigma.link = "logit"))
#'
#' # quantile fit - tau = 0.5
#'
#' tau <- 0.50
#' fitquant.logit <- gamlss(ARMS ~ AGE + BMI + SEX + IPAQ, data = bodyfat,
#' family = VASIQ(mu.link = "logit", sigma.link = "logit"))
#'
#' fittaus <- lapply(c(0.10, 0.25, 0.50, 0.75, 0.90), function(Tau)
#' {
#' tau <<- Tau;
#' gamlss(ARMS ~ AGE + BMI + SEX + IPAQ, data = bodyfat,
#' family = VASIQ(mu.link = "logit", sigma.link = "logit"))
#' })
#'
#' sapply(fittaus, summary, USE.NAMES = TRUE)
"bodyfat"
|
/scratch/gouwar.j/cran-all/cranData/vasicekreg/R/bodyfat.R
|
#' @importFrom gamlss gamlss
#' @importFrom gamlss.dist checklink
#' @importFrom mvtnorm pmvnorm
#' @importFrom stats dnorm qnorm runif
#' @name VASIM
#' @aliases VASIM dVASIM pVASIM qVASIM rVASIM
#'
#' @title The Vasicek distribution - mean parameterization
#'
#' @description The function \code{VASIM()} define the Vasicek distribution for a \code{gamlss.family} object to be used in GAMLSS fitting. \code{VASIM()} has mean equal to the parameter mu and sigma as shape parameter. The functions \code{dVASIM}, \code{pVASIM}, \code{qVASIM} and \code{rVASIM} define the density, distribution function, quantile function and random generation for Vasicek distribution.
#'
#' @author Josmar Mazucheli \email{[email protected]}
#' @author Bruna Alves \email{[email protected]}
#'
#' @references
#'
#' Hastie, T. J. and Tibshirani, R. J. (1990). \emph{Generalized Additive Models}. Chapman and Hall, London.
#'
#' Mazucheli, J., Alves, B. and Korkmaz, M. C. (2021). The Vasicek quantile regression model. \emph{(under review)}.
#'
#' Rigby, R. A. and Stasinopoulos, D. M. (2005). Generalized additive models for location, scale and shape (with discussion). \emph{Applied. Statistics}, \bold{54}(3), 507--554.
#'
#' Rigby, R. A., Stasinopoulos, D. M., Heller, G. Z. and De Bastiani, F. (2019). \emph{Distributions for modeling location, scale, and shape: Using GAMLSS in R}. Chapman and Hall/CRC.
#'
#' Stasinopoulos, D. M. and Rigby, R. A. (2007) Generalized additive models for location scale and shape (GAMLSS) in R. \emph{Journal of Statistical Software}, \bold{23}(7), 1--45.
#'
#' Stasinopoulos, D. M., Rigby, R. A., Heller, G., Voudouris, V. and De Bastiani F. (2017) \emph{Flexible Regression and Smoothing: Using GAMLSS in R}, Chapman and Hall/CRC.
#'
#' Vasicek, O. A. (1987). Probability of loss on loan portfolio. \emph{KMV Corporation}.
#'
#' Vasicek, O. A. (2002). The distribution of loan portfolio value. \emph{Risk}, \bold{15}(12), 1--10.
#'
#' @param x,q vector of quantiles on the (0,1) interval.
#' @param p vector of probabilities.
#' @param n number of observations. If \code{length(n) > 1}, the length is taken to be the number required.
#' @param log,log.p logical; If TRUE, probabilities p are given as log(p).
#' @param lower.tail logical; If TRUE, (default), \eqn{P(X \leq{x})} are returned, otherwise \eqn{P(X > x)}.
#' @param mu.link the mu link function with default logit.
#' @param sigma.link the sigma link function with default logit.
#' @param mu vector of the mean parameter values.
#' @param sigma vector of shape parameter values.
#'
#' @return \code{VASIM()} return a gamlss.family object which can be used to fit a Vasicek distribution by gamlss() function.
#'
#' @note Note that for \code{VASIQ()}, mu is the \eqn{\tau}-th quantile and sigma a shape parameter. The \code{\link[gamlss]{gamlss}} function is used for parameters estimation.
#'
#' @seealso \code{\link[vasicekreg]{VASIQ}}, \code{\link[mvtnorm]{pmvnorm}}.
#'
#' @details
#' Probability density function
#' \deqn{f(x\mid \mu ,\sigma )=\sqrt{\frac{1-\sigma }{\sigma }}\exp \left\{ \frac{1}{2}\left[ \Phi ^{-1}\left( x\right) ^{2}-\left( \frac{\Phi ^{-1}\left( x\right) \sqrt{1-\sigma }-\Phi ^{-1}\left( \mu \right) }{\sqrt{\sigma }}\right) ^{2}\right] \right\}}
#'
#' Cumulative distribution function
#' \deqn{F(x\mid \mu ,\sigma )=\Phi \left( \frac{\Phi ^{-1}\left( x\right) \sqrt{1-\sigma }-\Phi ^{-1}\left( \mu \right) }{\sqrt{\sigma }}\right)}
#'
#' Quantile function
#' \deqn{Q(\tau \mid \mu ,\sigma )=F^{-1}(\tau \mid \mu ,\sigma )=\Phi \left(\frac{\Phi ^{-1}\left(\mu\right) +\Phi ^{-1}\left( \tau \right) \sqrt{\sigma }}{\sqrt{1-\sigma }}\right) }
#'
#' Expected value
#' \deqn{E(X) = \mu}
#'
#' Variance
#' \deqn{Var(X) = \Phi_2\left ( \Phi^{-1}(\mu),\Phi^{-1}(\mu),\sigma \right )-\mu^2}
#' where \eqn{0<(x, \mu, \tau, \sigma)<1} and \eqn{\Phi_2(\cdot)} is the probability distribution function for the standard bivariate normal distribution with correlation \eqn{\sigma}.
#' @examples
#'
#' set.seed(123)
#' x <- rVASIM(n = 1000, mu = 0.50, sigma = 0.69)
#' R <- range(x)
#' S <- seq(from = R[1], to = R[2], length.out = 1000)
#'
#' hist(x, prob = TRUE, main = 'Vasicek')
#' lines(S, dVASIM(x = S, mu = 0.50, sigma = 0.69), col = 2)
#'
#' plot(ecdf(x))
#' lines(S, pVASIM(q = S, mu = 0.50, sigma = 0.69), col = 2)
#'
#' plot(quantile(x, probs = S), type = "l")
#' lines(qVASIM(p = S, mu = 0.50, sigma = 0.69), col = 2)
#'
#' library(gamlss)
#' set.seed(123)
#' data <- data.frame(y = rVASIM(n = 100, mu = 0.5, sigma = 0.69))
#'
#' fit <- gamlss(y ~ 1, data = data, mu.link = 'logit', sigma.link = 'logit', family = VASIM)
#' 1 /(1 + exp(-fit$mu.coefficients))
#' 1 /(1 + exp(-fit$sigma.coefficients))
#'
#' set.seed(123)
#' n <- 100
#' x <- rbinom(n, size = 1, prob = 0.5)
#' eta <- 0.5 + 1 * x;
#' mu <- 1 / (1 + exp(-eta));
#' sigma <- 0.1;
#' y <- rVASIM(n, mu, sigma)
#' data <- data.frame(y, x)
#'
#' fit <- gamlss(y ~ x, data = data, family = VASIM, mu.link = 'logit', sigma.link = 'logit');
#'
##################################################
#' @rdname VASIM
#' @export
#
dVASIM <- function (x, mu, sigma, log = FALSE)
{
stopifnot(x > 0, x < 1, mu > 0, mu < 1, sigma > 0, sigma < 1);
cpp_dvasicekmean (x, mu, sigma, log[1L]);
}
##################################################
#' @rdname VASIM
#' @export
#'
pVASIM <- function (q, mu, sigma, lower.tail = TRUE, log.p = FALSE)
{
stopifnot(q > 0, q < 1, mu > 0, mu < 1, sigma > 0, sigma < 1)
cpp_pvasicekmean (q, mu, sigma, lower.tail[1L], log.p[1L])
}
##################################################
#' @rdname VASIM
#' @export
#'
qVASIM <- function(p, mu, sigma, lower.tail = TRUE, log.p = FALSE)
{
stopifnot(p > 0, p < 1, mu > 0, mu < 1, sigma > 0, sigma < 1)
cpp_qvasicekmean (p, mu, sigma, lower.tail[1L], log.p[1L])
}
##################################################
#' @rdname VASIM
#' @export
#'
rVASIM <- function(n, mu, sigma)
{
cpp_qvasicekmean (runif(n), mu, sigma, TRUE, FALSE)
}
##################################################
#' @rdname VASIM
#' @export
#'
VASIM <- function (mu.link = "logit", sigma.link = "logit")
{
mstats <- checklink("mu.link", "VASIM", substitute(mu.link), c("logit", "probit", "cloglog", "cauchit", "log", "own"))
dstats <- checklink("sigma.link", "VASIM", substitute(sigma.link), c("logit", "probit", "cloglog", "cauchit", "log", "own"))
structure(list(family = c("VASIM", "Vasicekm"),
parameters = list(mu = TRUE, sigma = TRUE), nopar = 2, type = "Continuous", mu.link = as.character(substitute(mu.link)),
sigma.link = as.character(substitute(sigma.link)), mu.linkfun = mstats$linkfun, sigma.linkfun = dstats$linkfun, mu.linkinv = mstats$linkinv,
sigma.linkinv = dstats$linkinv, mu.dr = mstats$mu.eta, sigma.dr = dstats$mu.eta,
dldm = function(y, mu, sigma){
t2 <- sqrt(0.1e1 - sigma);
t4 <- qnorm(mu);
t8 <- 0.1e1 / dnorm(t4);
qnormx <- qnorm(y);
return(0.10e1 * (qnormx * t2 - t4) / sigma * t8);
},
d2ldm2 = function(y, mu, sigma){
t9 <- qnorm(mu);
t1 <- 0.1e1 / dnorm(t9);
t2 <- t1 * t1;
t3 <- 0.1e1 / sigma;
t7 <- sqrt(0.1e1 - sigma);
t12 <- t9 * (t1 ^ 0.2e1);
qnormx <- qnorm(y);
return(-0.10e1 * t2 * t3 + 0.10e1 * (qnormx * t7 - t9) * t3 * t12);
},
dldd = function(y, mu, sigma){
qnormx <- qnorm(y);
t1 <- 0.1e1 - sigma;
t4 <- 0.1e1 / sigma;
t6 <- sqrt(t1);
t8 <- qnorm(mu);
t9 <- qnormx * t6 - t8;
t15 <- t9 * t9;
t16 <- sigma * sigma;
return(-0.5e0 / t1 - 0.5e0 * t4 + 0.5e0 * t9 * t4 * qnormx / t6 + 0.5e0 * t15 / t16);
},
d2ldd2 = function(y, mu, sigma){
qnormx <- qnorm(y);
t1 <- 0.1e1 - sigma;
t2 <- t1 * t1;
t5 <- sigma * sigma;
t6 <- 0.1e1 / t5;
t8 <- qnormx * qnormx;
t11 <- 0.1e1 / sigma;
t14 <- sqrt(t1);
t16 <- qnorm(mu);
t17 <- qnormx * t14 - t16;
t29 <- t17 * t17;
return(-0.5e0 / t2 + 0.5e0 * t6 - 0.2500000000e0 * t8 / t1 * t11 - 0.10e1 * t17 * t6 * qnormx / t14 +
0.2500000000e0 * t17 * t11 * qnormx / t14 / t1 - 0.10e1 * t29 / t5 / sigma);
},
d2ldmdd = function(y, mu, sigma){
t1 <- qnorm(mu);
t2 <- sqrt(0.1e1 - sigma);
t6 <- 0.1e1 / dnorm(t1)
t13 <- sigma * sigma;
qnormx <- qnorm(y);
return(-0.5000000000e0 * qnormx / t2 / sigma * t6 - 0.10e1 * (qnormx * t2 - t1) / t13 * t6);
},
G.dev.incr = function(y, mu, sigma, w, ...) -2 * dVASIM(y, mu, sigma, log = TRUE),
rqres = expression(rqres(pfun = "pVASIM", type = "Continuous", y = y, mu = mu, sigma = sigma)),
mu.initial = expression({mu <- (y + mean(y))/2}),
sigma.initial = expression({sigma <- rep(0.5, length(y))}),
mu.valid = function(mu) all(mu > 0 & mu < 1),
sigma.valid = function(sigma) all(sigma > 0 & sigma < 1),
y.valid = function(y) all(y > 0 & y < 1),
mean = function(mu) mu, variance = function(mu,sigma) sapply(1:length(mu), function(i)
pmvnorm(lower=c(-Inf, -Inf),
upper= rep(qnorm(mu[i],2)),
mean = c(0, 0),
corr = matrix(c(1, sigma[i], sigma[i], 1), ncol = 2)) - mu[i] ^ 2)),class = c("gamlss.family","family"))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicekreg/R/dpqr-vasicekmean.R
|
#' @importFrom gamlss gamlss
#' @importFrom gamlss.dist checklink
#' @importFrom mvtnorm pmvnorm
#' @importFrom stats dnorm qnorm runif pnorm
#' @name VASIQ
#' @aliases VASIQ dVASIQ pVASIQ qVASIQ rVASIQ
#'
#' @title The Vasicek distribution - quantile parameterization
#'
#' @description The function \code{VASIQ()} define the Vasicek distribution for a \code{gamlss.family} object to be used in GAMLSS fitting. \code{VASIQ()} has the \eqn{\tau}-th quantile equal to the parameter mu and sigma as shape parameter. The functions \code{dVASIQ}, \code{pVASIQ}, \code{qVASIQ} and \code{rVASIQ} define the density, distribution function, quantile function and random generation for Vasicek distribution.
#'
#' @author Josmar Mazucheli \email{[email protected]}
#' @author Bruna Alves \email{[email protected]}
#'
#' @references
#'
#' Hastie, T. J. and Tibshirani, R. J. (1990). \emph{Generalized Additive Models}. Chapman and Hall, London.
#'
#' Mazucheli, J., Alves, B. and Korkmaz, M. C. (2021). The Vasicek quantile regression model. \emph{(under review)}.
#'
#' Rigby, R. A. and Stasinopoulos, D. M. (2005). Generalized additive models for location, scale and shape (with discussion). \emph{Applied. Statistics}, \bold{54}(3), 507--554.
#'
#' Rigby, R. A., Stasinopoulos, D. M., Heller, G. Z. and De Bastiani, F. (2019). \emph{Distributions for modeling location, scale, and shape: Using GAMLSS in R}. Chapman and Hall/CRC.
#'
#' Stasinopoulos, D. M. and Rigby, R. A. (2007) Generalized additive models for location scale and shape (GAMLSS) in R. \emph{Journal of Statistical Software}, \bold{23}(7), 1--45.
#'
#' Stasinopoulos, D. M., Rigby, R. A., Heller, G., Voudouris, V. and De Bastiani F. (2017) \emph{Flexible Regression and Smoothing: Using GAMLSS in R}, Chapman and Hall/CRC.
#'
#' Vasicek, O. A. (1987). Probability of loss on loan portfolio. \emph{KMV Corporation}.
#'
#' Vasicek, O. A. (2002). The distribution of loan portfolio value. \emph{Risk}, \bold{15}(12), 1--10.
#'
#' @param x,q vector of quantiles on the (0,1) interval.
#' @param p vector of probabilities.
#' @param n number of observations. If \code{length(n) > 1}, the length is taken to be the number required.
#' @param log,log.p logical; If TRUE, probabilities p are given as log(p).
#' @param lower.tail logical; If TRUE, (default), \eqn{P(X \leq{x})} are returned, otherwise \eqn{P(X > x)}.
#' @param mu.link the mu link function with default logit.
#' @param sigma.link the sigma link function with default logit.
#' @param mu vector of the \eqn{\tau}-th quantile parameter values.
#' @param sigma vector of shape parameter values.
#' @param tau the \eqn{\tau}-th fixed quantile in \[d-p-q-r\]-VASIQ function.
#'
#' @return \code{VASIQ()} return a gamlss.family object which can be used to fit a Vasicek distribution by gamlss() function.
#'
#' @note Note that for \code{VASIQ()}, mu is the \eqn{\tau}-th quantile and sigma a shape parameter. The \code{\link[gamlss]{gamlss}} function is used for parameters estimation.
#'
#' @seealso \code{\link[vasicekreg]{VASIM}}.
#'
#' @details
#' Probability density function
#' \deqn{f\left( {x\mid \mu ,\sigma ,\tau } \right) = \sqrt {{\textstyle{{1 - \sigma } \over \sigma }}} \exp \left\{ {\frac{1}{2}\left[ {\Phi ^{ - 1} \left( x \right)^2 - \left( {\frac{{\sqrt {1 - \sigma } \left[ {\Phi ^{ - 1} \left( x \right) - \Phi ^{ - 1} \left( \mu \right)} \right] - \sqrt \sigma \,\Phi ^{ - 1} \left( \tau \right)}}{{\sqrt \sigma }}} \right)^2 } \right]} \right\}}
#'
#' Cumulative distribution function
#' \deqn{F\left({x\mid \mu ,\sigma ,\tau } \right) = \Phi \left[ {\frac{{\sqrt {1 - \sigma } \left[ {\Phi ^{ - 1} \left( x \right) - \Phi ^{ - 1} \left( \mu \right)} \right] - \sqrt \sigma \,\Phi ^{ - 1} \left( \tau \right)}}{{\sqrt \sigma }}} \right]}
#'
#' where \eqn{0<(x, \mu, \tau, \sigma)<1}, \eqn{\mu} is the \eqn{\tau}-th quantile and \eqn{\sigma} is the shape parameter.
#' @examples
#'
#' set.seed(123)
#' x <- rVASIQ(n = 1000, mu = 0.50, sigma = 0.69, tau = 0.50)
#' R <- range(x)
#' S <- seq(from = R[1], to = R[2], length.out = 1000)
#'
#' hist(x, prob = TRUE, main = 'Vasicek')
#' lines(S, dVASIQ(x = S, mu = 0.50, sigma = 0.69, tau = 0.50), col = 2)
#'
#' plot(ecdf(x))
#' lines(S, pVASIQ(q = S, mu = 0.50, sigma = 0.69, tau = 0.50), col = 2)
#'
#' plot(quantile(x, probs = S), type = "l")
#' lines(qVASIQ(p = S, mu = 0.50, sigma = 0.69, tau = 0.50), col = 2)
#'
#' library(gamlss)
#' set.seed(123)
#' data <- data.frame(y = rVASIQ(n = 100, mu = 0.50, sigma = 0.69, tau = 0.50))
#'
#' tau <- 0.5
#' fit <- gamlss(y ~ 1, data = data, family = VASIQ(mu.link = 'logit', sigma.link = 'logit'))
#' 1 /(1 + exp(-fit$mu.coefficients)); 1 /(1 + exp(-fit$sigma.coefficients))
#'
#' set.seed(123)
#' n <- 100
#' x <- rbinom(n, size = 1, prob = 0.5)
#' eta <- 0.5 + 1 * x;
#' mu <- 1 / (1 + exp(-eta));
#' sigma <- 0.5;
#' y <- rVASIQ(n, mu, sigma, tau = 0.5)
#' data <- data.frame(y, x, tau = 0.5)
#'
#' tau <- 0.5;
#' fit <- gamlss(y ~ x, data = data, family = VASIQ)
#'
#' fittaus <- lapply(c(0.10, 0.25, 0.50, 0.75, 0.90), function(Tau)
#' {
#' tau <<- Tau;
#' gamlss(y ~ x, data = data, family = VASIQ)
#' })
#'
#' sapply(fittaus, summary)
##################################################
#' @rdname VASIQ
#' @export
#
dVASIQ <- function (x, mu, sigma, tau = 0.50, log = FALSE)
{
stopifnot(x > 0, x < 1, mu > 0, mu < 1, sigma > 0, sigma < 1, tau > 0, tau < 1);
cpp_dvasicekquant(x, mu, sigma, tau, log[1L]);
}
##################################################
#' @rdname VASIQ
#' @export
#'
pVASIQ <- function (q, mu, sigma, tau = 0.50, lower.tail = TRUE, log.p = FALSE)
{
stopifnot(q > 0, q < 1, mu > 0, mu < 1, sigma > 0, sigma < 1, tau > 0, tau < 1);
cpp_pvasicekquant(q, mu, sigma, tau, lower.tail[1L], log.p[1L])
}
##################################################
#' @rdname VASIQ
#' @export
#'
qVASIQ <- function(p, mu, sigma, tau = 0.50, lower.tail = TRUE, log.p = FALSE)
{
stopifnot(p > 0, p < 1, mu > 0, mu < 1, sigma > 0, sigma < 1, tau > 0, tau < 1);
cpp_qvasicekquant(p, mu, sigma, tau, lower.tail[1L], log.p[1L])
}
##################################################
#' @rdname VASIQ
#' @export
#'
rVASIQ <- function(n, mu, sigma, tau = 0.50)
{
cpp_qvasicekquant(runif(n), mu, sigma, tau, TRUE, FALSE)
}
##################################################
#' @rdname VASIQ
#' @export
#'
VASIQ <- function (mu.link = "logit", sigma.link = "logit")
{
mstats <- checklink("mu.link", "VasicekQ", substitute(mu.link), c("logit", "probit", "cloglog", "cauchit", "log", "own"))
dstats <- checklink("sigma.link", "VasicekQ", substitute(sigma.link), c("logit", "probit", "cloglog", "cauchit", "log", "own"))
structure(
list(family = c("VASIQ", "VasicekQ"),
parameters = list(mu = TRUE, sigma = TRUE),
nopar = 2,
type = "Continuous",
mu.link = as.character(substitute(mu.link)),
sigma.link = as.character(substitute(sigma.link)),
mu.linkfun = mstats$linkfun,
sigma.linkfun = dstats$linkfun,
mu.linkinv = mstats$linkinv,
sigma.linkinv = dstats$linkinv,
mu.dr = mstats$mu.eta,
sigma.dr = dstats$mu.eta,
dldm = function(y, mu, sigma, tau){
t2 <- sqrt(0.1e1 - sigma);
t4 <- qnorm(mu);
t6 <- qnorm(tau);
t7 <- sqrt(sigma);
t12 <- 0.1e1 / dnorm(t4);
qnormx <- qnorm(y);
return(0.10e1 * (qnormx * t2 - t4 * t2 + t6 * t7) / sigma * t12 * t2);
},
d2ldm2 = function(y, mu, sigma, tau){
t10 <- qnorm(mu);
t1 <- 0.1e1 / dnorm(t10)
t2 <- t1 * t1;
t3 <- 0.1e1 - sigma;
t5 <- 0.1e1 / sigma;
t8 <- sqrt(t3);
t12 <- qnorm(tau);
t13 <- sqrt(sigma);
t17 <- -t10;
qnormx <- qnorm(y);
return(-0.10e1 * t2 * t3 * t5 + 0.10e1 * (qnormx * t8 - t10 * t8 + t12 * t13) * t5 * t17 * t8);
},
dldd = function(y, mu, sigma, tau){
qnormx <- qnorm(y);
t1 <- 0.1e1 - sigma;
t4 <- 0.1e1 / sigma;
t6 <- sqrt(t1);
t8 <- qnorm(mu);
t10 <- qnorm(tau);
t11 <- sqrt(sigma);
t13 <- qnormx * t6 - t8 * t6 + t10 * t11;
t15 <- 0.1e1 / t6;
t23 <- t13 * t13;
t24 <- sigma * sigma;
return(-0.1e1 / t1 / 0.2e1 - t4 / 0.2e1 - 0.5000000000e0 * t13 * t4 *
(-qnormx * t15 + t8 * t15 + t10 / t11) + 0.5e0 * t23 / t24);
},
d2ldmdd = function(y, mu, sigma, tau){
t2 <- sqrt(0.1e1 - sigma);
t3 <- 0.1e1 / t2;
t5 <- qnorm(mu);
t7 <- qnorm(tau);
t8 <- sqrt(sigma);
t12 <- 0.1e1 / sigma;
t14 <- 0.1e1 / dnorm(t5);
t15 <- t14 * t2;
qnormx <- qnorm(y);
t21 <- qnormx * t2 - t5 * t2 + t7 * t8;
t22 <- sigma * sigma;
return(0.5000000000e0 * (-qnormx * t3 + t5 * t3 + t7 / t8) * t12 * t15 - 0.10e1 *
t21 / t22 * t15 - 0.5000000000e0 * t21 * t12 * t14 * t3);
},
d2ldd2 = function(y, mu, sigma, tau){
qnormx <- qnorm(y);
t1 <- 0.1e1 - sigma;
t2 <- t1 * t1;
t5 <- sigma * sigma;
t6 <- 0.1e1 / t5;
t8 <- sqrt(t1);
t9 <- 0.1e1 / t8;
t11 <- qnorm(mu);
t13 <- qnorm(tau);
t14 <- sqrt(sigma);
t17 <- -qnormx * t9 + t11 * t9 + t13 / t14;
t19 <- 0.1e1 / sigma;
t25 <- qnormx * t8 - t11 * t8 + t13 * t14;
t31 <- 0.1e1 / t8 / t1;
t40 <- t25 * t25;
return(-0.1e1 / t2 / 0.2e1 + t6 / 0.2e1 - 0.2500000000e0 * t17 * t17 * t19 + 0.1000000000e1 *
t25 * t6 * t17 - 0.2500000000e0 * t25 * t19 * (-qnormx * t31 + t11 * t31 - t13 / t14 / sigma) -
0.10e1 * t40 / t5 / sigma);
},
G.dev.incr = function(y, mu, sigma, tau, w, ...) -2 * dVASIQ(y, mu, sigma, tau, log = TRUE),
rqres = expression(rqres(pfun = "pVASIQ", type = "Continuous", y = y, mu = mu, sigma = sigma, tau = tau)),
mu.initial = expression({mu <- (y + mean(y))/2}),
sigma.initial = expression({sigma <- rep(0.5, length(y))}),
mu.valid = function(mu) all(mu > 0 & mu < 1),
sigma.valid = function(sigma) all(sigma > 0 & sigma < 1),
y.valid = function(y) all(y > 0 & y < 1),
mean = function(mu, sigma, tau) pnorm(qnorm(mu) * sqrt(1 - sigma) - qnorm(tau) * sqrt(sigma)),
variance = function(mu, sigma, tau) sapply(1:length(mu), function(i){
alpha <- pnorm(qnorm(mu[i]) * sqrt(1 - sigma[i]) - qnorm(tau[i]) * sqrt(sigma[i]));
pmvnorm(lower= c(-Inf, -Inf),
upper= rep(qnorm(alpha,2)),
mean = c(0, 0),
corr = matrix(c(1, sigma[i], sigma[i], 1), ncol = 2)) - alpha ^ 2;
})), class = c("gamlss.family","family"))
}
|
/scratch/gouwar.j/cran-all/cranData/vasicekreg/R/dpqr-vasicekquant.R
|
#' @docType package
#' @name vasicekreg-package
#' @aliases vasicekreg-package
#'
#' @title Overview of the vasicekreg package
#'
#' @description The \pkg{vasicekreg} package implements the probability density function, quantile function, cumulative distribution function and random number generation function for Vasicek distribution parameterized, either, as a function of its mean or its \eqn{\tau}-th quantile, \eqn{0 <\tau<1}. In addition, two gamlss frameworks for regression analysis are available. Some function are written in \proglang{C++} using \pkg{Rcpp}.
#'
#' @details
#'
#' \code{\link[vasicekreg]{bodyfat}}: Body fat data set.
#'
#' \code{\link[vasicekreg]{VASIM}}: For mean modeling (con/in)ditional on covariate(s).
#'
#' \code{\link[vasicekreg]{VASIQ}}: For quantile modeling (con/in)ditional on covariate(s).
#'
#' @author Josmar Mazucheli \email{[email protected]}
#' @author Bruna Alves \email{[email protected]}
#'
#'
#' @useDynLib vasicekreg
#' @importFrom Rcpp sourceCpp
NULL
.onUnload <- function (libpath) {
library.dynam.unload("vasicekreg", libpath)
}
|
/scratch/gouwar.j/cran-all/cranData/vasicekreg/R/vasicekreg-package.R
|
#' Vatcheckapi API Key
#'
#' \href{https://vatcheckapi.com}{vatcheckapi.com} requires authentication via an API key. For this package, the API key is saved as a
#' environmental variable. In interactive mode, using \code{vatcheckapi_api_key}
#' will require you to enter an API key. Alternatively, you can also use
#' \code{Sys.setenv(VATCHECKAPI_API_KEY = <key>)} to set the API key manually.
#'
#' @param force If \code{TRUE}, resets the API key & requires the user to provide a new API key. If \code{FALSE} and an API key
#' already exists, the key will be printed to the console. If no key exists,
#' you will be required to enter a key.
#' \code{force}. Defaults to \code{FALSE}.
#' @return Returns the set API key that has been stored as an enviroment variable.
#' @export
vatcheckapi_api_key <- function(force = FALSE) {
env <- Sys.getenv("VATCHECKAPI_API_KEY")
if (!identical(env, "") && !force) return(env)
if (!interactive()) {
stop("Please set environment variable VATCHECKAPI_API_KEY to your vatcheckapi API key",
call. = FALSE
)
message("Use `Sys.setenv(VATCHECKAPI_API_KEY = <key>)`")
}
message("Could not find environment variable VATCHECKAPI_API_KEY")
message("Please enter your API key and press enter:")
key <- readline(": ")
if (identical(key, "")) {
Sys.unsetenv("VATCHECKAPI_API_KEY")
stop("API key entry failed", call. = FALSE)
}
message("Updating VATCHECKAPI_API_KEY")
Sys.setenv(VATCHECKAPI_API_KEY = key)
return(key)
}
|
/scratch/gouwar.j/cran-all/cranData/vatcheckapi/R/apiKey.R
|
#' Get the current status of the API.
#' @return Returns your current quota. Requests to this endpoint do not count against your quota or rate limit.
#' @export
#'
get_api_status <- function() {
# ensure necessary packages are installed
if (!requireNamespace("httr", quietly = TRUE)) {
stop("Please install the 'httr' package to use this function.")
}
if (!requireNamespace("jsonlite", quietly = TRUE)) {
stop("Please install the 'jsonlite' package to use this function.")
}
# check for API key or ask for API key
apikey <- vatcheckapi_api_key()
# define the API URL
api_url <- "https://api.vatcheckapi.com/v2/status"
# generate query
params <- list(apikey = apikey)
# append params to query if not null
# make the API request
response <- httr::GET(api_url, query = params)
# check if the request was successful
data <- success_check(response)
data <- jsonlite::fromJSON(httr::content(response, as = 'text' ,type = 'application/json', encoding="UTF-8"), flatten = TRUE)
# return the result
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/vatcheckapi/R/getApiStatus.R
|
#' Validates any given vat number and returns its validity and company information
#' @param vat_number (required) The vat number you want to query (Either: including the country prefix, or without and you specify the country_code)
#' @param country_code An ISO Alpha 2 Country Code for the vat number (e.g. LU)
#' @return Returns all available information about the VAT ID.
#' @export
get_vat_info <- function(vat_number, country_code = NULL) {
# check for API key or ask for API key
apikey <- vatcheckapi_api_key()
# ensure necessary packages are installed
if (!requireNamespace("httr", quietly = TRUE)) {
stop("Please install the 'httr' package to use this function.")
}
if (!requireNamespace("jsonlite", quietly = TRUE)) {
stop("Please install the 'jsonlite' package to use this function.")
}
# define the API URL
api_url <- "https://api.vatcheckapi.com/v2/check"
# generate query
params <- list(apikey = apikey, vat_number = vat_number)
# append params to query if not null
if(!is.null(country_code)) {
params['country_code'] <- country_code
}
# make the API request
response <- httr::GET(api_url, query = params)
# check if the request was successful
data <- success_check(response)
data <- jsonlite::fromJSON(httr::content(response, as = 'text' ,type = 'application/json', encoding="UTF-8"), flatten = TRUE)
# return the result
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/vatcheckapi/R/getVatInfo.R
|
success_check <- function(res) {
if (!res$status_code) {
stop(paste(
"Error code:", res$error$code, "\n",
"Error message:", res$error$info,
"Error type:", res$error$type, "\n"
), call. = FALSE)
}
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/vatcheckapi/R/util-successCheck.R
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
|
/scratch/gouwar.j/cran-all/cranData/vatcheckapi/inst/doc/introduction.R
|
---
title: "introduction to vatcheckapi"
author: Dominik Kukacka
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{introduction}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# Introduction
`vatcheckapi` is the official package for accessing VAT ID data from [vatcheckapi.com](https://vatcheckapi.com). The API requires a registered API key. The free plan provides 100 free monthly requests. You can register an API key [here](https://app.vatcheckapi.com/register). [Premium plans](https://vatcheckapi.com/pricing/) provide access to more requests and more data endpoints. The full API documentation can be found [here](https://vatcheckapi.com/docs/)
## Setting up authentication
After registering your API key, set your API key locally by calling the helper function `vatcheckapi_api_key()` or by manually calling `Sys.setenv(VATCHECKAPI_API_KEY = <key>)`.
## Making your first API request
Call `get_vat_info("LU26375245")` to retrieve all information about the specified VAT ID.
## Available Functions
* `get_api_status()` - can be used to check whether the API is available. Requests do not count towards your monthly request volume. Information about your API key are provided. Available in `free & paid` plans.
* `get_vat_info()` - provides you with information about any VAT ID. Available in `free & paid` plans.
Please read our [API documentation](https://vatcheckapi.com/docs/) for all information.
|
/scratch/gouwar.j/cran-all/cranData/vatcheckapi/inst/doc/introduction.Rmd
|
---
title: "introduction to vatcheckapi"
author: Dominik Kukacka
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{introduction}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# Introduction
`vatcheckapi` is the official package for accessing VAT ID data from [vatcheckapi.com](https://vatcheckapi.com). The API requires a registered API key. The free plan provides 100 free monthly requests. You can register an API key [here](https://app.vatcheckapi.com/register). [Premium plans](https://vatcheckapi.com/pricing/) provide access to more requests and more data endpoints. The full API documentation can be found [here](https://vatcheckapi.com/docs/)
## Setting up authentication
After registering your API key, set your API key locally by calling the helper function `vatcheckapi_api_key()` or by manually calling `Sys.setenv(VATCHECKAPI_API_KEY = <key>)`.
## Making your first API request
Call `get_vat_info("LU26375245")` to retrieve all information about the specified VAT ID.
## Available Functions
* `get_api_status()` - can be used to check whether the API is available. Requests do not count towards your monthly request volume. Information about your API key are provided. Available in `free & paid` plans.
* `get_vat_info()` - provides you with information about any VAT ID. Available in `free & paid` plans.
Please read our [API documentation](https://vatcheckapi.com/docs/) for all information.
|
/scratch/gouwar.j/cran-all/cranData/vatcheckapi/vignettes/introduction.Rmd
|
##' Base object used by vaultr for all objects
##'
##' @title Base object type
##'
##' @name vault_client_object
##'
##' @importFrom R6 R6Class
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##'
##' if (!is.null(server)) {
##' client <- vaultr::vault_client(addr = server$addr)
##' client$operator$format()
##' client$operator$format(TRUE)
##' }
vault_client_object <- R6::R6Class(
"vault_client_object",
cloneable = FALSE,
private = list(
name = NULL,
help_name = NULL,
description = NULL
),
public = list(
##' @description Construct an object
##'
##' @param description Description for the object, will be printed
initialize = function(description) {
private$name <- sub("^(vault_|vault_client_)", "", class(self)[[1L]])
private$help_name <- class(self)[[1L]]
private$description <- description
},
##' @description Format method, overriding the R6 default
##'
##' @param brief Logical, indicating if this is the full format or
##' a brief (one line) format.
format = function(brief = FALSE) {
vault_client_format(self, brief, private$name, private$description)
},
##' @description Display help for this object
help = function() {
utils::help(private$help_name, package = "vaultr")
}
))
add_const_member <- function(target, name, object) {
target[[name]] <- object
lockBinding(name, target)
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/aaa.R
|
token_cache <- R6::R6Class(
"token_cache",
public = list(
tokens = setNames(list(), character()),
client_addr = function(api_client) {
api_client$addr
},
set = function(api_client, token, use_cache = TRUE) {
if (use_cache) {
self$tokens[[self$client_addr(api_client)]] <- token
}
},
get = function(api_client, use_cache = TRUE, quiet = TRUE) {
if (!use_cache) {
return(NULL)
}
addr <- self$client_addr(api_client)
token <- self$tokens[[addr]]
if (is.null(token)) {
return(NULL)
}
if (!api_client$verify_token(token, quiet)$success) {
self$tokens[[addr]] <- NULL
return(NULL)
}
token
},
clear = function() {
self$tokens <- setNames(list(), character())
},
delete = function(api_client) {
self$tokens[[self$client_addr(api_client)]] <- NULL
},
list = function() {
names(self$tokens)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/cache.R
|
vault_client_format <- function(object, brief, name, description) {
if (brief) {
return(description)
}
nms <- setdiff(ls(object), c("format", "clone", "initialize"))
fns <- vlapply(nms, function(x) is.function(object[[x]]))
is_obj <- vlapply(nms, function(x) inherits(object[[x]], "R6"))
calls <- vcapply(nms[fns], function(x) capture_args(object[[x]], x),
USE.NAMES = FALSE)
if (any(is_obj)) {
objs <- c(
" Command groups:",
vcapply(nms[is_obj], function(x) {
sprintf(" %s: %s", x, object[[x]]$format(TRUE))
}, USE.NAMES = FALSE))
} else {
objs <- NULL
}
c(sprintf("<vault: %s>", name),
objs,
" Commands:",
calls)
}
capture_args <- function(f, name, indent = 4, width = getOption("width"),
exdent = 4L) {
args <- formals(f)
if (length(args) == 0L) {
return(sprintf("%s%s()", strrep(" ", indent), name))
}
args_default <- vcapply(args, deparse)
args_str <- sprintf("%s = %s", names(args), args_default)
args_str[!nzchar(args_default)] <- names(args)[!nzchar(args_default)]
args_str[[1]] <- sprintf("%s(%s", name, args_str[[1]])
args_str[[length(args)]] <- paste0(args_str[[length(args)]], ")")
w <- width - indent - 2L
ret <- character()
s <- ""
for (i in args_str) {
ns <- nchar(s)
ni <- nchar(i)
if (ns == 0) {
s <- paste0(strrep(" ", indent + if (length(ret) > 0L) exdent else 0L), i)
} else if (ns + ni + 2 < w) {
s <- paste(s, i, sep = ", ")
} else {
ret <- c(ret, paste0(s, ","))
s <- paste0(strrep(" ", indent + exdent), i)
}
}
ret <- c(ret, s)
paste0(trimws(ret, "right"), collapse = "\n")
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/format.R
|
vault_request <- function(verb, url, verify, token, namespace, path, ...,
body = NULL, wrap_ttl = NULL,
to_json = TRUE,
allow_missing_token = FALSE) {
if (!is.null(token)) {
token <- httr::add_headers("X-Vault-Token" = token)
} else if (!allow_missing_token) {
stop("Have not authenticated against vault", call. = FALSE)
}
if (!is.null(namespace)) {
namespace <- httr::add_headers("X-Vault-Namespace" = namespace)
}
if (!is.null(wrap_ttl)) {
assert_is_duration(wrap_ttl)
wrap_ttl <- httr::add_headers("X-Vault-Wrap-TTL" = wrap_ttl)
}
res <- verb(paste0(url, prepare_path(path)), verify, token, namespace,
httr::accept_json(), wrap_ttl,
body = body, encode = "json", ...)
vault_client_response(res, to_json)
}
vault_client_response <- function(res, to_json = TRUE) {
code <- httr::status_code(res)
if (code >= 400 && code < 600) {
if (response_is_json(res)) {
dat <- response_to_json(res)
## https://developer.hashicorp.com/vault/api-docs#error-response
errors <- list_to_character(dat$errors)
text <- paste(errors, collapse = "\n")
} else {
errors <- NULL
text <- trimws(httr::content(res, "text", encoding = "UTF-8"))
}
stop(vault_error(code, text, errors))
}
if (code == 204) {
res <- NULL
} else if (to_json) {
res <- response_to_json(res)
}
res
}
vault_error <- function(code, text, errors) {
if (!nzchar(text)) {
text <- httr::http_status(code)$message
}
type <- switch(as.character(code),
"400" = "vault_invalid_request",
"401" = "vault_unauthorized",
"403" = "vault_forbidden",
"404" = "vault_invalid_path",
"429" = "vault_rate_limit_exceeded",
"500" = "vault_internal_server_error",
"501" = "vault_not_initialized",
"503" = "vault_down",
"vault_unknown_error")
err <- list(code = code,
errors = errors,
message = text)
class(err) <- c(type, "vault_error", "error", "condition")
err
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/http.R
|
##' Control a server for use with testing. This is designed to be
##' used only by other packages that wish to run tests against a vault
##' server. You will need to set `VAULTR_TEST_SERVER_BIN_PATH` to
##' point at the directory containing the vault binary, to the binary
##' itself, or to the value `auto` to try and find it on your `PATH`.
##'
##' Once created with `vault_test_server`, a server will stay
##' alive for as long as the R process is alive *or* until the
##' `vault_server_instance` object goes out of scope and is
##' garbage collected. Calling `$kill()` will explicitly stop
##' the server, but this is not strictly needed. See below for
##' methods to control the server instance.
##'
##' @section Warning:
##'
##' Starting a server in test mode must *not* be used for production
##' under any circumstances. As the name suggests,
##' `vault_test_server` is a server suitable for *tests* only and
##' lacks any of the features required to make vault secure. For
##' more information, please see the the official Vault
##' documentation on development servers:
##' https://developer.hashicorp.com/vault/docs/concepts/dev-server
##'
##' @title Control a test vault server
##'
##' @param https Logical scalar, indicating if a https-using server
##' should be created, rather than the default vault dev-mode
##' server. This is still *entirely* insecure, and uses self
##' signed certificates that are bundled with the package.
##'
##' @param init Logical scalar, indicating if the https-using server
##' should be initialised.
##'
##' @param if_disabled Callback function to run if the vault server is
##' not enabled. The default, designed to be used within tests, is
##' `testthat::skip`. Alternatively, inspect the
##' `$enabled` property of the returned object.
##'
##' @param quiet Logical, indicating if startup should be quiet and
##' not print messages
##'
##' @export
##' @rdname vault_test_server
##' @aliases vault_server_instance
##' @examples
##'
##' # Try and start a server; if one is not enabled (see details
##' # above) then this will return NULL
##' server <- vault_test_server(if_disabled = message)
##'
##' if (!is.null(server)) {
##' # We now have a server running on an arbitrary high port - note
##' # that we are running over http and in dev mode: this is not at
##' # all suitable for production use, just for tests
##' server$addr
##'
##' # Create clients using the client method - by default these are
##' # automatically authenticated against the server
##' client <- server$client()
##' client$write("/secret/password", list(value = "s3cret!"))
##' client$read("/secret/password")
##'
##' # The server stops automatically when the server object is
##' # garbage collected, or it can be turned off with the
##' # 'kill' method:
##' server$kill()
##' tryCatch(client$status(), error = function(e) message(e$message))
##' }
vault_test_server <- function(https = FALSE, init = TRUE,
if_disabled = testthat::skip,
quiet = FALSE) {
global_vault_server_manager()$new_server(https, init, if_disabled, quiet)
}
global_vault_server_manager <- function() {
if (is.null(vault_env$server_manager)) {
bin <- vault_server_manager_bin()
port <- vault_server_manager_port()
vault_env$server_manager <- vault_server_manager$new(bin, port)
}
vault_env$server_manager
}
vault_server_manager_bin <- function() {
if (!identical(Sys.getenv("NOT_CRAN"), "true")) {
return(NULL)
}
path <- Sys_getenv("VAULTR_TEST_SERVER_BIN_PATH", NULL)
if (is.null(path)) {
return(NULL)
}
if (identical(path, "auto")) {
path <- unname(Sys.which("vault"))
if (!nzchar(path)) {
return(NULL)
}
}
if (!file.exists(path)) {
return(NULL)
}
if (is_directory(path)) {
bin <- file.path(path, vault_exe_filename())
} else {
bin <- path
}
if (!file.exists(bin)) {
return(NULL)
}
normalizePath(bin, mustWork = TRUE)
}
vault_server_manager_port <- function() {
port <- Sys.getenv("VAULTR_TEST_SERVER_PORT", NA_character_)
if (is.na(port)) {
return(18200L)
}
if (!grepl("^[0-9]+$", port)) {
stop(sprintf("Invalid port '%s'", port))
}
as.integer(port)
}
vault_server_manager <- R6::R6Class(
"vault_server_manager",
public = list(
bin = NULL,
port = NULL,
enabled = FALSE,
initialize = function(bin, port) {
if (is.null(bin)) {
self$enabled <- FALSE
} else {
assert_scalar_character(bin)
assert_scalar_integer(port)
self$bin <- normalizePath(bin, mustWork = TRUE)
self$port <- port
self$enabled <- TRUE
}
},
new_port = function() {
gc() # try and free up any previous cases
ret <- free_port(self$port)
self$port <- self$port + 1L
ret
},
new_server = function(https = FALSE, init = TRUE,
if_disabled = testthat::skip,
quiet = FALSE) {
if (!self$enabled) {
if_disabled("vault is not enabled")
} else {
tryCatch(
vault_server_instance$new(self$bin, self$new_port(), https, init,
quiet),
error = function(e) {
testthat::skip(paste("vault server failed to start:",
e$message))
})
}
}
))
fake_token <- function() {
data <- sample(c(0:9, letters[1:6]), 32, TRUE)
n <- c(8, 4, 4, 4, 12)
paste(vcapply(split(data, rep(seq_along(n), n)), paste0, collapse = "",
USE.NAMES = FALSE), collapse = "-")
}
vault_server_wait <- function(test, process, timeout = 5, poll = 0.05,
quiet = FALSE) {
t1 <- Sys.time() + timeout
repeat {
ok <- tryCatch(test(), error = function(e) FALSE)
if (ok) {
break
}
if (!process$is_alive() || Sys.time() > t1) {
err <- paste(readLines(process$get_error_file()), collapse = "\n")
stop("vault has died:\n", err)
}
message_quietly("...waiting for Vault to start", quiet = quiet)
Sys.sleep(poll)
}
}
vault_server_start_dev <- function(bin, port, quiet) {
token <- fake_token()
args <- c("server", "-dev",
sprintf("-dev-listen-address=127.0.0.1:%s", port),
sprintf("-dev-root-token-id=%s", token))
stdout <- tempfile()
stderr <- tempfile()
process <-
processx::process$new(bin, args, stdout = stdout, stderr = stderr)
on.exit(process$kill())
addr <- sprintf("http://127.0.0.1:%d", port)
cl <- vault_client(addr = addr)
vault_server_wait(cl$operator$is_initialized, process, quiet = quiet)
on.exit()
for (i in 1:5) {
txt <- readLines(process$get_output_file())
re <- "\\s*Unseal Key:\\s+([^ ]+)\\s*$"
i <- grep(re, txt)
key <- NULL
if (length(i) == 1L) {
key <- sub(re, "\\1", txt[[i]])
break
}
Sys.sleep(0.5) # nocov
}
## See https://developer.hashicorp.com/vault/docs/secrets/kv/kv-v2#setup
##
## > when running a dev-mode server, the v2 kv secrets engine is
## > enabled by default at the path secret/ (for non-dev servers, it
## > is currently v1)
cl$login(token = token, quiet = TRUE)
info <- cl$secrets$list()
description <- info$description[info$path == "secret/"]
cl$secrets$disable("/secret")
cl$secrets$enable("kv", "/secret", description, 1L)
list(process = process,
addr = addr,
keys = key,
token = token)
}
vault_server_start_https <- function(bin, port, init, quiet) {
## Create a server configuration:
config_path <- system.file("server", package = "vaultr", mustWork = TRUE)
cfg <- readLines(file.path(config_path, "vault-tls.hcl"))
tr <- c(VAULT_CONFIG_PATH = config_path,
VAULT_ADDR = sprintf("127.0.0.1:%s", port))
path <- tempfile()
writeLines(strsub(cfg, tr), path)
args <- c("server", paste0("-config=", path))
stdout <- tempfile()
stderr <- tempfile()
process <- processx::process$new(bin, args, stdout = stdout, stderr = stderr)
on.exit(process$kill())
addr <- sprintf("https://127.0.0.1:%d", port)
cacert <- file.path(config_path, "server-cert.pem")
cl <- vault_client(addr = addr, tls_config = cacert)
## Here, our test function is a bit different because we're not
## expecting the server to be *initialised*, just to be ready to
## accept connections
vault_server_wait(function() !cl$operator$is_initialized(), process,
quiet = quiet)
if (init) {
res <- cl$operator$init(5, 3) # 5 / 3 key split
keys <- res$keys_base64
root_token <- res$root_token
for (k in keys) {
cl$operator$unseal(k)
}
} else {
keys <- NULL
root_token <- NULL
}
on.exit()
list(process = process,
addr = addr,
token = root_token,
keys = keys,
cacert = cacert)
}
vault_platform <- function(sysname = Sys.info()[["sysname"]]) {
switch(sysname,
Darwin = "darwin",
Windows = "windows",
Linux = "linux",
stop("Unknown sysname"))
}
vault_exe_filename <- function(platform = vault_platform()) {
if (platform == "windows") {
"vault.exe"
} else {
"vault"
}
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/server_manager.R
|
response_to_json <- function(res) {
jsonlite::fromJSON(httr::content(res, "text", encoding = "UTF-8"),
simplifyVector = FALSE)
}
to_json <- function(x) {
jsonlite::toJSON(x)
}
`%||%` <- function(a, b) { # nolint
if (is.null(a)) b else a
}
`%&&%` <- function(a, b) { # nolint
if (is.null(a)) NULL else b
}
list_to_character <- function(x) {
vapply(x, identity, character(1))
}
response_is_json <- function(x) {
content_type <- httr::headers(x)[["Content-Type"]]
dat <- httr::parse_media(content_type)
dat$type == "application" && dat$subtype == "json"
}
is_absolute_path <- function(path) {
substr(path, 1, 1) == "/"
}
vlapply <- function(X, FUN, ...) { # nolint
vapply(X, FUN, logical(1), ...)
}
vcapply <- function(X, FUN, ...) { # nolint
vapply(X, FUN, character(1), ...)
}
data_frame <- function(...) {
data.frame(..., stringsAsFactors = FALSE)
}
strsub <- function(str, tr) {
assert_character(tr)
assert_named(tr)
from <- names(tr)
to <- unname(tr)
for (i in seq_along(from)) {
str <- gsub(from[[i]], to[[i]], str, fixed = TRUE)
}
str
}
Sys_getenv <- function(name, unset = NULL, mode = "character") { # nolint
value <- Sys.getenv(name, NA_character_)
if (is.na(value)) {
value <- unset
} else if (mode == "integer") {
if (!grepl("^-?[0-9]+$", value)) {
stop(sprintf("Invalid input for integer '%s'", value))
}
value <- as.integer(value)
} else if (mode != "character") {
stop("Invalid value for 'mode'")
}
value
}
vault_arg <- function(x, name, mode = "character") {
x %||% Sys_getenv(name, NULL, mode)
}
drop_null <- function(x) {
x[!vlapply(x, is.null)]
}
read_password <- function(prompt) {
getPass::getPass(prompt, TRUE)
}
prepare_path <- function(path) {
assert_scalar_character(path)
if (!is_absolute_path(path)) {
path <- paste0("/", path)
}
path
}
rand_str <- function(n) {
paste0(sample(letters, n, TRUE), collapse = "")
}
string_starts_with <- function(x, sub) {
substr(x, 1, nchar(sub)) == sub
}
is_directory <- function(path) {
file.info(path, extra_cols = FALSE)$isdir
}
free_port <- function(port, max_tries = 20) {
for (i in seq_len(max_tries)) {
if (check_port(port)) {
return(port)
}
port <- port + 1L
}
stop(sprintf("Did not find a free port between %d..%d",
port - max_tries, port - 1),
call. = FALSE)
}
check_port <- function(port) {
timeout <- if (vault_platform() == "windows") 1 else 0.1
con <- tryCatch(suppressWarnings(socketConnection(
"localhost", port = port, timeout = timeout, open = "r")),
error = function(e) NULL)
if (is.null(con)) {
return(TRUE)
}
close(con)
FALSE
}
pretty_sec <- function(n) {
if (n < 60) { # less than a minute
sprintf("%ds", n)
} else if (n < 60 * 60) { # less than an hour
sprintf("~%dm", round(n / 60))
} else if (n < 60 * 60 * 24) { # less than a day
sprintf("~%dh", round(n / 60 / 60))
} else { # more than a day
sprintf("~%dd", round(n / 60 / 60 / 24))
}
}
pretty_lease <- function(lease) {
sprintf("ok, duration: %s s (%s)", lease, pretty_sec(lease))
}
squote <- function(x) {
sprintf("'%s'", x)
}
encode64 <- function(input) {
jsonlite::base64_enc(input)
}
decode64 <- function(input) {
jsonlite::base64_dec(input)
}
isFALSE <- function(x) { # nolint
is.logical(x) && length(x) == 1L && !is.na(x) && !x
}
## vault raw data inputs must be base64
raw_data_input <- function(data, name = deparse(substitute(data))) {
if (!is.raw(data)) {
## TODO: should this support base64 data?
stop(sprintf("Expected raw data for '%s'", name), call. = FALSE)
}
encode64(data)
}
message_quietly <- function(..., quiet) {
if (!quiet) {
message(...)
}
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/util.R
|
assert_is <- function(x, what, name = deparse(substitute(x))) {
if (!inherits(x, what)) {
stop(sprintf("'%s' must be a %s",
name, paste(what, collapse = " / ")))
}
invisible(x)
}
assert_length <- function(x, len, name = deparse(substitute(x))) {
if (length(x) != len) {
stop(sprintf("'%s' must have length %d", name, len))
}
invisible(x)
}
assert_scalar <- function(x, name = deparse(substitute(x))) {
if (length(x) != 1) {
stop(sprintf("'%s' must be a scalar", name), call. = FALSE)
}
invisible(x)
}
assert_character <- function(x, name = deparse(substitute(x))) {
if (!is.character(x)) {
stop(sprintf("'%s' must be a character", name), call. = FALSE)
}
invisible(x)
}
assert_integer <- function(x, strict = FALSE, name = deparse(substitute(x)),
what = "integer") {
if (!(is.integer(x))) {
usable_as_integer <-
!strict && is.numeric(x) && (max(abs(round(x) - x)) < 1e-8)
if (!usable_as_integer) {
stop(sprintf("'%s' must be %s", name, what), call. = FALSE)
}
}
invisible(x)
}
assert_logical <- function(x, name = deparse(substitute(x))) {
if (!is.logical(x)) {
stop(sprintf("'%s' must be a logical", name), call. = FALSE)
}
invisible(x)
}
assert_named <- function(x, name = deparse(substitute(x))) {
if (is.null(names(x)) && length(x) > 0L) {
stop(sprintf("'%s' must be named", name))
}
invisible(x)
}
assert_scalar_character <- function(x, name = deparse(substitute(x))) {
assert_scalar(x, name)
assert_character(x, name)
}
assert_scalar_integer <- function(x, strict = FALSE,
name = deparse(substitute(x))) {
assert_scalar(x, name)
assert_integer(x, strict, name)
}
assert_scalar_logical <- function(x, name = deparse(substitute(x))) {
assert_scalar(x, name)
assert_logical(x, name)
}
assert_scalar_logical_or_null <- function(x, name = deparse(substitute(x))) {
if (!is.null(x)) {
assert_scalar_logical(x, name)
}
invisible(x)
}
assert_scalar_character_or_null <- function(x, name = deparse(substitute(x))) {
if (!is.null(x)) {
assert_scalar_character(x, name)
}
invisible(x)
}
assert_absolute_path <- function(path) {
if (!is_absolute_path(path)) {
stop("Expected an absolute path")
}
invisible(path)
}
assert_file_exists <- function(path, name = deparse(substitute(path))) {
assert_scalar_character(path, name)
if (!file.exists(path)) {
stop(sprintf("The path '%s' does not exist (for '%s')", path, name),
call. = FALSE)
}
}
assert_is_duration <- function(x, name = deparse(substitute(x))) {
assert_scalar_character(x)
if (!grepl("^[0-9]+h$", x)) {
stop(sprintf("'%s' is not a valid time duration for '%s'", x, name),
call. = FALSE)
}
invisible(x)
}
assert_vault_version <- function(required, api_client, api, description) {
have <- api_client$server_version()
if (required > have) {
stop(vault_invalid_version(required, have, api, description))
}
}
vault_invalid_version <- function(required, server_version, api, description) {
str <- sprintf("%s (%s) requires vault version >= %s but server is %s",
description, api, required, server_version)
err <- list(message = str)
class(err) <- c("vault_invalid_version",
"vault_error", "error", "condition")
err
}
match_value <- function(arg, choices, name = deparse(substitute(arg))) {
assert_scalar_character(arg)
if (!(arg %in% choices)) {
stop(sprintf("%s must be one of %s",
name, paste(squote(choices), collapse = ", ")))
}
arg
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/util_assert.R
|
##' Low-level API client. This can be used to directly communicate
##' with the vault server. This object will primarily be useful for
##' debugging, testing or developing new vault methods, but is
##' nonetheless described here.
##'
##' @title Vault Low-Level Client
##' @name vault_api_client
##'
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' # Ordinarily, we would use the "vault_client" object for
##' # high-level access to the vault server
##' client <- server$client()
##' client$status()
##'
##' # The api() method returns the "api client" object:
##' api <- client$api()
##' api
##'
##' # This allows running arbitrary HTTP requests against the server:
##' api$GET("/sys/seal-status")
##'
##' # this is how vaultr is internally implemented so anything can
##' # be done here, for example following vault's API documentation
##' # https://www.vaultproject.io/api/secret/kv/kv-v1.html#sample-request-2
##' api$POST("/secret/mysecret", body = list(key = "value"))
##' api$GET("/secret/mysecret")
##' api$DELETE("/secret/mysecret")
##'
##' # cleanup
##' server$kill()
##' }
vault_api_client <- R6::R6Class(
"vault_api_client",
inherit = vault_client_object,
cloneable = FALSE,
public = list(
##' @field addr The vault address (with protocol, hostname and port)
addr = NULL,
##' @field base_url The base url (with protocol, hostname, port and
##' api version path)
base_url = NULL,
##' @field tls_config Information used in TLS config, if used
tls_config = NULL,
##' @field namespace The vault namespace, if used
namespace = NULL,
##' @field token The vault token, if authenticated
token = NULL,
##' @field version The vault server version, once queried
version = NULL,
##' @description Create a new api client
##'
##' @param addr Address of the vault server
##'
##' @param tls_config Optional TLS config
##'
##' @param namespace Optional namespace
initialize = function(addr = NULL, tls_config = NULL, namespace = NULL) {
super$initialize("Low-level API client")
self$addr <- vault_addr(addr)
self$base_url <- vault_base_url(self$addr, "/v1")
self$tls_config <- vault_tls_config(tls_config)
self$namespace <- vault_namespace(namespace)
},
##' @description Make a request to the api. Typically you should use
##' one of the higher-level wrappers, such as `$GET` or `$POST`.
##'
##' @param verb The HTTP verb to use, as a `httr` function (e.g.,
##' pass `httr::GET` for a `GET` request).
##'
##' @param path The request path
##'
##' @param ... Additional arguments passed to the `httr` function
##'
##' @param token Optional token, overriding the client token
request = function(verb, path, ..., token = self$token) {
## According to the docs there are some sys paths here that need
## the namespace dropped (or unset), but most are ones that we
## don't expect vaultr to interact with:
## https://developer.hashicorp.com/vault/docs/enterprise/namespaces
## - see "Root only API Paths"
vault_request(verb, self$base_url, self$tls_config, token, self$namespace,
path, ...)
},
##' @description Test if the vault client currently holds a vault token.
##' This method does not verify the token - only test that is present.
is_authenticated = function() {
!is.null(self$token)
},
##' @description Set a token within the client
##'
##' @param token String, with the new vault client token
##'
##' @param verify Logical, indicating if we should test that the token
##' is valid. If `TRUE`, then we use `$verify_token()` to test the
##' token before setting it and if it is not valid an error will be
##' thrown and the token not set.
##'
##' @param quiet Logical, if `TRUE`, then informational messages will be
##' suppressed.
set_token = function(token, verify = FALSE, quiet = FALSE) {
if (verify) {
dat <- self$verify_token(token, quiet)
if (!dat$success) {
stop("Token validation failed with error: ", dat$error)
}
}
self$token <- token
},
##' @description Test that a token is valid with the vault.
##' This will call vault's `/sys/capabilities-self` endpoint with the
##' token provided and check the `/sys` path.
##'
##' @param token String, with the vault client token to test
##'
##' @param quiet Logical, if `TRUE`, then informational messages will be
##' suppressed
verify_token = function(token, quiet = TRUE) {
message_quietly("Verifying token", quiet = quiet)
res <- tryCatch(
vault_request(httr::POST, self$base_url, self$tls_config, token,
self$namespace, "/sys/capabilities-self",
body = list(path = "/sys")),
error = identity)
success <- !inherits(res, "error")
list(success = success,
error = if (!success) res,
token = if (success) token)
},
##' @description Retrieve the vault server version. This is by default
##' cached within the client for a session. Will return an R
##' [numeric_version] object.
##'
##' @param refresh Logical, indicating if the server version information
##' should be refreshed even if known.
server_version = function(refresh = FALSE) {
if (is.null(self$version) || refresh) {
self$version <- numeric_version(
self$GET("/sys/seal-status", allow_missing_token = TRUE)$version)
}
self$version
},
##' @description Send a `GET` request to the vault server
##'
##' @param path The server path to use. This is the "interesting"
##' part of the path only, with the server base url and api version
##' information added.
##'
##' @param ... Additional `httr`-compatible options. These will be named
##' parameters or `httr` "request" objects.
GET = function(path, ...) {
self$request(httr::GET, path, ...)
},
##' @description Send a `LIST` request to the vault server
##'
##' @param path The server path to use. This is the "interesting"
##' part of the path only, with the server base url and api version
##' information added.
##'
##' @param ... Additional `httr`-compatible options. These will be named
##' parameters or `httr` "request" objects.
LIST = function(path, ...) {
self$request(httr_LIST, path, ...)
},
##' @description Send a `POST` request to the vault server
##'
##' @param path The server path to use. This is the "interesting"
##' part of the path only, with the server base url and api version
##' information added.
##'
##' @param ... Additional `httr`-compatible options. These will be named
##' parameters or `httr` "request" objects.
POST = function(path, ...) {
self$request(httr::POST, path, ...)
},
##' @description Send a `PUT` request to the vault server
##'
##' @param path The server path to use. This is the "interesting"
##' part of the path only, with the server base url and api version
##' information added.
##'
##' @param ... Additional `httr`-compatible options. These will be named
##' parameters or `httr` "request" objects.
PUT = function(path, ...) {
self$request(httr::PUT, path, ...)
},
##' @description Send a `DELETE` request to the vault server
##'
##' @param path The server path to use. This is the "interesting"
##' part of the path only, with the server base url and api version
##' information added.
##'
##' @param ... Additional `httr`-compatible options. These will be named
##' parameters or `httr` "request" objects.
DELETE = function(path, ...) {
self$request(httr::DELETE, path, ...)
}
))
vault_tls_config <- function(tls_config) {
tls_config <- vault_arg(tls_config, "VAULT_CAPATH")
if (is.null(tls_config)) {
NULL
} else if (identical(as.vector(tls_config), FALSE)) {
httr::config(ssl_verifypeer = 0, ssl_verifyhost = 0)
} else {
assert_file_exists(tls_config)
httr::config(cainfo = tls_config)
}
}
vault_addr <- function(addr) {
addr <- addr %||% Sys.getenv("VAULT_ADDR", "")
assert_scalar_character(addr)
if (!nzchar(addr)) {
stop("vault address not found: perhaps set 'VAULT_ADDR'", call. = FALSE)
}
if (!grepl("^https?://.+", addr)) {
stop("Expected an http or https url for vault addr")
}
addr
}
vault_namespace <- function(namespace) {
if (is.null(namespace)) {
namespace <- Sys.getenv("VAULT_NAMESPACE", NA_character_)
if (is.na(namespace)) {
namespace <- NULL
}
} else {
assert_scalar_character(namespace)
}
namespace
}
vault_base_url <- function(addr, api_prefix) {
assert_scalar_character(api_prefix)
paste0(addr, api_prefix)
}
httr_LIST <- function(...) { # nolint
httr::VERB("LIST", ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_api_client.R
|
##' Make a vault client. This must be done before accessing the
##' vault. The default values for arguments are controlled by
##' environment variables (see Details) and values provided as
##' arguments override these defaults.
##'
##' @section Environment variables:
##'
##' The creation of a client is affected by a number of environment
##' variables, following the main vault command line client.
##'
##' * `VAULT_ADDR`: The url of the vault server. Must
##' include a protocol (most likely `https://` but in testing
##' `http://` might be used)
##'
##' * `VAULT_CAPATH`: The path to CA certificates
##'
##' * `VAULT_TOKEN`: A vault token to use in authentication.
##' Only used for token-based authentication
##'
##' * `VAULT_AUTH_GITHUB_TOKEN`: As for the command line
##' client, a github token for authentication using the github
##' authentication backend
##'
##' * `VAULTR_AUTH_METHOD`: The method to use for
##' authentication
##'
##' @title Make a vault client
##'
##' @param login Login method. Specify a string to be passed along as
##' the `method` argument to `$login`. The default
##' `FALSE` means not to login. `TRUE` means to login
##' using a default method specified by the environment variable
##' `VAULTR_AUTH_METHOD` - if that variable is not set, an
##' error is thrown. The value of `NULL` is the same as
##' `TRUE` but does not throw an error if
##' `VAULTR_AUTH_METHOD` is not set. Supported methods are
##' `token`, `github`, `approle`, `ldap`, and `userpass`.
##'
##' @param ... Additional arguments passed along to the authentication
##' method indicated by `login`, if used.
##'
##' @param addr The vault address *including protocol and port*,
##' e.g., `https://vault.example.com:8200`. If not given, the
##' default is the environment variable `VAULT_ADDR`, which is
##' the same as used by vault's command line client.
##'
##' @param tls_config TLS (https) configuration. For most uses this
##' can be left blank. However, if your vault server uses a
##' self-signed certificate you will need to provide this. Defaults
##' to the environment variable `VAULT_CAPATH`, which is the
##' same as vault's command line client.
##'
##' @param namespace A vault namespace, when using enterprise
##' vault. If given, then this must be a string, and your vault must
##' support namespaces, which is an enterprise feature. If the
##' environment variable `VAULT_NAMESPACE` is set, we use that
##' namespace when `NULL` is provided as an argument (this is the
##' same variable as used by vault's command line client).
##'
##' @export
##' @author Rich FitzJohn
##' @examples
##'
##'
##' # We work with a test vault server here (see ?vault_test_server) for
##' # details. To use it, you must have a vault binary installed on your
##' # system. These examples will not affect any real running vault
##' # instance that you can connect to.
##' server <- vaultr::vault_test_server(if_disabled = message)
##'
##' if (!is.null(server)) {
##' # Create a vault_client object by providing the address of the vault
##' # server.
##' client <- vaultr::vault_client(addr = server$addr)
##'
##' # The client has many methods, grouped into a structure:
##' client
##'
##' # For example, token related commands:
##' client$token
##'
##' # The client is not authenticated by default:
##' try(client$list("/secret"))
##'
##' # A few methods are unauthenticated and can still be run
##' client$status()
##'
##' # Login to the vault, using the token that we know from the server -
##' # ordinarily you would use a login approach suitable for your needs
##' # (see the vault documentation).
##' token <- server$token
##' client$login(method = "token", token = token)
##'
##' # The vault contains no secrets at present
##' client$list("/secret")
##'
##' # Secrets can contain any (reasonable) number of key-value pairs,
##' # passed in as a list
##' client$write("/secret/users/alice", list(password = "s3cret!"))
##'
##' # The whole list can be read out
##' client$read("/secret/users/alice")
##' # ...or just a field
##' client$read("/secret/users/alice", "password")
##'
##' # Reading non-existant values returns NULL, not an error
##' client$read("/secret/users/bob")
##'
##' client$delete("/secret/users/alice")
##' }
vault_client <- function(login = FALSE, ..., addr = NULL, tls_config = NULL,
namespace = NULL) {
client <- vault_client_$new(addr, tls_config, namespace)
method <- vault_client_login_method(login)
if (!is.null(method)) {
client$login(..., method = method)
}
client
}
##' @rdname vault_client
vault_client_ <- R6::R6Class(
"vault_client",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL),
public = list(
##' @field auth Authentication backends: [vaultr::vault_client_auth]
auth = NULL,
##' @field audit Audit methods: [vaultr::vault_client_audit]
audit = NULL,
##' @field cubbyhole The vault cubbyhole key-value store:
##' [vaultr::vault_client_cubbyhole]
cubbyhole = NULL,
##' @field operator Operator methods: [vaultr::vault_client_operator]
operator = NULL,
##' @field policy Policy methods: [vaultr::vault_client_policy]
policy = NULL,
##' @field secrets Secret backends: [vaultr::vault_client_secrets]
secrets = NULL,
##' @field token Token methods: [vaultr::vault_client_token]
token = NULL,
##' @field tools Vault tools: [vaultr::vault_client_tools]
tools = NULL,
##' @description Create a new vault client. Not typically called
##' directly, but via the `vault_client` method.
##'
##' @param addr The vault address, including protocol and port
##'
##' @param tls_config The TLS config, if used
##'
##' @param namespace The namespace, if used
initialize = function(addr, tls_config, namespace) {
super$initialize("core methods for interacting with vault")
api_client <- vault_api_client$new(addr, tls_config, namespace)
private$api_client <- api_client
add_const_member(self, "auth", vault_client_auth$new(api_client))
add_const_member(self, "audit", vault_client_audit$new(api_client))
add_const_member(self, "operator", vault_client_operator$new(api_client))
add_const_member(self, "policy", vault_client_policy$new(api_client))
add_const_member(self, "secrets", vault_client_secrets$new(api_client))
add_const_member(self, "token", vault_client_token$new(api_client))
add_const_member(self, "tools", vault_client_tools$new(api_client))
},
##' @description Returns an api client object that can be used to
##' directly interact with the vault server.
api = function() {
private$api_client
},
## Root object kv1 methods
##' @description Read a value from the vault. This can be used to
##' read any value that you have permission to read, and can also
##' be used as an interface to a version 1 key-value store (see
##' [vaultr::vault_client_kv1]. Similar to the vault CLI command
##' `vault read`.
##'
##' @param path Path for the secret to read, such as
##' `/secret/mysecret`
##'
##' @param field Optional field to read from the secret. Each
##' secret is stored as a key/value set (represented in R as a
##' named list) and this is equivalent to using `[[field]]` on
##' the return value. The default, `NULL`, returns the full set
##' of values.
##'
##' @param metadata Logical, indicating if we should return
##' metadata for this secret (lease information etc) as an
##' attribute along with the values itself. Ignored if `field`
##' is specified.
read = function(path, field = NULL, metadata = FALSE) {
self$secrets$kv1$read(path, field, metadata)
},
##' @description Write data into the vault. This can be used to
##' write any value that you have permission to write, and can
##' also be used as an interface to a version 1 key-value store
##' (see [vaultr::vault_client_kv1]. Similar to the vault CLI
##' command `vault write`.
##'
##' @param path Path for the secret to write, such as
##' `/secret/mysecret`
##'
##' @param data A named list of values to write into the vault at
##' this path. This *replaces* any existing values.
write = function(path, data) {
self$secrets$kv1$write(path, data)
},
##' @description Delete a value from the vault
##'
##' @param path The path to delete
delete = function(path) {
self$secrets$kv1$delete(path)
},
## NOTE: no recursive list here
##' @description List data in the vault at a given path. This can
##' be used to list keys, etc (e.g., at `/secret`).
##'
##' @param path The path to list
##
##' @param full_names Logical, indicating if full paths (relative
##' to the vault root) should be returned.
##'
##' @return A character vector (of zero length if no keys are
##' found). Paths that are "directories" (i.e., that contain
##' keys and could themselves be listed) will be returned with a
##' trailing forward slash, e.g. `path/`
list = function(path, full_names = FALSE) {
self$secrets$kv1$list(path, full_names)
},
##' @description Login to the vault. This method is more
##' complicated than most.
##'
##' @param ... Additional named parameters passed through to the
##' underlying method
##'
##' @param method Authentication method to use, as a string.
##' Supported values include `token` (the default), `github`,
##' `approle`, `ldap`, and `userpass`.
##'
##' @param mount The mount path for the authentication backend, *if
##' it has been mounted in a nonstandard location*. If not
##' given, then it is assumed that the backend was mounted at a
##' path corresponding to the method name.
##'
##' @param renew Login, even if we appear to hold a valid token.
##' If `FALSE` and we have a token then `login` does nothing.
##'
##' @param quiet Suppress some informational messages
##'
##' @param token_only Logical, indicating that we do not want to
##' actually log in, but instead just generate a token and return
##' that. IF given then `renew` is ignored and we always
##' generate a new token.
##'
##' @param use_cache Logical, indicating if we should look in the
##' session cache for a token for this client. If this is `TRUE`
##' then when we log in we save a copy of the token for this
##' session and any subsequent calls to `login` at this vault
##' address that use `use_cache = TRUE` will be able to use this
##' token. Using cached tokens will make using some
##' authentication backends that require authentication with
##' external resources (e.g., `github`) much faster.
login = function(..., method = "token", mount = NULL,
renew = FALSE, quiet = FALSE,
token_only = FALSE, use_cache = TRUE) {
do_auth <-
assert_scalar_logical(renew) ||
assert_scalar_logical(token_only) ||
!private$api_client$is_authenticated()
if (!do_auth) {
return(NULL)
}
auth <- self$auth[[method]]
if (!inherits(auth, "R6")) {
stop(sprintf(
"Unknown login method '%s' - must be one of %s",
method, paste(squote(self$auth$backends()), collapse = ", ")),
call. = FALSE)
}
if (!is.null(mount)) {
if (method == "token") {
stop("method 'token' does not accept a custom mount")
}
auth <- auth$custom_mount(mount)
}
## TODO: Feedback usage information here on failure?
assert_scalar_character(method)
assert_named(list(...), "...")
if (method == "token") {
token <- auth$login(..., quiet = quiet)
} else {
token <- vault_env$cache$get(private$api_client,
use_cache && !token_only)
if (is.null(token)) {
data <- auth$login(...)
message_quietly(pretty_lease(data$lease_duration), quiet = quiet)
token <- data$client_token
if (!token_only) {
vault_env$cache$set(private$api_client, token, use_cache)
}
}
}
if (!token_only) {
private$api_client$set_token(token)
}
invisible(token)
},
##' @description Return the status of the vault server, including
##' whether it is sealed or not, and the vault server version.
status = function() {
self$operator$seal_status()
},
##' @description Returns the original response inside the given
##' wrapping token. The vault endpoints used by this method
##' perform validation checks on the token, returns the original
##' value on the wire rather than a JSON string representation of
##' it, and ensures that the response is properly audit-logged.
##'
##' @param token Specifies the wrapping token ID
unwrap = function(token) {
assert_scalar_character(token)
private$api_client$POST("/sys/wrapping/unwrap", token = token)
},
##' @description Look up properties of a wrapping token.
##'
##' @param token Specifies the wrapping token ID to lookup
wrap_lookup = function(token) {
assert_scalar_character(token)
private$api_client$POST("/sys/wrapping/lookup", token = token,
allow_missing_token = TRUE)$data
}
))
vault_client_login_method <- function(login) {
if (isFALSE(login)) {
return(NULL)
}
if (is.null(login) || isTRUE(login)) {
required <- isTRUE(login)
login <- Sys_getenv("VAULTR_AUTH_METHOD", NULL)
if (is.null(login)) {
if (required) {
stop("Default login method not set in 'VAULTR_AUTH_METHOD'",
call. = FALSE)
} else {
return(NULL)
}
}
}
assert_scalar_character(login)
login
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client.R
|
##' Interact with vault's audit devices. For more details, see
##' https://developer.hashicorp.com/vault/docs/audit
##'
##' @title Vault Audit Devices
##' @name vault_client_audit
##'
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##' # By default no audit engines are enabled with the testing server
##' client$audit$list()
##'
##' # Create a file-based audit device on a temporary file:
##' path <- tempfile()
##' client$audit$enable("file", options = list(file_path = path))
##' client$audit$list()
##'
##' # Generate some activity on the server:
##' client$write("/secret/mysecret", list(key = "value"))
##'
##' # The audit logs contain details about the activity - see the
##' # vault documentation for details in interpreting this
##' readLines(path)
##'
##' # cleanup
##' server$kill()
##' unlink(path)
##' }
vault_client_audit <- R6::R6Class(
"vault_client_audit",
inherit = vault_client_object,
cloneable = FALSE,
private = list(api_client = NULL),
public = list(
##' @description Create an audit object
##'
##' @param api_client a [vaultr::vault_api_client] object
initialize = function(api_client) {
super$initialize("Interact with vault's audit devices")
private$api_client <- api_client
},
##' @description List active audit devices. Returns a [data.frame]
##' of names, paths and descriptions of active audit devices.
list = function() {
dat <- private$api_client$GET("/sys/audit")
cols <- c("path", "type", "description")
ret <- lapply(cols, function(v) {
vcapply(dat$data, "[[", v, USE.NAMES = FALSE)
})
names(ret) <- cols
as.data.frame(ret, stringsAsFactors = FALSE, check.names = FALSE)
},
##' @description This endpoint enables a new audit device at the
##' supplied path.
##'
##' @param type Name of the audit device to enable
##'
##' @param description Human readable description for this audit device
##'
##' @param options Options to configure the device with. These vary
##' by device. This must be a named list of strings.
##'
##' @param path Path to mount the audit device. By default, `type` is used
##' as the path.
enable = function(type, description = NULL, options = NULL, path = NULL) {
assert_scalar_character(type)
if (is.null(description)) {
description <- ""
} else {
assert_scalar_character(description)
}
if (is.null(path)) {
path <- type
}
if (!is.null(options)) {
assert_named(options)
}
body <- drop_null(list(type = type,
description = description,
options = options))
private$api_client$PUT(paste0("/sys/audit", prepare_path(path)),
body = body)
invisible(NULL)
},
##' @description Disable an audit device
##'
##' @param path Path of the audit device to remove
disable = function(path) {
private$api_client$DELETE(paste0("/sys/audit", prepare_path(path)))
invisible(NULL)
},
##' @description The `hash` method is used to calculate the hash of the
##' data used by an audit device's hash function and salt. This can be
##' used to search audit logs for a hashed value when the original
##' value is known.
##'
##' @param input The input string to hash
##'
##' @param device The path of the audit device
hash = function(input, device) {
assert_scalar_character(input)
body <- list(input = input)
path <- paste0("/sys/audit-hash", prepare_path(device))
private$api_client$POST(path, body = body)$hash
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_audit.R
|
##' Interact with vault's authentication backends.
##'
##' @title Vault Authentication Configuration
##' @name vault_client_auth
##'
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # List configured authentication backends
##' client$auth$list()
##'
##' # cleanup
##' server$kill()
##' }
vault_client_auth <- R6::R6Class(
"vault_client_auth",
inherit = vault_client_object,
cloneable = FALSE,
private = list(api_client = NULL),
public = list(
##' @field approle Interact with vault's AppRole authentication. See
##' [`vaultr::vault_client_auth_approle`] for more information.
approle = NULL,
##' @field github Interact with vault's GitHub authentication. See
##' [`vaultr::vault_client_auth_github`] for more information.
github = NULL,
##' @field token Interact with vault's token authentication. See
##' [`vaultr::vault_client_token`] for more information.
token = NULL,
##' @field userpass Interact with vault's username/password based
##' authentication. See [`vaultr::vault_client_auth_userpass`] for
##' more information.
userpass = NULL,
##' @field ldap Interact with vault's LDAP based
##' authentication. See [`vaultr::vault_client_auth_ldap`] for
##' more information.
ldap = NULL,
##' @description Create a `vault_client_auth` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
initialize = function(api_client) {
super$initialize("administer vault's authentication methods")
private$api_client <- api_client
add_const_member(
self, "token",
vault_client_token$new(private$api_client))
add_const_member(
self, "github",
vault_client_auth_github$new(private$api_client, "github"))
add_const_member(
self, "userpass",
vault_client_auth_userpass$new(private$api_client, "userpass"))
add_const_member(
self, "ldap",
vault_client_auth_ldap$new(private$api_client, "ldap"))
add_const_member(
self, "approle",
vault_client_auth_approle$new(private$api_client, "approle"))
},
##' @description Return a character vector of supported
##' authentication backends. If a backend `x` is present, then
##' you can access it with `$auth$x`. Note that vault calls
##' these authentication *methods* but we use *backends* here to
##' differentiate with R6 methods. Note that these are backends
##' supported by `vaultr` and not necessarily supported by the
##' server - the server may not have enabled some of these
##' backends, and may support other authentication backends not
##' directly supported by vaultr. See the `$list()` method to
##' query what the server supports.
backends = function() {
nms <- ls(self)
i <- vlapply(nms, function(x) inherits(self[[x]], "R6"))
sort(nms[i])
},
##' @description List authentication backends supported by the
##' vault server, including information about where these
##' backends are mounted.
##'
##' @param detailed Logical, indicating if detailed information
##' should be returned
list = function(detailed = FALSE) {
if (detailed) {
stop("Detailed auth information not supported")
}
dat <- private$api_client$GET("/sys/auth")
cols <- c("type", "accessor", "description")
## TODO: later versions include config etc
ret <- lapply(cols, function(v) {
vapply(dat$data, "[[", "", v, USE.NAMES = FALSE)
})
names(ret) <- cols
## TODO: empty strings here might be better as NA
as.data.frame(c(list(path = names(dat$data)), ret),
stringsAsFactors = FALSE, check.names = FALSE)
},
##' @description Enable an authentication backend in the vault
##' server.
##'
##' @param type The type of authentication backend (e.g.,
##' `userpass`, `github`, `ldap`)
##'
##' @param description Human-friendly description of the backend;
##' will be returned by `$list()`
##'
##' @param local Specifies if the auth method is local only. Local
##' auth methods are not replicated nor (if a secondary) removed
##' by replication.
##'
##' @param path Specifies the path in which to enable the auth
##' method. Defaults to be the same as `type`.
enable = function(type, description = NULL, local = FALSE, path = NULL) {
## TODO: not passing in config here
assert_scalar_character(type)
if (is.null(description)) {
description <- ""
} else {
assert_scalar_character(description)
}
if (is.null(path)) {
path <- type
}
data <- drop_null(list(type = type,
description = description,
local = assert_scalar_logical(local)))
private$api_client$POST(paste0("/sys/auth/", path), body = data)
invisible(NULL)
},
##' @description Disable an active authentication backend.
##'
##' @param path The path of the authentication backend to disable.
disable = function(path) {
private$api_client$DELETE(paste0("/sys/auth/", path))
invisible(NULL)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_auth.R
|
##' Interact with vault's AppRole authentication backend. For more
##' details about this, see the vault documentation at
##' https://developer.hashicorp.com/vault/docs/auth/approle
##'
##' @title Vault AppRole Authentication Configuration
##' @name vault_client_auth_approle
##'
##' @examples
##'
##' vaultr::vault_client(addr = "https://localhost:8200")$auth$approle
vault_client_auth_approle <- R6::R6Class(
"vault_client_auth_approle",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL
),
public = list(
##' @description Create a `vault_client_approle` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
##'
##' @param mount Mount point for the backend
initialize = function(api_client, mount) {
super$initialize("Interact and configure vault's AppRole support")
assert_scalar_character(mount)
private$mount <- sub("^/", "", mount)
private$api_client <- api_client
},
##' @description Set up a `vault_client_auth_approle` object at a
##' custom mount. For example, suppose you mounted the `approle`
##' authentication backend at `/approle-dev` you might use `ar <-
##' vault$auth$approle2$custom_mount("/approle-dev")` - this pattern
##' is repeated for other secret and authentication backends.
##'
##' @param mount String, indicating the path that the engine is mounted at.
custom_mount = function(mount) {
vault_client_auth_approle$new(private$api_client, mount)
},
##' @description
##' This endpoint returns a list the existing AppRoles in the method.
role_list = function() {
path <- sprintf("/auth/%s/role", private$mount)
tryCatch(
list_to_character(private$api_client$LIST(path)$data$keys),
vault_invalid_path = function(e) character(0))
},
##' @description
##' Creates a new AppRole or updates an existing AppRole. This
##' endpoint supports both create and update capabilities. There can
##' be one or more constraints enabled on the role. It is required to
##' have at least one of them enabled while creating or updating a
##' role.
##'
##' @param role_name Name of the AppRole
##'
##' @param bind_secret_id Require secret_id to be presented when
##' logging in using this AppRole (boolean, default is `TRUE`).
##'
##' @param secret_id_bound_cidrs Character vector of CIDR blocks;
##' if set, specifies blocks of IP addresses which can perform
##' the login operation.
##'
##' @param token_bound_cidrs Character vector of if set, specifies
##' blocks of IP addresses which can use the auth tokens
##' generated by this role.
##'
##' @param policies Character vector of policies set on tokens
##' issued via this AppRole.
##'
##' @param secret_id_num_uses Number of times any particular
##' SecretID can be used to fetch a token from this AppRole,
##' after which the SecretID will expire. A value of zero will
##' allow unlimited uses.
##'
##' @param secret_id_ttl Duration, after which any SecretID expires.
##'
##' @param token_num_uses Number of times issued tokens can be
##' used. A value of 0 means unlimited uses
##'
##' @param token_ttl Duration to set as the TTL for issued tokens
##' and at renewal time.
##'
##' @param token_max_ttl Duration, after which the issued token can
##' no longer be renewed.
##'
##' @param period A duration; when set, the token generated using
##' this AppRole is a periodic token; so long as it is renewed it
##' never expires, but the TTL set on the token at each renewal
##' is fixed to the value specified here. If this value is
##' modified, the token will pick up the new value at its next
##' renewal.
##'
##' @param enable_local_secret_ids Boolean, if `TRUE`, then the
##' secret IDs generated using this role will be cluster
##' local. This can only be set during role creation and once
##' set, it can't be reset later.
##'
##' @param token_type The type of token that should be generated
##' via this role. Can be `service`, `batch`, or `default` to use
##' the mount's default (which unless changed will be service
##' tokens).
role_write = function(role_name, bind_secret_id = NULL,
secret_id_bound_cidrs = NULL,
token_bound_cidrs = NULL,
policies = NULL,
secret_id_num_uses = NULL, secret_id_ttl = NULL,
token_num_uses = NULL, token_ttl = NULL,
token_max_ttl = NULL, period = NULL,
enable_local_secret_ids = NULL, token_type = NULL) {
role_name <- assert_scalar_character(role_name)
body <- list(
bind_secret_id =
bind_secret_id %&&% assert_scalar_boolean(bind_secret_id),
secret_id_bound_cidrs =
secret_id_bound_cidrs %&&% I(assert_character(secret_id_bound_cidrs)),
token_bound_cidrs =
token_bound_cidrs %&&% I(assert_character(token_bound_cidrs)),
policies = policies %&&% paste(assert_character(policies),
collapse = ","),
secret_id_num_uses =
secret_id_num_uses %&&% assert_scalar_integer(secret_id_num_uses),
secret_id_ttl = secret_id_ttl %&&% assert_is_duration(secret_id_ttl),
token_num_uses =
token_num_uses %&&% assert_scalar_integer(token_num_uses),
token_ttl = token_ttl %&&% assert_is_duration(token_ttl),
token_max_ttl = token_max_ttl %&&% assert_is_duration(token_max_ttl),
enable_local_secret_ids =
enable_local_secret_ids %&&%
assert_scalar_character(enable_local_secret_ids),
period = period %&&% assert_is_duration(period),
token_type = token_type %&&% assert_scalar_character(token_type))
path <- sprintf("/auth/%s/role/%s", private$mount, role_name)
private$api_client$POST(path, body = drop_null(body))
invisible(NULL)
},
##' @description Reads the properties of an existing AppRole.
##'
##' @param role_name Name of the AppRole
role_read = function(role_name) {
assert_scalar_character(role_name)
path <- sprintf("/auth/%s/role/%s", private$mount, role_name)
ret <- private$api_client$GET(path)$data
ret$policies <- list_to_character(ret$policies)
ret
},
##' @description Deletes an existing AppRole from the method.
##'
##' @param role_name Name of the AppRole to delete
role_delete = function(role_name) {
assert_scalar_character(role_name)
path <- sprintf("/auth/%s/role/%s", private$mount, role_name)
private$api_client$DELETE(path)
invisible(NULL)
},
##' @description Reads the RoleID of an existing AppRole.
##'
##' @param role_name Name of the AppRole
role_id_read = function(role_name) {
assert_scalar_character(role_name)
path <- sprintf("/auth/%s/role/%s/role-id", private$mount, role_name)
private$api_client$GET(path)$data$role_id
},
##' @description Updates the RoleID of an existing AppRole to a
##' custom value.
##'
##' @param role_name Name of the AppRole (string)
##'
##' @param role_id Value to be set as RoleID (string)
role_id_write = function(role_name, role_id) {
assert_scalar_character(role_name)
body <- list(role_id = assert_scalar_character(role_id))
path <- sprintf("/auth/%s/role/%s/role-id", private$mount, role_name)
private$api_client$POST(path, body = body)
invisible(NULL)
},
##' @description Generates and issues a new SecretID on an existing
##' AppRole. Similar to tokens, the response will also contain a
##' `secret_id_accessor` value which can be used to read the
##' properties of the SecretID without divulging the SecretID
##' itself, and also to delete the SecretID from the AppRole.
##'
##' @param role_name Name of the AppRole.
##'
##' @param metadata Metadata to be tied to the SecretID. This
##' should be a named list of key-value pairs. This metadata will
##' be set on tokens issued with this SecretID, and is logged in
##' audit logs in plaintext.
##'
##' @param cidr_list Character vector CIDR blocks enforcing secret
##' IDs to be used from specific set of IP addresses. If
##' `bound_cidr_list` is set on the role, then the list of CIDR
##' blocks listed here should be a subset of the CIDR blocks
##' listed on the role.
##'
##' @param token_bound_cidrs Character vector of CIDR blocks; if
##' set, specifies blocks of IP addresses which can use the auth
##' tokens generated by this SecretID. Overrides any role-set
##' value but must be a subset.
secret_id_generate = function(role_name, metadata = NULL,
cidr_list = NULL, token_bound_cidrs = NULL) {
assert_scalar_character(role_name)
## TODO: cidr_list interacts with bound_cidr_list but I don't
## see that as a parameter in the POST endpoints
body <- list(
metadata = metadata %&&% as.character(to_json(metadata)),
cidr_list = cidr_list %&&% I(assert_character(cidr_list)),
token_bound_cidrs =
token_bound_cidrs %&&% I(assert_character(token_bound_cidrs)))
path <- sprintf("/auth/%s/role/%s/secret-id", private$mount, role_name)
res <- private$api_client$POST(path, body = body)
list(id = res$data$secret_id, accessor = res$data$secret_id_accessor)
},
##' @description Lists the accessors of all the SecretIDs issued
##' against the AppRole. This includes the accessors for "custom"
##' SecretIDs as well.
##'
##' @param role_name Name of the AppRole
secret_id_list = function(role_name) {
assert_scalar_character(role_name)
path <- sprintf("/auth/%s/role/%s/secret-id", private$mount, role_name)
tryCatch(
list_to_character(private$api_client$LIST(path)$data$keys),
vault_invalid_path = function(e) character(0))
},
##' @description Reads out the properties of a SecretID.
##'
##' @param role_name Name of the AppRole
##'
##' @param secret_id Secret ID attached to the role
##'
##' @param accessor Logical, if `TRUE`, treat `secret_id` as an
##' accessor rather than a secret id.
secret_id_read = function(role_name, secret_id, accessor = FALSE) {
assert_scalar_character(role_name)
if (accessor) {
path <- sprintf("/auth/%s/role/%s/secret-id-accessor/lookup",
private$mount, role_name)
body <- list(secret_id_accessor = assert_scalar_character(secret_id))
} else {
path <- sprintf("/auth/%s/role/%s/secret-id/lookup",
private$mount, role_name)
body <- list(secret_id = assert_scalar_character(secret_id))
}
private$api_client$POST(path, body = body)$data
},
##' @description Delete an AppRole secret ID
##'
##' @param role_name Name of the AppRole
##'
##' @param secret_id Secret ID attached to the role
##'
##' @param accessor Logical, if `TRUE`, treat `secret_id` as an
##' accessor rather than a secret id.
secret_id_delete = function(role_name, secret_id, accessor = FALSE) {
assert_scalar_character(role_name)
if (accessor) {
path <- sprintf("/auth/%s/role/%s/secret-id-accessor/destroy",
private$mount, role_name)
body <- list(secret_id_accessor = assert_scalar_character(secret_id))
} else {
path <- sprintf("/auth/%s/role/%s/secret-id/destroy",
private$mount, role_name)
body <- list(secret_id = assert_scalar_character(secret_id))
}
private$api_client$POST(path, body = body)
invisible(NULL)
},
## Create Custom AppRole Secret ID (push)
## Read, Update, or Delete AppRole Properties (separate here)
## Tidy Tokens
##' @description Log into the vault using AppRole authentication.
##' Normally you would not call this directly but instead use
##' `$login` with `method = "approle"` and proving the `role_id`
##' and `secret_id` arguments. This function returns a vault
##' token but does not set it as the client token.
##'
##' @param role_id RoleID of the AppRole
##' @param secret_id SecretID belonging to AppRole
login = function(role_id, secret_id) {
body <- list(role_id = assert_scalar_character(role_id),
secret_id = assert_scalar_character(secret_id))
path <- sprintf("/auth/%s/login", private$mount)
res <- private$api_client$POST(path, body = body,
allow_missing_token = TRUE)
res$auth
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_auth_approle.R
|
##' Interact with vault's GitHub authentication backend. For more
##' details, please see the vault documentation at
##' https://developer.hashicorp.com/vault/docs/auth/github
##'
##' @title Vault GitHub Authentication Configuration
##' @name vault_client_auth_github
##'
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' token <- Sys.getenv("VAULT_TEST_AUTH_GITHUB_TOKEN")
##' if (!is.null(server) && nzchar(token)) {
##' client <- server$client()
##'
##' client$auth$enable("github")
##' # To enable login for members of the organisation "example":
##' client$auth$github$configure(organization = "example")
##' # To map members of the "robots" team *within* that organisation
##' # to the "defaut" policy:
##' client$auth$github$write("development", "default")
##'
##' # Once configured like this, if we have a PAT for a member of
##' # the "development" team saved as an environment variable
##' # "VAULT_AUTH_GITHUB_TOKEN" then doing
##' #
##' # vaultr::vault_client(addr = ..., login = "github")
##' #
##' # will contact GitHub to verify the user token and vault will
##' # then issue a client token
##'
##' # cleanup
##' server$kill()
##' }
vault_client_auth_github <- R6::R6Class(
"vault_client_auth_github",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL
),
public = list(
##' @description Create a `vault_client_github` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
##'
##' @param mount Mount point for the backend
initialize = function(api_client, mount) {
super$initialize("Interact and configure vault's github support")
assert_scalar_character(mount)
private$mount <- sub("^/", "", mount)
private$api_client <- api_client
},
##' @description Set up a `vault_client_auth_github` object at a
##' custom mount. For example, suppose you mounted the `github`
##' authentication backend at `/github-myorg` you might use `gh
##' <- vault$auth$github2$custom_mount("/github-myorg")` - this
##' pattern is repeated for other secret and authentication
##' backends.
##'
##' @param mount String, indicating the path that the engine is
##' mounted at.
custom_mount = function(mount) {
vault_client_auth_github$new(private$api_client, mount)
},
##' @description Configures the connection parameters for
##' GitHub-based authentication.
##'
##' @param organization The organization users must be part of
##' (note American spelling).
##'
##' @param base_url The API endpoint to
##' use. Useful if you are running GitHub Enterprise or an
##' API-compatible authentication server.
##'
##' @param ttl Duration after which authentication will be expired
##'
##' @param max_ttl Maximum duration after which authentication will
##' be expired
configure = function(organization, base_url = NULL, ttl = NULL,
max_ttl = NULL) {
path <- sprintf("/auth/%s/config", private$mount)
assert_scalar_character(organization)
body <- list(organization = organization,
base_url = base_url,
ttl = ttl,
max_ttl = max_ttl)
private$api_client$POST(path, body = drop_null(body))
invisible(TRUE)
},
##' @description Reads the connection parameters for GitHub-based
##' authentication.
configuration = function() {
private$api_client$GET(sprintf("/auth/%s/config", private$mount))$data
},
##' @description Write a mapping between a GitHub team or user and
##' a set of vault policies.
##'
##' @param team_name String, with the GitHub team name
##'
##' @param policies A character vector of vault policies that this
##' user or team will have for vault access if they match this
##' team or user.
##'
##' @param user Scalar logical - if `TRUE`, then `team_name` is
##' interpreted as a *user* instead.
write = function(team_name, policies, user = FALSE) {
type <- if (assert_scalar_logical(user)) "users" else "teams"
assert_scalar_character(team_name)
path <- sprintf("/auth/%s/map/%s/%s", private$mount, type, team_name)
assert_character(policies)
body <- list(value = paste(policies, collapse = ","))
private$api_client$POST(path, body = body)
invisible(NULL)
},
##' @description Write a mapping between a GitHub team or user and
##' a set of vault policies.
##'
##' @param team_name String, with the GitHub team name
##'
##' @param user Scalar logical - if `TRUE`, then `team_name` is
##' interpreted as a *user* instead.
read = function(team_name, user = FALSE) {
type <- if (assert_scalar_logical(user)) "users" else "teams"
assert_scalar_character(team_name)
path <- sprintf("/auth/%s/map/%s/%s", private$mount, type, team_name)
private$api_client$GET(path)$data
},
##' @description Log into the vault using GitHub authentication.
##' Normally you would not call this directly but instead use
##' `$login` with `method = "github"` and proving the `token`
##' argument. This function returns a vault token but does not
##' set it as the client token.
##'
##' @param token A GitHub token to authenticate with.
login = function(token = NULL) {
path <- sprintf("/auth/%s/login", private$mount)
body <- list(token = vault_auth_github_token(token))
res <- private$api_client$POST(path, body = body,
allow_missing_token = TRUE)
res$auth
}
))
vault_auth_github_token <- function(token) {
if (is.null(token)) {
token <- Sys_getenv("VAULT_AUTH_GITHUB_TOKEN", NULL)
}
if (is.null(token)) {
stop(
"GitHub token was not found: perhaps set 'VAULT_AUTH_GITHUB_TOKEN'")
}
assert_scalar_character(token)
token
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_auth_github.R
|
##' Interact with vault's LDAP authentication backend. This backend
##' can be used to configure users based on their presence or group
##' membership in an LDAP server. For more information, please see
##' the vault documentation
##' https://developer.hashicorp.com/vault/docs/auth/ldap
##'
##' @title Vault LDAP Authentication Configuration
##' @name vault_client_auth_ldap
##'
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' root <- server$client()
##'
##' # The ldap authentication backend is not enabled by default,
##' # so we need to enable it first
##' root$auth$enable("ldap")
##'
##' # Considerable configuration is required to make this work. Here
##' # we use the public server available at
##' # https://www.forumsys.com/2022/05/10/online-ldap-test-server/
##' root$auth$ldap$configure(
##' url = "ldap://ldap.forumsys.com",
##' binddn = "cn=read-only-admin,dc=example,dc=com",
##' bindpass = "password",
##' userdn = "dc=example,dc=com",
##' userattr = "uid",
##' groupdn = "dc=example,dc=com",
##' groupattr = "ou",
##' groupfilter = "(uniqueMember={{.UserDN}})")
##'
##' # You can associate groups of users with policies:
##' root$auth$ldap$write("scientists", "default")
##'
##' # Create a new client and login with this user:
##' newton <- vaultr::vault_client(
##' addr = server$addr,
##' login = "ldap",
##' username = "newton",
##' password = "password")
##'
##' # (it is not recommended to login with the password like this as
##' # it will end up in the command history, but in interactive use
##' # you will be prompted securely for password)
##'
##' # Isaac Newton has now logged in and has only "default" policies
##' newton$auth$token$lookup_self()$policies
##'
##' # (wheras our original root user has the "root" policy)
##' root$auth$token$lookup_self()$policies
##' }
vault_client_auth_ldap <- R6::R6Class(
"vault_client_auth_ldap",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL
),
public = list(
##' @description Create a `vault_client_auth_ldap` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
##'
##' @param mount Mount point for the backend
initialize = function(api_client, mount) {
super$initialize("Interact and configure vault's LDAP support")
assert_scalar_character(mount)
private$mount <- sub("^/", "", mount)
private$api_client <- api_client
},
##' @description Set up a `vault_client_auth_ldap` object at a
##' custom mount. For example, suppose you mounted the `ldap`
##' authentication backend at `/ldap-dev` you might use `ldap <-
##' vault$auth$ldap2$custom_mount("/ldap-dev")` - this pattern
##' is repeated for other secret and authentication backends.
##'
##' @param mount String, indicating the path that the engine is mounted at.
custom_mount = function(mount) {
vault_client_auth_ldap$new(private$api_client, mount)
},
##' @description Configures the connection parameters for
##' LDAP-based authentication. Note that there are many options
##' here and not all may be well supported. You are probably best
##' to configure your vault-LDAP interaction elsewhere, and this
##' method should be regarded as experimental and for testing
##' purposes only.
##'
##' See the official docs
##' (https://developer.hashicorp.com/vault/api-docs/auth/ldap,
##' "Configure LDAP") for the list of accepted parameters here
##' via the dots argument; these are passed through directly
##' (with the exception of `url` which is the only required
##' parameter and for which concatenation of multiple values is
##' done for you.
##'
##' @param url The LDAP server to connect to. Examples:
##' `ldap://ldap.myorg.com`,
##' `ldaps://ldap.myorg.com:636`. Multiple URLs can be specified
##' with a character vector, e.g. `c("ldap://ldap.myorg.com", ,
##' "ldap://ldap2.myorg.com")`; these will be tried in-order.
##'
##' @param ... Additional arguments passed through with the body
configure = function(url, ...) {
path <- sprintf("/auth/%s/config", private$mount)
assert_character(url)
body <- list(url = paste(url, collapse = ","), ...)
private$api_client$POST(path, body = drop_null(body))
invisible(TRUE)
},
##' @description Reads the connection parameters for LDAP-based
##' authentication.
configuration = function() {
private$api_client$GET(sprintf("/auth/%s/config", private$mount))$data
},
##' @description Create or update a policy
##'
##' @param name The name of the group (or user)
##'
##' @param policies A character vector of vault policies that this
##' group (or user) will have for vault access.
##'
##' @param user Scalar logical - if `TRUE`, then `name` is
##' interpreted as a *user* instead of a group.
write = function(name, policies, user = FALSE) {
type <- if (assert_scalar_logical(user)) "users" else "groups"
assert_scalar_character(name)
path <- sprintf("/auth/%s/%s/%s", private$mount, type, name)
assert_character(policies)
body <- list(policies = paste(policies, collapse = ","))
private$api_client$POST(path, body = body)
invisible(NULL)
},
##' @description Write a mapping between a LDAP group or user and
##' a set of vault policies.
##'
##' @param name The name of the group (or user)
##'
##' @param user Scalar logical - if `TRUE`, then `name` is
##' interpreted as a *user* instead of a group.
read = function(name, user = FALSE) {
type <- if (assert_scalar_logical(user)) "users" else "groups"
assert_scalar_character(name)
path <- sprintf("/auth/%s/%s/%s", private$mount, type, name)
ret <- private$api_client$GET(path)$data
ret$policies <- list_to_character(ret$policies)
ret
},
##' @description List groups or users known to vault via LDAP
##'
##' @param user Scalar logical - if `TRUE`, then list users
##' instead of groups.
list = function(user = FALSE) {
type <- if (assert_scalar_logical(user)) "users" else "groups"
path <- sprintf("/auth/%s/%s", private$mount, type)
tryCatch(
list_to_character(private$api_client$LIST(path)$data$keys),
vault_invalid_path = function(e) character(0))
},
##' @description Delete a group or user (just the mapping to vault,
##' no data on the LDAP server is modified).
##'
##' @param name The name of the group (or user)
##'
##' @param user Scalar logical - if `TRUE`, then `name` is
##' interpreted as a *user* instead of a group.
delete = function(name, user = FALSE) {
type <- if (assert_scalar_logical(user)) "users" else "groups"
assert_scalar_character(name)
path <- sprintf("/auth/%s/%s/%s", private$mount, type, name)
private$api_client$DELETE(path)$data
},
##' @description Log into the vault using LDAP authentication.
##' Normally you would not call this directly but instead use
##' `$login` with `method = "ldap"` and proving the `username`
##' and optionally the `password` argument.
##' argument. This function returns a vault token but does not
##' set it as the client token.
##'
##' @param username Username to authenticate with
##'
##' @param password Password to authenticate with. If omitted or
##' `NULL` and the session is interactive, the password will be
##' prompted for.
login = function(username, password) {
data <- userpass_data(username, password)
path <- sprintf("/auth/%s/login/%s", private$mount, username)
body <- list(password = data$password)
res <- private$api_client$POST(path, body = body,
allow_missing_token = TRUE)
res$auth
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_auth_ldap.R
|
##' Interact with vault's username/password authentication backend.
##' This backend can be used to configure basic username+password
##' authentication, suitable for human users. For more information,
##' please see the vault documentation
##' https://developer.hashicorp.com/vault/docs/auth/userpass
##'
##' @title Vault Username/Password Authentication Configuration
##' @name vault_client_auth_userpass
##'
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' root <- server$client()
##'
##' # The userpass authentication backend is not enabled by default,
##' # so we need to enable it first
##' root$auth$enable("userpass")
##'
##' # Then we can add users:
##' root$auth$userpass$write("alice", "p4ssw0rd")
##'
##' # Create a new client and login with this user:
##' alice <- vaultr::vault_client(
##' addr = server$addr,
##' login = "userpass",
##' username = "alice",
##' password = "p4ssw0rd")
##'
##' # (it is not recommended to login with the password like this as
##' # it will end up in the command history, but in interactive use
##' # you will be prompted securely for password)
##'
##' # Alice has now logged in and has only "default" policies
##' alice$auth$token$lookup_self()$policies
##'
##' # (wheras our original root user has the "root" policy)
##' root$auth$token$lookup_self()$policies
##' }
vault_client_auth_userpass <- R6::R6Class(
"vault_client_auth_userpass",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL
),
public = list(
##' @description Create a `vault_client_userpass` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
##'
##' @param mount Mount point for the backend
initialize = function(api_client, mount) {
super$initialize("Interact and configure vault's userpass support")
assert_scalar_character(mount)
private$mount <- sub("^/", "", mount)
private$api_client <- api_client
},
##' @description Set up a `vault_client_auth_userpass` object at a
##' custom mount. For example, suppose you mounted the
##' `userpass` authentication backend at `/userpass2` you might
##' use `up <- vault$auth$userpass2$custom_mount("/userpass2")` -
##' this pattern is repeated for other secret and authentication
##' backends.
##'
##' @param mount String, indicating the path that the engine is mounted at.
custom_mount = function(mount) {
vault_client_auth_userpass$new(private$api_client, mount)
},
##' @description Create or update a user.
##'
##' @param username Username for the user
##'
##' @param password Password for the user (required when creating a
##' user only)
##'
##' @param policies Character vector of policies for the user
##'
##' @param ttl The lease duration which decides login expiration
##'
##' @param max_ttl Maximum duration after which login should expire
##'
##' @param bound_cidrs Character vector of CIDRs. If set,
##' restricts usage of the login and token to client IPs falling
##' within the range of the specified CIDR(s).
write = function(username, password = NULL, policies = NULL, ttl = NULL,
max_ttl = NULL, bound_cidrs = NULL) {
username <- assert_scalar_character(username)
body <- list(
password = assert_scalar_character_or_null(password),
policies = policies %&&%
paste(assert_character(policies), collapse = ","),
ttl = ttl %&&% assert_is_duration(ttl),
max_ttl = max_ttl %&&% assert_is_duration(max_ttl),
bound_cidrs = bound_cidrs %&&% I(assert_character(bound_cidrs)))
path <- sprintf("/auth/%s/users/%s", private$mount, username)
private$api_client$POST(path, body = drop_null(body))
invisible(NULL)
},
##' @description Reads the properties of an existing username.
##'
##' @param username Username to read
read = function(username) {
assert_scalar_character(username)
path <- sprintf("/auth/%s/users/%s", private$mount, username)
ret <- private$api_client$GET(path)$data
ret$policies <- list_to_character(ret$policies)
ret
},
##' @description Delete a user
##'
##' @param username Username to delete
delete = function(username) {
assert_scalar_character(username)
path <- sprintf("/auth/%s/users/%s", private$mount, username)
private$api_client$DELETE(path)
invisible(NULL)
},
##' @description Update password for a user
##'
##' @param username Username for the user to update
##'
##' @param password New password for the user
update_password = function(username, password) {
assert_scalar_character(username)
body <- list(password = assert_scalar_character(password))
path <- sprintf("/auth/%s/users/%s/password", private$mount, username)
private$api_client$POST(path, body = drop_null(body))
invisible(NULL)
},
##' @description Update vault policies for a user
##'
##' @param username Username for the user to update
##'
##' @param policies Character vector of policies for this user
update_policies = function(username, policies) {
assert_scalar_character(username)
body <- list(policies = paste(assert_character(policies),
collapse = ","))
path <- sprintf("/auth/%s/users/%s/policies", private$mount, username)
private$api_client$POST(path, body = drop_null(body))
invisible(NULL)
},
##' @description List users known to vault
list = function() {
path <- sprintf("/auth/%s/users", private$mount)
tryCatch(
list_to_character(private$api_client$LIST(path)$data$keys),
vault_invalid_path = function(e) character(0))
},
##' @description Log into the vault using username/password
##' authentication. Normally you would not call this directly
##' but instead use `$login` with `method = "userpass"` and
##' proving the `username` argument and optionally the `password`
##' argument. This function returns a vault token but does not
##' set it as the client token.
##'
##' @param username Username to authenticate with
##'
##' @param password Password to authenticate with. If omitted or
##' `NULL` and the session is interactive, the password will be
##' prompted for.
login = function(username, password = NULL) {
data <- userpass_data(username, password)
path <- sprintf("/auth/%s/login/%s", private$mount, username)
body <- list(password = data$password)
res <- private$api_client$POST(path, body = body,
allow_missing_token = TRUE)
res$auth
}
))
## Needs to be a free function so that we can mock out the password
## read reliably
userpass_data <- function(username, password) {
assert_scalar_character(username, "username")
if (is.null(password)) {
msg <- sprintf("Password for '%s': ", username)
password <- read_password(msg)
}
assert_scalar_character(password, "password")
list(username = username, password = password)
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_auth_userpass.R
|
##' Interact with vault's cubbyhole key-value store. This is useful
##' for storing simple key-value data without versioning or metadata
##' (c.f. [vaultr::vault_client_kv2]) that is scoped to your
##' current token only and not accessible to anyone else. For more
##' details please see the vault documentation
##' https://developer.hashicorp.com/vault/docs/secrets/cubbyhole
##'
##' @title Cubbyhole secret store
##' @name vault_client_cubbyhole
##'
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # Shorter path for easier reading:
##' cubbyhole <- client$secrets$cubbyhole
##' cubbyhole
##'
##' # Write a value
##' cubbyhole$write("cubbyhole/secret", list(key = "value"))
##' # List it
##' cubbyhole$list("cubbyhole")
##' # Read it
##' cubbyhole$read("cubbyhole/secret")
##' # Delete it
##' cubbyhole$delete("cubbyhole/secret")
##'
##' # cleanup
##' server$kill()
##' }
vault_client_cubbyhole <- R6::R6Class(
"vault_client_cubbyhole",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = "cubbyhole"
),
public = list(
##' @description Create a `vault_client_cubbyhole` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
initialize = function(api_client) {
super$initialize("Interact with vault's cubbyhole secret backend")
private$api_client <- api_client
},
##' @description Read a value from your cubbyhole
##'
##' @param path Path for the secret to read, such as
##' `/cubbyhole/mysecret`
##'
##' @param field Optional field to read from the secret. Each
##' secret is stored as a key/value set (represented in R as a
##' named list) and this is equivalent to using `[[field]]`
##' on the return value. The default, `NULL`, returns the
##' full set of values.
##'
##' @param metadata Logical, indicating if we should return
##' metadata for this secret (lease information etc) as an
##' attribute along with the values itself. Ignored if
##' `field` is specified.
read = function(path, field = NULL, metadata = FALSE) {
vault_kv_read(private$api_client, private$mount, path, field, metadata)
},
##' @description Write data into your cubbyhole.
##'
##' @param path Path for the secret to write, such as
##' `/cubbyhole/mysecret`
##'
##' @param data A named list of values to write into the vault at
##' this path. This *replaces* any existing values.
write = function(path, data) {
vault_kv_write(private$api_client, private$mount, path, data)
},
##' @description List data in the vault at a give path. This can
##' be used to list keys, etc (e.g., at `/cubbyhole`).
##'
##' @param path The path to list
##'
##' @param full_names Logical, indicating if full paths (relative
##' to the vault root) should be returned.
##'
##' @param value A character vector (of zero length if no keys are
##' found). Paths that are "directories" (i.e., that contain
##' keys and could themselves be listed) will be returned with
##' a trailing forward slash, e.g. `path/`
list = function(path, full_names = FALSE) {
vault_kv_list(private$api_client, private$mount, path, full_names)
},
##' @description Delete a value from the vault
##'
##' @param path The path to delete
delete = function(path) {
vault_kv_delete(private$api_client, private$mount, path)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_cubbyhole.R
|
##' Interact with vault's version 1 key-value store. This is useful
##' for storing simple key-value data without versioning or metadata
##' (see [vaultr::vault_client_kv2] for a richer key-value store).
##'
##' Up to vault version 0.12.0 this was mounted by default at
##' `/secret`. It can be accessed from vault with either the `$read`,
##' `$write`, `$list` and `$delete` methods on the main
##' [vaultr::vault_client] object or by the `$kv1` member of the
##' `secrets` member of the main vault client
##' ([vaultr::vault_client_secrets])
##'
##' @title Key-Value Store (Version 1)
##' @name vault_client_kv1
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # Write secrets
##' client$secrets$kv1$write("/secret/path/mysecret", list(key = "value"))
##'
##' # List secrets - note the trailing "/" indicates a folder
##' client$secrets$kv1$list("/secret")
##' client$secrets$kv1$list("/secret/path")
##'
##' # Read secrets
##' client$secrets$kv1$read("/secret/path/mysecret")
##' client$secrets$kv1$read("/secret/path/mysecret", field = "key")
##'
##' # Delete secrets
##' client$secrets$kv1$delete("/secret/path/mysecret")
##' client$secrets$kv1$read("/secret/path/mysecret")
##'
##' # cleanup
##' server$kill()
##' }
vault_client_kv1 <- R6::R6Class(
"vault_client_kv1",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL
),
public = list(
##' @description Create a `vault_client_kv1` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
##'
##' @param mount Mount point for the backend
initialize = function(api_client, mount) {
super$initialize("Interact with vault's key/value store (version 1)")
private$api_client <- api_client
if (!is.null(mount)) {
private$mount <- sub("^/", "", mount)
}
},
##' @description Set up a `vault_client_kv1` object at a custom
##' mount. For example, suppose you mounted another copy of the
##' `kv1` secret backend at `/secret2` you might use `kv <-
##' vault$secrets$kv1$custom_mount("/secret2")` - this pattern is
##' repeated for other secret and authentication backends.
##'
##' @param mount String, indicating the path that the engine is
##' mounted at.
custom_mount = function(mount) {
vault_client_kv1$new(private$api_client, mount)
},
##' @description Read a value from the vault. This can be used to
##' read any value that you have permission to read in this
##' store.
##'
##' @param path Path for the secret to read, such as
##' `/secret/mysecret`
##'
##' @param field Optional field to read from the secret. Each
##' secret is stored as a key/value set (represented in R as a
##' named list) and this is equivalent to using `[[field]]` on
##' the return value. The default, `NULL`, returns the full set
##' of values.
##'
##' @param metadata Logical, indicating if we should return
##' metadata for this secret (lease information etc) as an
##' attribute along with the values itself. Ignored if `field`
##' is specified.
read = function(path, field = NULL, metadata = FALSE) {
vault_kv_read(private$api_client, private$mount, path, field, metadata)
},
##' @description Write data into the vault. This can be used to
##' write any value that you have permission to write in this
##' store.
##'
##' @param path Path for the secret to write, such as
##' `/secret/mysecret`
##'
##' @param data A named list of values to write into the vault at
##' this path. This *replaces* any existing values.
write = function(path, data) {
vault_kv_write(private$api_client, private$mount, path, data)
},
##' @description List data in the vault at a give path. This can
##' be used to list keys, etc (e.g., at `/secret`).
##'
##' @param path The path to list
##'
##' @param full_names Logical, indicating if full paths (relative
##' to the vault root) should be returned.
##'
##' @param value A character vector (of zero length if no keys are
##' found). Paths that are "directories" (i.e., that contain
##' keys and could themselves be listed) will be returned with a
##' trailing forward slash, e.g. `path/`
list = function(path, full_names = FALSE) {
vault_kv_list(private$api_client, private$mount, path, full_names)
},
##' @description Delete a value from the vault
##'
##' @param path The path to delete
delete = function(path) {
vault_kv_delete(private$api_client, private$mount, path)
}
))
vault_kv_read <- function(api_client, mount, path, field = NULL,
metadata = FALSE) {
path <- vault_validate_path(path, mount)
res <- tryCatch(
api_client$GET(path),
vault_invalid_path = function(e) NULL,
error = function(e) {
e$message <- sprintf("While reading %s:\n %s", path, e$message)
stop(e)
})
if (is.null(res)) {
ret <- NULL
} else {
ret <- res$data
if (!is.null(field)) {
assert_scalar_character(field)
ret <- res$data[[field]]
} else if (metadata) {
attr <- res[setdiff(names(res), "data")]
attr(ret, "metadata") <- attr[lengths(attr) > 0]
}
}
ret
}
vault_kv_write <- function(api_client, mount, path, data) {
path <- vault_validate_path(path, mount)
assert_named(data)
api_client$POST(path, body = data)
invisible(NULL)
}
vault_kv_list <- function(api_client, mount, path, full_names = FALSE) {
path <- vault_validate_path(path, mount)
dat <- tryCatch(
api_client$LIST(path),
vault_invalid_path = function(e) NULL)
ret <- list_to_character(dat$data$keys)
if (full_names) {
ret <- paste(sub("/+$", "", path), ret, sep = "/")
}
ret
}
vault_kv_delete <- function(api_client, mount, path) {
api_client$DELETE(path)
invisible(NULL)
}
vault_validate_path <- function(path, mount) {
path <- sub("^/", "", path)
if (is.null(mount)) {
return(path)
}
if (!string_starts_with(path, mount)) {
stop(sprintf(
"Invalid mount given for this path - expected '%s'", mount),
call. = FALSE)
}
path
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_kv1.R
|
##' Interact with vault's version 2 key-value store. This is useful
##' for storing simple key-value data that can be versioned and for
##' storing metadata alongside the secrets (see
##' [vaultr::vault_client_kv1] for a simpler key-value store, and see
##' https://developer.hashicorp.com/vault/docs/secrets/kv/kv-v2 for
##' detailed information about this secret store.
##'
##' A `kv2` store can be mounted anywhere, so all methods accept
##' a `mount` argument. This is different to the CLI which lets
##' you try and read values from any vault path, but similar to other
##' secret and auth backends which accept arguments like
##' `-mount-point`. So if the `kv2` store is mounted at
##' `/project-secrets` for example, with a vault client
##' `vault` one could write
##'
##' ```
##' vault$secrets$kv2$get("/project-secrets/mysecret",
##' mount = "project-secrets")
##' ```
##'
##' or
##'
##' ```
##' kv2 <- vault$secrets$kv2$custom_mount("project-secrets")
##' kv2$get("mysecret")
##' ```
##'
##' If the leading part of of a path to secret within a `kv2`
##' store does not match the mount point, `vaultr` will throw an
##' error. This approach results in more predictable error messages,
##' though it is a little more typing than for the CLI vault client.
##'
##' @title Key-Value Store (Version 2)
##' @name vault_client_kv2
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##' # With the test server as created by vaultr, the kv2 storage
##' # engine is not enabled. To use the kv2 store we must first
##' # enable it; the command below will add it at the path /kv on
##' # our vault server
##' client$secrets$enable("kv", version = 2)
##'
##' # For ease of reading, create a 'kv' object for interacting with
##' # the store (see below for the calls without this object)
##' kv <- client$secrets$kv2$custom_mount("kv")
##' kv$config()
##'
##' # The version-2 kv store can be treated largely the same as the
##' # version-1 store, though with slightly different command names
##' # (put instead of write, get instead of read)
##' kv$put("/kv/path/secret", list(key = "value"))
##' kv$get("/kv/path/secret")
##'
##' # But it also allows different versions to be stored at the same path:
##' kv$put("/kv/path/secret", list(key = "s3cret!"))
##' kv$get("/kv/path/secret")
##'
##' # Old versions can be retrieved still:
##' kv$get("/kv/path/secret", version = 1)
##'
##' # And metadata about versions can be retrieved
##' kv$metadata_get("/kv/path/secret")
##'
##' # cleanup
##' server$kill()
##' }
vault_client_kv2 <- R6::R6Class(
"vault_client_kv2",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL,
validate_path = function(path, mount, zero_length_ok = FALSE) {
path <- sub("^/", "", path)
mount <- mount %||% private$mount
if (!string_starts_with(path, mount)) {
stop(sprintf(
"Invalid mount given for this path - expected '%s'", mount))
}
relative <- substr(path, nchar(mount) + 2, nchar(path))
if (!zero_length_ok && !nzchar(relative)) {
stop("Invalid path")
}
list(mount = mount,
relative = relative,
data = sprintf("/%s/data/%s", mount, relative),
metadata = sprintf("/%s/metadata/%s", mount, relative),
delete = sprintf("/%s/delete/%s", mount, relative),
undelete = sprintf("/%s/undelete/%s", mount, relative),
destroy = sprintf("/%s/destroy/%s", mount, relative))
},
validate_version = function(version, multiple_allowed = FALSE) {
if (is.null(version)) {
NULL
} else {
if (multiple_allowed) {
assert_integer(version)
## NOTE: The 'I' here is to stop httr "helpfully" unboxing
## length-1 arrays. The alternative solution would be to
## manually convert to json, which is what we'll need to do
## if dropping httr in favour of plain curl
list(versions = I(version))
} else {
assert_scalar_integer(version)
list(version = version)
}
}
}
),
public = list(
##' @description Create a `vault_client_kv2` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
##'
##' @param mount Mount point for the backend
initialize = function(api_client, mount) {
super$initialize("Interact with vault's key/value store (version 2)")
assert_scalar_character(mount)
private$mount <- sub("^/", "", mount)
private$api_client <- api_client
},
##' @description Fetch the configuration for this `kv2` store.
##' Returns a named list of values, the contents of which will
##' depend on the vault version.
##'
##' @param mount Custom mount path to use for this store (see `Details`).
config = function(mount = NULL) {
path <- sprintf("%s/config", mount %||% private$mount)
private$api_client$GET(path)$data
},
##' @description Set up a `vault_client_kv2` object at a custom
##' mount. For example, suppose you mounted another copy of the
##' `kv2` secret backend at `/secret2` you might use `kv <-
##' vault$secrets$kv2$custom_mount("/secret2")` - this pattern is
##' repeated for other secret and authentication backends.
##'
##' @param mount String, indicating the path that the engine is
##' mounted at.
custom_mount = function(mount) {
vault_client_kv2$new(private$api_client, mount)
},
##' @description Delete a secret from the vault. This marks the
##' version as deleted and will stop it from being returned from
##' reads, but the underlying data will not be removed. A delete
##' can be undone using the undelete method.
##'
##' @param path Path to delete
##'
##' @param version Optional version to delete. If `NULL` (the
##' default) then the latest version of the secret is deleted.
##' Otherwise, `version` can be a vector of integer versions to
##' delete.
##'
##' @param mount Custom mount path to use for this store (see `Details`).
delete = function(path, version = NULL, mount = NULL) {
path <- private$validate_path(path, mount)
if (is.null(version)) {
private$api_client$DELETE(path$data)
} else {
body <- private$validate_version(version, TRUE)
private$api_client$POST(path$delete, body = body)
}
invisible(NULL)
},
##' @description Delete a secret entirely. Unlike `delete` this
##' operation is irreversible and is more like the `delete`
##' operation on [`vaultr::vault_client_kv1`] stores.
##'
##' @param path Path to delete
##'
##' @param version Version numbers to delete, as a vector of
##' integers (this is required)
##'
##' @param mount Custom mount path to use for this store (see `Details`).
destroy = function(path, version, mount = NULL) {
path <- private$validate_path(path, mount)
body <- private$validate_version(version, TRUE)
private$api_client$POST(path$destroy, body = body)
invisible(NULL)
},
##' @description Read a secret from the vault
##'
##' @param path Path of the secret to read
##'
##' @param version Optional version of the secret to read. If
##' `NULL` (the default) then the most recent version is read.
##' Otherwise this must be a scalar integer.
##'
##' @param field Optional field to read from the secret. Each
##' secret is stored as a key/value set (represented in R as a
##' named list) and this is equivalent to using `[[field]]` on
##' the return value. The default, `NULL`, returns the full set
##' of values.
##'
##' @param metadata Logical, indicating if we should return
##' metadata for this secret (lease information etc) as an
##' attribute along with the values itself. Ignored if `field`
##' is specified.
##'
##' @param mount Custom mount path to use for this store (see `Details`).
get = function(path, version = NULL, field = NULL,
metadata = FALSE, mount = NULL) {
path <- private$validate_path(path, mount)
query <- private$validate_version(version)
assert_scalar_logical(metadata)
assert_scalar_character_or_null(field)
res <- tryCatch(
private$api_client$GET(path$data, query = query),
vault_invalid_path = function(e) NULL)
if (is.null(res)) {
return(NULL)
}
ret <- res$data$data
if (!is.null(field)) {
ret <- ret[[field]]
} else if (metadata) {
attr(ret, "metadata") <- res$data$metadata
}
ret
},
##' @description List data in the vault at a give path. This can
##' be used to list keys, etc (e.g., at `/secret`).
##'
##' @param path The path to list
##'
##' @param full_names Logical, indicating if full paths (relative
##' to the vault root) should be returned.
##'
##' @param mount Custom mount path to use for this store (see `Details`).
##'
##' @param value A character vector (of zero length if no keys are
##' found). Paths that are "directories" (i.e., that contain
##' keys and could themselves be listed) will be returned with a
##' trailing forward slash, e.g. `path/`
list = function(path, full_names = FALSE, mount = NULL) {
## TODO: support full_names here?
path <- private$validate_path(path, mount, TRUE)
res <- tryCatch(
private$api_client$LIST(path$metadata),
vault_invalid_path = function(e) NULL)
ret <- list_to_character(res$data$keys)
if (full_names) {
ret <- paste(sub("/+$", "", path$mount), ret, sep = "/")
}
ret
},
##' @description Read secret metadata and versions at the specified
##' path
##'
##' @param path Path of secret to read metadata for
##'
##' @param mount Custom mount path to use for this store (see `Details`).
metadata_get = function(path, mount = NULL) {
path <- private$validate_path(path, mount)
res <- tryCatch(
private$api_client$GET(path$metadata),
vault_invalid_path = function(e) NULL)
if (is.null(res)) {
return(NULL)
}
res$data
},
##' @description Update metadata for a secret. This is allowed
##' even if a secret does not yet exist, though this requires the
##' `create` vault permission at this path.
##'
##' @param path Path of secret to update metadata for
##'
##' @param cas_required Logical, indicating that if If true the key
##' will require the cas parameter to be set on all write
##' requests (see `put`). If `FALSE`, the backend's configuration
##' will be used.
##'
##' @param max_versions Integer, indicating the
##' maximum number of versions to keep per key. If not set, the
##' backend's configured max version is used. Once a key has more
##' than the configured allowed versions the oldest version will
##' be permanently deleted.
##'
##' @param mount Custom mount path to use for this store (see `Details`).
metadata_put = function(path, cas_required = NULL, max_versions = NULL,
mount = NULL) {
path <- private$validate_path(path, mount)
body <- drop_null(list(
cas_required = cas_required, max_versions = max_versions))
private$api_client$POST(path$metadata, body = body)
invisible(NULL)
},
##' @description This method permanently deletes the key metadata
##' and all version data for the specified key. All version
##' history will be removed.
##'
##' @param path Path to delete
##'
##' @param mount Custom mount path to use for this store (see `Details`).
metadata_delete = function(path, mount = NULL) {
path <- private$validate_path(path, mount)
private$api_client$DELETE(path$metadata)
invisible(NULL)
},
##' @description Create or update a secret in this store.
##'
##' @param path Path for the secret to write, such as
##' `/secret/mysecret`
##'
##' @param data A named list of values to write into the vault at
##' this path.
##'
##' @param cas Integer, indicating the "cas" value to use a
##' "Check-And-Set" operation. If not set the write will be
##' allowed. If set to 0 a write will only be allowed if the key
##' doesn't exist. If the index is non-zero the write will only
##' be allowed if the key's current version matches the version
##' specified in the cas parameter.
##'
##' @param mount Custom mount path to use for this store (see `Details`).
put = function(path, data, cas = NULL, mount = NULL) {
assert_named(data)
body <- list(data = data)
if (!is.null(cas)) {
assert_scalar_integer(cas)
body$options <- list(cas = cas)
}
path <- private$validate_path(path, mount)
ret <- private$api_client$POST(path$data, body = body)
invisible(ret$data)
},
## TODO: implement patch
##' @description Undeletes the data for the provided version and
##' path in the key-value store. This restores the data, allowing
##' it to be returned on get requests. This works with data
##' deleted with `$delete` but not with `$destroy`.
##'
##' @param path The path to undelete
##'
##' @param version Integer vector of versions to undelete
##'
##' @param mount Custom mount path to use for this store (see `Details`).
undelete = function(path, version, mount = NULL) {
path <- private$validate_path(path, mount)
body <- private$validate_version(version, TRUE)
private$api_client$POST(path$undelete, body = body)
invisible(NULL)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_kv2.R
|
##' Administration commands for vault operators. Very few of these
##' commands should be used without consulting the vault documentation
##' as they affect the administration of a vault server, but they are
##' included here for completeness.
##'
##' @title Vault Administration
##' @name vault_client_operator
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # Our test server is by default unsealed:
##' client$status()$sealed
##'
##' # We can seal the vault to prevent all access:
##' client$operator$seal()
##' client$status()$sealed
##'
##' # And then unseal it again
##' client$operator$unseal(server$keys)
##' client$status()$sealed
##' }
vault_client_operator <- R6::R6Class(
"vault_client_operator",
inherit = vault_client_object,
cloneable = FALSE,
private = list(api_client = NULL),
public = list(
##' @description Create a `vault_client_operator` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
initialize = function(api_client) {
super$initialize("Administration commands for vault operators")
private$api_client <- api_client
},
##' @description Return information about the current encryption
##' key of Vault.
key_status = function() {
private$api_client$GET("/sys/key-status")
},
##' @description Returns the initialization status of Vault
is_initialized = function() {
d <- private$api_client$GET("/sys/init", allow_missing_token = TRUE)
d$initialized
},
##' @description This endpoint initializes a new Vault. The Vault
##' must not have been previously initialized.
##'
##' @param secret_shares Integer, specifying the number of shares
##' to split the master key into
##'
##' @param secret_threshold Integer, specifying the number of
##' shares required to reconstruct the master key. This must be
##' less than or equal secret_shares
init = function(secret_shares, secret_threshold) {
## TODO: pgp not supported here
assert_scalar_integer(secret_shares)
assert_scalar_integer(secret_threshold)
body <- list(secret_shares = secret_shares,
secret_threshold = secret_threshold)
res <- private$api_client$PUT("/sys/init", body = body,
allow_missing_token = TRUE)
res$keys <- list_to_character(res$keys)
res$keys_base64 <- list_to_character(res$keys_base64)
res
},
##' @description Check the high availability status and current
##' leader of Vault
leader_status = function() {
private$api_client$GET("/sys/leader")
},
##' @description Reads the configuration and progress of the
##' current rekey attempt
rekey_status = function() {
private$api_client$GET("/sys/rekey/init")
},
##' @description This method begins a new rekey attempt. Only a
##' single rekey attempt can take place at a time, and changing
##' the parameters of a rekey requires cancelling and starting a
##' new rekey, which will also provide a new nonce.
##'
##' @param secret_shares Integer, specifying the number of shares
##' to split the master key into
##'
##' @param secret_threshold Integer, specifying the number of
##' shares required to reconstruct the master key. This must be
##' less than or equal secret_shares
rekey_start = function(secret_shares, secret_threshold) {
assert_scalar_integer(secret_shares)
assert_scalar_integer(secret_threshold)
body <- list(secret_shares = secret_shares,
secret_threshold = secret_threshold,
backup = FALSE,
require_verification = FALSE)
## TODO: this is incorrect in the vault api docs
ans <- private$api_client$PUT("/sys/rekey/init", body = body)
ans
},
##' @description This method cancels any in-progress rekey. This
##' clears the rekey settings as well as any progress made. This
##' must be called to change the parameters of the rekey. Note
##' verification is still a part of a rekey. If rekeying is
##' cancelled during the verification flow, the current unseal
##' keys remain valid.
rekey_cancel = function() {
private$api_client$DELETE("/sys/rekey/init")
invisible(NULL)
},
##' @description This method is used to enter a single master key
##' share to progress the rekey of the Vault. If the threshold
##' number of master key shares is reached, Vault will complete
##' the rekey. Otherwise, this method must be called multiple
##' times until that threshold is met. The rekey nonce operation
##' must be provided with each call.
##'
##' @param key Specifies a single master share key (a string)
##'
##' @param nonce Specifies the nonce of the rekey operation (a
##' string)
rekey_submit = function(key, nonce) {
assert_scalar_character(key)
assert_scalar_character(nonce)
body <- list(key = key, nonce = nonce)
ans <- private$api_client$PUT("/sys/rekey/update", body = body)
if (isTRUE(ans$complete)) {
ans$keys <- list_to_character(ans$keys)
ans$keys_base64 <- list_to_character(ans$keys_base64)
}
ans
},
##' @description This method triggers a rotation of the backend
##' encryption key. This is the key that is used to encrypt data
##' written to the storage backend, and is not provided to
##' operators. This operation is done online. Future values are
##' encrypted with the new key, while old values are decrypted
##' with previous encryption keys.
rotate = function() {
private$api_client$PUT("/sys/rotate")
invisible(NULL)
},
##' @description Seal the vault, preventing any access to it.
##' After the vault is sealed, it must be unsealed for further
##' use.
seal = function() {
private$api_client$PUT("/sys/seal")
invisible(NULL)
},
##' @description Check the seal status of a Vault. This method can
##' be used even when the client is not authenticated with the
##' vault (which will the case for a sealed vault).
seal_status = function() {
private$api_client$GET("/sys/seal-status", allow_missing_token = TRUE)
},
##' @description Submit a portion of a key to unseal the vault.
##' This method is typically called by multiple different
##' operators to assemble the master key.
##'
##' @param key The master key share
##'
##' @param reset Logical, indicating if the unseal process should
##' start be started again.
unseal = function(key, reset = FALSE) {
assert_scalar_character(key)
assert_scalar_logical(reset)
body <- list(key = key, reset = reset)
private$api_client$PUT("/sys/unseal", body = body,
allow_missing_token = TRUE)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_operator.R
|
##' Interact with vault's policies. To get started, you may want to
##' read up on policies as described in the vault manual, here:
##' https://developer.hashicorp.com/vault/docs/concepts/policies
##'
##' @title Vault Policy Configuration
##' @name vault_client_policy
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # The test server starts with only the policies "root" (do
##' # everything) and "default" (do nothing).
##' client$policy$list()
##'
##' # Here let's make a policy that allows reading secrets from the
##' # path /secret/develop/* but nothing else
##' rules <- 'path "secret/develop/*" {policy = "read"}'
##' client$policy$write("read-secret-develop", rules)
##'
##' # Our new rule is listed and can be read
##' client$policy$list()
##' client$policy$read("read-secret-develop")
##'
##' # For testing, let's create a secret under this path, and under
##' # a different path:
##' client$write("/secret/develop/password", list(value = "password"))
##' client$write("/secret/production/password", list(value = "k2e89be@rdC#"))
##'
##' # Create a token that can use this policy:
##' token <- client$auth$token$create(policies = "read-secret-develop")
##'
##' # Login to the vault using this token:
##' alice <- vaultr::vault_client(addr = server$addr,
##' login = "token", token = token)
##'
##' # We can read the paths that we have been granted access to:
##' alice$read("/secret/develop/password")
##'
##' # We can't read secrets that are outside our path:
##' try(alice$read("/secret/production/password"))
##'
##' # And we can't write:
##' try(alice$write("/secret/develop/password", list(value = "secret")))
##'
##' # cleanup
##' server$kill()
##' }
vault_client_policy <- R6::R6Class(
"vault_client_policy",
inherit = vault_client_object,
cloneable = FALSE,
private = list(api_client = NULL),
public = list(
##' @description Create a `vault_client_policy` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
initialize = function(api_client) {
super$initialize("Interact with policies")
private$api_client <- api_client
},
##' @description This endpoint deletes the policy with the given
##' name. This will immediately affect all users associated with
##' this policy.
##'
##' @param name Specifies the name of the policy to delete.
delete = function(name) {
assert_scalar_character(name)
private$api_client$DELETE(paste0("/sys/policy/", name))
invisible(NULL)
},
##' @description Lists all configured policies.
list = function() {
dat <- private$api_client$GET("/sys/policy")
list_to_character(dat$data$keys)
},
##' @description Retrieve the policy body for the named policy
##'
##' @param name Specifies the name of the policy to retrieve
read = function(name) {
assert_scalar_character(name)
dat <- private$api_client$GET(paste0("/sys/policy/", name))
dat$data$rules
},
##' @description Create or update a policy. Once a policy is
##' updated, it takes effect immediately to all associated users.
##'
##' @param name Name of the policy to update
##'
##' @param rules Specifies the policy document. This is a string
##' in "HashiCorp configuration language". At present this must
##' be read in as a single string (not a character vector of
##' strings); future versions of vaultr may allow more flexible
##' specification such as `@filename`
write = function(name, rules) {
assert_scalar_character(name)
assert_scalar_character(rules)
body <- list(rules = rules)
private$api_client$PUT(paste0("/sys/policy/", name), body = body)
invisible(NULL)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_policy.R
|
##' Interact with vault's secret backends.
##'
##' @title Vault Secret Configuration
##' @name vault_client_secrets
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # To remove the default version 1 kv store and replace with a
##' # version 2 store:
##' client$secrets$disable("/secret")
##' client$secrets$enable("kv", "/secret", version = 2)
##'
##' # cleanup
##' server$kill()
##' }
vault_client_secrets <- R6::R6Class(
"vault_client_secrets",
inherit = vault_client_object,
cloneable = FALSE,
private = list(api_client = NULL),
public = list(
##' @field cubbyhole The cubbyhole backend:
##' [vaultr::vault_client_cubbyhole]
cubbyhole = NULL,
##' @field kv1 The version 1 key-value backend:
##' [vaultr::vault_client_kv1]
kv1 = NULL,
##' @field kv2 The version 2 key-value backend:
##' [vaultr::vault_client_kv2]
kv2 = NULL,
##' @field transit The transit backend:
##' [vaultr::vault_client_transit]
transit = NULL,
##' @description Create a `vault_client_secrets` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
initialize = function(api_client) {
super$initialize("Interact with secret engines")
private$api_client <- api_client
add_const_member(self, "cubbyhole",
vault_client_cubbyhole$new(api_client))
add_const_member(self, "kv1",
vault_client_kv1$new(api_client, NULL))
add_const_member(self, "kv2",
vault_client_kv2$new(api_client, "secret"))
add_const_member(self, "transit",
vault_client_transit$new(api_client, "transit"))
},
##' @description Disable a previously-enabled secret engine
##'
##' @param path Path of the secret engine
disable = function(path) {
if (!is_absolute_path(path)) {
path <- paste0("/", path)
}
private$api_client$DELETE(paste0("/sys/mounts", path))
invisible(NULL)
},
##' @description Enable a secret backend in the vault server
##'
##' @param type The type of secret backend (e.g., `transit`, `kv`).
##'
##' @param description Human-friendly description of the backend;
##' will be returned by `$list()`
##'
##' @param path Specifies the path in which to enable the auth
##' method. Defaults to be the same as `type`.
##'
##' @param version Used only for the `kv` backend, where an integer
##' is used to select between [vaultr::vault_client_kv1] and
##' [vaultr::vault_client_kv2] engines.
enable = function(type, path = type, description = NULL, version = NULL) {
## TODO: there are many additional options here that are not
## currently supported and which would come through the "config"
## argument.
assert_scalar_character(type)
assert_scalar_character(path)
assert_scalar_character_or_null(description)
if (!is_absolute_path(path)) {
path <- paste0("/", path)
}
data <- list(type = type,
description = description)
if (!is.null(version)) {
data$options <- list(version = as.character(version))
}
private$api_client$POST(paste0("/sys/mounts", path), body = data)
invisible(path)
},
##' @description List enabled secret engines
##'
##' @param detailed Logical, indicating if detailed output is
##' wanted.
list = function(detailed = FALSE) {
if (detailed) {
stop("Detailed secret information not supported")
}
dat <- private$api_client$GET("/sys/mounts")
cols <- c("type", "accessor", "description")
ret <- lapply(cols, function(v) {
vcapply(dat$data, "[[", v, USE.NAMES = FALSE)
})
names(ret) <- cols
as.data.frame(c(list(path = names(dat$data)), ret),
stringsAsFactors = FALSE, check.names = FALSE)
},
##' @description Move the path that a secret engine is mounted at
##'
##' @param from Original path
##'
##' @param to New path
move = function(from, to) {
assert_scalar_character(from)
assert_scalar_character(to)
body <- list(from = from, to = to)
private$api_client$POST("/sys/remount", body = body)
invisible(NULL)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_secrets.R
|
##' Interact with vault's token methods. This includes support for
##' querying, creating and deleting tokens. Tokens are fundamental to
##' the way that vault works, so there are a lot of methods here. The
##' vault documentation has a page devoted to token concepts:
##' https://developer.hashicorp.com/vault/docs/concepts/tokens - there
##' is also a page with commands:
##' https://developer.hashicorp.com/vault/docs/commands/token - these
##' have names very similar to the names used here.
##'
##' @section Token Accessors:
##'
##' Many of the methods use "token accessors" - whenever a token is
##' created, an "accessor" is created at the same time. This is
##' another token that can be used to perform limited actions with the
##' token such as
##'
##' * Look up a token's properties (not including the actual token ID)
##' * Look up a token's capabilities on a path
##' * Revoke the token
##'
##' However, accessors cannot be used to login, nor to retrieve the
##' actual token itself.
##'
##' @title Vault Tokens
##' @name vault_client_token
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # There are lots of token methods here:
##' client$token
##'
##' # To demonstrate, it will be useful to create a restricted
##' # policy that can only read from the /secret path
##' rules <- 'path "secret/*" {policy = "read"}'
##' client$policy$write("read-secret", rules)
##' client$write("/secret/path", list(key = "value"))
##'
##' # Create a token that has this policy
##' token <- client$auth$token$create(policies = "read-secret")
##' alice <- vaultr::vault_client(addr = server$addr)
##' alice$login(method = "token", token = token)
##' alice$read("/secret/path")
##'
##' client$token$lookup(token)
##'
##' # We can query the capabilities of this token
##' client$token$capabilities("secret/path", token)
##'
##' # Tokens are not safe to pass around freely because they *are*
##' # the ability to login, but the `token$create` command also
##' # provides an accessor:
##' accessor <- attr(token, "info")$accessor
##'
##' # It is not possible to derive the token from the accessor, but
##' # we can use the accessor to ask vault what it could do if it
##' # did have the token (and do things like revoke the token)
##' client$token$capabilities_accessor("secret/path", accessor)
##'
##' client$token$revoke_accessor(accessor)
##' try(client$token$capabilities_accessor("secret/path", accessor))
##'
##' # cleanup
##' server$kill()
##' }
vault_client_token <- R6::R6Class(
"vault_client_token",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL
),
public = list(
##' @description Create a `vault_client_token` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
initialize = function(api_client) {
super$initialize("Interact and configure vault's token support")
private$api_client <- api_client
},
##' @description List token accessors, returning a character vector
list = function() {
dat <- private$api_client$LIST("/auth/token/accessors")
list_to_character(dat$data$keys)
},
##' @description Fetch the capabilities of a token on the given
##' paths. The capabilities returned will be derived from the
##' policies that are on the token, and from the policies to
##' which the token is entitled to through the entity and
##' entity's group memberships.
##'
##' @param path Vector of paths on which capabilities are being
##' queried
##'
##' @param token Single token for which capabilities are being
##' queried
capabilities = function(path, token) {
body <- list(paths = I(assert_character(path)),
token = assert_scalar_character(token))
data <- private$api_client$POST("/sys/capabilities", body = body)
lapply(data$data[path], list_to_character)
},
##' @description As for the `capabilities` method, but for the
##' client token used to make the request.
##'
##' @param path Vector of paths on which capabilities are being
##' queried
capabilities_self = function(path) {
body <- list(paths = I(assert_character(path)))
data <- private$api_client$POST("/sys/capabilities-self", body = body)
lapply(data$data[path], list_to_character)
},
##' @description As for the `capabilities` method, but using a
##' token *accessor* rather than a token itself.
##'
##' @param path Vector of paths on which capabilities are being
##' queried
##'
##' @param accessor Accessor of the token for which capabilities
##' are being queried
capabilities_accessor = function(path, accessor) {
body <- list(paths = I(assert_character(path)),
accessor = assert_scalar_character(accessor))
data <- private$api_client$POST("/sys/capabilities-accessor", body = body)
lapply(data$data[path], list_to_character)
},
##' @description
##' Return the current client token
client = function() {
private$api_client$token
},
##' @description Create a new token
##'
##' @param role_name The name of the token role
##'
##' @param id The ID of the client token. Can only be specified by
##' a root token. Otherwise, the token ID is a randomly generated
##' value
##'
##' @param policies A character vector of policies for the
##' token. This must be a subset of the policies belonging to the
##' token making the request, unless root. If not specified,
##' defaults to all the policies of the calling token.
##'
##' @param meta A named list of strings as metadata to pass through
##' to audit devices.
##'
##' @param orphan Logical, indicating if the token created should
##' be an orphan (they will have no parent). As such, they will
##' not be automatically revoked by the revocation of any other
##' token.
##'
##' @param no_default_policy Logical, if `TRUE`, then the default
##' policy will not be contained in this token's policy set.
##'
##' @param max_ttl Provides a maximum lifetime for any tokens
##' issued against this role, including periodic tokens. Unlike
##' direct token creation, where the value for an explicit max
##' TTL is stored in the token, for roles this check will always
##' use the current value set in the role. The main use of this
##' is to provide a hard upper bound on periodic tokens, which
##' otherwise can live forever as long as they are renewed. This
##' is an integer number of seconds
##'
##' @param display_name The display name of the token
##'
##' @param num_uses Maximum number of uses that a token can have.
##' This can be used to create a one-time-token or limited use
##' token. The default, or the value of 0, has no limit to the
##' number of uses.
##'
##' @param period If specified, the token will be periodic; it will
##' have no maximum TTL (unless a `max_ttl` is also set) but
##' every renewal will use the given period. Requires a
##' root/sudo token to use.
##'
##' @param ttl The TTL period of the token, provided as "1h", where
##' hour is the largest suffix. If not provided, the token is
##' valid for the default lease TTL, or indefinitely if the root
##' policy is used.
##'
##' @param wrap_ttl Indicates that the secret should be wrapped.
##' This is discussed in the vault documentation:
##' https://developer.hashicorp.com/vault/docs/concepts/response-wrapping
##' When this option is used, `vault` will take the response it
##' would have sent to an HTTP client and instead insert it into
##' the cubbyhole of a single-use token, returning that
##' single-use token instead. Logically speaking, the response is
##' wrapped by the token, and retrieving it requires an unwrap
##' operation against this token (see the `$unwrap` method
##' [vaultr::vault_client]. Must be specified as a valid
##' duration (e.g., `1h`).
create = function(role_name = NULL, id = NULL, policies = NULL,
meta = NULL, orphan = FALSE, no_default_policy = FALSE,
max_ttl = NULL, display_name = NULL,
num_uses = 0L, period = NULL, ttl = NULL,
wrap_ttl = NULL) {
body <- list(
role_name = role_name %&&% assert_scalar_character(role_name),
policies = policies %&&% I(assert_character(policies)),
meta = meta,
no_default_policy = assert_scalar_logical(no_default_policy),
explicit_max_ttl = max_ttl %&&% assert_scalar_integer(max_ttl),
display_name = display_name %&&% assert_scalar_character(display_name),
num_uses = num_uses %&&% assert_scalar_integer(num_uses),
ttl = ttl %&&% assert_is_duration(ttl),
## root only:
id = role_name %&&% assert_scalar_character(id),
period = period %&&% assert_is_duration(period),
no_parent = assert_scalar_logical(orphan))
body <- drop_null(body)
res <- private$api_client$POST("/auth/token/create", body = body,
wrap_ttl = wrap_ttl)
if (is.null(wrap_ttl)) {
info <- res$auth
info$policies <- list_to_character(info$policies)
token <- info$client_token
} else {
info <- res$wrap_info
token <- info$token
}
attr(token, "info") <- info
token
},
##' @description Returns information about the client token
##'
##' @param token The token to lookup
lookup = function(token = NULL) {
body <- list(token = assert_scalar_character(token))
res <- private$api_client$POST("/auth/token/lookup", body = body)
data <- res$data
data$policies <- list_to_character(data$policies)
data
},
##' @description Returns information about the current client token
##' (as if calling `$lookup` with the token the client is using.
lookup_self = function() {
res <- private$api_client$GET("/auth/token/lookup-self")
data <- res$data
data$policies <- list_to_character(data$policies)
data
},
##' @description Returns information about the client token from
##' the accessor.
##'
##' @param accessor The token accessor to lookup
lookup_accessor = function(accessor) {
body <- list(accessor = assert_scalar_character(accessor))
res <- private$api_client$POST("/auth/token/lookup-accessor", body = body)
data <- res$data
data$policies <- list_to_character(data$policies)
data
},
##' @description Renews a lease associated with a token. This is
##' used to prevent the expiration of a token, and the automatic
##' revocation of it. Token renewal is possible only if there is
##' a lease associated with it.
##'
##' @param token The token to renew
##'
##' @param increment An optional requested lease increment can be
##' provided. This increment may be ignored. If given, it should
##' be a duration (e.g., `1h`).
renew = function(token, increment = NULL) {
body <- list(token = assert_scalar_character(token))
if (!is.null(increment)) {
body$increment <- assert_is_duration(increment)
}
res <- private$api_client$POST("/auth/token/renew", body = body)
info <- res$auth
info$policies <- list_to_character(info$policies)
info
},
##' @description Renews a lease associated with the calling
##' token. This is used to prevent the expiration of a token, and
##' the automatic revocation of it. Token renewal is possible
##' only if there is a lease associated with it. This is
##' equivalent to calling `$renew()` with the client token.
##'
##' @param increment An optional requested lease increment can be
##' provided. This increment may be ignored. If given, it should
##' be a duration (e.g., `1h`).
renew_self = function(increment = NULL) {
body <- list(
increment = increment %&&% assert_is_duration(increment))
res <- private$api_client$POST("/auth/token/renew-self",
body = drop_null(body))
info <- res$auth
info$policies <- list_to_character(info$policies)
info
},
##' @description Revokes a token and all child tokens. When the
##' token is revoked, all dynamic secrets generated with it are
##' also revoked.
##'
##' @param token The token to revoke
revoke = function(token) {
body <- list(token = assert_scalar_character(token))
private$api_client$POST("/auth/token/revoke", body = body)
invisible(NULL)
},
##' @description Revokes the token used to call it and all child
##' tokens. When the token is revoked, all dynamic secrets
##' generated with it are also revoked. This is equivalent to
##' calling `$revoke()` with the client token.
revoke_self = function() {
private$api_client$POST("/auth/token/revoke-self")
invisible(NULL)
},
##' @description Revoke the token associated with the accessor and
##' all the child tokens. This is meant for purposes where there
##' is no access to token ID but there is need to revoke a token
##' and its children.
##'
##' @param accessor Accessor of the token to revoke.
revoke_accessor = function(accessor) {
body <- list(accessor = assert_scalar_character(accessor))
private$api_client$POST("/auth/token/revoke-accessor", body = body)
invisible(NULL)
},
##' @description Revokes a token but not its child tokens. When the
##' token is revoked, all secrets generated with it are also
##' revoked. All child tokens are orphaned, but can be revoked
##' subsequently using /auth/token/revoke/. This is a
##' root-protected method.
##'
##' @param token The token to revoke
revoke_and_orphan = function(token) {
body <- list(token = assert_scalar_character(token))
private$api_client$POST("/auth/token/revoke-orphan", body = body)
invisible(NULL)
},
##' @description Fetches the named role configuration.
##'
##' @param role_name The name of the token role.
role_read = function(role_name) {
path <- sprintf("/auth/token/roles/%s",
assert_scalar_character(role_name))
data <- private$api_client$GET(path)$data
data$allowed_policies <- list_to_character(data$allowed_policies)
data$disallowed_policies <- list_to_character(data$disallowed_policies)
data
},
##' @description List available token roles.
role_list = function() {
dat <- tryCatch(private$api_client$LIST("/auth/token/roles"),
vault_invalid_path = function(e) NULL)
list_to_character(dat$data$keys)
},
##' @description Creates (or replaces) the named role. Roles
##' enforce specific behaviour when creating tokens that allow
##' token functionality that is otherwise not available or would
##' require sudo/root privileges to access. Role parameters, when
##' set, override any provided options to the create
##' endpoints. The role name is also included in the token path,
##' allowing all tokens created against a role to be revoked
##' using the `/sys/leases/revoke-prefix` endpoint.
##'
##' @param role_name Name for the role - this will be used later to
##' refer to the role (e.g., in `$create` and other `$role_*`
##' methods.
##'
##' @param allowed_policies Character vector of policies allowed
##' for this role. If set, tokens can be created with any subset
##' of the policies in this list, rather than the normal
##' semantics of tokens being a subset of the calling token's
##' policies. The parameter is a comma-delimited string of policy
##' names. If at creation time `no_default_policy` is not set and
##' "default" is not contained in disallowed_policies, the
##' "default" policy will be added to the created token
##' automatically.
##'
##' @param disallowed_policies Character vector of policies
##' forbidden for this role. If set, successful token creation
##' via this role will require that no policies in the given list
##' are requested. Adding "default" to this list will prevent
##' "default" from being added automatically to created tokens.
##'
##' @param orphan If `TRUE`, then tokens created against this
##' policy will be orphan tokens (they will have no parent). As
##' such, they will not be automatically revoked by the
##' revocation of any other token.
##'
##' @param period A duration (e.g., `1h`). If specified, the token
##' will be periodic; it will have no maximum TTL (unless an
##' "explicit-max-ttl" is also set) but every renewal will use
##' the given period. Requires a root/sudo token to use.
##'
##' @param renewable Set to `FALSE` to disable the ability of the
##' token to be renewed past its initial TTL. The default value
##' of `TRUE` will allow the token to be renewable up to the
##' system/mount maximum TTL.
##'
##' @param explicit_max_ttl An integer number of seconds. Provides
##' a maximum lifetime for any tokens issued against this role,
##' including periodic tokens. Unlike direct token creation,
##' where the value for an explicit max TTL is stored in the
##' token, for roles this check will always use the current value
##' set in the role. The main use of this is to provide a hard
##' upper bound on periodic tokens, which otherwise can live
##' forever as long as they are renewed. This is an integer
##' number of seconds.
##'
##' @param path_suffix A string. If set, tokens created against
##' this role will have the given suffix as part of their path in
##' addition to the role name. This can be useful in certain
##' scenarios, such as keeping the same role name in the future
##' but revoking all tokens created against it before some point
##' in time. The suffix can be changed, allowing new callers to
##' have the new suffix as part of their path, and then tokens
##' with the old suffix can be revoked via
##' `/sys/leases/revoke-prefix`.
##'
##' @param bound_cidrs Character vector of CIDRS. If set,
##' restricts usage of the generated token to client IPs falling
##' within the range of the specified CIDR(s). Unlike most other
##' role parameters, this is not reevaluated from the current
##' role value at each usage; it is set on the token itself. Root
##' tokens with no TTL will not be bound by these CIDRs; root
##' tokens with TTLs will be bound by these CIDRs.
##'
##' @param token_type Specifies the type of tokens that should be
##' returned by the role. If either service or batch is
##' specified, that kind of token will always be returned. If
##' `default-service`, then `service` tokens will be returned
##' unless the client requests a batch type token at token
##' creation time. If `default-batch`, then `batch` tokens will
##' be returned unless the client requests a service type token
##' at token creation time.
role_write = function(role_name, allowed_policies = NULL,
disallowed_policies = NULL, orphan = NULL,
period = NULL, renewable = NULL,
explicit_max_ttl = NULL, path_suffix = NULL,
bound_cidrs = NULL, token_type = NULL) {
path <- sprintf("/auth/token/roles/%s",
assert_scalar_character(role_name))
body <- list(
allowed_policies =
allowed_policies %&&% assert_character(allowed_policies),
disallowed_policies =
disallowed_policies %&&% assert_character(disallowed_policies),
orphan = orphan %&&% assert_scalar_logical(orphan),
period = period %&&% assert_duration(period),
renewable = orphan %&&% assert_scalar_logical(orphan),
explicit_max_ttl =
explicit_max_ttl %&&% assert_scalar_integer(explicit_max_ttl),
path_suffix = path_suffix %&&% assert_scalar_character(path_suffix),
bound_cidrs = bound_cidrs %&&% assert_character(bound_cidrs),
token_type = token_type %&&% assert_scalar_character(token_type))
private$api_client$POST(path, body = drop_null(body))
invisible(NULL)
},
##' @description Delete a named token role
##'
##' @param role_name The name of the role to delete
role_delete = function(role_name) {
path <- sprintf("/auth/token/roles/%s",
assert_scalar_character(role_name))
private$api_client$DELETE(path)
invisible(NULL)
},
##' @description Performs some maintenance tasks to clean up
##' invalid entries that may remain in the token
##' store. Generally, running this is not needed unless upgrade
##' notes or support personnel suggest it. This may perform a lot
##' of I/O to the storage method so should be used sparingly.
tidy = function() {
private$api_client$POST("/auth/token/tidy")
invisible(NULL)
},
## Not really a *login* as such, but this is where we centralise
## the variable lookup information:
##' @description Unlike other auth backend `login` methods, this
##' does not actually log in to the vault. Instead it verifies
##' that a token can be used to communicate with the vault.
##'
##' @param token The token to test
##'
##' @param quiet Logical scalar, set to `TRUE` to suppress
##' informational messages.
login = function(token = NULL, quiet = FALSE) {
token <- vault_auth_vault_token(token)
res <- private$api_client$verify_token(token, quiet = quiet)
if (!res$success) {
stop(paste("Token login failed with error:", res$error$message),
call. = FALSE)
}
res$token
}
))
vault_auth_vault_token <- function(token) {
if (is.null(token)) {
token <- Sys_getenv("VAULT_TOKEN", NULL)
}
if (is.null(token)) {
stop("Vault token was not found: perhaps set 'VAULT_TOKEN'",
call. = FALSE)
}
assert_scalar_character(token)
token
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_token.R
|
##' Interact with vault's cryptographic tools. This provides support
##' for high-quality random numbers and cryptographic hashes. This
##' functionality is also available through the transit secret engine.
##'
##' @title Vault Tools
##' @name vault_client_tools
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' # Random bytes in hex
##' client$tools$random()
##' # base64
##' client$tools$random(format = "base64")
##' # raw
##' client$tools$random(10, format = "raw")
##'
##' # Hash data:
##' data <- charToRaw("hello vault")
##' # will produce 55e702...92efd40c2a4
##' client$tools$hash(data)
##'
##' # sha2-512 hash:
##' client$tools$hash(data, "sha2-512")
##'
##' # cleanup
##' server$kill()
##' }
vault_client_tools <- R6::R6Class(
"vault_client_tools",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL
),
public = list(
##' @description Create a `vault_client_tools` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
initialize = function(api_client) {
private$api_client <- api_client
super$initialize("General tools provided by vault")
},
##' @description Generates high-quality random bytes of the
##' specified length. This is totally independent of R's random
##' number stream and provides random numbers suitable for
##' cryptographic purposes.
##'
##' @param bytes Number of bytes to generate (as an integer)
##'
##' @param format The output format to produce; must be one of
##' `hex` (a single hex string such as `d1189e2f83b72ab6`),
##' `base64` (a single base64 encoded string such as
##' `8TDJekY0mYs=`) or `raw` (a raw vector of length `bytes`).
random = function(bytes = 32, format = "hex") {
body <- list(bytes = assert_scalar_integer(bytes),
format = assert_scalar_character(format))
if (format == "raw") {
body$format <- "base64"
}
res <- private$api_client$POST("/sys/tools/random", body = body)
bytes <- res$data$random_bytes
if (format == "raw") {
decode64(bytes)
} else {
bytes
}
},
##' @description Generates a cryptographic hash of given data using
##' the specified algorithm.
##'
##' @param data A raw vector of data to hash. To generate a raw
##' vector from an R object, one option is to use `unserialize(x,
##' NULL)` but be aware that version information may be included.
##' Alternatively, for a string, one might use `charToRaw`.
##'
##' @param algorithm A string indicating the hash algorithm to use.
##' The exact set of supported algorithms may depend by vault
##' server version, but as of version 1.0.0 vault supports
##' `sha2-224`, `sha2-256`, `sha2-384` and `sha2-512`. The
##' default is `sha2-256`.
##'
##' @param format The format of the output - must be one of `hex`
##' or `base64`.
hash = function(data, algorithm = NULL, format = "hex") {
body <- list(input = raw_data_input(data),
algorithm = algorithm,
format = assert_scalar_character(format))
private$api_client$POST("/sys/tools/hash", body = body)$data$sum
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_tools.R
|
##' Interact with vault's `transit` engine. This is useful for
##' encrypting arbitrary data without storing it in the vault - like
##' "cryptography as a service" or "encryption as a service". The
##' transit secrets engine can also sign and verify data; generate
##' hashes and HMACs of data; and act as a source of random bytes.
##' See
##' https://developer.hashicorp.com/vault/docs/secrets/transit
##' for an introduction to the capabilities of the `transit`
##' engine.
##'
##' @title Transit Engine
##' @name vault_client_transit
##' @examples
##' server <- vaultr::vault_test_server(if_disabled = message)
##' if (!is.null(server)) {
##' client <- server$client()
##'
##' client$secrets$enable("transit")
##' transit <- client$secrets$transit
##'
##' # Before encrypting anything, create a key. Note that it will
##' # not be returned to you, and is accessed purely by name
##' transit$key_create("test")
##'
##' # Some text to encrypt
##' plaintext <- "hello world"
##'
##' # Encrypted:
##' cyphertext <- transit$data_encrypt("test", charToRaw(plaintext))
##'
##' # Decrypt the data
##' res <- transit$data_decrypt("test", cyphertext)
##' rawToChar(res)
##'
##' # This approach works with R objects too, if used with serialise.
##' # First, serialise an R object to a raw vector:
##' data <- serialize(mtcars, NULL)
##'
##' # Then encrypt this data:
##' enc <- transit$data_encrypt("test", data)
##'
##' # The resulting string can be safely passed around (e.g., over
##' # email) or written to disk, and can later be decrypted by
##' # anyone who has access to the "test" key in the vault:
##' data2 <- transit$data_decrypt("test", enc)
##'
##' # Once decrypted, the data can be "unserialised" back into an R
##' # object:
##' unserialize(data2)
##'
##' # cleanup
##' server$kill()
##' }
vault_client_transit <- R6::R6Class(
"vault_client_transit",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
api_client = NULL,
mount = NULL,
verify = function(name, data, payload, payload_type,
hash_algorithm = NULL,
signature_algorithm = NULL,
context = NULL, prehashed = FALSE) {
path <- sprintf("/%s/verify/%s",
private$mount, assert_scalar_character(name))
payload_type <- match_value(payload_type, c("signature", "hmac"))
body <- list(
hash_algorithm =
hash_algorithm %&&% assert_scalar_integer(hash_algorithm),
input = raw_data_input(data),
context = context %&&% raw_data_input(context),
prehashed = assert_scalar_logical(prehashed),
signature_algorithm =
signature_algorithm %&&% assert_scalar_integer(signature_algorithm))
body[[payload_type]] <- assert_scalar_character(payload)
private$api_client$POST(path, body = drop_null(body))$data$valid
}
),
public = list(
##' @description Create a `vault_client_transit` object. Not typically
##' called by users.
##'
##' @param api_client A [vaultr::vault_api_client] object
##'
##' @param mount Mount point for the backend
initialize = function(api_client, mount) {
super$initialize("Cryptographic functions for data in-transit")
assert_scalar_character(mount)
private$mount <- sub("^/", "", mount)
private$api_client <- api_client
},
##' @description Set up a `vault_client_transit` object at a custom
##' mount. For example, suppose you mounted the `transit` secret
##' backend at `/transit2` you might use `tr <-
##' vault$secrets$transit$custom_mount("/transit2")` - this
##' pattern is repeated for other secret and authentication
##' backends.
##'
##' @param mount String, indicating the path that the engine is
##' mounted at.
custom_mount = function(mount) {
vault_client_transit$new(private$api_client, mount)
},
##' @description Create a new named encryption key of the specified
##' type. The values set here cannot be changed after key
##' creation.
##'
##' @param name Name for the key. This will be used in all future
##' interactions with the key - the key itself is not returned.
##'
##' @param key_type Specifies the type of key to create. The default is
##' `aes256-gcm96`. The currently-supported types are:
##'
##' * `aes256-gcm96`: AES-256 wrapped with GCM using a 96-bit nonce
##' size AEAD (symmetric, supports derivation and convergent
##' encryption)
##'
##' * `chacha20-poly1305`: ChaCha20-Poly1305 AEAD (symmetric,
##' supports derivation and convergent encryption)
##'
##' * `ed25519`: ED25519 (asymmetric, supports derivation). When
##' using derivation, a sign operation with the same context will
##' derive the same key and signature; this is a signing analogue
##' to `convergent_encryption`
##'
##' * `ecdsa-p256`: ECDSA using the P-256 elliptic curve
##' (asymmetric)
##'
##' * `rsa-2048`: RSA with bit size of 2048 (asymmetric)
##'
##' * `rsa-4096`: RSA with bit size of 4096 (asymmetric)
##'
##' @param convergent_encryption Logical with default of `FALSE`.
##' If `TRUE`, then the key will support convergent encryption,
##' where the same plaintext creates the same ciphertext. This
##' requires derived to be set to true. When enabled, each
##' encryption(/decryption/rewrap/datakey) operation will derive
##' a `nonce` value rather than randomly generate it.
##'
##' @param derived Specifies if key derivation is to be used. If
##' enabled, all encrypt/decrypt requests to this named key must
##' provide a context which is used for key derivation (default
##' is `FALSE`).
##'
##' @param exportable Enables keys to be exportable. This allows
##' for all the valid keys in the key ring to be exported. Once
##' set, this cannot be disabled (default is `FALSE`).
##'
##' @param allow_plaintext_backup If set, enables taking backup of
##' named key in the plaintext format. Once set, this cannot be
##' disabled (default is `FALSE`).
key_create = function(name, key_type = NULL, convergent_encryption = NULL,
derived = NULL, exportable = NULL,
allow_plaintext_backup = NULL) {
path <- sprintf("/%s/keys/%s", private$mount,
assert_scalar_character(name))
body <- list(
type = key_type %&&% assert_scalar_character(key_type),
convergent_encryption = convergent_encryption %&&%
assert_scalar_logical(convergent_encryption),
derived = derived %&&% assert_scalar_logical(derived),
exportable = exportable %&&% assert_scalar_logical(exportable),
allow_plaintext_backup = allow_plaintext_backup %&&%
assert_scalar_logical(allow_plaintext_backup))
private$api_client$POST(path, body = drop_null(body))
invisible(NULL)
},
##' @description Read information about a previously generated key.
##' The returned object shows the creation time of each key
##' version; the values are not the keys themselves. Depending on
##' the type of key, different information may be returned,
##' e.g. an asymmetric key will return its public key in a
##' standard format for the type.
##'
##' @param name The name of the key to read
key_read = function(name) {
path <- sprintf("/%s/keys/%s", private$mount,
assert_scalar_character(name))
private$api_client$GET(path)$data
},
##' @description List names of all keys
key_list = function() {
data <- tryCatch(
private$api_client$LIST(sprintf("/%s/keys", private$mount)),
vault_invalid_path = function(e) NULL)
list_to_character(data$data$keys)
},
##' @description Delete a key by name. It will no longer be
##' possible to decrypt any data encrypted with the named
##' key. Because this is a potentially catastrophic operation,
##' the `deletion_allowed` tunable must be set using
##' `$key_update()`.
##'
##' @param name The name of the key to delete.
key_delete = function(name) {
path <- sprintf("/%s/keys/%s", private$mount,
assert_scalar_character(name))
private$api_client$DELETE(path)
invisible(NULL)
},
##' @description This method allows tuning configuration values for
##' a given key. (These values are returned during a read
##' operation on the named key.)
##'
##' @param name The name of the key to update
##'
##' @param min_decryption_version Specifies the minimum version of
##' ciphertext allowed to be decrypted, as an integer (default is
##' `0`). Adjusting this as part of a key rotation policy can
##' prevent old copies of ciphertext from being decrypted, should
##' they fall into the wrong hands. For signatures, this value
##' controls the minimum version of signature that can be
##' verified against. For HMACs, this controls the minimum
##' version of a key allowed to be used as the key for
##' verification.
##'
##' @param min_encryption_version Specifies the minimum version of
##' the key that can be used to encrypt plaintext, sign payloads,
##' or generate HMACs, as an integer (default is `0`). Must be 0
##' (which will use the latest version) or a value greater or
##' equal to `min_decryption_version`.
##'
##' @param deletion_allowed Specifies if the key is allowed to be
##' deleted, as a logical (default is `FALSE`).
##'
##' @param exportable Enables keys to be exportable. This allows
##' for all the valid keys in the key ring to be exported. Once
##' set, this cannot be disabled.
##'
##' @param allow_plaintext_backup If set, enables taking backup of
##' named key in the plaintext format. Once set, this cannot be
##' disabled.
key_update = function(name, min_decryption_version = NULL,
min_encryption_version = NULL,
deletion_allowed = NULL,
exportable = NULL,
allow_plaintext_backup = NULL) {
path <- sprintf("/%s/keys/%s/config", private$mount,
assert_scalar_character(name))
body <- list(
min_decryption_version = min_decryption_version %&&%
assert_scalar_integer(min_decryption_version),
min_encryption_version = min_encryption_version %&&%
assert_scalar_integer(min_encryption_version),
deletion_allowed = deletion_allowed %&&%
assert_scalar_logical(deletion_allowed),
exportable = exportable %&&% assert_scalar_integer(exportable),
allow_plaintext_backup = allow_plaintext_backup %&&%
assert_scalar_integer(allow_plaintext_backup))
private$api_client$POST(path, body = drop_null(body))
invisible(NULL)
},
##' @description Rotates the version of the named key. After
##' rotation, new plaintext requests will be encrypted with the
##' new version of the key. To upgrade ciphertext to be encrypted
##' with the latest version of the key, use the rewrap
##' endpoint. This is only supported with keys that support
##' encryption and decryption operations.
##'
##' @param name The name of the key to rotate
key_rotate = function(name) {
path <- sprintf("/%s/keys/%s/rotate", private$mount,
assert_scalar_character(name))
private$api_client$POST(path)
invisible(NULL)
},
##' @description Export the named key. If version is specified, the
##' specific version will be returned. If latest is provided as
##' the version, the current key will be provided. Depending on
##' the type of key, different information may be returned. The
##' key must be exportable to support this operation and the
##' version must still be valid.
##'
##' For more details see
##' https://github.com/hashicorp/vault/issues/2667 where
##' HashiCorp says "Part of the "contract" of transit is that the
##' key is never exposed outside of Vault. We added the ability
##' to export keys because some enterprises have key escrow
##' requirements, but it leaves a permanent mark in the key
##' metadata. I suppose we could at some point allow importing a
##' key and also leave such a mark."
##'
##' @param name Name of the key to export
##'
##' @param key_type Specifies the type of the key to export. Valid
##' values are `encryption-key`, `signing-key` and `hmac-key`.
##'
##' @param version Specifies the version of the key to read. If
##' omitted, all versions of the key will be returned. If the
##' version is set to latest, the current key will be returned
key_export = function(name, key_type, version = NULL) {
assert_scalar_character(name)
assert_scalar_character(key_type)
if (is.null(version)) {
path <- sprintf("/%s/export/%s/%s",
private$mount, key_type, name)
} else {
assert_scalar_integer(version)
path <- sprintf("/%s/export/%s/%s/%d",
private$mount, key_type, name, version)
}
keys <- private$api_client$GET(path)$data$keys
if (is.null(version)) keys[[1]] else keys
},
##' @description This endpoint encrypts the provided plaintext
##' using the named key.
##'
##' @param key_name Specifies the name of the encryption key to
##' encrypt against.
##'
##' @param data Data to encrypt, as a raw vector
##'
##' @param key_version Key version to use, as an integer. If not
##' set, uses the latest version. Must be greater than or equal
##' to the key's `min_encryption_version`, if set.
##'
##' @param context Specifies the context for key derivation. This
##' is required if key derivation is enabled for this key. Must
##' be a raw vector.
data_encrypt = function(key_name, data, key_version = NULL,
context = NULL) {
## nonce = not accepted
## batch_input = different interface
## type, convergent_encryption = not clear at this point
body <- list(
plaintext = raw_data_input(data),
context = context %&&% raw_data_input(context),
key_version = key_version %&&% assert_scalar_integer(key_version))
path <- sprintf("/%s/encrypt/%s",
private$mount, assert_scalar_character(key_name))
data <- private$api_client$POST(path, body = drop_null(body))$data
data$ciphertext
},
##' @description Decrypts the provided ciphertext using the named
##' key.
##'
##' @param key_name Specifies the name of the encryption key to
##' decrypt with.
##'
##' @param data The data to decrypt. Must be a string, as returned
##' by `$data_encrypt`.
##'
##' @param context Specifies the context for key derivation. This
##' is required if key derivation is enabled for this key. Must
##' be a raw vector.
data_decrypt = function(key_name, data, context = NULL) {
## nonce = not accepted
## batch_input = different interface
body <- list(
ciphertext = assert_scalar_character(data),
context = context %&&% raw_data_input(context))
path <- sprintf("/%s/decrypt/%s",
private$mount, assert_scalar_character(key_name))
data <- private$api_client$POST(path, body = drop_null(body))$data
decode64(data$plaintext)
},
##' @description Rewraps the provided ciphertext using the latest
##' version of the named key. Because this never returns
##' plaintext, it is possible to delegate this functionality to
##' untrusted users or scripts.
##'
##' @param key_name Specifies the name of the encryption key to
##' re-encrypt against
##'
##' @param data The data to decrypt. Must be a string, as returned
##' by `$data_encrypt`.
##'
##' @param context Specifies the context for key derivation. This
##' is required if key derivation is enabled for this key. Must
##' be a raw vector.
##'
##' @param key_version Specifies the version of the key to use for
##' the operation. If not set, uses the latest version. Must be
##' greater than or equal to the key's `min_encryption_version`,
##' if set.
data_rewrap = function(key_name, data, key_version = NULL,
context = NULL) {
## nonce = not accepted
## batch_input = different interface
body <- list(
context = context %&&% raw_data_input(context),
ciphertext = assert_scalar_character(data))
path <- sprintf("/%s/rewrap/%s",
private$mount, assert_scalar_character(key_name))
data <- private$api_client$POST(path, body = drop_null(body))$data
data$ciphertext
},
##' @description This endpoint generates a new high-entropy key and
##' the value encrypted with the named key. Optionally return the
##' plaintext of the key as well.
##'
##' @param name Specifies the name of the encryption key to use to
##' encrypt the datakey
##'
##' @param plaintext Logical, indicating if the plaintext key
##' should be returned.
##'
##' @param bits Specifies the number of bits in the desired
##' key. Can be 128, 256, or 512.
##'
##' @param context Specifies the context for key derivation. This
##' is required if key derivation is enabled for this key. Must
##' be a raw vector.
datakey_create = function(name, plaintext = FALSE, bits = NULL,
context = NULL) {
assert_scalar_character(name)
assert_scalar_logical(plaintext)
datakey_type <- if (plaintext) "plaintext" else "wrapped"
path <- sprintf("%s/datakey/%s/%s", private$mount, datakey_type, name)
body <- list(bits = bits %&&% assert_scalar_integer(bits),
context = context %&&% raw_data_input(context))
private$api_client$POST(path, body = drop_null(body))$data
},
##' @description Generates high-quality random bytes of the
##' specified length. This is totally independent of R's random
##' number stream and provides random numbers suitable for
##' cryptographic purposes.
##'
##' @param bytes Number of bytes to generate (as an integer)
##'
##' @param format The output format to produce; must be one of
##' `hex` (a single hex string such as `d1189e2f83b72ab6`),
##' `base64` (a single base64 encoded string such as
##' `8TDJekY0mYs=`) or `raw` (a raw vector of length `bytes`).
random = function(bytes = 32, format = "hex") {
bytes <- assert_scalar_integer(bytes)
body <- list(bytes = assert_scalar_integer(bytes),
format = assert_scalar_character(format))
if (format == "raw") {
body$format <- "base64"
}
path <- sprintf("/%s/random", private$mount)
res <- private$api_client$POST(path, body = body)
bytes <- res$data$random_bytes
if (format == "raw") {
decode64(bytes)
} else {
bytes
}
},
##' @description Generates a cryptographic hash of given data using
##' the specified algorithm.
##'
##' @param data A raw vector of data to hash. To generate a raw
##' vector from an R object, one option is to use `unserialize(x,
##' NULL)` but be aware that version information may be included.
##' Alternatively, for a string, one might use `charToRaw`.
##'
##' @param algorithm A string indicating the hash algorithm to use.
##' The exact set of supported algorithms may depend by vault
##' server version, but as of version 1.0.0 vault supports
##' `sha2-224`, `sha2-256`, `sha2-384` and `sha2-512`. The
##' default is `sha2-256`.
##'
##' @param format The format of the output - must be one of `hex`
##' or `base64`.
hash = function(data, algorithm = NULL, format = "hex") {
path <- sprintf("/%s/hash", private$mount)
body <- list(
input = raw_data_input(data),
algorithm = algorithm %&&% assert_scalar_character(algorithm),
format = assert_scalar_character(format))
private$api_client$POST(path, body = drop_null(body))$data$sum
},
##' @description This endpoint returns the digest of given data
##' using the specified hash algorithm and the named key. The key
##' can be of any type supported by the `transit` engine; the raw
##' key will be marshalled into bytes to be used for the HMAC
##' function. If the key is of a type that supports rotation, the
##' latest (current) version will be used.
##'
##' @param name Specifies the name of the encryption key to
##' generate hmac against
##'
##' @param data The input data, as a raw vector
##'
##' @param key_version Specifies the version of the key to use for
##' the operation. If not set, uses the latest version. Must be
##' greater than or equal to the key's `min_encryption_version`,
##' if set.
##'
##' @param algorithm Specifies the hash algorithm to
##' use. Currently-supported algorithms are `sha2-224`,
##' `sha2-256`, `sha2-384` and `sha2-512`. The default is
##' `sha2-256`.
hmac = function(name, data, key_version = NULL, algorithm = NULL) {
path <- sprintf("/%s/hmac/%s",
private$mount, assert_scalar_character(name))
body <- list(
key_version = key_version %&&% assert_scalar_integer(key_version),
algorithm = algorithm %&&% assert_scalar_character(algorithm),
input = raw_data_input(data))
private$api_client$POST(path, body = drop_null(body))$data$hmac
},
##' @description Returns the cryptographic signature of the given
##' data using the named key and the specified hash
##' algorithm. The key must be of a type that supports signing.
##'
##' @param name Specifies the name of the encryption key to use for
##' signing
##'
##' @param data The input data, as a raw vector
##'
##' @param hash_algorithm Specifies the hash algorithm to
##' use. Currently-supported algorithms are `sha2-224`,
##' `sha2-256`, `sha2-384` and `sha2-512`. The default is
##' `sha2-256`.
##'
##' @param prehashed Set to true when the input is already
##' hashed. If the key type is `rsa-2048` or `rsa-4096`, then the
##' algorithm used to hash the input should be indicated by the
##' `hash_algorithm` parameter.
##'
##' @param signature_algorithm When using a RSA key, specifies the
##' RSA signature algorithm to use for signing. Supported
##' signature types are `pss` (the default) and `pkcs1v15`.
##'
##' @param key_version Specifies the version of the key to use for
##' signing. If not set, uses the latest version. Must be greater
##' than or equal to the key's `min_encryption_version`, if set.
##'
##' @param context Specifies the context for key derivation. This
##' is required if key derivation is enabled for this key. Must
##' be a raw vector.
sign = function(name, data, key_version = NULL, hash_algorithm = NULL,
prehashed = FALSE, signature_algorithm = NULL,
context = NULL) {
path <- sprintf("/%s/sign/%s",
private$mount, assert_scalar_character(name))
body <- list(
key_version = key_version %&&% assert_scalar_integer(key_version),
hash_algorithm =
hash_algorithm %&&% assert_scalar_integer(hash_algorithm),
signature_algorithm =
signature_algorithm %&&% assert_scalar_integer(signature_algorithm),
input = raw_data_input(data),
context = context %&&% raw_data_input(context),
prehashed = assert_scalar_logical(prehashed))
private$api_client$POST(path, body = drop_null(body))$data$signature
},
##' @description Determine whether the provided signature is valid
##' for the given data.
##'
##' @param name Name of the key
##'
##' @param data Data to verify, as a raw vector
##'
##' @param signature The signed data, as a string.
##'
##' @param hash_algorithm Specifies the hash algorithm to use. This
##' can also be specified as part of the URL (see `$sign` and
##' `$hmac` for details).
##'
##' @param signature_algorithm When using a RSA key, specifies the
##' RSA signature algorithm to use for signature verification
##'
##' @param context Specifies the context for key derivation. This
##' is required if key derivation is enabled for this key. Must
##' be a raw vector.
##'
##' @param prehashed Set to `TRUE` when the input is already hashed
verify_signature = function(name, data, signature, hash_algorithm = NULL,
signature_algorithm = NULL, context = NULL,
prehashed = FALSE) {
private$verify(name, data, signature, "signature",
hash_algorithm, signature_algorithm,
context, prehashed)
},
##' @description Determine whether the provided signature is valid
##' for the given data.
##'
##' @param name Name of the key
##'
##' @param data Data to verify, as a raw vector
##'
##' @param signature The signed data, as a string.
##'
##' @param hash_algorithm Specifies the hash algorithm to use. This
##' can also be specified as part of the URL (see `$sign` and
##' `$hmac` for details).
##'
##' @param signature_algorithm When using a RSA key, specifies the
##' RSA signature algorithm to use for signature verification
##'
##' @param context Specifies the context for key derivation. This
##' is required if key derivation is enabled for this key. Must
##' be a raw vector.
##'
##' @param prehashed Set to `TRUE` when the input is already hashed
verify_hmac = function(name, data, signature, hash_algorithm = NULL,
signature_algorithm = NULL, context = NULL,
prehashed = FALSE) {
private$verify(name, data, signature, "hmac",
hash_algorithm, signature_algorithm,
context, prehashed)
},
##' @description Returns a plaintext backup of a named key. The
##' backup contains all the configuration data and keys of all
##' the versions along with the HMAC key. The response from this
##' endpoint can be used with `$key_restore` to restore the key.
##'
##' @param name Name of the key to backup
key_backup = function(name) {
path <- sprintf("/%s/backup/%s",
private$mount, assert_scalar_character(name))
private$api_client$GET(path)$data$backup
},
##' @description Restores the backup as a named key. This will
##' restore the key configurations and all the versions of the
##' named key along with HMAC keys. The input to this method
##' should be the output of `$key_restore` method.
##'
##' @param name Name of the restored key.
##'
##' @param backup Backed up key data to be restored. This should be
##' the output from the `$key_backup` endpoint.
##'
##' @param force Logical. If `TRUE`, then force the restore to
##' proceed even if a key by this name already exists.
key_restore = function(name, backup, force = FALSE) {
path <- sprintf("/%s/restore/%s",
private$mount, assert_scalar_character(name))
body <- list(backup = assert_scalar_character(backup),
force = assert_scalar_logical(force))
private$api_client$POST(path, body = body)
invisible(NULL)
},
##' @description This endpoint trims older key versions setting a
##' minimum version for the keyring. Once trimmed, previous
##' versions of the key cannot be recovered.
##'
##' @param name Key to trim
##'
##' @param min_version The minimum version for the key ring. All
##' versions before this version will be permanently
##' deleted. This value can at most be equal to the lesser of
##' `min_decryption_version` and `min_encryption_version`. This
##' is not allowed to be set when either `min_encryption_version`
##' or `min_decryption_version` is set to zero.
key_trim = function(name, min_version) {
path <- sprintf("/%s/keys/%s/trim",
private$mount, assert_scalar_character(name))
assert_vault_version("0.11.4", private$api_client, path,
"transit key trim")
## TODO: this differs from the spec here:
## https://developer.hashicorp.com/vault/api-docs/secret/transit#trim-key
## (claims min_version)
body <- list(min_available_version = assert_scalar_integer(min_version))
private$api_client$POST(path, body = body)
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_client_transit.R
|
##' Use vault to resolve secrets. This is a convenience function that
##' wraps a pattern that we have used in a few applications of vault.
##' The idea is to allow replacement of data in configuration with
##' special strings that indicate that the string refers to a vault
##' secret. This function resolves those secrets.
##'
##' For each element of the data, if a string matches the form:
##'
##' ```
##' VAULT:<path to secret>:<field>
##' ```
##'
##' then it will be treated as a vault secret and resolved. The
##' `<path to get>` will be something like
##' `/secret/path/password` and the `<field>` the name of a
##' field in the key/value data stored at that path. For example,
##' suppose you have the data `list(username = "alice", password =
##' "s3cret!")` stored at `/secret/database/user`, then the
##' string
##'
##' ```
##' VAULT:/secret/database/user:password
##' ```
##'
##' would refer to the value `s3cret!`
##'
##' @title Resolve secrets from R objects
##'
##' @param x List of values, some of which may refer to vault secrets
##' (see Details for pattern). Any values that are not strings or
##' do not match the pattern of a secret are left as-is.
##'
##' @param ... Args to be passed to [vaultr::vault_client] call.
##'
##' @param login Login method to be passed to call to
##' [vaultr::vault_client].
##'
##' @param vault_args As an alternative to using `login` and `...`, a
##' list of (named) arguments can be provided here, equivalent to
##' the full set of arguments that you might pass to
##' [vaultr::vault_client]. If provided, then `login` is ignored
##' and if additional arguments are provided through `...` an error
##' will be thrown.
##'
##' @return List of properties with any vault secrets resolved.
##'
##' @export
##'
##' @examples
##'
##' server <- vaultr::vault_test_server(if_disabled = message)
##'
##' if (!is.null(server)) {
##' client <- server$client()
##' # The example from above:
##' client$write("/secret/database/user",
##' list(username = "alice", password = "s3cret!"))
##'
##' # A list of data that contains a mix of secrets to be resolved
##' # and other data:
##' x <- list(user = "alice",
##' password = "VAULT:/secret/database/user:password",
##' port = 5678)
##'
##' # Explicitly pass in the login details and resolve the secrets:
##' vaultr::vault_resolve_secrets(x, login = "token", token = server$token,
##' addr = server$addr)
##'
##' # Alternatively, if appropriate environment variables are set
##' # then this can be done more easily:
##' if (requireNamespace("withr", quietly = TRUE)) {
##' env <- c(VAULTR_AUTH_METHOD = "token",
##' VAULT_TOKEN = server$token,
##' VAULT_ADDR = server$addr)
##' withr::with_envvar(env, vault_resolve_secrets(x))
##' }
##' }
vault_resolve_secrets <- function(x, ..., login = TRUE, vault_args = NULL) {
re <- "^VAULT:(.+):(.+)"
if (is.list(x)) {
i <- vlapply(x, function(el) is.character(el) && grepl(re, el))
if (any(i)) {
x[i] <- vault_resolve_secrets(vcapply(x[i], identity),
..., login = login,
vault_args = vault_args)
}
} else {
i <- grepl(re, x)
if (any(i)) {
if (is.null(vault_args)) {
vault_args <- list(login = login, ...)
} else {
vault_args$login <- vault_args$login %||% TRUE
if (length(list(...)) > 0L) {
stop("Do not provide both '...' and 'vault_args'")
}
}
vault <- do.call(vault_client, vault_args)
key <- unname(sub(re, "\\1", x[i]))
field <- unname(sub(re, "\\2", x[i]))
x[i] <- unname(Map(vault$read, key, field))
}
}
x
}
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_resolve_secrets.R
|
##' @rdname vault_test_server
vault_server_instance <- R6::R6Class(
"vault_server_instance",
inherit = vault_client_object,
cloneable = FALSE,
private = list(
process = NULL,
finalize = function() {
self$kill()
}
),
public = list(
##' @field port The vault port (read-only).
port = NULL,
##' @field addr The vault address; this is suitable for using with
##' [vaultr::vault_client] (read-only).
addr = NULL,
##' @field token The vault root token, from when the testing vault
##' server was created. If the vault is rekeyed this will no
##' longer be accurate (read-only).
token = NULL,
##' @field keys Key shares from when the vault was initialised
##' (read-only).
keys = NULL,
##' @field cacert Path to the https certificate, if running in
##' https mode (read-only).
cacert = NULL,
##' @description Create a `vault_server_instance` object. Not typically
##' called by users.
##'
##' @param bin Path to the vault binary
##'
##' @param port Port to use
##'
##' @param https Logical, indicating if we should use TLS/https
##'
##' @param init Logical, indicating if we should initialise
##'
##' @param quiet Logical, indicating if startup should be quiet
initialize = function(bin, port, https, init, quiet = FALSE) {
super$initialize("Vault server instance")
assert_scalar_integer(port)
self$port <- port
bin <- normalizePath(bin, mustWork = TRUE)
if (https) {
assert_scalar_logical(init)
dat <- vault_server_start_https(bin, self$port, init, quiet)
} else {
dat <- vault_server_start_dev(bin, self$port, quiet)
}
private$process <- dat$process
self$addr <- dat$addr
self$token <- dat$token
self$cacert <- dat$cacert
self$keys <- dat$keys
for (v in c("addr", "port", "token", "keys", "cacert")) {
lockBinding(v, self)
}
},
##' @description Return the server version, as a [numeric_version]
##' object.
version = function() {
self$client(FALSE)$api()$server_version()
},
##' @description Create a new client that can use this server. The
##' client will be a [vaultr::vault_client] object.
##'
##' @param login Logical, indicating if the client should login to
##' the server (default is `TRUE`).
##'
##' @param quiet Logical, indicating if informational messages
##' should be suppressed. Default is `TRUE`, in contrast with
##' most other methods.
client = function(login = TRUE, quiet = TRUE) {
vault_client(if (login) "token" else FALSE, token = self$token,
quiet = quiet, addr = self$addr, tls_config = self$cacert,
use_cache = FALSE)
},
##' @description Return a named character vector of environment
##' variables that can be used to communicate with this vault
##' server (`VAULT_ADDR`, `VAULT_TOKEN`, etc).
env = function() {
c(VAULT_ADDR = self$addr,
VAULT_TOKEN = self$token %||% NA_character_,
VAULT_CACERT = self$cacert %||% NA_character_,
VAULTR_AUTH_METHOD = "token")
},
##' @description Export the variables returned by the `$env()`
##' method to the environment. This makes them available to
##' child processes.
export = function() {
env <- self$env()
i <- is.na(env)
do.call("Sys.setenv", as.list(env[!i]))
if (any(i)) {
Sys.unsetenv(names(env[i]))
}
},
##' @description Clear any session-cached token for this server.
##' This is intended for testing new authentication backends.
clear_cached_token = function() {
vault_env$cache$delete(self)
},
##' @description Kill the server.
kill = function() {
if (!is.null(private$process)) {
private$process$kill()
private$process <- NULL
}
}
))
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vault_server_instance.R
|
##' Vault client for secrets and sensitive data; this package provides
##' wrappers for HashiCorp's [vault server](https://vaultproject.io).
##' The package wraps most of the high-level API, and includes support
##' for authentication via a number of backends (tokens, username and
##' password, github, and "AppRole"), as well as a number of secrets
##' engines (two key-value stores, vault's cubbyhole and the transit
##' backend for encryption-as-a-service).
##'
##' To get started, you might want to start with the "vaultr"
##' vignette, available from the package with `vignette("vaultr")`.
##'
##' The basic design of the package is that it has very few
##' entrypoints - for most uses one will interact almost entirely with
##' the [vaultr::vault_client] function. That function returns an
##' R6 object with several methods (functions) but also several
##' objects that themselves contain more methods and objects, creating
##' a nested tree of functionality.
##'
##' From any object, online help is available via the help method, for
##' example
##'
##' ```
##' client <- vaultr::vault_client()
##' client$secrets$transit$help()
##' ```
##'
##' For testing packages that rely on vault, there is support for
##' creating temporary vault servers; see `vaultr::vault_test_server`
##' and the "packages" vignette.
##'
##' @title Vault Client for Secrets and Sensitive Data
"_PACKAGE"
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/vaultr.R
|
vault_env <- new.env(parent = new.env())
vault_env$cache <- token_cache$new()
|
/scratch/gouwar.j/cran-all/cranData/vaultr/R/zzz.R
|
---
title: "Using vaultr in packages"
author: "Rich FitzJohn"
date: "2023-11-09"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using vaultr in packages}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
`vaultr` includes some machinery for using `vault` and `vaultr`
within packages, and within tests in particular. They are designed
to work well with
[`testthat`](https://cran.r-project.org/package=testthat) but
should be easily adapted to work with any other testing framework.
In order to use this, you must set some environment variables:
* `VAULTR_TEST_SERVER_BIN_PATH` must be set to a directory where
the `vault` binary can be found, the path to the vault executable,
or to the string `auto` to find vault on the `PATH`
* `VAULTR_TEST_SERVER_PORT` can be set to the port where we start
creating vault servers (by default this is 18200 but any high
port number can be selected - we'll create servers *starting* at
this port number and incrementing - see below for details)
To create a vault server, run:
```r
srv <- vaultr::vault_test_server()
```
```
## ...waiting for Vault to start
```
As soon as `srv` goes out of scope and is garbage collected, the
vault server will be stopped. So keep `srv` within the scope of
your tests.
This object contains
* `addr`: which is vault's address
* `token`: a root token for this vault
* `keys`: a vector of unseal keys
By default the `vault` server is stared in ["Dev" server
mode](https://www.vaultproject.io/docs/concepts/dev-server.html) in
which we run with http (not https), a single unseal key and
in-memory storage. **It is not suited for any production use**.
You can create clients using `vaultr::vault_client()` and passing
in appropriate parameters, but it may be more convenient to use
`srv$client()`:
```r
vault <- srv$client()
vault
```
```
## <vault: client>
## Command groups:
## audit: Interact with vault's audit devices
## auth: administer vault's authentication methods
## operator: Administration commands for vault operators
## policy: Interact with policies
## secrets: Interact with secret engines
## token: Interact and configure vault's token support
## tools: General tools provided by vault
## Commands:
## api()
## delete(path)
## help()
## list(path, full_names = FALSE)
## login(..., method = "token", mount = NULL, renew = FALSE,
## quiet = FALSE, token_only = FALSE, use_cache = TRUE)
## read(path, field = NULL, metadata = FALSE)
## status()
## unwrap(token)
## wrap_lookup(token)
## write(path, data)
```
```r
vault$list("secret")
```
```
## character(0)
```
By default the client is logged in, but you can pass `login =
FALSE` to create a client that needs to log in:
```r
vault <- srv$client(login = FALSE)
```
```r
vault$list("secret")
```
```
## Error: Have not authenticated against vault
```
```r
vault$login(token = srv$token)
```
```
## Verifying token
```
```r
vault$list("secret")
```
```
## character(0)
```
You can use `$export` to export appropriate environment variables
to connect to your vault:
```r
srv$export()
Sys.getenv("VAULT_ADDR")
```
```
## [1] "http://127.0.0.1:18200"
```
```r
Sys.getenv("VAULT_TOKEN")
```
```
## [1] "870e5c90-c908-bb4f-331e-c0cba32a457e"
```
## Handling lack of vault gracefully
The `vaultr::vault_test_server` function takes an argument
`if_disabled` which is a callback function that will be called on
failure to start a vault server. This could be for reasons such as:
* the user has not opted in by setting `VAULTR_TEST_SERVER_BIN_PATH`
* the binary is not in place
* a port could not be opened
By default this calls `testthat::skip`, which interactively will
appear to cause an error but if called within a `test_that` block
in a test will gracefully skip a test
```r
Sys.setenv("VAULTR_TEST_SERVER_BIN_PATH" = NA_character_)
```
```r
srv <- vaultr::vault_test_server()
## Error: vault is not enabled
```
Alternatively, provide your own handler:
```r
srv <- vaultr::vault_test_server(if_disabled = message)
```
```
## vault is not enabled
```
```r
srv
```
```
## NULL
```
With that approach, you might wrap vault-requiring tests with
```r
if (!is.null(srv)) {
# ... vault requiring code here ...
}
```
All together (and assuming `testthat`), use of vault within tests
might look like this example from the `vaultr` tests:
```r
test_that("list", {
srv <- vault_test_server()
cl <- srv$client()
cl$write("secret/a", list(key = 1))
cl$write("secret/b/c", list(key = 2))
cl$write("secret/b/d/e", list(key = 2))
expect_setequal(cl$list("secret"), c("a", "b/"))
expect_setequal(cl$list("secret", TRUE), c("secret/a", "secret/b/"))
expect_setequal(cl$list("secret/b"), c("c", "d/"))
expect_setequal(cl$list("secret/b", TRUE), c("secret/b/c", "secret/b/d/"))
})
```
If you use one vault per test, as here, there's no need to clean up
- we can assume that the vault is empty at the start of the test
block and not worry about cleanup at the end. If vault is not
enabled this test will be skipped over gracefully.
## Installing vault
To develop your package, you will need vault installed; please see [the official vault docs](https://developer.hashicorp.com/vault/docs/install) for this.
If you use github actions, you can follow the same approach as `vaultr` itself; add the environment variables `VAULTR_TEST_SERVER_BIN_PATH` and `VAULTR_TEST_SERVER_PORT`:
```yaml
env:
...
VAULTR_TEST_SERVER_BIN_PATH: auto
VAULTR_TEST_SERVER_PORT: 18200
```
then use the [`eLco/setup-vault`](https://github.com/marketplace/actions/setup-vault-cli) action to install a suitable vault binary:
```yaml
- uses: eLco/setup-vault@v1
```
See [the `vaultr` actions](https://github.com/vimc/vaultr/blob/master/.github/workflows/R-CMD-check.yaml) for full details.
|
/scratch/gouwar.j/cran-all/cranData/vaultr/inst/doc/packages.Rmd
|
---
title: "vaultr"
author: "Rich FitzJohn"
date: "2023-11-09"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{vaultr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Connecting to vault
The first part of the vignette assumes that vault is set up; later
we show how to control login behaviour and configure vault itself.
Access of vault requires several environment variables configured,
in particular:
* `VAULT_ADDR`: the address of vault
* `VAULT_TOKEN`: the token to authenticate to vault with
* `VAULTR_AUTH_METHOD`: the method to use to authenticate with
(login to) vault.
(environment variables starting with `VAULT_` are shared with the
vault cli, variables starting `VAULTR_` are specific to this
package).
in this vignette, these are already configured:
```r
Sys.getenv(c("VAULT_ADDR", "VAULT_TOKEN", "VAULTR_AUTH_METHOD"))
```
```
## VAULT_ADDR VAULT_TOKEN
## "http://127.0.0.1:18200" "1cd28503-0d1d-cb1d-80ce-30d3bfeb2e31"
## VAULTR_AUTH_METHOD
## "token"
```
To access vault, first create a client:
```r
vault <- vaultr::vault_client(login = TRUE, quiet = TRUE)
```
This creates an [`R6`](https://CRAN.R-project.org/package=R6)
object with methods for interacting with vault:
```r
vault
```
```
## <vault: client>
## Command groups:
## audit: Interact with vault's audit devices
## auth: administer vault's authentication methods
## operator: Administration commands for vault operators
## policy: Interact with policies
## secrets: Interact with secret engines
## token: Interact and configure vault's token support
## tools: General tools provided by vault
## Commands:
## api()
## delete(path)
## help()
## list(path, full_names = FALSE)
## login(..., method = "token", mount = NULL, renew = FALSE,
## quiet = FALSE, token_only = FALSE, use_cache = TRUE)
## read(path, field = NULL, metadata = FALSE)
## status()
## unwrap(token)
## wrap_lookup(token)
## write(path, data)
```
Because there are many methods, these are organised
_hierarchically_, similar to the vault cli client. For example
`vault$auth` contains commands for interacting with authentication
backends (and itself contains further command groups):
```r
vault$auth
```
```
## <vault: auth>
## Command groups:
## approle: Interact and configure vault's AppRole support
## github: Interact and configure vault's github support
## ldap: Interact and configure vault's LDAP support
## token: Interact and configure vault's token support
## userpass: Interact and configure vault's userpass support
## Commands:
## backends()
## disable(path)
## enable(type, description = NULL, local = FALSE, path = NULL)
## help()
## list(detailed = FALSE)
```
## Reading, writing, listing and deleting secrets
It is anticipated that the vast majority of `vaultr` usage will be
interacting with vault's key-value stores - this is is done with
the `$read`, `$write`, `$list` and `$delete` methods of the base
vault client object. By default, a vault server will have a
[version-1 key value
store](https://www.vaultproject.io/docs/secrets/kv/kv-v1.html)
mounted at `/secret`.
List secrets with `$list`:
```r
vault$list("secret")
```
```
## [1] "database/"
```
```r
vault$list("secret/database")
```
```
## [1] "admin" "readonly"
```
values that terminate in `/` are "directories".
Read secrets with `$read`:
```r
vault$read("secret/database/readonly")
```
```
## $value
## [1] "passw0rd"
```
secrets are returned as a `list`, because multiple secrets may be
stored at a path. To access a single field, use the `field`
argument:
```r
vault$read("secret/database/readonly", field = "value")
```
```
## [1] "passw0rd"
```
Delete secrets with `$delete`:
```r
vault$delete("secret/database/readonly")
```
After which the data is no longer available:
```r
vault$read("secret/database/readonly")
```
```
## NULL
```
Write new secrets with `$write`:
```r
vault$write("secret/webserver", list(password = "horsestaple"))
```
(be aware that this may well write the secret into your R history
file `.Rhistory` - to be more secure you may want to read these in
from environment variables and use `Sys.getenv()` to read them into
R).
## Alternative login approaches
Using the `token` approach for authentication requires that you
have already authenticated with vault to get a token. It is
usually more convenient to instead use some other method. Vault
itself supports [many authentication
methods](https://www.vaultproject.io/docs/auth/index.html) but
`vaultr` currently supports only GitHub and username/password at
this point.
**This document should not be used as a reference point for
configuring vault in any situation other than testing. Please
refer to the [vault
documentation](https://www.vaultproject.io/docs/auth/index.html)
first.**
If you want to configure vault from R rather than the command line
client, you will find a very close mapping between argument
names. We will here assume that the methods are already configured
by your vault administrator and show how to interact with them.
### Username and password (`userpass`)
Assume vault has been configured to support
[userpass](https://www.vaultproject.io/docs/auth/userpass.html)
authentication and that a user `alice` exists with password
`p4ssw0rd`.
```r
cl <- vaultr::vault_client(login = "userpass", username = "alice",
password = "p4ssw0rd")
```
```
## ok, duration: 2764800 s (~32d)
```
```r
cl$read("secret/webserver")
```
```
## $password
## [1] "horsestaple"
```
This is obviously insecure! `vaultr` can use
[`getPass`](https://cran.r-project.org/package=getPass) to securely
prompt for a password:
```r
cl <- vaultr::vault_client(login = "userpass", username = "alice")
## Password for 'alice': ********
## ok, duration: 2764800 s (~32d)
```
### GitHub (`github`)
Assuming that vault has been configured to support
[GitHub](https://developer.hashicorp.com/vault/docs/auth/github), and
that the environment variable `VAULT_AUTH_GITHUB_TOKEN` contains a
personal access token for a team that has been configured to have
vault access, then you can log in with github:
```r
cl <- vaultr::vault_client(login = "github")
```
See `?vault_client_auth_github` for details.
### LDAP (`ldap`)
If your organisation uses LDAP and has configured vault to enable that at the server level, you can login using that by passing login = "ldap" along with your username:
```r
cl <- vaultr::vault_client(login = "ldap", username = "alice")
## Password for 'alice': ********
## ok, duration: 2764800 s (~32d)
```
This will authenticate with the LDAP server, and generate an appropriate token. See `?vault_client_auth_ldap` for details.
|
/scratch/gouwar.j/cran-all/cranData/vaultr/inst/doc/vaultr.Rmd
|
---
title: "Using vaultr in packages"
author: "Rich FitzJohn"
date: "2023-11-09"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using vaultr in packages}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
`vaultr` includes some machinery for using `vault` and `vaultr`
within packages, and within tests in particular. They are designed
to work well with
[`testthat`](https://cran.r-project.org/package=testthat) but
should be easily adapted to work with any other testing framework.
In order to use this, you must set some environment variables:
* `VAULTR_TEST_SERVER_BIN_PATH` must be set to a directory where
the `vault` binary can be found, the path to the vault executable,
or to the string `auto` to find vault on the `PATH`
* `VAULTR_TEST_SERVER_PORT` can be set to the port where we start
creating vault servers (by default this is 18200 but any high
port number can be selected - we'll create servers *starting* at
this port number and incrementing - see below for details)
To create a vault server, run:
```r
srv <- vaultr::vault_test_server()
```
```
## ...waiting for Vault to start
```
As soon as `srv` goes out of scope and is garbage collected, the
vault server will be stopped. So keep `srv` within the scope of
your tests.
This object contains
* `addr`: which is vault's address
* `token`: a root token for this vault
* `keys`: a vector of unseal keys
By default the `vault` server is stared in ["Dev" server
mode](https://www.vaultproject.io/docs/concepts/dev-server.html) in
which we run with http (not https), a single unseal key and
in-memory storage. **It is not suited for any production use**.
You can create clients using `vaultr::vault_client()` and passing
in appropriate parameters, but it may be more convenient to use
`srv$client()`:
```r
vault <- srv$client()
vault
```
```
## <vault: client>
## Command groups:
## audit: Interact with vault's audit devices
## auth: administer vault's authentication methods
## operator: Administration commands for vault operators
## policy: Interact with policies
## secrets: Interact with secret engines
## token: Interact and configure vault's token support
## tools: General tools provided by vault
## Commands:
## api()
## delete(path)
## help()
## list(path, full_names = FALSE)
## login(..., method = "token", mount = NULL, renew = FALSE,
## quiet = FALSE, token_only = FALSE, use_cache = TRUE)
## read(path, field = NULL, metadata = FALSE)
## status()
## unwrap(token)
## wrap_lookup(token)
## write(path, data)
```
```r
vault$list("secret")
```
```
## character(0)
```
By default the client is logged in, but you can pass `login =
FALSE` to create a client that needs to log in:
```r
vault <- srv$client(login = FALSE)
```
```r
vault$list("secret")
```
```
## Error: Have not authenticated against vault
```
```r
vault$login(token = srv$token)
```
```
## Verifying token
```
```r
vault$list("secret")
```
```
## character(0)
```
You can use `$export` to export appropriate environment variables
to connect to your vault:
```r
srv$export()
Sys.getenv("VAULT_ADDR")
```
```
## [1] "http://127.0.0.1:18200"
```
```r
Sys.getenv("VAULT_TOKEN")
```
```
## [1] "870e5c90-c908-bb4f-331e-c0cba32a457e"
```
## Handling lack of vault gracefully
The `vaultr::vault_test_server` function takes an argument
`if_disabled` which is a callback function that will be called on
failure to start a vault server. This could be for reasons such as:
* the user has not opted in by setting `VAULTR_TEST_SERVER_BIN_PATH`
* the binary is not in place
* a port could not be opened
By default this calls `testthat::skip`, which interactively will
appear to cause an error but if called within a `test_that` block
in a test will gracefully skip a test
```r
Sys.setenv("VAULTR_TEST_SERVER_BIN_PATH" = NA_character_)
```
```r
srv <- vaultr::vault_test_server()
## Error: vault is not enabled
```
Alternatively, provide your own handler:
```r
srv <- vaultr::vault_test_server(if_disabled = message)
```
```
## vault is not enabled
```
```r
srv
```
```
## NULL
```
With that approach, you might wrap vault-requiring tests with
```r
if (!is.null(srv)) {
# ... vault requiring code here ...
}
```
All together (and assuming `testthat`), use of vault within tests
might look like this example from the `vaultr` tests:
```r
test_that("list", {
srv <- vault_test_server()
cl <- srv$client()
cl$write("secret/a", list(key = 1))
cl$write("secret/b/c", list(key = 2))
cl$write("secret/b/d/e", list(key = 2))
expect_setequal(cl$list("secret"), c("a", "b/"))
expect_setequal(cl$list("secret", TRUE), c("secret/a", "secret/b/"))
expect_setequal(cl$list("secret/b"), c("c", "d/"))
expect_setequal(cl$list("secret/b", TRUE), c("secret/b/c", "secret/b/d/"))
})
```
If you use one vault per test, as here, there's no need to clean up
- we can assume that the vault is empty at the start of the test
block and not worry about cleanup at the end. If vault is not
enabled this test will be skipped over gracefully.
## Installing vault
To develop your package, you will need vault installed; please see [the official vault docs](https://developer.hashicorp.com/vault/docs/install) for this.
If you use github actions, you can follow the same approach as `vaultr` itself; add the environment variables `VAULTR_TEST_SERVER_BIN_PATH` and `VAULTR_TEST_SERVER_PORT`:
```yaml
env:
...
VAULTR_TEST_SERVER_BIN_PATH: auto
VAULTR_TEST_SERVER_PORT: 18200
```
then use the [`eLco/setup-vault`](https://github.com/marketplace/actions/setup-vault-cli) action to install a suitable vault binary:
```yaml
- uses: eLco/setup-vault@v1
```
See [the `vaultr` actions](https://github.com/vimc/vaultr/blob/master/.github/workflows/R-CMD-check.yaml) for full details.
|
/scratch/gouwar.j/cran-all/cranData/vaultr/vignettes/packages.Rmd
|
---
title: "vaultr"
author: "Rich FitzJohn"
date: "2023-11-09"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{vaultr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Connecting to vault
The first part of the vignette assumes that vault is set up; later
we show how to control login behaviour and configure vault itself.
Access of vault requires several environment variables configured,
in particular:
* `VAULT_ADDR`: the address of vault
* `VAULT_TOKEN`: the token to authenticate to vault with
* `VAULTR_AUTH_METHOD`: the method to use to authenticate with
(login to) vault.
(environment variables starting with `VAULT_` are shared with the
vault cli, variables starting `VAULTR_` are specific to this
package).
in this vignette, these are already configured:
```r
Sys.getenv(c("VAULT_ADDR", "VAULT_TOKEN", "VAULTR_AUTH_METHOD"))
```
```
## VAULT_ADDR VAULT_TOKEN
## "http://127.0.0.1:18200" "1cd28503-0d1d-cb1d-80ce-30d3bfeb2e31"
## VAULTR_AUTH_METHOD
## "token"
```
To access vault, first create a client:
```r
vault <- vaultr::vault_client(login = TRUE, quiet = TRUE)
```
This creates an [`R6`](https://CRAN.R-project.org/package=R6)
object with methods for interacting with vault:
```r
vault
```
```
## <vault: client>
## Command groups:
## audit: Interact with vault's audit devices
## auth: administer vault's authentication methods
## operator: Administration commands for vault operators
## policy: Interact with policies
## secrets: Interact with secret engines
## token: Interact and configure vault's token support
## tools: General tools provided by vault
## Commands:
## api()
## delete(path)
## help()
## list(path, full_names = FALSE)
## login(..., method = "token", mount = NULL, renew = FALSE,
## quiet = FALSE, token_only = FALSE, use_cache = TRUE)
## read(path, field = NULL, metadata = FALSE)
## status()
## unwrap(token)
## wrap_lookup(token)
## write(path, data)
```
Because there are many methods, these are organised
_hierarchically_, similar to the vault cli client. For example
`vault$auth` contains commands for interacting with authentication
backends (and itself contains further command groups):
```r
vault$auth
```
```
## <vault: auth>
## Command groups:
## approle: Interact and configure vault's AppRole support
## github: Interact and configure vault's github support
## ldap: Interact and configure vault's LDAP support
## token: Interact and configure vault's token support
## userpass: Interact and configure vault's userpass support
## Commands:
## backends()
## disable(path)
## enable(type, description = NULL, local = FALSE, path = NULL)
## help()
## list(detailed = FALSE)
```
## Reading, writing, listing and deleting secrets
It is anticipated that the vast majority of `vaultr` usage will be
interacting with vault's key-value stores - this is is done with
the `$read`, `$write`, `$list` and `$delete` methods of the base
vault client object. By default, a vault server will have a
[version-1 key value
store](https://www.vaultproject.io/docs/secrets/kv/kv-v1.html)
mounted at `/secret`.
List secrets with `$list`:
```r
vault$list("secret")
```
```
## [1] "database/"
```
```r
vault$list("secret/database")
```
```
## [1] "admin" "readonly"
```
values that terminate in `/` are "directories".
Read secrets with `$read`:
```r
vault$read("secret/database/readonly")
```
```
## $value
## [1] "passw0rd"
```
secrets are returned as a `list`, because multiple secrets may be
stored at a path. To access a single field, use the `field`
argument:
```r
vault$read("secret/database/readonly", field = "value")
```
```
## [1] "passw0rd"
```
Delete secrets with `$delete`:
```r
vault$delete("secret/database/readonly")
```
After which the data is no longer available:
```r
vault$read("secret/database/readonly")
```
```
## NULL
```
Write new secrets with `$write`:
```r
vault$write("secret/webserver", list(password = "horsestaple"))
```
(be aware that this may well write the secret into your R history
file `.Rhistory` - to be more secure you may want to read these in
from environment variables and use `Sys.getenv()` to read them into
R).
## Alternative login approaches
Using the `token` approach for authentication requires that you
have already authenticated with vault to get a token. It is
usually more convenient to instead use some other method. Vault
itself supports [many authentication
methods](https://www.vaultproject.io/docs/auth/index.html) but
`vaultr` currently supports only GitHub and username/password at
this point.
**This document should not be used as a reference point for
configuring vault in any situation other than testing. Please
refer to the [vault
documentation](https://www.vaultproject.io/docs/auth/index.html)
first.**
If you want to configure vault from R rather than the command line
client, you will find a very close mapping between argument
names. We will here assume that the methods are already configured
by your vault administrator and show how to interact with them.
### Username and password (`userpass`)
Assume vault has been configured to support
[userpass](https://www.vaultproject.io/docs/auth/userpass.html)
authentication and that a user `alice` exists with password
`p4ssw0rd`.
```r
cl <- vaultr::vault_client(login = "userpass", username = "alice",
password = "p4ssw0rd")
```
```
## ok, duration: 2764800 s (~32d)
```
```r
cl$read("secret/webserver")
```
```
## $password
## [1] "horsestaple"
```
This is obviously insecure! `vaultr` can use
[`getPass`](https://cran.r-project.org/package=getPass) to securely
prompt for a password:
```r
cl <- vaultr::vault_client(login = "userpass", username = "alice")
## Password for 'alice': ********
## ok, duration: 2764800 s (~32d)
```
### GitHub (`github`)
Assuming that vault has been configured to support
[GitHub](https://developer.hashicorp.com/vault/docs/auth/github), and
that the environment variable `VAULT_AUTH_GITHUB_TOKEN` contains a
personal access token for a team that has been configured to have
vault access, then you can log in with github:
```r
cl <- vaultr::vault_client(login = "github")
```
See `?vault_client_auth_github` for details.
### LDAP (`ldap`)
If your organisation uses LDAP and has configured vault to enable that at the server level, you can login using that by passing login = "ldap" along with your username:
```r
cl <- vaultr::vault_client(login = "ldap", username = "alice")
## Password for 'alice': ********
## ok, duration: 2764800 s (~32d)
```
This will authenticate with the LDAP server, and generate an appropriate token. See `?vault_client_auth_ldap` for details.
|
/scratch/gouwar.j/cran-all/cranData/vaultr/vignettes/vaultr.Rmd
|
#' Example of a hypothetical vaccine clinical trial data set
#'
#' A dataset containing immunogenicity data, and clinical outcome data in the vaccinated and control groups. The dataset is provided in the form of a data frame.
#'
#' @format Data frame:
#' \describe{
#' \item{ID}{identification of subjects}
#' \item{nAb1}{value of neutralizing titer for serotype 1}
#' \item{nAb2}{value of neutralizing titer for serotype 2}
#' \item{group}{binary indicator of a baseline demographic characteristics of interest}
#' \item{vaccine}{binary indicator of treatment arm, with value 1 in vaccinated and 0 in control subjects}
#' \item{type_disease}{serotype of disease}
#' \item{disease_any}{binary indicator of disease caused by any serotype}
#' }
"data_temp"
|
/scratch/gouwar.j/cran-all/cranData/vaxpmx/R/data.R
|
#' vaxpmx
#'
#' pharmacometric modeling in vaccines
#'
#'
#'
#'
#' @name vaxpmx
#' @docType package
#' @author Julie Dudasova
NULL
|
/scratch/gouwar.j/cran-all/cranData/vaxpmx/R/vaxpmx.R
|
#' @title Vaccine efficacy estimation
#'
#' @description Calculates vaccine efficacy and confidence interval as described in Dudasova et al., 2024, BMC Med Res Methodol
#'
#' @param Fit an object of class inheriting from \code{"glm"} representing the fitted model
#' @param Data a data frame containing the variables in the fitted model; data must include a column called "vaccine" with binary indicator of vaccination status
#' @param nboot a numeric value for number of bootstrap samples for confidence interval construction
#'
#' @return a value of vaccine efficacy \code{VE} and lower and upper bound of confidence interval \code{CI}
#'
#' @usage
#' ve(Fit, Data, nboot = 2000)
#'
#' @examples
#' # Load an example dataset
#' data(data_temp)
#'
#' # Fit logistic model relating neutralizing titer to disease status
#' logisticFit <- glm(disease_any ~ nAb1, data = data_temp, family = binomial())
#'
#' # Estimate vaccine efficacy and 95\% confidence interval based on the fitted model
#' ve(logisticFit, data_temp, nboot = 500)
#'
#' @importFrom dplyr %>%
#' @importFrom dplyr filter
#' @importFrom stats predict
#'
#' @export
ve <- function(Fit, Data, nboot = 2000){
vaccine <- NULL
Data.vaccinated <- Data %>% filter(vaccine == 1)
Data.control <- Data %>% filter(vaccine == 0)
if (as.character(Fit$call)[1] == "glm"){
VE <- (1-(sum(predict(Fit, Data.vaccinated, type="response"))/nrow(Data.vaccinated))/
(sum(predict(Fit, Data.control, type="response"))/nrow(Data.control))) * 100
efficacySet <- glmParametricSampling(Fit, nboot, Data.vaccinated, Data.control)
CI <- lapply(EfficacyCI(efficacySet),"*", 100)
} else {
return(NULL)
}
return (list(VE = VE,
CI = list(LB = CI$CILow, UB = CI$CIHigh)))
}
#' @title Accounting for the uncertainty on the fitted \code{"glm"} model and observed data
#'
#' @description \code{glmParametricSampling} is used for vaccine efficacy confidence interval construction.
#' It provides a vector of vaccine efficacy values, with length of \code{nboot}. 95\% confidence interval, defined by 2.5th and 97.5th percentile of this vector,
#' accounts for the uncertainty on the model fit (via parametric resampling of the posterior distribution of the model parameters) and observed data (via bootstrapping).
#'
#' @param Fit an object of class inheriting from \code{"glm"} representing the fitted model
#' @param nboot a numeric value for number of bootstrap samples for confidence interval construction
#' @param Data.vaccinated a data frame for the vaccinated group, containing the variables in the fitted model; data must include a column called "vaccine" with binary indicator of vaccination status
#' @param Data.control a data frame for the control group, containing the variables in the fitted model; data must include a column called "vaccine" with binary indicator of vaccination status
#'
#' @return a vector of vaccine efficacy values \code{VE_set}, with length of \code{nboot}
#'
#' @usage
#' glmParametricSampling(Fit, nboot = 2000, Data.vaccinated, Data.control)
#'
#' @examples
#' # Load required packages
#' library(dplyr)
#'
#' # Load an example dataset
#' data(data_temp)
#' Data.vaccinated <- filter(data_temp, vaccine == 1)
#' Data.control <- filter(data_temp, vaccine == 0)
#'
#' # Fit logistic model relating neutralizing titer to disease status, specific to serotype 2
#' logisticFit <- glm(disease_any ~ nAb1, data = data_temp, family = binomial())
#'
#' # Estimate 95\% confidence interval of vaccine efficacy based on the fitted model
#' efficacySet <- glmParametricSampling(logisticFit, nboot = 500, Data.vaccinated, Data.control)
#' CI <- lapply(EfficacyCI(efficacySet),"*", 100)
#'
#' @importFrom MASS mvrnorm
#' @importFrom stats vcov
#' @importFrom stats predict
#' @importFrom dplyr filter
#' @importFrom dplyr %>%
#' @export
glmParametricSampling <- function (Fit, nboot = 2000, Data.vaccinated = NULL, Data.control = NULL){
d <- data.frame(mvrnorm(n=nboot,
mu = Fit$coefficients,
Sigma = vcov(Fit)))
Fit_util <- Fit
VE_set<- c(0)
for (i in 1:nboot){
k <- ncol(d)
for(j in 1:k){
Fit_util$coefficients[[j]]<-d[i,j]
}
bootData.vaccinated <- Data.vaccinated[sample(seq_len(nrow(Data.vaccinated)), nrow(Data.vaccinated), replace=TRUE), ]
bootData.control <- Data.control[sample(seq_len(nrow(Data.control)), nrow(Data.control), replace=TRUE), ]
VE_set[i] <- 1-(sum(predict(Fit_util, bootData.vaccinated, type="response"))/nrow(bootData.vaccinated))/
(sum(predict(Fit_util, bootData.control, type="response"))/nrow(bootData.control))
}
return(VE_set)
}
#' @title Efficacy summary (mean, median, confidence intervals)
#'
#' @description
#' Function summarizes efficacy statistics (mean, median, confidence intervals) based on the set of estimated efficacy values and chosen condfidence interval.
#'
#' @param efficacySet numeric vector - vector of estimated efficacy values
#' @param ci numeric - required confidence level
#'
#' @return
#' named list - mean, median, CILow, CIHigh
#'
#' @usage
#' EfficacyCI(efficacySet, ci = 0.95)
#'
#' @examples
#' # Load required packages
#' library(dplyr)
#'
#' # Load an example dataset
#' data(data_temp)
#' Data.vaccinated <- filter(data_temp, vaccine == 1)
#' Data.control <- filter(data_temp, vaccine == 0)
#'
#' # Fit logistic model relating neutralizing titer to disease status, specific to serotype 2
#' logisticFit <- glm(disease_any ~ nAb1, data = data_temp, family = binomial())
#'
#' # Estimate 95\% confidence interval of vaccine efficacy based on the fitted model
#' efficacySet <- glmParametricSampling(logisticFit, nboot = 500, Data.vaccinated, Data.control)
#' EfficacyCI(efficacySet)
#'
#' @details
#' Confidence intervals are calculated using quantiles of estimated efficacy values.
#'
#' @importFrom stats median
#' @importFrom stats quantile
#' @export
EfficacyCI <- function(efficacySet, ci = 0.95) {
CILow <- quantile(efficacySet, (1 - ci) / 2, names = F)
CIHigh <- quantile(efficacySet, ci + (1 - ci) / 2, names = F)
return(
list(
mean = mean(efficacySet),
median = median(efficacySet),
CILow = CILow,
CIHigh = CIHigh
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/vaxpmx/R/ve.R
|
set.seed(1)
ID <- seq(1,600)
nAb1 <- rnorm(600, mean = 5, sd = 2)
nAb2 <- rnorm(600, mean = 8, sd = 1)
group <- rbinom(n = 600, size = 1, prob = 0.5)
vaccine <- rbinom(n = 600, size = 1, prob = 0.5)
type_disease <- rbinom(n = 600, size = 2, prob = 0.1)
disease_any <- as.numeric(type_disease>0)
disease_type1 <- as.numeric(type_disease==1)
disease_type2 <- as.numeric(type_disease==2)
data_temp <- data.frame(ID, nAb1, nAb2, group, vaccine, type_disease, disease_any)
# save(data_temp, file = "data/data_temp.rda")
|
/scratch/gouwar.j/cran-all/cranData/vaxpmx/inst/extdata/vaxpmx_mockupData.R
|
#' Varying-Coefficient Disparity Decomposition Analysis for a Longitudinal Data
#'
#' The \code{vc.pb} offers Peters-Belson(PB) type of nonparametric varying-coefficient regression method which measures the disparity between a majority group
#' and a minority group for the longitudinal data.
#' @param formula a formula for the model.
#' @param group a vector within the \code{data} which is used for separating majority and minority groups.
#' @param data a data frame and data has to be included with the form of \code{data.frame}.
#' @param id a vector within the \code{data} which is used for identifying the observations.
#' @param local_time (optional) a vector used for the local points of time variable in the kernel regression.
#' @param modifier (optional) a vector from the \code{data} which is an optional argument to add the varying term into the model. The default is \code{NULL}. If the class of the vector is given as
#' \code{integer} then, the continuous version of \code{vc.PB} is performed and if the class is \code{factor} or \code{character}, then the discrete version is proceeded. Three different sets of
#' inputs are needed for different versions.
#' @param bandwidth_M (optional) a bandwidth for the time variable used for estimating the time-varying coefficient of the majority group.
#' @param bandwidth_m (optional) a bandwidth for the time variable used for estimating the time-varying coefficient of the minority group.
#' @param bandwidth_xM (optional) a vector of \code{p} number of bandwidths for estimating the local expectations of the design matrix for the majority group.
#' @param bandwidth_xm (optional) a vector of \code{p} number of bandwidths for estimating the local expectations of the design matrix for the minority group.
#' @param bandwidth_Z_M (optional) a bandwidth for the varying variable used for estimating the time-varying coefficient of the majority group. Used only when the class of \code{modifier} is \code{integer}.
#' @param bandwidth_Z_m (optional) a bandwidth for the varying variable used for estimating the time-varying coefficient of the minority group. Used only when the class of \code{modifier} is \code{integer}.
#' @param bandwidth_Z_xM (optional) a vector of \code{p} number of bandwidths for estimating the local expectations of the design matrix related to varying variable for the majority group. Used only when the class of \code{modifier} is \code{integer}.
#' @param bandwidth_Z_xm (optional) a vector of \code{p} number of bandwidths for estimating the local expectations of the design matrix related to varying variable for the minority group. Used only when the class of \code{modifier} is \code{integer}.
#' @param detail a bool argument whether the detailed results are provided or not.
#' @param ... used for controlling the others.
#' @author Sang Kyu Lee
#' @return \code{vc.pb} returns an object of class \code{"vc.pb"}, which is a list containing
#' following components:
#' @return
#' \item{call}{a matched call.}
#' \item{overall_disparity}{overall disparity between major and minor groups.}
#' \item{explained_disparity}{explained disparity between major and minor groups, this component is given only when \code{varying} is null.}
#' \item{explained_disparity_by_X}{explained disparity from the variables without \code{modifier} variable given that the modifier variable is from the majority group, this component is given only when \code{varying} is not null.}
#' \item{explained_disparity_by_Z}{explained disparity from \code{modifier} variable, this component is given only when \code{varying} is not null.}
#' \item{unexplained_disparity}{unexplained disparity between major and minor groups.}
#' \item{times}{local time points used for kernel regression.}
#' \item{major}{a majority group label.}
#' \item{minor}{a minority group label.}
#' \item{modfier, varying.type}{the modifier variable and the type of the modifier variable, these components are given only when \code{varying} is not null.}
#' \item{bandwidths}{various corresponding bandwidths. Please see the details or the attached reference for more information.}
#' @examples
#' set.seed(1)
#' n <- 100
#' x1 <- rnorm(n)
#' x2 <- rnorm(n)
#' time <- rep(1:5, 20) + runif(n)
#' y <- rnorm(n)
#' sub_id <- rep(1:25, 1, each = 4)
#' group <- rep(as.character(1:2), 25, each = 2)
#' z <- as.character(rbinom(n, 1, prob = 0.5))
#'
#' data <- data.frame(y = y, x1 = x1, x2 = x2, z = z, group = group, time = time, sub_id = sub_id)
#'
#' fit <- vc.pb(y ~ (x1|time) + x2, data = data, id = sub_id, group = group)
#' fit
#' @importFrom rlist list.append
#' @importFrom KernSmooth dpill
#' @importFrom stats complete.cases dnorm glm lm model.extract model.matrix model.response na.pass model.frame quasibinomial
#' @export
vc.pb <-function(formula, group, data, id,
modifier = NULL, local_time = NULL,
bandwidth_M = NULL, bandwidth_m = NULL,
bandwidth_xM = NULL, bandwidth_xm = NULL,
bandwidth_Z_M = NULL, bandwidth_Z_m = NULL,
bandwidth_Z_xM = NULL, bandwidth_Z_xm = NULL,
detail = FALSE, ...)
{
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m1 <- match(c("formula", "group", "id", "data"), names(mf), 0)
m2 <- match(c("formula", "data"), names(mf), 0)
mf1 <- mf[c(1, m1)]
mf1$drop.unused.levels <- TRUE
mf1$na.action <- na.pass
mf1[[1]] <- quote(model.frame)
mf1$formula <- lme4::subbars(mf1$formula)
mf1 <- eval(mf1, parent.frame())
mt1 <- attr(mf1, "terms")
mod <- getvc(formula)
vf <- mod[[1]]
tf <- mod[[2]]
mf2 <- mf[c(1, m2)]
mf2$drop.unused.levels <- TRUE
mf2$na.action <- na.pass
mf2[[1]] <- quote(model.frame)
mf2$formula <- formula(paste("~", paste0(vf, collapse = "+")))
mf2 <- eval(mf2, parent.frame())
varyingX <- names(mf2)
mf3 <- mf[c(1, m2)]
mf3$drop.unused.levels <- TRUE
mf3$na.action <- na.pass
mf3[[1]] <- quote(model.frame)
mf3$formula <- formula(paste("~", tf))
mf3 <- eval(mf3, parent.frame())
group <- model.extract(mf1, "group")
if(is.null(group)) stop("group has to be defined properly.")
disparity.var <- colnames(group)
disparity.group <- levels(as.factor(model.extract(mf1, "group")))
major <- disparity.group[1]
minor <- disparity.group[2]
subjectid <- model.extract(mf1, "id")
if(is.null(subjectid)) stop("id has to be defined properly.")
time <- mf3
yM <- model.response(mf1, "numeric")[group == disparity.group[1]]
xM <- model.frame(mt1, mf1, contrasts.arg = NULL, xlev = NULL)[group == disparity.group[1],]
timeM <- time[group == disparity.group[1],]
subjectidM <- subjectid[group == disparity.group[1]]
ym <- model.response(mf1, "numeric")[group == disparity.group[2]]
xm <- model.frame(mt1, mf1, contrasts.arg = NULL, xlev = NULL)[group == disparity.group[2],]
timem <- time[group == disparity.group[2],]
subjectidm <- subjectid[group == disparity.group[2]]
xM <- xM[,!(names(xM) %in% names(time))]
xm <- xm[,!(names(xm) %in% names(time))]
completeM <- complete.cases(xM) & complete.cases(yM) & complete.cases(timeM) & complete.cases(subjectidM)
completem <- complete.cases(xm) & complete.cases(ym) & complete.cases(timem) & complete.cases(subjectidm)
if(sum(!completeM) > 0 | sum(!completem) > 0){
xM <- xM[completeM, ]
xm <- xm[completem, ]
yM <- yM[completeM]
ym <- ym[completem]
timeM <- timeM[completeM]
timem <- timem[completem]
subjectidM <- subjectidM[completeM]
subjectidm <- subjectidm[completem]
warning("The data is not complete, the missing observations are ignored.")
}
xM <- xM[,-1]
xm <- xm[,-1]
if(is.null(local_time)) local_time <- seq(min(c(timeM, timem)), max(c(timeM, timem)),
length.out = 100)
if(is.null(modifier)){
if(!is.null(bandwidth_Z_M)) warning("bandwidth_Z_M is ignored, since it is not required in the model.")
if(!is.null(bandwidth_Z_m)) warning("bandwidth_Z_m is ignored, since it is not required in the model.")
if(!is.null(bandwidth_Z_xM)) warning("bandwidth_Z_xM is ignored, since it is not required in the model.")
if(!is.null(bandwidth_Z_xm)) warning("bandwidth_Z_xm is ignored, since it is not required in the model.")
fitted <- time.disparity(yM = yM, xM = xM,
ym = ym, xm = xm,
time_M = timeM, time_m = timem,
qx = local_time,
varying = modifier,
subjectid_M = subjectidM,
subjectid_m = subjectidm,
varying_X = varyingX,
bandwidth_m = bandwidth_m,
bandwidth_M = bandwidth_M,
bandwidth_xm = bandwidth_xm,
bandwidth_xM = bandwidth_xM,
detail = detail)
} else if (!is.null(modifier)){
# changing
modm <- unlist(as.vector(xm[modifier]))
modM <- unlist(as.vector(xM[modifier]))
if((is.character(modm) & is.character(modM)) | (is.factor(modm) & is.factor(modM))){
if(!is.null(bandwidth_Z_M)) warning("bandwidth_Z_M is ignored, since it is not required in the model.")
if(!is.null(bandwidth_Z_m)) warning("bandwidth_Z_m is ignored, since it is not required in the model.")
if(!is.null(bandwidth_Z_xM)) warning("bandwidth_Z_xM is ignored, since it is not required in the model.")
if(!is.null(bandwidth_Z_xm)) warning("bandwidth_Z_xm is ignored, since it is not required in the model.")
fitted <- time.disparity.varying.discrete(yM = yM, xM = xM,
ym = ym, xm = xm,
time_M = timeM, time_m = timem,
qx = local_time,
subjectid_M = subjectidM,
subjectid_m = subjectidm,
bandwidth_m = bandwidth_m,
bandwidth_M = bandwidth_M,
bandwidth_xm = bandwidth_xm,
bandwidth_xM = bandwidth_xM,
varying_X = varyingX,
varying = modifier)
} else if((is.integer(modm) & is.integer(modM)) | (is.numeric(modm) & is.numeric(modM))){
fitted <- time.disparity.varying.continuous(yM = yM, xM = xM,
ym = ym, xm = xm,
time_M = timeM, time_m = timem,
qx = local_time,
varying_X = varyingX,
subjectid_M = subjectidM,
subjectid_m = subjectidm,
bandwidth1_m = bandwidth_m,
bandwidth1_M = bandwidth_M,
bandwidth1_xm = bandwidth_xm,
bandwidth1_xM = bandwidth_xM,
bandwidth2_m = bandwidth_Z_m,
bandwidth2_M = bandwidth_Z_M,
bandwidth2_xm = bandwidth_Z_xm,
bandwidth2_xM = bandwidth_Z_xM,
varying = modifier)
} else {
stop("The class of varying should be defined as the one of factor, character, integer and numeric.")
}
} else {
stop("modifier should be defined properly.")
}
if(is.null(modifier)){
res <- list(
call = cl,
overall_disparity = drop(fitted$result$All_Disparity),
explained_disparity = drop(fitted$result$Explained),
unexplained_disparity = drop(fitted$result$Unexplained),
times = local_time,
major = major,
minor = minor,
bandwidth_xM = drop(fitted$result$bandwidth_xM),
bandwidth_xm = drop(fitted$result$bandwidth_xm),
bandwidth_M = drop(fitted$result$bandwidth_M),
bandwidth_m = drop(fitted$result$bandwidth_m)
)
if(detail) res$results = fitted$result
} else if((!is.null(modifier) & ((is.integer(modm) & is.integer(modM)) | (is.numeric(modm) & is.numeric(modM))))){
res <- list(
call = cl,
overall_disparity = drop(fitted$result$All_Disparity),
explained_disparity_by_Z = drop(fitted$result$Explained),
explained_disparity_by_X = drop(fitted$result$Explained_X_given_Z),
unexplained_disparity = drop(fitted$result$Unexplained),
times = local_time,
modifier = modifier,
major = major,
minor = minor,
varying.type = fitted$varying.type,
bandwidth_xM = drop(fitted$result$bandwidth1_xM_seq),
bandwidth_xm = drop(fitted$result$bandwidth1_xm_seq),
bandwidth_M = drop(fitted$result$bandwidth1_M),
bandwidth_m = drop(fitted$result$bandwidth1_m),
bandwidth_Z_xM = drop(fitted$result$bandwidth2_xM_seq),
bandwidth_Z_xm = drop(fitted$result$bandwidth2_xm_seq),
bandwidth_Z_M = drop(fitted$result$bandwidth2_M),
bandwidth_Z_m = drop(fitted$result$bandwidth2_m)
)
if(detail) res$results = fitted$result
} else {
varying_combination_idx = fitted$varying_combination_idx
res <- list(
call = cl,
overall_disparity = drop(fitted$All_Disparity),
explained_disparity_by_Z = drop(fitted$Explained),
explained_disparity_by_X = drop(fitted$Explained_X_given_Z),
unexplained_disparity = drop(fitted$Unexplained),
times = local_time,
modifier = modifier,
major = major,
minor = minor,
disp.name = fitted$varying_combination,
varying_combination_idx = varying_combination_idx,
varying.type = fitted$varying.type,
bandwidth_xM = drop(fitted$bandwidth_xM),
bandwidth_xm = drop(fitted$bandwidth_xm),
bandwidth_M = drop(fitted$bandwidth_M),
bandwidth_m = drop(fitted$bandwidth_m)
)
if(detail) res$results = fitted
}
class(res) = "vc.pb"
res
}
#' @method print vc.pb
#' @importFrom stats quantile
#' @export
print.vc.pb <- function(x, digits = max(3, getOption("digits") - 3), ...){
cat("\nCall:\n\n")
time.quantiles <- seq(0.1, 0.9, length.out = 5)
print(x$call)
cat("\nGroup Variables:\n\n")
cat("Major:", x$major,"\n")
cat("Minor:", x$minor,"\n")
time.quantiles.value <- stats::quantile(x$times, probs = time.quantiles)
idx <- NULL
for(i in 1:length(time.quantiles.value)){
idx <- c(idx, which.min(x$times < time.quantiles.value[i]))
}
if(!is.null(x$modifier)){
result.mat <- matrix(0, ncol = length(idx), nrow = 4)
colnames(result.mat) <- paste0("t = ", round(x$times[idx], digits = digits))
# rownames(result.mat) <- c(" Overall Disparity: ", "Explained Disparity by Z: ",
# "Explained Disparity by X: ", " Unexplained Disparity: ")
rownames(result.mat) <- c(" Overall Disparity: ",
"Explained Disparity by the modifier: ",
" Explained Disparity by X: ",
" Unexplained Disparity: ")
cat("\nDisparity Summary Results:\n\n")
# cat("\nDisparity Summary Results:\n")
# cat("\n ", paste0("t = ", round(x$times[idx], digits = digits)))
# cat("\n Overall Disparity: ")
# cat(round(x$overall_disparity[idx], digits = digits))
# cat("\nExplained Disparity by the modifier: ")
# cat(round(x$explained_disparity_by_Z[idx], digits = digits))
# cat("\n Explained Disparity by X: ")
# cat(round(x$explained_disparity_by_X[idx], digits = digits))
# cat("\n Unexplained Disparity: ")
# cat(round(x$unexplained_disparity[idx], digits = digits))
result.mat[1,] <- round(x$overall_disparity[idx], digits = digits)
result.mat[2,] <- round(x$explained_disparity_by_Z[idx], digits = digits)
result.mat[3,] <- round(x$explained_disparity_by_X[idx], digits = digits)
result.mat[4,] <- round(x$unexplained_disparity[idx], digits = digits)
} else {
result.mat <- matrix(0, ncol = length(idx), nrow = 3)
colnames(result.mat) <- paste0("t = ", round(x$times[idx], digits = digits))
rownames(result.mat) <- c(" Overall Disparity: ",
" Explained Disparity: ",
"Unexplained Disparity: ")
cat("\nDisparity Summary Results:\n\n")
# cat("\n ", paste0("t = ", round(x$times[idx], digits = digits)))
# cat("\n Overall Disparity: ")
# cat(round(x$overall_disparity[idx], digits = digits))
# cat("\n Explained Disparity: ")
# cat(round(x$explained_disparity[idx], digits = digits))
# cat("\nUnexplained Disparity: ")
# cat(round(x$unexplained_disparity[idx], digits = digits), "\n\n")
result.mat[1,] <- round(x$overall_disparity[idx], digits = digits)
result.mat[2,] <- round(x$explained_disparity[idx], digits = digits)
result.mat[3,] <- round(x$unexplained_disparity[idx], digits = digits)
}
print(result.mat)
cat("\n")
}
#' @importFrom lme4 expandDoubleVerts
#' @importFrom methods is
sb = function(term){
fb <- function(term) {
if (is.name(term) || !is.language(term))
return(NULL)
if (term[[1]] == as.name("("))
return(fb(term[[2]]))
stopifnot(is.call(term))
if (term[[1]] == as.name("|"))
return(term)
if (length(term) == 2)
return(fb(term[[2]]))
c(fb(term[[2]]), fb(term[[3]]))
}
modterm <- lme4::expandDoubleVerts(if (is(term, "formula"))
term[[length(term)]]
else term)
strsplit(as.character(fb(modterm)), split = " | ")
}
getvc <- function(f){
bars <- sb(f)
res.varying <- NULL
res.time <- bars[[1]][3]
for(j in 1:length(bars)){
res.varying <- c(res.varying, bars[[j]][1])
if(bars[[j]][3] != res.time) stop("time variables have to be the same for the varying variables")
}
res = list(res.varying = res.varying, res.time = res.time)
res
}
time.disparity.varying.discrete = function(yM, xM, ym, xm, varying, varying_X,
time_M, time_m,
qx = seq(min(c(time_M, time_m)), max(c(time_M, time_m)),
length.out = 100),
subjectid_M, subjectid_m,
bandwidth_M = NULL, bandwidth_m = NULL,
bandwidth_xM = NULL, bandwidth_xm = NULL){
varying_idx = which(names(xM) %in% varying)
varying_lbl = levels(as.factor(xM[,names(xM) %in% varying]))
l = length(varying_lbl)
nM = length(yM)
nm = length(ym)
varying_list_M = list()
varying_list_m = list()
for(q in 1:l){
varying_list_M[[q]] = cbind(yM[xM[,varying_idx] == varying_lbl[q]],
time_M[xM[,varying_idx] == varying_lbl[q]],
xM[xM[,varying_idx] == varying_lbl[q], which(!(names(xM) %in% varying))])
varying_list_m[[q]] = cbind(ym[xm[,varying_idx] == varying_lbl[q]],
time_m[xm[,varying_idx] == varying_lbl[q]],
xm[xm[,varying_idx] == varying_lbl[q], which(!(names(xm) %in% varying))])
}
varying_list_M_n = unlist(lapply(varying_list_M, function(x) dim(x)[1]))
varying_list_m_n = unlist(lapply(varying_list_m, function(x) dim(x)[1]))
varying_lbl_M = varying_lbl[which.max(unlist(lapply(lapply(varying_list_M, dim), function(x) x[1])))]
varying_lbl_m = varying_lbl[which.max(unlist(lapply(lapply(varying_list_m, dim), function(x) x[1])))]
varying_lbl_M_idx = which.max(unlist(lapply(lapply(varying_list_M, dim), function(x) x[1])))
varying_lbl_m_idx = which.max(unlist(lapply(lapply(varying_list_m, dim), function(x) x[1])))
res_list = list()
for(k in 1:l){
xM_temp = varying_list_M[[k]][,-c(1,2)]
yM_temp = varying_list_M[[k]][,1]
time_M_temp = varying_list_M[[k]][,2]
if(k == 1){
p = ncol(xM_temp)
charac = sapply(xM_temp, is.character)
fac = sapply(xM_temp, is.factor)
varying_coef_bool = names(xM_temp) %in% varying_X
xM_model = list()
xm_model = list()
cat_idx = NULL
idx = 1
for(j in 1:p){
# the model.matrix function does not work if there is only one level
# in the variable, however, the estimation is nonsense for this case
# so I don't have to worry about this
xM_model[[j]] = model.matrix(~., data = as.data.frame(xM_temp[,j]))
if((charac[j] == T | fac[j] == T) & (dim(xM_model[[j]])[2] == 2) & varying_coef_bool[j]){
cat_idx = c(cat_idx, (idx + 1))
idx = idx + 1
} else if((charac[j] == T | fac[j] == T) & (dim(xM_model[[j]])[2] > 2) & varying_coef_bool[j]){
cat_idx = c(cat_idx, (idx + 1:(dim(xM_model[[j]])[2]-1)))
idx = max(idx + 1:(dim(xM_model[[j]])[2]-1))
} else{
idx = idx + 1
}
}
}
xM_model = model.matrix(~., data = as.data.frame(xM_temp))
varying_coef_model_idx = which(colnames(xM_model) %in% varying_X)
xm_temp = varying_list_m[[k]][,-c(1,2)]
ym_temp = varying_list_m[[k]][,1]
time_m_temp = varying_list_m[[k]][,2]
xm_model = model.matrix(~., data = as.data.frame(xm_temp))
pred_xM = matrix(0, nrow = length(qx), ncol = dim(xm_model)[2] - 1)
pred_xm = matrix(0, nrow = length(qx), ncol = dim(xm_model)[2] - 1)
bandwidth_xM_seq <- NULL
bandwidth_xm_seq <- NULL
for(i in 1:length(qx)){
for(j in 2:dim(xM_model)[2]){
if(j %in% varying_coef_model_idx){
if(i == 1){
bandwidth_xM_temp <- ifelse(is.null(bandwidth_xM), 1.5*KernSmooth::dpill(x = time_M_temp, y = xM_model[,j]), bandwidth_xM[which(varying_coef_model_idx %in% j)])
bandwidth_xm_temp <- ifelse(is.null(bandwidth_xm), 1.5*KernSmooth::dpill(x = time_m_temp, y = xm_model[,j]), bandwidth_xm[which(varying_coef_model_idx %in% j)])
bandwidth_xM_seq <- c(bandwidth_xM_temp, bandwidth_xM_seq)
bandwidth_xm_seq <- c(bandwidth_xm_temp, bandwidth_xm_seq)
}
kernel_M = dnorm((time_M_temp - qx[i])/bandwidth_xM_temp)
kernel_m = dnorm((time_m_temp - qx[i])/bandwidth_xm_temp)
}
if(j %in% cat_idx){
pred_xM[i,(j-1)] = mean(glm(xM_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_M)$fitted.values)
pred_xm[i,(j-1)] = mean(glm(xm_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_m)$fitted.values)
} else if(j %in% varying_coef_model_idx){
pred_xM[i,(j-1)] = mean(lm(xM_model[,j] ~ 1, weights=kernel_M)$fitted.values)
pred_xm[i,(j-1)] = mean(lm(xm_model[,j] ~ 1, weights=kernel_m)$fitted.values)
} else {
pred_xM[i,(j-1)] = mean(xM_model[,j])
pred_xm[i,(j-1)] = mean(xm_model[,j])
}
# if(j %in% cat_idx){
# pred_xM[i,(j-1)] = mean(glm(xM_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_M)$fitted.values)
# pred_xm[i,(j-1)] = mean(glm(xm_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_m)$fitted.values)
# } else {
# pred_xM[i,(j-1)] = mean(lm(xM_model[,j] ~ 1, weights=kernel_M)$fitted.values)
# pred_xm[i,(j-1)] = mean(lm(xm_model[,j] ~ 1, weights=kernel_m)$fitted.values)
# }
}
}
hatcoeffM = matrix(0,length(qx), dim(xM_model)[2])
hatcoeffm = matrix(0,length(qx), dim(xm_model)[2])
bandwidth_M_temp <- ifelse(is.null(bandwidth_M), 1.5*KernSmooth::dpill(x = time_M_temp, y = as.numeric(yM_temp)), bandwidth_M)
bandwidth_m_temp <- ifelse(is.null(bandwidth_m), 1.5*KernSmooth::dpill(x = time_m_temp, y = as.numeric(ym_temp)), bandwidth_m)
for(i in 1:length(qx))
{
kernel_M = dnorm((time_M_temp - qx[i])/bandwidth_M_temp)
kernel_m = dnorm((time_m_temp - qx[i])/bandwidth_m_temp)
hatcoeffM[i,] = lm(yM ~. , data = data.frame(yM = as.numeric(yM_temp), xM_temp),
weights=kernel_M)$coefficient
hatcoeffm[i,] = lm(ym ~. , data = data.frame(ym = as.numeric(ym_temp), xm_temp),
weights=kernel_m)$coefficient
}
hatcoeff1M = hatcoeffM
hatcoeff1m = hatcoeffm
pred_X1M = t(pred_xM)
pred_X1m = t(pred_xm) # z^M with coefficient minor part
if(k == 1){
eq3 = (hatcoeff1M[,1] - hatcoeff1m[,1]) * varying_list_M_n[k]/nM
eq4 = (diag((hatcoeff1M[,-1] - hatcoeff1m[,-1]) %*% (pred_X1M))) * varying_list_M_n[k]/nM
eq5 = (diag(hatcoeff1m[,-1]%*%((pred_X1M) - (pred_X1m)))) * varying_list_M_n[k]/nM
eq6 = hatcoeff1m[,1] * varying_list_M_n[k]/nM - hatcoeff1m[,1] * varying_list_m_n[k]/nm
eq7 = (diag(hatcoeff1m[,-1]%*%(pred_X1m))) * varying_list_M_n[k]/nM - (diag(hatcoeff1m[,-1]%*%(pred_X1m))) * varying_list_m_n[k]/nm
} else {
eq3 = eq3 + (hatcoeff1M[,1] - hatcoeff1m[,1]) * varying_list_M_n[k]/nM
eq4 = eq4 + (diag((hatcoeff1M[,-1] - hatcoeff1m[,-1]) %*% (pred_X1M))) * varying_list_M_n[k]/nM
eq5 = eq5 + (diag(hatcoeff1m[,-1]%*%((pred_X1M) - (pred_X1m)))) * varying_list_M_n[k]/nM
eq6 = eq6 + hatcoeff1m[,1] * varying_list_M_n[k]/nM - hatcoeff1m[,1] * varying_list_m_n[k]/nm
eq7 = eq7 + (diag(hatcoeff1m[,-1]%*%(pred_X1m))) * varying_list_M_n[k]/nM - (diag(hatcoeff1m[,-1]%*%(pred_X1m))) * varying_list_m_n[k]/nm
}
# result$Unexplained = eq3 + eq4
# result$Explained_X_given_Z = eq5
# result$Direct_Explained = eq6
# result$Indirect_Explained = eq7
# result$Explained = eq6 + eq7
# result$All_Disparity = eq3 + eq4 + eq5 + eq6 + eq7
# result$time = qx
# result$varying_coef_model_idx = varying_coef_model_idx
# result$varying_coef_bool = varying_coef_bool
# result$bandwidth_xM_seq = bandwidth_xM_seq
# result$bandwidth_xm_seq = bandwidth_xm_seq
# result$bandwidth_M = bandwidth_M_temp
# result$bandwidth_m = bandwidth_m_temp
}
obj.names = as.vector(t(outer(varying_lbl, varying_lbl, FUN = paste)))
res_list$Unexplained = eq3 + eq4
res_list$Explained_X_given_Z = eq5
res_list$Direct_Explained = eq6
res_list$Indirect_Explained = eq7
res_list$Explained = eq6 + eq7
res_list$All_Disparity = eq3 + eq4 + eq5 + eq6 + eq7
res_list$varying_X = varying_X
res_list$yM = yM
res_list$ym = ym
res_list$xM = xM
res_list$xm = xm
res_list$varying = varying
res_list$varying_combination = paste(varying_lbl_M, varying_lbl_m)
res_list$varying_combination_idx = (varying_lbl_M_idx-1)*l + varying_lbl_m_idx
res_list$time_M = time_M
res_list$time_m = time_m
res_list$qx = qx
if(is.null(bandwidth_M)){
res_list$bandwidth_M = bandwidth_M_temp
} else {
res_list$bandwidth_M = bandwidth_M
}
if(is.null(bandwidth_m)){
res_list$bandwidth_m = bandwidth_m_temp
} else {
res_list$bandwidth_m = bandwidth_m
}
if(is.null(bandwidth_xM)){
res_list$bandwidth_xM = bandwidth_xM_seq
} else {
res_list$bandwidth_xM = bandwidth_xM
}
if(is.null(bandwidth_xm)){
res_list$bandwidth_xm = bandwidth_xm_seq
} else {
res_list$bandwidth_xm = bandwidth_xm
}
res_list$obj.names = obj.names
res_list$varying.type = "discrete"
res_list$subjectid_M = subjectid_M
res_list$subjectid_m = subjectid_m
res_list
}
time.disparity.varying.continuous = function(yM, xM, ym, xm, varying, varying_X,
time_M, time_m,
qx = seq(min(c(time_M, time_m)), max(c(time_M, time_m)),
length.out = 100),
subjectid_M, subjectid_m,
bandwidth1_m = NULL,
bandwidth1_M = NULL,
bandwidth1_xm = NULL,
bandwidth1_xM = NULL,
bandwidth2_m = NULL,
bandwidth2_M = NULL,
bandwidth2_xm = NULL,
bandwidth2_xM = NULL,
trace = F){
varying_idx = which(names(xM) %in% varying)
varying_list_M = cbind(yM,
time_M,
xM[, which(!(names(xM) %in% varying))])
varying_list_m = cbind(ym,
time_m,
xm[, which(!(names(xm) %in% varying))])
res_list = list()
xM_temp = varying_list_M[,-c(1,2)]
yM_temp = varying_list_M[,1]
time_M_temp = varying_list_M[,2]
varying_M_temp = xM[, which(names(xM) %in% varying)]
# if(is.null(varying_M_mean)){
# varying_M_temp_mean = mean(varying_M_temp)
# } else {
# varying_M_temp_mean = varying_M_mean
# }
p = ncol(xM_temp)
charac = sapply(xM_temp, is.character)
fac = sapply(xM_temp, is.factor)
varying_coef_bool = names(xM_temp) %in% varying_X
xM_model = list()
xm_model = list()
cat_idx = NULL
idx = 1
for(j in 1:p){
# the model.matrix function does not work if there is only one level
# in the variable, however, the estimation is nonsense for this case
# so I don't have to worry about this
xM_model[[j]] = model.matrix(~., data = as.data.frame(xM_temp[,j]))
if((charac[j] == T | fac[j] == T) & (dim(xM_model[[j]])[2] == 2)){
cat_idx = c(cat_idx, (idx + 1))
idx = idx + 1
} else if((charac[j] == T | fac[j] == T) & (dim(xM_model[[j]])[2] > 2)){
cat_idx = c(cat_idx, (idx + 1:(dim(xM_model[[j]])[2]-1)))
idx = max(idx + 1:(dim(xM_model[[j]])[2]-1))
} else{
idx = idx + 1
}
}
xM_model = model.matrix(~., data = as.data.frame(xM_temp))
varying_coef_model_idx = which(colnames(xM_model) %in% varying_X)
xm_temp = varying_list_m[,-c(1,2)]
ym_temp = varying_list_m[,1]
time_m_temp = varying_list_m[,2]
varying_m_temp = xm[, which(names(xm) %in% varying)]
# if(is.null(varying_m_mean)){
# varying_m_temp_mean = mean(varying_m_temp)
# } else {
# varying_m_temp_mean = varying_m_mean
# }
xm_model = model.matrix(~., data = as.data.frame(xm_temp))
for(q in 1:length(varying_M_temp)){
if(trace) cat(q, "\n")
pred_xM = matrix(0, nrow = length(qx), ncol = dim(xM_model)[2] - 1)
pred_xm = matrix(0, nrow = length(qx), ncol = dim(xm_model)[2] - 1)
bandwidth1_xM_seq <- NULL
bandwidth1_xm_seq <- NULL
bandwidth2_xM_seq <- NULL
bandwidth2_xm_seq <- NULL
for(i in 1:length(qx)){
for(j in 2:dim(xM_model)[2]){
if(j %in% varying_coef_model_idx){
if(i == 1){
bandwidth1_xM_temp <- ifelse(is.null(bandwidth1_xM), 1.5*KernSmooth::dpill(x = time_M_temp, y = xM_model[,j]), bandwidth1_xM[which(varying_coef_model_idx %in% j)])
bandwidth1_xm_temp <- ifelse(is.null(bandwidth1_xm), 1.5*KernSmooth::dpill(x = time_m_temp, y = xm_model[,j]), bandwidth1_xm[which(varying_coef_model_idx %in% j)])
bandwidth2_xM_temp <- ifelse(is.null(bandwidth2_xM), 1.5*KernSmooth::dpill(x = varying_M_temp, y = xM_model[,j]), bandwidth2_xM[which(varying_coef_model_idx %in% j)])
bandwidth2_xm_temp <- ifelse(is.null(bandwidth2_xm), 1.5*KernSmooth::dpill(x = varying_m_temp, y = xm_model[,j]), bandwidth2_xm[which(varying_coef_model_idx %in% j)])
bandwidth1_xM_seq <- c(bandwidth1_xM_temp, bandwidth1_xM_seq)
bandwidth1_xm_seq <- c(bandwidth1_xm_temp, bandwidth1_xm_seq)
bandwidth2_xM_seq <- c(bandwidth2_xM_temp, bandwidth2_xM_seq)
bandwidth2_xm_seq <- c(bandwidth2_xm_temp, bandwidth2_xm_seq)
}
kernel_M = dnorm((time_M_temp - qx[i])/bandwidth1_xM_temp) * dnorm((varying_M_temp - varying_M_temp[q])/bandwidth2_xM_temp)
kernel_m = dnorm((time_m_temp - qx[i])/bandwidth1_xm_temp) * dnorm((varying_m_temp - varying_M_temp[q])/bandwidth2_xm_temp)
}
if(j %in% cat_idx){
pred_xM[i,(j-1)] = mean(glm(xM_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_M)$fitted.values)
pred_xm[i,(j-1)] = mean(glm(xm_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_m)$fitted.values)
} else if(j %in% varying_coef_model_idx){
pred_xM[i,(j-1)] = mean(lm(xM_model[,j] ~ 1, weights=kernel_M)$fitted.values)
pred_xm[i,(j-1)] = mean(lm(xm_model[,j] ~ 1, weights=kernel_m)$fitted.values)
} else {
pred_xM[i,(j-1)] = mean(xM_model[,j])
pred_xm[i,(j-1)] = mean(xm_model[,j])
}
}
}
hatcoeffM = matrix(0,length(qx), dim(xM_model)[2])
hatcoeffm = matrix(0,length(qx), dim(xm_model)[2])
bandwidth1_M_temp <- ifelse(is.null(bandwidth1_M), 1.5*KernSmooth::dpill(x = time_M_temp, y = as.numeric(yM_temp)), bandwidth1_M)
bandwidth1_m_temp <- ifelse(is.null(bandwidth1_m), 1.5*KernSmooth::dpill(x = time_m_temp, y = as.numeric(ym_temp)), bandwidth1_m)
bandwidth2_M_temp <- ifelse(is.null(bandwidth2_M), 1.5*KernSmooth::dpill(x = varying_M_temp, y = as.numeric(yM_temp)), bandwidth2_M)
bandwidth2_m_temp <- ifelse(is.null(bandwidth2_m), 1.5*KernSmooth::dpill(x = varying_m_temp, y = as.numeric(ym_temp)), bandwidth2_m)
for(i in 1:length(qx))
{ # kernel part needs to be changed 3:42 / (08/21)
kernel_M = dnorm((time_M_temp - qx[i])/bandwidth1_M_temp) * dnorm((varying_M_temp - varying_M_temp[q])/bandwidth2_M_temp)
kernel_m = dnorm((time_m_temp - qx[i])/bandwidth1_m_temp) * dnorm((varying_m_temp - varying_M_temp[q])/bandwidth2_m_temp)
hatcoeffM[i,] = lm(yM ~. , data = data.frame(yM = as.numeric(yM_temp), xM_temp),
weights=kernel_M)$coefficient
hatcoeffm[i,] = lm(ym ~. , data = data.frame(ym = as.numeric(ym_temp), xm_temp),
weights=kernel_m)$coefficient
}
hatcoeff1M = hatcoeffM
hatcoeff1m = hatcoeffm
pred_X1M = t(pred_xM)
pred_X1m = t(pred_xm)
if(q == 1){
eq3 = hatcoeff1M[,1] - hatcoeff1m[,1]
eq4 = diag((hatcoeff1M[,-1] - hatcoeff1m[,-1]) %*% (pred_X1M))
eq5 = diag(hatcoeff1m[,-1]%*%((pred_X1M) - (pred_X1m)))
eq6_1 = hatcoeff1m[,1]
eq7_1 = diag(hatcoeff1m[,-1]%*%(pred_X1m))
} else {
eq3 = eq3 + hatcoeff1M[,1] - hatcoeff1m[,1]
eq4 = eq4 + diag((hatcoeff1M[,-1] - hatcoeff1m[,-1]) %*% (pred_X1M))
eq5 = eq5 + diag(hatcoeff1m[,-1]%*%((pred_X1M) - (pred_X1m)))
eq6_1 = eq6_1 + hatcoeff1m[,1]
eq7_1 = eq7_1 + diag(hatcoeff1m[,-1]%*%(pred_X1m))
}
}
for(q in 1:length(varying_m_temp)){
if(trace) cat(q, "\n")
pred_xm = matrix(0, nrow = length(qx), ncol = dim(xm_model)[2] - 1)
for(i in 1:length(qx)){
# kernel part needs to be changed 3:42 / (08/21)
for(j in 2:dim(xm_model)[2]){
if(j %in% varying_coef_model_idx){
if(i == 1){
bandwidth1_xm_temp <- ifelse(is.null(bandwidth1_xm), 1.5*KernSmooth::dpill(x = time_m_temp, y = xm_model[,j]), bandwidth1_xm[which(varying_coef_model_idx %in% j)])
bandwidth2_xm_temp <- ifelse(is.null(bandwidth2_xm), 1.5*KernSmooth::dpill(x = varying_m_temp, y = xm_model[,j]), bandwidth2_xm[which(varying_coef_model_idx %in% j)])
}
kernel_mm = dnorm((time_m_temp - qx[i])/bandwidth1_xm_temp) * dnorm((varying_m_temp - varying_m_temp[q])/bandwidth2_xm_temp)
}
if(j %in% cat_idx){
pred_xm[i,(j-1)] = mean(glm(xm_model[,j] ~ 1, weights = kernel_mm, family = quasibinomial(link = "logit"))$fitted.values)
} else if(j %in% varying_coef_model_idx) {
pred_xm[i,(j-1)] = mean(lm(xm_model[,j] ~ 1, weights = kernel_mm)$fitted.values)
} else {
pred_xm[i,(j-1)] = mean(xm_model[,j])
}
}
}
hatcoeffm = matrix(0,length(qx), dim(xm_model)[2])
for(i in 1:length(qx))
{
# kernel part needs to be changed 3:42 / (08/21)
kernel_m = dnorm((time_m_temp - qx[i])/bandwidth1_m_temp) * dnorm((varying_m_temp - varying_m_temp[q])/bandwidth2_m_temp)
hatcoeffm[i,] = lm(ym ~. , data = data.frame(ym = as.numeric(ym_temp), xm_temp),
weights=kernel_m)$coefficient
}
hatcoeff2m = hatcoeffm
pred_X2m = t(pred_xm)
if(q == 1){
eq6_2 = hatcoeff2m[,1]
eq7_2 = diag(hatcoeff2m[,-1]%*%(pred_X2m))
} else {
eq6_2 = eq6_2 + hatcoeff2m[,1]
eq7_2 = eq7_2 + diag(hatcoeff2m[,-1]%*%(pred_X2m))
}
}
result = list()
eq3 = eq3/length(varying_M_temp)
eq4 = eq4/length(varying_M_temp)
eq5 = eq5/length(varying_M_temp)
eq6 = eq6_1/length(varying_M_temp) - eq6_2/length(varying_m_temp)
eq7 = eq7_1/length(varying_M_temp) - eq7_2/length(varying_m_temp)
result$Unexplained = eq3 + eq4
result$Explained_X_given_Z = eq5
result$Direct_Explained = eq6
result$Indirect_Explained = eq7
result$Explained = eq6 + eq7
result$All_Disparity = eq3 + eq4 + eq5 + eq6 + eq7
result$time = qx
result$bandwidth1_xM_seq = bandwidth1_xM_seq
result$bandwidth1_xm_seq = bandwidth1_xm_seq
result$bandwidth1_M = bandwidth1_M_temp
result$bandwidth1_m = bandwidth1_m_temp
result$bandwidth2_xM_seq = bandwidth2_xM_seq
result$bandwidth2_xm_seq = bandwidth2_xm_seq
result$bandwidth2_M = bandwidth2_M_temp
result$bandwidth2_m = bandwidth2_m_temp
res_list$result = result
res_list$yM = yM
res_list$ym = ym
res_list$xM = xM
res_list$xm = xm
res_list$varying = varying
res_list$varying_X = varying_X
res_list$time_M = time_M
res_list$time_m = time_m
res_list$qx = qx
res_list$varying.type = "continuous"
res_list$subjectid_M = subjectid_M
res_list$subjectid_m = subjectid_m
res_list
}
time.disparity = function(yM, xM, ym, xm,
time_M, time_m,
varying = NULL, varying_X = NULL,
subjectid_M, subjectid_m,
qx = seq(min(c(time_M, time_m)), max(c(time_M, time_m)),
length.out = 100),
bandwidth_M = NULL, bandwidth_m = NULL,
bandwidth_xM = NULL, bandwidth_xm = NULL,
detail = T){
varying_list_M = cbind(yM, time_M, xM)
varying_list_m = cbind(ym, time_m, xm)
res_list = list()
xM_temp = varying_list_M[,-c(1,2)]
yM_temp = varying_list_M[,1]
time_M_temp = varying_list_M[,2]
if(!is.null(varying)){
varying_idx = which(names(xM) %in% varying) # not including the intercept
}
p = ncol(xM_temp)
charac = sapply(xM_temp, is.character)
fac = sapply(xM_temp, is.factor)
varying_coef_bool = names(xM_temp) %in% varying_X
xM_model = list()
xm_model = list()
cat_idx = NULL
idx = 1
for(j in 1:p){
# the model.matrix function does not work if there is only one level
# in the variable, however, the estimation is nonsense for this case
# so I don't have to worry about this
xM_model[[j]] = model.matrix(~., data = as.data.frame(xM_temp[,j]))
if((charac[j] == T | fac[j] == T) & (dim(xM_model[[j]])[2] == 2) & varying_coef_bool[j]){
if(!is.null(varying)){
if(j == varying_idx){
varying_idx = idx
}
}
cat_idx = c(cat_idx, (idx + 1))
idx = idx + 1
} else if((charac[j] == T | fac[j] == T) & (dim(xM_model[[j]])[2] > 2) & varying_coef_bool[j]){
if(!is.null(varying)){
if(j == varying_idx){
varying_idx = idx + 1:(dim(xM_model[[j]])[2]-1) - 1
}
}
cat_idx = c(cat_idx, (idx + 1:(dim(xM_model[[j]])[2]-1)))
idx = max(idx + 1:(dim(xM_model[[j]])[2]-1))
} else{
idx = idx + 1
}
}
xM_model = model.matrix(~., data = as.data.frame(xM_temp))
varying_coef_model_idx = which(colnames(xM_model) %in% varying_X)
xm_temp = varying_list_m[,-c(1,2)]
ym_temp = varying_list_m[,1]
time_m_temp = varying_list_m[,2]
xm_model = model.matrix(~., data = as.data.frame(xm_temp))
pred_xM = matrix(0, nrow = length(qx), ncol = dim(xM_model)[2] - 1)
pred_xm = matrix(0, nrow = length(qx), ncol = dim(xm_model)[2] - 1)
bandwidth_xM_seq <- NULL
bandwidth_xm_seq <- NULL
for(i in 1:length(qx)){
for(j in 2:dim(xM_model)[2]){
if(j %in% varying_coef_model_idx){
if(i == 1){
bandwidth_xM_temp <- ifelse(is.null(bandwidth_xM), 1.5*KernSmooth::dpill(x = time_M_temp, y = xM_model[,j]), bandwidth_xM[which(varying_coef_model_idx %in% j)])
bandwidth_xm_temp <- ifelse(is.null(bandwidth_xm), 1.5*KernSmooth::dpill(x = time_m_temp, y = xm_model[,j]), bandwidth_xm[which(varying_coef_model_idx %in% j)])
bandwidth_xM_seq <- c(bandwidth_xM_temp, bandwidth_xM_seq)
bandwidth_xm_seq <- c(bandwidth_xm_temp, bandwidth_xm_seq)
}
kernel_M = dnorm((time_M_temp - qx[i])/bandwidth_xM_temp)
kernel_m = dnorm((time_m_temp - qx[i])/bandwidth_xm_temp)
}
if(j %in% cat_idx){
pred_xM[i,(j-1)] = mean(glm(xM_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_M)$fitted.values)
pred_xm[i,(j-1)] = mean(glm(xm_model[,j] ~ 1, family = quasibinomial(link = "logit"), weights=kernel_m)$fitted.values)
} else if(j %in% varying_coef_model_idx) {
pred_xM[i,(j-1)] = mean(lm(xM_model[,j] ~ 1, weights=kernel_M)$fitted.values)
pred_xm[i,(j-1)] = mean(lm(xm_model[,j] ~ 1, weights=kernel_m)$fitted.values)
} else {
pred_xM[i,(j-1)] = mean(xM_model[,j])
pred_xm[i,(j-1)] = mean(xm_model[,j])
}
}
}
hatcoeffM = matrix(0,length(qx), dim(xM_model)[2])
hatcoeffm = matrix(0,length(qx), dim(xm_model)[2])
bandwidth_M_temp <- ifelse(is.null(bandwidth_M), 1.5*KernSmooth::dpill(x = time_M_temp, y = as.numeric(yM_temp)), bandwidth_M)
bandwidth_m_temp <- ifelse(is.null(bandwidth_m), 1.5*KernSmooth::dpill(x = time_m_temp, y = as.numeric(ym_temp)), bandwidth_m)
for(i in 1:length(qx))
{
kernel_M = dnorm((time_M_temp - qx[i])/bandwidth_M_temp)
kernel_m = dnorm((time_m_temp - qx[i])/bandwidth_m_temp)
hatcoeffM[i,] = lm(yM ~. , data = data.frame(yM = as.numeric(yM_temp), xM_temp),
weights=kernel_M)$coefficient
hatcoeffm[i,] = lm(ym ~. , data = data.frame(ym = as.numeric(ym_temp), xm_temp),
weights=kernel_m)$coefficient
}
hatcoeff1M = hatcoeffM
hatcoeff1m = hatcoeffm
pred_X1M = t(pred_xM)
pred_X1m = t(pred_xm)
result = list()
eq3 = hatcoeff1M[,1] - hatcoeff1m[,1]
eq4 = diag((hatcoeff1M[,-1] - hatcoeff1m[,-1]) %*% (pred_X1M))
if(detail & !is.null(varying)){
eq5 = diag(hatcoeff1m[,-c(1, varying_idx + 1)]%*%((pred_X1M[-varying_idx,]) - (pred_X1m[-varying_idx,])))
if(length(varying_idx == 1)){
eq6 = diag(hatcoeff1m[,(varying_idx + 1)]%*%t((pred_X1M[varying_idx,]) - (pred_X1m[varying_idx,])))
} else if(length(varying_idx > 1)){
eq6 = diag(hatcoeff1m[,(varying_idx + 1)]%*%((pred_X1M[varying_idx,]) - (pred_X1m[varying_idx,])))
}
} else {
eq5 = diag(hatcoeff1m[,-c(1)]%*%((pred_X1M) - (pred_X1m)))
}
result$Unexplained = eq3 + eq4
result$Explained = eq5
if(detail){
result$Explained_by_Z = eq6
result$All_Disparity = eq3 + eq4 + eq5 + eq6
} else {
result$All_Disparity = eq3 + eq4 + eq5
}
result$time = qx
result$bandwidth_xM_seq = bandwidth_xM_seq
result$bandwidth_xm_seq = bandwidth_xm_seq
result$bandwidth_M = bandwidth_M_temp
result$bandwidth_m = bandwidth_m_temp
res_list$result = result
res_list$yM = yM
res_list$ym = ym
res_list$xM = xM
res_list$xm = xm
res_list$time_M = time_M
res_list$time_m = time_m
res_list$qx = qx
res_list$varying = varying
res_list$bandwidth_m = bandwidth_m
res_list$bandwidth_M = bandwidth_M
res_list$bandwidth_xm = bandwidth_xm
res_list$bandwidth_xM = bandwidth_xM
res_list$hatcoeff1m = hatcoeff1m
res_list$pred_X1M = pred_X1M
res_list$pred_X1m = pred_X1m
res_list$subjectid_M = subjectid_M
res_list$subjectid_m = subjectid_m
res_list$names = colnames(xM_model)
res_list
}
#' Peters-Belson Disparity Analysis
#'
#' Function \code{pb} offers Peters-Belson(PB) type of regression method which gets the disparity between a majority group
#' and a minority group based on various regression models.
#' @param formula a formula for the model.
#' @param group a vector within the \code{data} which is used for separating majority and minority groups.
#' @param data a data frame and data has to be included with the form of \code{data.frame}.
#' @param family a character indicating which model should be used. Details can be found later.
#' @return \code{pb} returns an object of class \code{"pb"}, which is a list containing
#' following components:
#' @return
#' \item{call}{a matched call.}
#' \item{overall_disparity}{overall disparity between major and minor groups.}
#' \item{explained_disparity}{explained disparity between major and minor groups.}
#' \item{unexplained_disparity}{unexplained disparity between major and minor groups.}
#' \item{major}{a majority group label.}
#' \item{minor}{a minority group label.}
#' @export
pb <-function(formula, group, data, family="gaussian")
{
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "group", "data"), names(mf), 0)
mf <- mf[c(1, m)]
mf$drop.unused.levels <- TRUE
mf$na.action <- na.pass
mf[[1]] <- quote(model.frame)
names(mf)[2] <- "formula"
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
group <- model.extract(mf, "group")
disparity.var <- colnames(group)
disparity.group <- levels(as.factor(model.extract(mf, "group")))
major <- disparity.group[1]
minor <- disparity.group[2]
yM <- model.response(mf, "numeric")[group == disparity.group[1]]
xM <- model.matrix(mt, mf, contrasts.arg = NULL, xlev = NULL)[group == disparity.group[1],]
ym <- model.response(mf, "numeric")[group == disparity.group[2]]
xm <- model.matrix(mt, mf, contrasts.arg = NULL, xlev = NULL)[group == disparity.group[2],]
completeM <- complete.cases(xM) & complete.cases(yM)
completem <- complete.cases(xm) & complete.cases(ym)
if(sum(!completeM) > 0 | sum(!completem) > 0){
xM <- xM[completeM,]
xm <- xm[completem,]
yM <- yM[completeM]
ym <- ym[completem]
warning("The data is not complete, the missing observations are ignored.")
}
xM <- xM[,-1]
xm <- xm[,-1]
fitted <- pb.fit(yM = yM, xM = xM, ym = ym, xm = xm, var.equal = T)
res <- list(
call = cl,
overall_disparity = drop(fitted$all_disparity),
explained_disparity = drop(fitted$explained),
unexplained_disparity = drop(fitted$unexplained),
major = major,
minor = minor
)
class(res) = "pb"
res
}
#' @method print pb
#' @export
print.pb <- function(x, digits = max(3, getOption("digits") - 3), ...){
cat("\nCall:\n")
print(x$call)
cat("\nGroup variable:\n\n")
cat("Major:", x$major,"\n")
cat("Minor:", x$minor,"\n")
cat("\n Overall Disparity: ")
cat(round(x$overall_disparity, digits = digits))
cat("\n Explained Disparity: ")
cat(round(x$explained_disparity, digits = digits))
cat("\nUnexplained Disparity: ")
cat(round(x$unexplained_disparity, digits = digits))
cat("\n\n")
}
pb.fit <- function(yM, xM, ym, xm, var.equal = T){
Mfit.coef <- lm(yM ~ xM)$coefficients
mfit.coef <- lm(ym ~ xm)$coefficients
if(!is.matrix(xM) | !is.matrix(xm)){
xM <- as.matrix(xM)
xm <- as.matrix(xm)
}
if(dim(xM)[2] > 1){
bar.xM <- colMeans(xM)
bar.xm <- colMeans(xm)
} else {
bar.xM <- mean(xM)
bar.xm <- mean(xm)
}
explained <- cbind(1, (bar.xM - bar.xm)) %*% Mfit.coef
unexplained <- cbind(1, bar.xm) %*% (Mfit.coef - mfit.coef)
all_disparity <- explained + unexplained
res = list(
all_disparity = all_disparity,
explained = explained,
unexplained = unexplained
)
res
}
|
/scratch/gouwar.j/cran-all/cranData/vcPB/R/vcPB.R
|
Genind <- function(ind) {
ind_series <- c()
for (i in 1:dim(ind)[1]) {
ind_series <- c(ind_series, ind[i, 1]:ind[i, 2])
}
return(ind_series)
}
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
MultiGenpSeudoSample <- function(p, T, X, t_start, t_end) {
tSam <- stats::rgeom(T, p) + 1
subnum <- dim(X)[1] / T
GeoSam <- tSam[1:which.min(cumsum(tSam) <= (t_end - t_start))]
I_series <- sample(t_end:t_start, length(GeoSam), replace = T)
ind <- cbind(I_series, I_series + GeoSam - 1)
Y <- c()
Z <- rbind(X, X)
for (i in 1:subnum) {
Z1 <- Z[Genind(ind) + (i - 1) * T, ]
Y <- rbind(Y, Z1[1:(t_end - t_start), ])
}
return(Y)
}
MultiSeudoInd <- function(seudo, t, start, end, subnum) {
sam <- c()
for (i in 1:subnum) {
sam <- rbind(sam, seudo[(start + (i - 1) * t):(end - 1 + (i - 1) * t), ])
}
return(sam[, -1])
}
Multi_CDR_NewTestPoint <- function(t_point, t_start, t_end, X, delta, CDR, trunc_tree, family_set, p, N, sig_alpha) {
T <- length(unique(X[, 1]))
subnum <- dim(X)[1] / T
p_X = dim(X)[2] - 1
seudo_BIC <- dis_cut_BIC <- c()
family_set <- unlist(family_set)
if (CDR == "R") {
BIC0 <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC
test_BIC <- BIC0 - (RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
#pb <- utils::txtProgressBar(style = 3)
for (i in 1:N) {
#utils::setTxtProgressBar(pb, i / N)
seudo <- MultiGenpSeudoSample(p, T, X, t_start, t_end)
t <- t_end - t_start
seudo_BIC[i] <- RVineStructureSelect(MultiSeudoInd(seudo, t, 1, t_point - t_start + 1, subnum),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiSeudoInd(seudo, t, (t_point - t_start + 1), (t_end - t_start + 1), subnum),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC
seudo_BIC0 <- RVineStructureSelect(MultiSeudoInd(seudo, t, 1, t_end - t_start + 1, subnum),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC
dis_cut_BIC[i] <- seudo_BIC0 - seudo_BIC[i]
}
#close(pb)
} else {
if (CDR == "C") {
BIC0 <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC
test_BIC <- BIC0 - (RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
#pb <- utils::txtProgressBar(style = 3)
for (i in 1:N) {
#utils::setTxtProgressBar(pb, i / N)
seudo <- MultiGenpSeudoSample(p, T, X, t_start, t_end)
t <- t_end - t_start
seudo_BIC[i] <- RVineStructureSelect(MultiSeudoInd(seudo, t, 1, t_point - t_start + 1, subnum),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiSeudoInd(seudo, t, (t_point - t_start + 1), (t_end - t_start + 1), subnum),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC
seudo_BIC0 <- RVineStructureSelect(MultiSeudoInd(seudo, t, 1, t_end - t_start + 1, subnum),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC
dis_cut_BIC[i] <- seudo_BIC0 - seudo_BIC[i]
}
#close(pb)
} else {
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
test_BIC <- RVineCopSelect(MultiInd(X, t_start, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiInd(X, t_start, t_point), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiInd(X, t_point, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
for (i in 1:N) {
seudo <- MultiGenpSeudoSample(p, T, X, t_start, t_end)
t <- t_end - t_start
dis_cut_BIC[i] <- RVineCopSelect(MultiSeudoInd(seudo, t, 1, t_end - t_start + 1, subnum),
selectioncrit = "BIC",method = "mle",
Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiSeudoInd(seudo, t, (t_point - t_start + 1), (t_end - t_start + 1), subnum),
selectioncrit = "BIC",method = "mle",
Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiSeudoInd(seudo, t, (t_point - t_start + 1), (t_end - t_start + 1), subnum),
selectioncrit = "BIC",method = "mle",
Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
}
}
}
return(c(test_BIC, stats::quantile(dis_cut_BIC, sig_alpha), stats::quantile(dis_cut_BIC, 1 - sig_alpha)))
}
TestPoints.Boot <- function(v_t_point, X_raw, delta, CDR = "D", trunc_tree = NA, family_set = 1,
pre_white = 0, ar_num = 1, p = 0.3, N = 100, sig_alpha = 0.05) {
T <- length(unique(X_raw[, 1]))
subnum <- dim(X_raw)[1] / T
X <- X_raw
v_t_point = sort(v_t_point)
if(sum(c(v_t_point,T)-c(0,v_t_point)<dim(X_raw)[2]-1)>0) stop("Some candidates are too close to each other or to the boundary (distance < p)")
if (pre_white == 1) {
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i - 1) * T + 1):(i * T), -1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid) == TRUE)] <- 0
X[((i - 1) * T + 1):(i * T), -1] <- ar_resid
}
}
X[, -1] <- VineCopula::pobs(X[, -1])
test_result <- as.data.frame(matrix(0, length(v_t_point), 5))
if (length(v_t_point) == 0) {
return(test_result)
} else {
test_result[, 1] <- v_t_point
a <- c(1, v_t_point, T + 1)
full_point <- a[!duplicated(a)]
message("Perform stationary bootstrap test on candidates...")
for (i in 1:length(v_t_point)) {
test_result[i, 2:4] <- Multi_CDR_NewTestPoint(
full_point[i + 1], full_point[i],
full_point[i + 2], X, delta, CDR, trunc_tree, family_set, p, N, sig_alpha
)
if (test_result[i, 2] > test_result[i, 4]) {
test_result[i, 5] <- "significant"
} else {
test_result[i, 5] <- "not significant"
}
}
names(test_result) <- c("t", "reduced BIC", "Lower_CI", "Upper_CI", "judgement")
return(test_result)
}
}
GetTestPlot.Boot <- function(test_result, T) {
if (dim(test_result)[1] == 0) {
graphics::plot(1:T,1:T,type = "n",yaxt="n",ylab = NA)
graphics::text("No candidate is found.")
}
else {
reduced_BIC <- lwr <- upr <- rep(0, T)
reduced_BIC[test_result[, 1]] <- test_result[, 2]
plot(1:T, reduced_BIC,
type = "h",
ylim = c(min(test_result[, 2:4]) - 3, max(test_result[, 2:4] + 10, 0)), lwd = 2
)
graphics::points(test_result[, 1], test_result[, 4], pch = 20, col = "red")
graphics::points(test_result[, 1], test_result[, 3], pch = 20, col = "red")
if (sum(test_result[, 5] == "significant") != 0) {
graphics::text(test_result[test_result[, 5] == "significant", 1], test_result[test_result[, 5] == "significant", 2] + 5,
labels = test_result[test_result[, 5] == "significant", 1], cex = 0.8
)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/BootsTest.R
|
VC_MOSUM <- function(X_raw, delta, G = 0.1, test = "V", CDR = "D", trunc_tree = NA,
family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
if (test == "V") {
infer <- VC_MOSUM_Vuong(
X_raw, delta, G, CDR, trunc_tree,
family_set, pre_white, ar_num,
sig_alpha
)
return(infer)
} else {
if (test == "B") {
infer <- VC_MOSUM_Boot(
X_raw, delta, G, CDR,
trunc_tree, family_set,
pre_white, ar_num, p, N, sig_alpha
)
return(infer)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/MOSUM_VC.R
|
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
MultiGenXLocal <- function(X_raw, delta, CDR, trunc_tree, family_set, pre_white, ar_num) {
T <- length(unique(X_raw[, 1]))
subnum <- dim(X_raw)[1] / T
cut_point0 <- c(1, T + 1)
p_X = dim(X_raw)[2] - 1
X <- X_raw
if (pre_white == 1) {
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i - 1) * T + 1):(i * T), -1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid) == TRUE)] <- 0
X[((i - 1) * T + 1):(i * T), -1] <- ar_resid
}
}
X[, -1] <- VineCopula::pobs(X[, -1])
BIC_de <- rep(0, T)
family_set <- unlist(family_set)
for (i in (delta + 1):(T - delta - 1)) {
if (CDR == "R") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, (i - delta), (i + delta)),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, (i - delta), i),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, i, (i + delta)),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
# print(c(BIC_de[i],i))
} else {
if (CDR == "C") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, (i - delta), (i + delta)),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, (i - delta), i),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, i, (i + delta)),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
# print(c(BIC_de[i],i))
} else {
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
BIC_de[i] <- RVineCopSelect(MultiInd(X, (i - delta), (i + delta)), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiInd(X, (i - delta), i), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiInd(X, i, (i + delta)), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
# print(c(BIC_de[i],i))
}
}
}
return(list(BIC_de, X))
}
FindLocalMax <- function(BIC_re, range_set) {
local_max <- c()
k <- 1
for (i in 1:(length(range_set) - 1)) {
t_start <- range_set[i]
t_end <- range_set[i + 1]
if (max(BIC_re[t_start:(t_end - 1)]) > 0) {
local_max[k] <- which.max(BIC_re[t_start:t_end]) + t_start - 1
k <- k + 1
}
}
return(local_max)
}
VC_MOSUM_Boot <- function(X_raw, delta, G = 0.1, CDR = "D", trunc_tree = NA, family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
message("MOSUM search ...")
re <- MultiGenXLocal(X_raw, delta, CDR, trunc_tree, family_set, pre_white, ar_num)
T <- length(unique(X_raw[, 1]))
BIC_re <- re[[1]]
te <- mosum::mosum(BIC_re, G)
graphics::plot(te, display = "data", sub = "MOSUM segmentation")
a <- sort(c(1, T + 1, te$cpts))
ini_po <- a[!duplicated(a)]
points0 <- FindLocalMax(BIC_re, ini_po)
if (length(points0) == 0) {
message("No candidate is found.")
return(matrix(0, 0, 5))
} else {
if (length(points0) == 1) {
tema_NRVBS <- TestPoints.Boot(
points0, X_raw, delta, CDR, trunc_tree, family_set,
pre_white, ar_num, p, N, sig_alpha
)
return(tema_NRVBS)
} else {
points_new <- points <- points0[order(-BIC_re[points0])]
j <- 1
while (j <= length(points_new)) {
d_p <- abs(points_new[j] - points_new)
points_new <- points_new[d_p >= delta | d_p == 0]
j <- j + 1
}
points_new <- unique(sort(points_new))
tema_NRVBS <- TestPoints.Boot(
points_new, X_raw, delta, CDR, trunc_tree, family_set,
pre_white, ar_num, p, N, sig_alpha
)
return(tema_NRVBS)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/MOSUM_VC_Boot.R
|
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
VuongMultiGenXLocal <- function(X_raw, delta, CDR, trunc_tree, family_set, pre_white, ar_num) {
T <- length(unique(X_raw[, 1]))
subnum <- dim(X_raw)[1] / T
cut_point0 <- c(1, T + 1)
p_X = dim(X_raw)[2] - 1
X <- X_raw
if (pre_white == 1) {
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i - 1) * T + 1):(i * T), -1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid) == TRUE)] <- 0
X[((i - 1) * T + 1):(i * T), -1] <- ar_resid
}
}
X[, -1] <- VineCopula::pobs(X[, -1])
BIC_de <- rep(0, T)
family_set <- unlist(family_set)
for (i in (delta + 1):(T - delta - 1)) {
if (CDR == "R") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, (i - delta), (i + delta)),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, (i - delta), i),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, i, (i + delta)),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
# print(c(BIC_de[i],i))
} else {
if (CDR == "C") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, (i - delta), (i + delta)),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, (i - delta), i),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, i, (i + delta)),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
# print(c(BIC_de[i],i))
} else {
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
BIC_de[i] <- RVineCopSelect(MultiInd(X, (i - delta), (i + delta)), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiInd(X, (i - delta), i), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiInd(X, i, (i + delta)), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
# print(c(BIC_de[i],i))
}
}
}
return(list(BIC_de, X))
}
FindLocalMax <- function(BIC_re, range_set) {
local_max <- c()
k <- 1
for (i in 1:(length(range_set) - 1)) {
t_start <- range_set[i]
t_end <- range_set[i + 1]
if (max(BIC_re[t_start:(t_end - 1)]) > 0) {
local_max[k] <- which.max(BIC_re[t_start:t_end]) + t_start - 1
k <- k + 1
}
}
return(local_max)
}
VC_MOSUM_Vuong <- function(X_raw, delta, G = 0.1, CDR = "D", trunc_tree = NA, family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
message("MOSUM search ...")
re <- VuongMultiGenXLocal(X_raw, delta, CDR, trunc_tree, family_set, pre_white, ar_num)
X <- re[[2]]
T <- length(unique(X_raw[, 1]))
BIC_re <- re[[1]]
te <- mosum::mosum(BIC_re, G)
graphics::plot(te, display = "data", sub = "MOSUM segmentation")
a <- sort(c(1, T + 1, te$cpts))
ini_po <- a[!duplicated(a)]
points0 <- FindLocalMax(BIC_re, ini_po)
if (length(points0) == 0) {
message("No candidate is found.")
return(matrix(0, 0, 4))
} else {
if (length(points0) == 1) {
tema_NRVBS <- TestPoints.Vuong(
points0, X_raw, delta, CDR, trunc_tree, family_set,
pre_white, ar_num, sig_alpha
)
return(tema_NRVBS)
} else {
points_new <- points <- points0[order(-BIC_re[points0])]
j <- 1
while (j <= length(points_new)) {
d_p <- abs(points_new[j] - points_new)
points_new <- points_new[d_p >= delta | d_p == 0]
j <- j + 1
}
points_new <- unique(sort(points_new))
tema_NRVBS <- TestPoints.Vuong(
points_new, X_raw, delta, CDR, trunc_tree, family_set,
pre_white, ar_num, sig_alpha
)
return(tema_NRVBS)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/MOSUM_VC_Vuong.R
|
MultiInd <- function(X, start, end) {
T <- length(unique(X[, 1]))
subnum <- dim(X)[1] / T
sam <- c()
for (i in 1:subnum) {
sam <- rbind(sam, X[(start + (i - 1) * T):(end - 1 + (i - 1) * T), ])
}
return(sam[, -1])
}
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
VC.NBS.FindPoints <- function(X_raw, delta, CDR = "D", trunc_tree = NA, family_set = 1, pre_white = 0, ar_num = 1) {
T <- length(unique(X_raw[, 1]))
subnum <- dim(X_raw)[1] / T
cut_point0 <- c(1, T + 1)
BIC_cut <- 1
k <- 0
X <- X_raw
p_X = dim(X_raw)[2] - 1
if (pre_white == 1) {
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i - 1) * T + 1):(i * T), -1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid) == TRUE)] <- 0
X[((i - 1) * T + 1):(i * T), -1] <- ar_resid
}
}
X[, -1] <- VineCopula::pobs(X[, -1])
while (BIC_cut > 0) {
k <- k + 1
message(paste("Binary search, round",k,"..."))
BIC_de <- rep(0, T)
for (i in delta:(T - delta)) {
if (sum(is.element((i - delta + 1):(i + delta), cut_point0)) != 0) {
next
} else {
t_point <- i
t_start <- cut_point0[which.max(i <= cut_point0) - 1]
t_end <- cut_point0[which.max(i <= cut_point0)]
if (CDR == "R") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
print(c(BIC_de[i], i))
} else {
if (CDR == "C") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
#print(c(BIC_de[i], i))
} else {
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
BIC_de[i] <- RVineCopSelect(MultiInd(X, t_start, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiInd(X, t_start, t_point), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiInd(X, t_point, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
#print(c(BIC_de[i], i))
}
}
}
}
BIC_cut <- max(BIC_de)
cut_new_point <- which.max(BIC_de)
# if(BIC_cut > 0){
# message(paste("Find candidate",k,": t =",cut_new_point))
# }else{
# message(paste("No more candidate is found. \n \n"),fill = TRUE)
# }
cut_point0 <- sort(c(cut_point0, cut_new_point))
}
return(c(cut_point0[cut_point0 != cut_new_point & cut_point0 != T + 1 & cut_point0 != 1]))
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/NBS_FindPoints.R
|
VC_NBS <- function(X_raw, delta, test = "V", CDR = "D", trunc_tree = NA,
family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
result = VC.NBS.FindPoints(X_raw, delta, CDR, trunc_tree, family_set,
pre_white, ar_num)
if(test=="V"){
infer = TestPoints.Vuong(result, X_raw, delta, CDR,
trunc_tree, family_set,
pre_white, ar_num, sig_alpha)
return(infer)
}else{
if(test=="B"){
infer = TestPoints.Boot(result, X_raw, delta, CDR,
trunc_tree, family_set,
pre_white, ar_num, p, N, sig_alpha)
return(infer)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/NBS_VC.R
|
VC_OBS <- function(X_raw, delta, test = "V", CDR = "D", trunc_tree = NA,
family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
if(test=="V"){
infer = VC_OBS_Vuong(X_raw, delta, CDR, trunc_tree,
family_set, pre_white, ar_num,
sig_alpha)
return(infer)
}else{
if(test=="B"){
infer = VC_OBS_Boot(X_raw, delta, CDR,
trunc_tree, family_set,
pre_white, ar_num, p, N, sig_alpha)
return(infer)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/OBS_VC.R
|
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
VC_OBS_Boot <- function(X_raw, delta, CDR = "D", trunc_tree = NA, family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
T <- length(unique(X_raw[, 1]))
subnum <- dim(X_raw)[1] / T
cut_point0 <- c(1, T + 1)
p_X = dim(X_raw)[2] - 1
BIC_cut <- 1
k <- 0
X <- X_raw
if (pre_white == 1) {
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i - 1) * T + 1):(i * T), -1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid) == TRUE)] <- 0
X[((i - 1) * T + 1):(i * T), -1] <- ar_resid
}
}
X[, -1] <- VineCopula::pobs(X[, -1])
TestMatrix <- as.data.frame(matrix(0, 1, 5))
names(TestMatrix) <- c("t", "reduced BIC", "Lower_CI", "Upper_CI", "judgement")
while (BIC_cut > 0) {
k <- k + 1
message(paste("Binary search + stationary bootstrap test for round",k,"..."))
BIC_de <- rep(0, T)
for (i in delta:(T - delta)) {
if (sum(is.element((i - delta + 1):(i + delta), cut_point0)) != 0) {
next
} else {
t_point <- i
t_start <- cut_point0[which.max(i <= cut_point0) - 1]
t_end <- cut_point0[which.max(i <= cut_point0)]
if (CDR == "R") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
} else {
if (CDR == "C") {
BIC_de[i] <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC -
(RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)$BIC)
} else {
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
BIC_de[i] <- RVineCopSelect(MultiInd(X, t_start, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiInd(X, t_start, t_point), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiInd(X, t_point, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
}
}
}
}
BIC_cut <- max(BIC_de)
if (BIC_cut > 0) {
cut_new_point <- which.max(BIC_de)
#message(paste("Perform stationary bootstrap test on candidate", k, ": t =", cut_new_point))
t_before <- cut_point0[which.max(cut_new_point <= cut_point0) - 1]
t_after <- cut_point0[which.max(cut_new_point <= cut_point0)]
testPoint <- Multi_CDR_NewTestPoint(cut_new_point, t_before, t_after, X, delta, CDR, trunc_tree, family_set, p, N, sig_alpha)
if (testPoint[1] >= testPoint[3]) {
cut_point0 <- sort(c(cut_point0, cut_new_point))
TestMatrix <- rbind(TestMatrix, c(cut_new_point, testPoint, "significant"))
TestMatrix[, 1] <- as.numeric(TestMatrix[, 1])
TestMatrix[, 2] <- as.numeric(TestMatrix[, 2])
TestMatrix[, 3] <- as.numeric(TestMatrix[, 3])
TestMatrix[, 4] <- as.numeric(TestMatrix[, 4])
} else {
TestMatrix <- rbind(TestMatrix, c(cut_new_point, testPoint, "not significant"))
TestMatrix[, 1] <- as.numeric(TestMatrix[, 1])
TestMatrix[, 2] <- as.numeric(TestMatrix[, 2])
TestMatrix[, 3] <- as.numeric(TestMatrix[, 3])
TestMatrix[, 4] <- as.numeric(TestMatrix[, 4])
return(TestMatrix[-1, ])
}
} else {
return(TestMatrix[-1, ])
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/OBS_VC_Boot.R
|
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
VC_OBS_Vuong <- function(X_raw, delta, CDR = "D", trunc_tree = NA, family_set = 1, pre_white = 0, ar_num = 1,
sig_alpha = 0.05) {
T <- length(unique(X_raw[,1]))
subnum <- dim(X_raw)[1]/T
p_X = dim(X_raw)[2] - 1
X <- X_raw
if (pre_white == 1) {
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i - 1) * T + 1):(i * T), -1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid) == TRUE)] <- 0
X[((i - 1) * T + 1):(i * T), -1] <- ar_resid
}
}
X[, -1] <- VineCopula::pobs(X[, -1])
cut_point0 <- c(1, T+1)
BIC_cut <- 1
k=0
TestMatrix <- as.data.frame(matrix(0, 1, 4))
names(TestMatrix) <- c("t", "left Schwarz p", "right Schwarz p", "judgement")
while (BIC_cut > 0) {
k=k+1
message(paste("Binary search + Vuong test for round",k,"..."))
BIC_de <- rep(0, T)
for (i in delta:(T-delta)) {
if(sum(is.element((i-delta+1):(i+delta) , cut_point0)) != 0){
next
}else{
t_point <- i
t_start <- cut_point0[which.max(i <= cut_point0) - 1]
t_end <- cut_point0[which.max(i <= cut_point0)]
if(CDR=="R"){
BIC_de[i] <- RVineStructureSelect(MultiInd(X,t_start,t_end),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
( RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = unlist(family_set),
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC )
}else{
if(CDR=="C"){
BIC_de[i] <- RVineStructureSelect(MultiInd(X,t_start,t_end),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
( RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = unlist(family_set), type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC )
}else{
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
BIC_de[i] <- RVineCopSelect(MultiInd(X, t_start, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiInd(X, t_start, t_point), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiInd(X, t_point, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
}
}
}
}
BIC_cut <- max(BIC_de)
if(BIC_cut > 0){
cut_new_point <- which.max(BIC_de)
#cat(paste("Test for candidate", k, ": t =", cut_new_point), fill = TRUE)
t_before <- cut_point0[which.max(cut_new_point <= cut_point0) - 1]
t_after <- cut_point0[which.max(cut_new_point <= cut_point0)]
testPoint <- Vuong_Multi_CDR_NewTestPoint(cut_new_point, t_before, t_after, X, delta, CDR, trunc_tree, family_set)
#print(testPoint)
if(testPoint[1] < 0 & abs(testPoint[1]) < sig_alpha &
testPoint[2] < 0 & abs(testPoint[2]) < sig_alpha
){
cut_point0 <- sort(c(cut_point0, cut_new_point))
TestMatrix <- rbind(TestMatrix, c(cut_new_point, testPoint, "significant"))
TestMatrix[,1] <- as.numeric(TestMatrix[,1])
TestMatrix[,2] <- as.numeric(TestMatrix[,2])
TestMatrix[,3] <- as.numeric(TestMatrix[,3])
}else{
TestMatrix <- rbind(TestMatrix, c(cut_new_point, testPoint, "not significant"))
TestMatrix[,1] <- as.numeric(TestMatrix[,1])
TestMatrix[,2] <- as.numeric(TestMatrix[,2])
TestMatrix[,3] <- as.numeric(TestMatrix[,3])
return(TestMatrix[-1,])
}
}else{
return(TestMatrix[-1,])
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/OBS_VC_Vuong.R
|
#' Simulate multivariate normal data with 2 change points
#'
#' This function simulates a multivariate normal data set with 2
#' change points in the network structure.
#'
#' @param nobs A positive integer, which defines the length of the time series.
#' It must be a multiple of 3 since change points occur at time points T/3
#' and 2T/3.
#'
#' @param n_ser A positive integer number indicating the dimensionality of the
#' time series. \code{n_ser} must be equal to or larger than 8 as \code{mvn.sim.2.cps}
#' generates 3 different network structures among 8 connected nodes. The remaining
#' variables are generated as independent data.
#'
#' @param seed A positive integer with default value equal to 101.
#' It is used to ensure reproducibility.
#'
#'
#' @return A \code{nobs} * \code{n_ser} matrix with 2 change points
#' at time points \code{nobs/3+1} and \code{nobs*2/3+1}.
#'
#' @export
#' @examples
#' ## Simulate MVN data with 2 change points
#' data <- mvn.sim.2.cps(180, 8, seed = 101)
mvn.sim.2.cps <- function(nobs, n_ser, seed = 101) {
data <- c()
nobs <- nobs / 3
ppp_11 <- 1
qqq_11 <- 3
rrr_11 <- 5
sss_11 <- 7
ttt_11 <- 8
qqq_12 <- 2
sss_12 <- 6
ttt_12 <- 3
qqq_21 <- 1
rrr_21 <- 4
sss_21 <- 5
ttt_21 <- 7
uuu_21 <- 3
qqq_31 <- 2
rrr_31 <- 3
sss_31 <- 4
ttt_31 <- 6
uuu_31 <- 1
www_31 <- 5
sss_32 <- 1
ttt_32 <- 7 # negatively correlated
# =============================================================================
# 1st Section
set.seed(nobs * seed + 1)
burn_in <- 100
sigma.1 <- array(c(
1, 0.69, 0.67, 0.76, 0.77, 0.69, 1, 0.64, 0.66, 0.69, 0.67, 0.64, 1,
0.7, 0.72, 0.76, 0.66, 0.7, 1, 0.72, 0.77, 0.69, 0.72, 0.72, 1
), c(5, 5))
data.1 <- mvtnorm::rmvnorm(nobs + burn_in, sigma = sigma.1)
data.1 <- data.1[(burn_in + 1):(nobs + burn_in), ]
set.seed(nobs * seed + 10001)
burn_in <- 100
sigma.2 <- array(c(1, 0.7, 0.65, 0.7, 1, 0.71, 0.65, 0.71, 1), c(3, 3))
data.2 <- mvtnorm::rmvnorm(nobs + burn_in, sigma = sigma.2)
data.2 <- data.2[(burn_in + 1):(nobs + burn_in), ]
t <- n_ser # number of noise series
data_1_used <- c()
for (i in 1:t) {
set.seed(nobs * 1 + 2 * i * 10001 + i + seed)
data_1_used <- cbind(data_1_used, stats::rnorm(nobs))
}
data_1_used[, ppp_11] <- data.1[, 1]
data_1_used[, qqq_11] <- data.1[, 2]
data_1_used[, rrr_11] <- data.1[, 3]
data_1_used[, sss_11] <- data.1[, 4]
data_1_used[, ttt_11] <- data.1[, 5]
data_1_used[, qqq_12] <- data.2[, 1]
data_1_used[, sss_12] <- data.2[, 2]
data_1_used[, ttt_12] <- data.2[, 3]
# =============================================================================
# 2nd Section
set.seed(nobs * seed + 3 * 10001)
burn_in <- 100
sigma.1 <- array(c(
1, 0.70, 0.695, 0.73, 0.67, 0.70, 1, 0.68, 0.66, 0.69, 0.695, 0.68, 1,
0.7, 0.72, 0.73, 0.66, 0.7, 1, 0.75, 0.67, 0.69, 0.72, 0.75, 1
), c(5, 5))
data.1 <- mvtnorm::rmvnorm(nobs + burn_in, sigma = sigma.1)
data.1 <- data.1[(burn_in + 1):(nobs + burn_in), ]
t <- n_ser # number of noise series
data_2_used <- c()
for (i in 1:t) {
set.seed(nobs * seed + 5 * i * 10001 + i)
data_2_used <- cbind(data_2_used, stats::rnorm(nobs))
}
data_2_used[, qqq_21] <- data.1[, 1]
data_2_used[, rrr_21] <- data.1[, 2]
data_2_used[, sss_21] <- data.1[, 3]
data_2_used[, ttt_21] <- data.1[, 4]
data_2_used[, uuu_21] <- data.1[, 5]
# =============================================================================
# 3rd Section
set.seed(nobs * seed + 6 * 10001)
burn_in <- 100
sigma.1 <- array(c(
1, 0.81, 0.65, 0.76, 0.68, 0.73, 0.81, 1, 0.68, 0.767, 0.69, 0.69, 0.65,
0.68, 1, 0.7, 0.72, 0.71, 0.76, 0.767, 0.7, 1, 0.75, 0.68, 0.68, 0.69, 0.72,
0.75, 1, 0.77, 0.73, 0.69, 0.71, 0.68, 0.77, 1
), c(6, 6))
data.1 <- mvtnorm::rmvnorm(nobs + burn_in, sigma = sigma.1)
data.1 <- data.1[(burn_in + 1):(nobs + burn_in), ]
set.seed(nobs * seed + 8 * 10001)
burn_in <- 100
data.2 <- mvtnorm::rmvnorm(nobs + burn_in, sigma = array(c(1, -.8, -.8, 1), c(2, 2)))
data.2 <- data.2[(burn_in + 1):(nobs + burn_in), ]
t <- n_ser # number of noise series
data_3_used <- c()
for (i in 1:t) {
set.seed(nobs * seed + 10 * i * 10001 + i)
data_3_used <- cbind(data_3_used, stats::rnorm(nobs))
}
data_3_used[, qqq_31] <- data.1[, 1]
data_3_used[, rrr_31] <- data.1[, 2]
data_3_used[, sss_31] <- data.1[, 3]
data_3_used[, ttt_31] <- data.1[, 4]
data_3_used[, uuu_31] <- data.1[, 5]
data_3_used[, www_31] <- data.1[, 6]
data_3_used[, sss_32] <- data.2[, 1]
data_3_used[, ttt_32] <- data.2[, 2]
# Combine three data sets
data <- rbind(data_1_used, data_2_used, data_3_used)
return(data)
}
# =============================================================================
# =============================================================================
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/Sim_Data.R
|
#' Multiple change point detection in the vine copula structure of multivariate time series
#'
#' This function detects multiple change points in the vine
#' copula structure of a multivariate time series using
#' vine copulas, various state-of-the-art segmentation methods to identify
#' multiple change points, and a likelihood ratio test or the stationary bootstrap
#' for inference.
#'
#' The time series \code{X_t} is of dimensionality p and we are
#' looking for changes in the vine copula structure between
#' the different time series components \code{X_{t}^{(1)}, X_{t}^{(2)},
#' ..., X_{t}^{(p)}}. VCCP uses vine copulas, various state-of-the-art
#' segmentation methods to identify multiple change points,
#' and a likelihood ratio test or the stationary bootstrap for inference.
#'
#' @param X A numerical matrix representing the multivariate
#' time series, with the columns representing its components.
#' If multiple subjects are included (panel data), vertically
#' stack the subject data and identify timestamps of each subject in the first column.
#'
#' @param method A character string, which defines the
#' segmentation method. If \code{method} = "NBS", which is the
#' default method, then the adapted binary segmentation is used.
#' Similarly, if \code{method} = "OBS", "MOSUM" or "WBS", then binary
#' segmentation, MOSUM and wild binary segmentation are used, respectively.
#'
#' @param delta A positive integer number with default value equal to 30.
#' It is used to define the minimum distance acceptable between
#' change points. In general, \code{delta} >= 5*ncol(X))
#' is recommended to ensure sufficient data when estimating the
#' vine copula model.
#'
#' @param G A positive real number between 0 and 1 with default value equal to 0.1.
#' It is used to define the moving sum bandwidth relative to \code{T} in MOSUM when
#' \code{method} = "MOSUM" is chosen. Alternatively, a positive integer
#' less than half of the time series length can be set to define the absolute bandwidth.
#'
#' @param M A positive integer with default value equal to floor(9*log(T)) (T is the length of the time series).
#' It represents the number of sub-samples in WBS when
#' \code{method} = "WBS" is chosen.
#'
#' @param test A character string, which defines the inference
#' method used. If \code{test} = "V", which is the default method,
#' the Vuong test is performed. If \code{test} = "B", the
#' stationary bootstrap is performed.
#'
#' @param CDR A character string, which defines the vine structure.
#' If \code{CDR} = "D", which is the default method,
#' a D-vine is used. Similarly, if \code{CDR} = "C" or \code{CDR}
#' = "R", a C-vine or an R-vine is used, respectively.
#'
#' @param trunc_tree A positive integer, which defines the level
#' of truncation for the vine copula. If \code{trunc_tree} = "NA",
#' which is the default value, the Vine contains \code{dim(X)[2]-2}
#' levels of trees.
#'
#' @param family_set A positive integer, which defines the bivariate copula
#' family. If \code{familyset} = 1, which is the default value, only the
#' Gauss copula is selected and VCCP detects change points in
#' the linear correlation graph. Coding of pair-copula
#' families is the same as in \code{\link[VineCopula]{BiCop}}.
#'
#' @param pre_white A positive integer, which defines whether
#' the data is pre-whitened. If \code{pre-white} = 0, which is the
#' default value, no pre-whitening is performed. If
#' \code{pre_white} = 1, an autoregressive time series model
#' (method: yule-walker) is used to preprocess the raw data.
#'
#' @param ar_num A positive integer, which defines the maximum
#' order of model to fit to preprocess the data (see \code{pre_white}).
#' If \code{ar_num} = 1, which is the default value, then an AR(1)
#' model is fit to the data.
#'
#' @param p A positive real number between 0 and 1 which is
#' defined as the block size in the stationary bootstrap
#' method (\code{rgeom(T,p)}) if \code{test} = "B" is chosen.
#' If \code{p} = 0.3, which is the default value, each resampled block
#' has 1/0.3 time points on average.
#'
#' @param N A positive integer, which defines the number
#' of the stationary bootstrap resamples used. The default value is \code{N} = 100.
#'
#' @param sig_alpha A positive real number between 0 and 1, which
#' defines the significance level of the inference test.
#' The default values is 0.05.
#'
#' @return A list with the following components:
#'
#' \tabular{ll}{
#' \code{loc_of_cpts} \tab The locations of the detected change points. \cr
#' \code{no_of_cpts} \tab The number of detected change points. \cr
#' \code{test_df} \tab A dataframe containing the test result. \cr
#' \code{compute_time} \tab Time (in minutes) to run \code{vccp.fun}. \cr
#' \code{T} \tab The length of the time series data. \cr
#' \code{sig_alpha} \tab The significance level for the inference test. \cr
#' }
#'
#'
#' @export
#' @examples
#' \donttest{
#' ## Simulate MVN data with 2 change points
#' data <- cbind(1:180, mvn.sim.2.cps(180, 8, seed = 101))
#' T <- 180
#' ## Change point detection using VCCP (it may take several minutes to complete...)
#' result.NV <- vccp.fun(data, method = "NBS", delta = 30, test = "V")
#' ## Plot the results
#' getTestPlot(result.NV)
#' #title("VCCP: NBS + Vuong")
#'
#' ## Change point detection using NBS and stationary bootstrap for inference
#' result.NB <- vccp.fun(data, method = "NBS", delta = 30, test = "B")
#' ## Plot the results
#' getTestPlot(result.NB)
#' title("VCCP: NBS + Stationary Bootstrap")
#' }
#' @seealso \code{\link{getTestPlot}}
#' @section Author(s):
#' Xin Xiong, Ivor Cribben (\email{cribben@@ualberta.ca})
#' @section References:
#' "Beyond linear dynamic functional connectivity: a vine copula change point model", Xiong and Cribben (2021), bioRxiv 2021.04.25.441254.
vccp.fun <- function(X, method = 'NBS', delta = 30, G = 0.1, M = NA, test = "V", CDR = "D", trunc_tree = NA,
family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
if (method != "NBS" & method != "OBS" & method != "MOSUM" & method != "WBS"){
stop("You can only specify method as 'NBS', 'OBS', 'MOSUM' or 'WBS'!")
}else{
if (CDR != "C" & CDR != "D" & CDR != "R") {
stop("You can only specify CDR as 'C', 'D' or 'R'!")
} else {
if (test != "V" & test != 'B') {
stop("You can only specify test as 'B' or 'V'!")
} else {
re.list = list()
t = proc.time()
result = switch (method,
"NBS" = VC_NBS(X, delta, test, CDR, trunc_tree,
family_set, pre_white, ar_num, p, N, sig_alpha),
"OBS" = VC_OBS(X, delta, test, CDR, trunc_tree,
family_set, pre_white, ar_num, p, N, sig_alpha),
"MOSUM" = VC_MOSUM(X, delta, G, test, CDR, trunc_tree,
family_set, pre_white, ar_num, p, N, sig_alpha),
"WBS" = VC_WBS(X, delta, M, test, CDR, trunc_tree,
family_set, pre_white, ar_num, p, N, sig_alpha))
compute = (proc.time() - t)[3]/60
re.list = list("loc_of_cpts"=result$t,
"no_of_cpts" = length(result$t),
"test_df" = result,
"compute_time" = compute,
"T"=length(unique(X[, 1])),
"sig_alpha"=sig_alpha)
return(re.list)
}
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/VCCP.R
|
#' vccp: Detect multiple change points in the vine copula structure of multivariate time series by Vine Copula Change Point Model
#'
#' The vccp package implements the Vine Copula Change Point (VCCP)
#' methodology for the estimation of the number and location of multiple
#' change points in the vine copula structure of multivariate time series.
#' The method uses vine copulas, various state-of-the-art segmentation methods
#' to identify multiple change points, and a likelihood ratio test or the
#' stationary bootstrap for inference. The vine copulas allow for various forms
#' of dependence between time series including tail, symmetric and asymmetric
#' dependence. The functions have been extensively tested on simulated multivariate
#' time series data and fMRI data. For details on the VCCP methodology, please see
#' Xiong & Cribben (2021).
#'
#' @section vccp functions:
#' \link{mvn.sim.2.cps}, \link{getTestPlot} and \link{vccp.fun}
#' @examples
#' # See examples in the function vccp.fun.
#'
#' @section Author(s):
#' Xin Xiong, Ivor Cribben (\email{cribben@@ualberta.ca})
#' @section References:
#' "Beyond linear dynamic functional connectivity: a vine copula change point model", Xiong and Cribben (2021), bioRxiv 2021.04.25.441254.
#' @docType package
#' @name vccp
NULL
#> NULL
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/VCCP_package.R
|
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
Vuong_Multi_CDR_NewTestPoint <- function(t_point, t_start, t_end, X, delta, CDR, trunc_tree, family_set) {
T <- length(unique(X[, 1]))
subnum <- dim(X)[1] / T
family_set <- unlist(family_set)
p_X = dim(X)[2] - 1
if (CDR == "R") {
RV0 <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)
RV1 <- RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)
RV2 <- RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)
Vuong_test_left <- RVineVuongTest(MultiInd(X, t_start, t_point), RV0, RV1)
Vuong_test_right <- RVineVuongTest(MultiInd(X, t_point, t_end), RV0, RV2)
re <- matrix(c(
sign(Vuong_test_left$statistic.Schwarz) * Vuong_test_left$p.value.Schwarz,
sign(Vuong_test_right$statistic.Schwarz) * Vuong_test_right$p.value.Schwarz
), 1, 2)
colnames(re) <- c("left Schwarz p", "right Schwarz p")
} else {
if (CDR == "C") {
RV0 <- RVineStructureSelect(MultiInd(X, t_start, t_end),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)
RV1 <- RVineStructureSelect(MultiInd(X, t_start, t_point),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)
RV2 <- RVineStructureSelect(MultiInd(X, t_point, t_end),
familyset = family_set, type = 1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree
)
Vuong_test_left <- RVineVuongTest(MultiInd(X, t_start, t_point), RV0, RV1)
Vuong_test_right <- RVineVuongTest(MultiInd(X, t_point, t_end), RV0, RV2)
re <- matrix(c(
sign(Vuong_test_left$statistic.Schwarz) * Vuong_test_left$p.value.Schwarz,
sign(Vuong_test_right$statistic.Schwarz) * Vuong_test_right$p.value.Schwarz
), 1, 2)
colnames(re) <- c("left Schwarz p", "right Schwarz p")
} else {
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
RV0 = RVineCopSelect(MultiInd(X, t_start, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)
RV1 = RVineCopSelect(MultiInd(X, t_start, t_point), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)
RV2 = RVineCopSelect(MultiInd(X, t_point, t_end), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)
Vuong_test_left <- RVineVuongTest(MultiInd(X, t_start, t_point), RV0, RV1)
Vuong_test_right <- RVineVuongTest(MultiInd(X, t_point, t_end), RV0, RV2)
re <- matrix(c(
sign(Vuong_test_left$statistic.Schwarz) * Vuong_test_left$p.value.Schwarz,
sign(Vuong_test_right$statistic.Schwarz) * Vuong_test_right$p.value.Schwarz
), 1, 2)
colnames(re) <- c("left Schwarz p", "right Schwarz p")
}
}
return(re)
}
TestPoints.Vuong <- function(v_t_point, X_raw, delta, CDR = "D", trunc_tree = NA, family_set = 1,
pre_white = 0, ar_num = 1, sig_alpha = 0.05) {
T <- length(unique(X_raw[, 1]))
subnum <- dim(X_raw)[1] / T
X <- X_raw
v_t_point = sort(v_t_point)
if(sum(c(v_t_point,T)-c(0,v_t_point)<dim(X_raw)[2]-1)>0) stop("Some candidates are too close to each other or to the boundary (distance < p)")
if (pre_white == 1) {
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i - 1) * T + 1):(i * T), -1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid) == TRUE)] <- 0
X[((i - 1) * T + 1):(i * T), -1] <- ar_resid
}
}
X[, -1] <- VineCopula::pobs(X[, -1])
test_result <- as.data.frame(matrix(0, length(v_t_point), 4))
if (length(v_t_point) == 0) {
return(test_result)
} else {
test_result[, 1] <- v_t_point
a <- c(1, v_t_point, T + 1)
full_point <- a[!duplicated(a)]
message("Perform Vuong test on candidates...")
for (i in 1:length(v_t_point)) {
test_result[i, 2:3] <- Vuong_Multi_CDR_NewTestPoint(
full_point[i + 1], full_point[i],
full_point[i + 2], X, delta, CDR, trunc_tree, family_set
)
if (test_result[i, 2] < 0 & abs(test_result[i, 2]) < sig_alpha &
test_result[i, 3] < 0 & abs(test_result[i, 3]) < sig_alpha
) {
test_result[i, 4] <- "significant"
} else {
test_result[i, 4] <- "not significant"
}
}
names(test_result) <- c("t", "left Schwarz p", "right Schwarz p", "judgement")
return(test_result)
}
}
GetTestPlot.Vuong <- function(test_result, T, sig_alpha = 0.05) {
if (dim(test_result)[1] == 0) {
graphics::plot(1:T,1:T,type = "n",yaxt="n",ylab = NA)
graphics::text("No candidate is found.")
}
else {
LeftSch <- RightSch <- rep(0, T)
for (ii in 1:dim(test_result)[1]) {
if (1 / abs(test_result[ii, 2]) > 1e100) test_result[ii, 2] <- -1e-100
if (1 / abs(test_result[ii, 3]) > 1e100) test_result[ii, 3] <- -1e-100
}
LeftSch[test_result[, 1]] <- log(abs(1 / test_result[, 2]))
RightSch[test_result[, 1]] <- log(abs(1 / test_result[, 3]))
y_min <- min(LeftSch, RightSch)
y_max <- max(LeftSch, RightSch)
graphics::plot(1:T, rep(1, T),
ylab = c("log(1/p_value)"), type = "n", cex = .5, pch = 16,
ylim = c(max(0.1, y_min - 0.1), y_max + 6)
)
n_point <- dim(test_result)[1]
for (i in 1:n_point) {
graphics::lines(data.frame(
x = c(test_result[i, 1], test_result[i, 1]),
y = c(
log(1 / abs(min(test_result[i, 2:3]))),
log(1 / abs(max(test_result[i, 2:3])))
)
))
}
graphics::points(test_result[test_result[, 2] < 0, 1], log(-1 / test_result[test_result[, 2] < 0, 2]), pch = 20, col = "blue")
graphics::points(test_result[test_result[, 3] < 0, 1], log(-1 / test_result[test_result[, 3] < 0, 3]), pch = 20, col = "green")
graphics::points(test_result[test_result[, 2] > 0, 1], log(1 / test_result[test_result[, 2] > 0, 2]), pch = 4, col = 1)
graphics::points(test_result[test_result[, 3] > 0, 1], log(1 / test_result[test_result[, 3] > 0, 3]), pch = 4, col = 1)
graphics::abline(h = c(0, log(1 / sig_alpha)), lwd = 1)
graphics::text(70, log(1 / sig_alpha) - 0.3, labels = paste(
"alpha =", sig_alpha,
"log(1/sig_alpha) =", round(log(1 / sig_alpha), digits = 3)
), cex = .6)
txt <- c("left Schwarz p", "right Schwarz p", "sign_stat>0")
graphics::legend("topright", legend = txt, col = c("blue", "green", 1), pch = c(16, 16, 4), cex = .6)
if (sum(test_result[, 4] == "significant") != 0) {
sig_re <- test_result[test_result[, 4] == "significant", ]
log_inv_sig_re <- log(-1 / sig_re[, c(-1, -4)])
p_max <- apply(log_inv_sig_re, 1, max)
graphics::text(test_result[test_result[, 4] == "significant", 1], p_max + 1,
labels = test_result[test_result[, 4] == "significant", 1], cex = 0.8
)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/VuongTest.R
|
MultiGenRandomInterval <- function(X_raw, delta, start, end, M, pre_white, ar_num){
T <- length(unique(X_raw[,1]))
subnum <- dim(X_raw)[1]/T
X <- X_raw
if(pre_white == 1){
for (i in 1:subnum) {
armodel <- stats::ar(X_raw[((i-1)*T+1):(i*T),-1], FALSE, ar_num)
ar_resid <- armodel$resid
ar_resid[which(is.na(ar_resid)==TRUE)] <- 0
X[((i-1)*T+1):(i*T),-1] <- ar_resid
}
}
X[,-1] <- VineCopula::pobs(X[,-1])
t1 <- sample(start:end, M, replace = TRUE)
t2 <- sample(start:end, M, replace = TRUE)
t <- cbind(t1, t2)
t_sort <- t(apply(t, 1, sort))
t_sort <- t_sort[t_sort[,2]-t_sort[,1]>2*delta, ]
X_subsam <- list()
for (i in 1:dim(t_sort)[1]) {
X_subsam1 <- c()
for (j in 1:subnum) {
X_subsam1 <- rbind(X_subsam1,
X[((j-1)*T+t_sort[i,1]):((j-1)*T+t_sort[i,2]), ])
}
X_subsam=c(list(X_subsam1),X_subsam)
}
return(X_subsam)
}
#' @importFrom VineCopula RVineStructureSelect
#' @importFrom VineCopula D2RVine
#' @importFrom VineCopula RVineCopSelect
#' @importFrom VineCopula RVineVuongTest
VC_WBS_FindPoints <- function(X_raw, delta, M=NA, CDR="D", trunc_tree=NA, family_set=1, pre_white=0, ar_num=1){
T <- length(unique(X_raw[, 1]))
if(is.na(M)==TRUE){
M <- floor(9*log(T))
}
p_X = dim(X_raw)[2] - 1
X_list = MultiGenRandomInterval(X_raw, delta, 1, T, M, pre_white, ar_num)
BIC_cut_series <- cut_new_point_series <- c()
X_list_new <- list()
k=0
message("Search for pseudo sample data...")
for (j in 1:length(X_list)) {
#message(paste("Search for pseudo sample data (",j,"/",length(X_list),") ..."),fill = TRUE)
BIC_de <- rep(0, T)
t_Xj <- length(unique(X_list[[j]][,1]))
cut_point0 <- c(min(unique(X_list[[j]][,1])),max(unique(X_list[[j]][,1]))+1)
for (i in cut_point0[1]:cut_point0[2]) {
if(sum(is.element((i-delta):(i+delta) , cut_point0)) != 0){
next
}else{
if(CDR=="R"){
t_point <- i
BIC_de[i] <- RVineStructureSelect(MultiInd(X_list[[j]], 1, t_Xj+1),
familyset=family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
( RVineStructureSelect(MultiInd(X_list[[j]], 1, i - cut_point0[1]+1),
familyset=family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineStructureSelect(MultiInd(X_list[[j]],(i - cut_point0[1] + 1), t_Xj+1),
familyset=family_set,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC )
#print(c(BIC_de[i],i))
}else{
if(CDR=="C"){
t_point <- i
BIC_de[i] <- RVineStructureSelect(MultiInd(X_list[[j]], 1, t_Xj+1),
familyset=family_set, type=1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
( RVineStructureSelect(MultiInd(X_list[[j]], 1, i - cut_point0[1]+1),
familyset=family_set, type=1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineStructureSelect(MultiInd(X_list[[j]],(i - cut_point0[1] + 1), t_Xj+1),
familyset=family_set, type=1,
selectioncrit = "BIC", method = "mle",
indeptest = TRUE, trunclevel = trunc_tree)$BIC )
#print(c(BIC_de[i],i))
}else{
t_point <- i
D_X = D2RVine(1:p_X, family = rep(0, p_X*(p_X-1)/2),
par = rep(0, p_X*(p_X-1)/2),
par2 = rep(0, p_X*(p_X-1)/2))
BIC_de[i] <- RVineCopSelect(MultiInd(X_list[[j]], 1, t_Xj+1), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC -
(
RVineCopSelect(MultiInd(X_list[[j]], 1, i - cut_point0[1]+1), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC +
RVineCopSelect(MultiInd(X_list[[j]],(i - cut_point0[1] + 1), t_Xj+1), selectioncrit = "BIC",
method = "mle", Matrix = D_X$Matrix,familyset = unlist(family_set),
indeptest = TRUE, trunclevel = trunc_tree)$BIC
)
#print(c(BIC_de[i],i))
}
}
}
}
max_BIC_de <- max(BIC_de)
if(max_BIC_de > 0){
k=k+1
# if(which.max(BIC_de) %in% cut_new_point_series){
# cat(paste("Find candidate", k,
# ": t =", which.max(BIC_de),"(duplicated) \n \n"), fill = TRUE)
# }else{
# cat(paste("Find candidate", k,
# ": t =", which.max(BIC_de),"\n \n"), fill = TRUE)
# }
X_list_new[[k]] <- X_list[[j]]
BIC_cut_series[k] <- max(BIC_de)
cut_new_point_series[k] <- which.max(BIC_de)
}else{
# cat(paste("No candidate is found in this sample data. \n\n"), fill = TRUE)
}
}
return(list(X_list_new, cut_new_point_series, BIC_cut_series))
}
Multi_Find_startend_ind <- function(rank_X_list){
re <- matrix(0, length(rank_X_list), 2)
for (i in 1:length(rank_X_list)) {
re[i, 1] <- min(unique(rank_X_list[[i]][,1]))
re[i, 2] <- max(unique(rank_X_list[[i]][,1]))
}
return(re)
}
TwoMulti <- function(x, y){
z <- c()
for (i in 1:length(x)) {
z[i] <- x[i] * y[i]
}
return(z)
}
VC_WBS_Boot <- function(X_raw, delta, M=NA, CDR="D", trunc_tree=NA,
family_set=1, pre_white=0, ar_num=1, p=0.3, N=100, sig_alpha=0.05){
VC_WBS_FindPoints.result <- VC_WBS_FindPoints(X_raw, delta, M, CDR, trunc_tree,
family_set, pre_white, ar_num)
X_list_new = VC_WBS_FindPoints.result[[1]]
cut_new_point_series = VC_WBS_FindPoints.result[[2]]
BIC_cut_series = VC_WBS_FindPoints.result[[3]]
rank_cut_point_series <- c()
rank_X_list <- list()
ind <- which(!duplicated(BIC_cut_series))
cut_new_point_series <- cut_new_point_series[!duplicated(BIC_cut_series)]
BIC_cut_series <- BIC_cut_series[!duplicated(BIC_cut_series)]
X_list_2 <- list()
m=1
tema <- as.data.frame(matrix(0, 1, 5))
names(tema) <- c("t", "reduced BIC", "Lower_CI", "Upper_CI", "judgement")
if(length(ind)==0){
message("No candidate is found.")
return(tema[-1,0])
}else{
for (i in 1:length(ind)) {
X_list_2[[m]] <- X_list_new[[ind[i]]]
m=m+1
}
X_list_new <- X_list_2
ra <- floor(rank(-BIC_cut_series))
rank_cut_point_series[ra] <- cut_new_point_series
for (i in 1:length(cut_new_point_series)) {
rank_X_list[[ra[i]]] <- X_list_new[[i]]
}
rank_ind_ma <- Multi_Find_startend_ind(rank_X_list)
rank_BIC_cut_series <- sort(BIC_cut_series, decreasing = TRUE)
test_I <- "significant"
tema <- as.data.frame(matrix(0, 1, 5))
names(tema) <- c("t", "reduced BIC", "Lower_CI", "Upper_CI", "judgement")
k=1
sig_cut_point <- c()
kk <- rep(1, length(rank_ind_ma[, 1]))
aa = 0
message("Perform stationary bootstrap test on candidates...")
while (test_I == "significant") {
aa = aa + 1
# cat(paste("Test for candidate", aa, ": t =", rank_cut_point_series[k]), fill = TRUE)
t_start <- rank_X_list[[k]][1,1]
t_end <- rank_X_list[[k]][dim(rank_X_list[[k]])[1],1] + 1
test_CI <- Multi_CDR_NewTestPoint(rank_cut_point_series[k] - t_start + 1,
1, t_end - t_start+1, rank_X_list[[k]][,-1],
delta, CDR, trunc_tree, family_set, p, N,sig_alpha)
if(test_CI[1] > test_CI[3]){
test_I <- "significant"
#cat("Significant! \n\n")
sig_cut_point <- c(sig_cut_point, rank_cut_point_series[k])
tema <- rbind(tema, c(rank_cut_point_series[k], test_CI, test_I))
tema[,1] <- as.numeric(tema[,1])
tema[,2] <- as.numeric(tema[,2])
tema[,3] <- as.numeric(tema[,3])
tema[,4] <- as.numeric(tema[,4])
kk <- TwoMulti(kk ,rank_ind_ma[, 1] > rank_cut_point_series[k] |
rank_ind_ma[, 2] < rank_cut_point_series[k])
if(sum(kk!=0)==0) test_I <- "not significant" else k <- which.max(kk)
}else{
test_I <- "not significant"
#cat("Insignificant! \n\n")
tema <- rbind(tema, c(rank_cut_point_series[k], test_CI, test_I))
tema[,1] <- as.numeric(tema[,1])
tema[,2] <- as.numeric(tema[,2])
tema[,3] <- as.numeric(tema[,3])
tema[,4] <- as.numeric(tema[,4])
}
}
return(tema[-1,])
}
}
VC_WBS_Vuong <- function(X_raw, delta, M=NA, CDR="D", trunc_tree=NA,
family_set=1, p=0.3, N=100, pre_white=0,
ar_num=1, sig_alpha=0.05){
VC_WBS_FindPoints.result <- VC_WBS_FindPoints(X_raw, delta, M, CDR, trunc_tree,
family_set, pre_white, ar_num)
X_list_new = VC_WBS_FindPoints.result[[1]]
cut_new_point_series = VC_WBS_FindPoints.result[[2]]
BIC_cut_series = VC_WBS_FindPoints.result[[3]]
rank_cut_point_series <- c()
rank_X_list <- list()
ind <- which(!duplicated(BIC_cut_series))
cut_new_point_series <- cut_new_point_series[!duplicated(BIC_cut_series)]
BIC_cut_series <- BIC_cut_series[!duplicated(BIC_cut_series)]
X_list_2 <- list()
m=1
tema <- as.data.frame(matrix(0, 1, 4))
names(tema) <- c("t", "left Schwarz p", "right Schwarz p", "judgement")
if(length(ind)==0){
message("No candidate is found.")
return(tema[-1,0])
}else{
for (i in 1:length(ind)) {
X_list_2[[m]] <- X_list_new[[ind[i]]]
m=m+1
}
X_list_new <- X_list_2
ra <- floor(rank(-BIC_cut_series))
rank_cut_point_series[ra] <- cut_new_point_series
for (i in 1:length(cut_new_point_series)) {
rank_X_list[[ra[i]]] <- X_list_new[[i]]
}
rank_ind_ma <- Multi_Find_startend_ind(rank_X_list)
rank_BIC_cut_series <- sort(BIC_cut_series, decreasing = TRUE)
test_I <- "significant"
tema <- as.data.frame(matrix(0, 1, 4))
names(tema) <- c("t", "left Schwarz p", "right Schwarz p", "judgement")
k=1
sig_cut_point <- c()
kk <- rep(1, length(rank_ind_ma[, 1]))
aa = 0
message("Perform Vuong test on candidates...")
while (test_I == "significant") {
aa = aa + 1
# cat(paste("Test for candidate", aa, ": t =", rank_cut_point_series[k]), fill = TRUE)
t_start <- rank_X_list[[k]][1,1]
t_end <- rank_X_list[[k]][dim(rank_X_list[[k]])[1],1] + 1
test_CI <- Vuong_Multi_CDR_NewTestPoint(rank_cut_point_series[k] - t_start + 1,
1, t_end - t_start+1, rank_X_list[[k]][,-1],
delta, CDR, trunc_tree, family_set)
if(test_CI[1] < 0 & abs(test_CI[1]) < sig_alpha &
test_CI[2] < 0 & abs(test_CI[2]) < sig_alpha ){
test_I <- "significant"
# cat("Significant! \n\n")
sig_cut_point <- c(sig_cut_point, rank_cut_point_series[k])
tema <- rbind(tema, c(rank_cut_point_series[k], test_CI, test_I))
tema[,1] <- as.numeric(tema[,1])
tema[,2] <- as.numeric(tema[,2])
tema[,3] <- as.numeric(tema[,3])
kk <- TwoMulti(kk ,rank_ind_ma[, 1] > rank_cut_point_series[k] |
rank_ind_ma[, 2] < rank_cut_point_series[k])
if(sum(kk!=0)==0) test_I <- "not significant" else k <- which.max(kk)
}else{
# cat("Insignificant! \n\n")
test_I <- "not significant"
tema <- rbind(tema, c(rank_cut_point_series[k], test_CI, test_I))
tema[,1] <- as.numeric(tema[,1])
tema[,2] <- as.numeric(tema[,2])
tema[,3] <- as.numeric(tema[,3])
}
}
return(tema[-1,])
}
}
VC_WBS <- function(X_raw, delta, M = NA, test = "V", CDR = "D", trunc_tree = NA,
family_set = 1, pre_white = 0, ar_num = 1,
p = 0.3, N = 100, sig_alpha = 0.05) {
if (test == "V") {
infer <- VC_WBS_Vuong(
X_raw, delta, M, CDR, trunc_tree,
family_set, pre_white, ar_num, sig_alpha
)
return(infer)
} else {
if (test == "B") {
infer <- VC_WBS_Boot(
X_raw, delta, M, CDR,
trunc_tree, family_set,
pre_white, ar_num, p, N, sig_alpha
)
return(infer)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/WBS_VC.R
|
#' Plot output from the VCCP model
#'
#' This function plots the change points in the network structure between multivariate time series detected by the VCCP model.
#'
#' @param vccp_result A list generated from \code{\link{vccp.fun}}.
#' @return No return value, called for a plotting purpose.
#' @export
#' @examples
#' \donttest{
#' ## Simulate MVN data with 2 change points
#' data = cbind(1:180, mvn.sim.2.cps(180,8,seed=101))
#' ## Change point detection using VCCP (it may take several minutes to complete...)
#' result = vccp.fun(data, "NBS", test = "V")
#' ## Plot the result
#' getTestPlot(result)
#'
#' result.2 = vccp.fun(data, "NBS", test = "B")
#' ## Plot the result
#' getTestPlot(result.2)
#' }
#' @seealso \code{\link{vccp.fun}}
getTestPlot <- function(vccp_result){
if(length(vccp_result)==0){
return(cat("Inappropriate VCCP model specification!"))
}else{
if(dim(vccp_result$test_df)[2]==4){
GetTestPlot.Vuong(vccp_result$test_df, vccp_result$T,
vccp_result$sig_alpha)
}else{
GetTestPlot.Boot(vccp_result$test_df, vccp_result$T)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vccp/R/getTestPlot.R
|
Kappa <- function (x, weights = c("Equal-Spacing", "Fleiss-Cohen"))
{
if (is.character(weights))
weights <- match.arg(weights)
d <- diag(x)
n <- sum(x)
nc <- ncol(x)
colFreqs <- colSums(x)/n
rowFreqs <- rowSums(x)/n
## Kappa
kappa <- function (po, pc)
(po - pc) / (1 - pc)
std <- function (p, pc, kw, W = diag(1, ncol = nc, nrow = nc)) {
sqrt((sum(p * sweep(sweep(W, 1, W %*% colSums(p) * (1 - kw)), 2, W %*% rowSums(p) * (1 - kw)) ^ 2) - (kw - pc * (1 - kw)) ^ 2) / crossprod(1 - pc) / n)
}
## unweighted
po <- sum(d) / n
pc <- crossprod(colFreqs, rowFreqs)[1]
k <- kappa(po, pc)
s <- std(x / n, pc, k)
## weighted
W <- if (is.matrix(weights))
weights
else if (weights == "Equal-Spacing")
1 - abs(outer(1:nc, 1:nc, "-")) / (nc - 1)
else
1 - (abs(outer(1:nc, 1:nc, "-")) / (nc - 1))^2
pow <- sum(W * x) / n
pcw <- sum(W * colFreqs %o% rowFreqs)
kw <- kappa(pow, pcw)
sw <- std(x / n, pcw, kw, W)
structure(
list(Unweighted = c(
value = k,
ASE = s
),
Weighted = c(
value = kw,
ASE = sw
),
Weights = W
),
class = "Kappa"
)
}
print.Kappa <-
function (x, digits=max(getOption("digits") - 3, 3), CI=FALSE, level=0.95, ...)
{
tab <- rbind(x$Unweighted, x$Weighted)
z <- tab[,1] / tab[,2]
tab <- cbind(tab, z, `Pr(>|z|)` = 2 * pnorm(-abs(z)))
if (CI) {
q <- qnorm((1 + level)/2)
lower <- tab[,1] - q * tab[,2]
upper <- tab[,1] + q * tab[,2]
tab <- cbind(tab, lower, upper)
}
rownames(tab) <- names(x)[1:2]
print(tab, digits=digits, ...)
invisible(x)
}
summary.Kappa <- function (object, ...)
structure(object, class = "summary.Kappa")
print.summary.Kappa <- function (x, ...) {
print.Kappa(x, ...)
cat("\nWeights:\n")
print(x$Weights, ...)
invisible(x)
}
confint.Kappa <- function(object, parm, level = 0.95, ...) {
q <- qnorm((1 + level) / 2)
matrix(c(max(-1, object[[1]][1] - object[[1]][2] * q),
min(1, object[[1]][1] + object[[1]][2] * q),
max(-1, object[[2]][1] - object[[2]][2] * q),
min(1, object[[2]][1] + object[[2]][2] * q)),
ncol = 2, byrow = TRUE,
dimnames = list(Kappa = c("Unweighted","Weighted"), c("lwr","upr"))
)
}
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/Kappa.R
|
# This should be revised to allow graphical parameters to be more easily passed
# for points and lines
# For now, added lwd, lty and col args for lines, with more useful defaults
Ord_plot <- function(obj, legend = TRUE, estimate = TRUE, tol = 0.1,
type = NULL, xlim = NULL, ylim = NULL, xlab = "Number of occurrences",
ylab = "Frequency ratio", main = "Ord plot", gp = gpar(cex = 0.5),
lwd = c(2,2), lty=c(2,1), col=c("black", "red"),
name = "Ord_plot", newpage = TRUE, pop = TRUE,
return_grob = FALSE, ...)
{
if(is.vector(obj)) {
obj <- table(obj)
}
if(is.table(obj)) {
if(length(dim(obj)) > 1) stop ("obj must be a 1-way table")
x <- as.vector(obj)
count <- as.numeric(names(obj))
} else {
if(!(!is.null(ncol(obj)) && ncol(obj) == 2))
stop("obj must be a 2-column matrix or data.frame")
x <- as.vector(obj[,1])
count <- as.vector(obj[,2])
}
y <- count * x/c(NA, x[-length(x)])
fm <- lm(y ~ count)
fmw <- lm(y ~ count, weights = sqrt(pmax(x, 1) - 1))
fit1 <- predict(fm, data.frame(count))
fit2 <- predict(fmw, data.frame(count))
if(is.null(xlim)) xlim <- range(count)
if(is.null(ylim)) ylim <- range(c(y, fit1, fit2), na.rm = TRUE)
xlim <- xlim + c(-1, 1) * diff(xlim) * 0.04
ylim <- ylim + c(-1, 1) * diff(ylim) * 0.04
lwd <- rep_len(lwd, 2) # assure length=2
lty <- rep_len(lty, 2)
col <- rep_len(col, 2)
if(newpage) grid.newpage()
pushViewport(plotViewport(xscale = xlim, yscale = ylim, default.units = "native", name = name))
grid.points(x = count, y = y, default.units = "native", gp = gp, ...)
grid.lines(x = count, y = fit1, default.units = "native", gp = gpar(lwd=lwd[1], lty=lty[1], col=col[1]))
grid.lines(x = count, y = fit2, default.units = "native", gp = gpar(lwd=lwd[2], lty=lty[2], col=col[2]))
grid.rect(gp = gpar(fill = "transparent"))
grid.xaxis()
grid.yaxis()
grid.text(xlab, y = unit(-3.5, "lines"))
grid.text(ylab, x = unit(-3, "lines"), rot = 90)
grid.text(main, y = unit(1, "npc") + unit(2, "lines"), gp = gpar(fontface = "bold"))
RVAL <- coef(fmw)
names(RVAL) <- c("Intercept", "Slope")
if(legend)
{
legend.text <- c(paste("slope =", round(RVAL[2], digits = 3)),
paste("intercept =", round(RVAL[1], digits = 3)))
if(estimate) {
ordfit <- Ord_estimate(RVAL, type = type, tol = tol)
legend.text <- c(legend.text, "", paste("type:", ordfit$type),
paste("estimate:", names(ordfit$estimate),"=", round(ordfit$estimate, digits = 3)))
legend.text <- paste(legend.text, collapse = "\n")
}
grid.text(legend.text, min(count), ylim[2] * 0.95, default.units = "native", just = c("left", "top"))
}
if(pop) popViewport() else upViewport()
if(return_grob)
invisible(structure(RVAL, grob = grid.grab()))
else
invisible(RVAL)
}
Ord_estimate <- function(x, type = NULL, tol = 0.1)
{
a <- x[1]
b <- x[2]
if(!is.null(type))
type <- match.arg(type, c("poisson", "binomial", "nbinomial", "log-series"))
else {
if(abs(b) < tol) type <- "poisson"
else if(b < (-1 * tol)) type <- "binomial"
else if(a > (-1 * tol)) type <- "nbinomial"
else if(abs(a + b) < 4*tol) type <- "log-series"
else type <- "none"
}
switch(type,
"poisson" = {
par <- a
names(par) <- "lambda"
if(par < 0) warning("lambda not > 0")
},
"binomial" = {
par <- b/(b - 1)
names(par) <- "prob"
if(abs(par - 0.5) > 0.5) warning("prob not in (0,1)")
},
"nbinomial" = {
par <- 1 - b
names(par) <- "prob"
if(abs(par - 0.5) > 0.5) warning("prob not in (0,1)")
},
"log-series" = {
par <- b
names(par) <- "theta"
if(par < 0) warning("theta not > 0")
},
"none" = {
par <- NA
})
list(estimate = par, type = type)
}
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/Ord_plot.R
|
## Modified 1/25/2012 11:43AM by M. friendly
# -- added fill_col argument, specifying a function to be used to fill the tiles
# -- added xscale, yscale arguments to show the marginal frequencies at top & right
# -- added line_col to change the color of the diagonal line
## Modified 3/24/2012 11:38AM by M. friendly
# -- fixed buglet with yscale=TRUE and reverse_y=FALSE
"agreementplot" <- function (x, ...)
UseMethod ("agreementplot")
"agreementplot.formula" <-
function (formula, data = NULL, ..., subset)
{
m <- match.call(expand.dots = FALSE)
edata <- eval(m$data, parent.frame())
if (inherits(edata, "ftable") || inherits(edata, "table")) {
data <- as.table(data)
varnames <- attr(terms(formula), "term.labels")
if (all(varnames != "."))
data <- margin.table(data, match(varnames, names(dimnames(data))))
agreementplot(data, ...)
}
else {
if (is.matrix(edata))
m$data <- as.data.frame(data)
m$... <- NULL
m[[1L]] <- quote(stats::model.frame)
mf <- eval(m, parent.frame())
if (length(formula) == 2) {
by <- mf
y <- NULL
}
else {
i <- attr(attr(mf, "terms"), "response")
by <- mf[-i]
y <- mf[[i]]
}
by <- lapply(by, factor)
x <- if (is.null(y))
do.call("table", by)
else if (NCOL(y) == 1)
tapply(y, by, sum)
else {
z <- lapply(as.data.frame(y), tapply, by, sum)
array(unlist(z), dim = c(dim(z[[1]]), length(z)),
dimnames = c(dimnames(z[[1]]),
list(names(z))))
}
x[is.na(x)] <- 0
agreementplot(x, ...)
}
}
"agreementplot.default" <- function(x,
reverse_y = TRUE,
main = NULL,
weights = c(1, 1 - 1 / (ncol(x) - 1)^2),
margins = par("mar"),
newpage = TRUE,
pop = TRUE,
xlab = names(dimnames(x))[2],
ylab = names(dimnames(x))[1],
xlab_rot = 0, xlab_just = "center",
ylab_rot = 90, ylab_just = "center",
fill_col = function(j) gray((1 - (weights[j]) ^ 2) ^ 0.5),
line_col = "red",
xscale=TRUE, yscale = TRUE,
return_grob = FALSE,
prefix = "",
...)
{
if (length(dim(x)) > 2)
stop("Function implemented for two-way tables only!")
if (ncol(x) != nrow(x))
stop("Dimensions must have equal length!")
nc <- ncol(x)
## compute relative frequencies
n <- sum(x)
colFreqs <- colSums(x) / n
rowFreqs <- rowSums(x) / n
## open viewport
if (newpage) grid.newpage()
pushViewport(plotViewport(margins,
name = paste(prefix,"agreementplot")))
pushViewport(viewport(width = unit(1, "snpc"),
height = unit(1, "snpc")))
if(!is.null(main))
grid.text(main, y = unit(1.1, "npc"),
gp = gpar(fontsize = 25))
## axis labels
grid.text(xlab, y = -0.12, gp = gpar(fontsize = 20))
grid.text(ylab, x = -0.1, gp = gpar(fontsize = 20), rot = 90)
grid.rect(gp = gpar(fill = "transparent"))
xc <- c(0, cumsum(colFreqs))
yc <- c(0, cumsum(rowFreqs))
my.text <- if(reverse_y)
function(y, ...) grid.text(y = y, ...)
else
function(y, ...) grid.text(y = 1 - y, ...)
my.rect <- if(reverse_y)
function(xleft, ybottom, xright, ytop, ...)
grid.rect(x = xleft, y = ybottom, width = xright - xleft,
height = ytop - ybottom, just = c("left","bottom"), ...)
else
function(xleft, ybottom, xright, ytop, ...)
grid.rect(x = xleft, y = 1 - ybottom, width = xright - xleft,
height = ytop - ybottom, just = c("left","top"), ...)
A <- matrix(0, length(weights), nc)
for (i in 1:nc) {
## x - axis
grid.text(dimnames(x)[[2]][i],
x = xc[i] + (xc[i + 1] - xc[i]) / 2,
y = - 0.04, check.overlap = TRUE, rot = xlab_rot, just = xlab_just, ...)
## y - axis
my.text(dimnames(x)[[1]][i],
y = yc[i] + (yc[i + 1] - yc[i]) / 2,
x = - 0.03, check.overlap = TRUE, rot = ylab_rot, just = ylab_just, ...)
## expected rectangle
my.rect(xc[i], yc[i], xc[i + 1], yc[i + 1])
## observed rectangle
y0 <- c(0, cumsum(x[i,])) / sum(x[i,])
x0 <- c(0, cumsum(x[,i])) / sum(x[,i])
rec <- function (col, dens, lb, tr)
my.rect(xc[i] + (xc[i + 1] - xc[i]) * x0[lb],
yc[i] + (yc[i + 1] - yc[i]) * y0[lb],
xc[i] + (xc[i + 1] - xc[i]) * x0[tr],
yc[i] + (yc[i + 1] - yc[i]) * y0[tr],
gp = gpar(fill = fill_col(j), col = col, rot = 135)
)
for (j in length(weights):1) {
lb <- max(1, i - j + 1)
tr <- 1 + min(nc, i + j - 1)
A[j, i] <- sum(x[lb:(tr-1),i]) * sum(x[i, lb:(tr-1)])
rec("white", NULL, lb, tr) ## erase background
rec("black", if (weights[j] < 1) weights[j] * 20 else NULL, lb, tr)
}
## correct A[j,i] -> not done by Friendly==Bug?
for (j in length(weights):1)
if (j > 1) A[j, i] <- A[j, i] - A[j - 1, i]
}
if (reverse_y)
grid.lines(c(0, 1), c(0, 1), gp = gpar(col = line_col, linetype = "longdash"))
else
grid.lines(c(0, 1), c(1, 0), gp = gpar(col = line_col, linetype = "longdash"))
if (xscale) {
cx <- xc[-(nc+1)] + diff(xc)/2
grid.text(colSums(x),
x = cx,
y = 1.03, rot = xlab_rot, just = xlab_just, ...)
grid.xaxis(at = xc, label = FALSE, main=FALSE,
gp = gpar(fontsize=10), draw = TRUE, vp = NULL)
}
if (yscale) {
cy <- yc[-(nc+1)] + diff(yc)/2
my.text(rowSums(x),
x = 1.04,
y = cy, rot = 0, just = ylab_just, ...)
grid.yaxis(at = if(reverse_y) yc else 1-yc,
FALSE, main=FALSE,
gp = gpar(fontsize=10), draw = TRUE, vp = NULL)
}
if (pop) popViewport(2) else upViewport(2)
## Statistics - Returned invisibly
ads <- crossprod(diag(x))
ar <- n * n * crossprod(colFreqs, rowFreqs)
if (return_grob)
invisible(structure(list(
Bangdiwala = ads / ar,
Bangdiwala_Weighted = (sum(weights * A)) / ar,
weights = weights),
grob = grid.grab()
)
)
else
invisible(list(
Bangdiwala = ads / ar,
Bangdiwala_Weighted = (sum(weights * A)) / ar,
weights = weights)
)
}
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/agreementplot.R
|
#################################################################333
## assocplot
assoc <- function(x, ...)
UseMethod("assoc")
assoc.formula <-
function(formula, data = NULL, ..., subset = NULL, na.action = NULL,
main = NULL, sub = NULL)
{
if (is.logical(main) && main)
main <- deparse(substitute(data))
else if (is.logical(sub) && sub)
sub <- deparse(substitute(data))
assoc.default(structable(formula, data, subset = subset,
na.action = na.action),
main = main, sub = sub, ...)
}
assoc.default <- function(x,
row_vars = NULL, col_vars = NULL,
compress = TRUE, xlim = NULL, ylim = NULL,
spacing = spacing_conditional(sp = 0),
spacing_args = list(),
split_vertical = NULL,
keep_aspect_ratio = FALSE,
xscale = 0.9, yspace = unit(0.5, "lines"),
main = NULL,
sub = NULL,
...,
residuals_type = "Pearson",
gp_axis = gpar(lty = 3)
) {
if (is.logical(main) && main)
main <- deparse(substitute(x))
else if (is.logical(sub) && sub)
sub <- deparse(substitute(x))
if (!inherits(x, "ftable"))
x <- structable(x)
tab <- as.table(x)
dl <- length(dim(tab))
## spacing
cond <- rep(TRUE, dl)
cond[length(attr(x, "row.vars")) + c(0, length(attr(x, "col.vars")))] <- FALSE
if (inherits(spacing, "grapcon_generator"))
spacing <- do.call("spacing", spacing_args)
spacing <- spacing(dim(tab), condvars = which(cond))
## splitting arguments
if (is.null(split_vertical))
split_vertical <- attr(x, "split_vertical")
if(match.arg(tolower(residuals_type), "pearson") != "pearson")
warning("Only Pearson residuals can be visualized with association plots.")
strucplot(tab,
spacing = spacing,
split_vertical = split_vertical,
core = struc_assoc(compress = compress, xlim = xlim, ylim = ylim,
yspace = yspace, xscale = xscale, gp_axis = gp_axis),
keep_aspect_ratio = keep_aspect_ratio,
residuals_type = "Pearson",
main = main,
sub = sub,
...)
}
## old code: more elegant conceptually, but less performant
##
## struc_assoc2 <- function(compress = TRUE, xlim = NULL, ylim = NULL,
## yspace = unit(0.5, "lines"), xscale = 0.9,
## gp_axis = gpar(lty = 3))
## function(residuals, observed = NULL, expected, spacing, gp, split_vertical, prefix = "") {
## dn <- dimnames(expected)
## dnn <- names(dn)
## dx <- dim(expected)
## dl <- length(dx)
## ## axis limits
## resid <- structable(residuals, split_vertical = split_vertical)
## sexpected <- structable(sqrt(expected), split_vertical = split_vertical)
## rfunc <- function(x) c(min(x, 0), max(x, 0))
## if (is.null(ylim))
## ylim <- if (compress)
## matrix(apply(as.matrix(resid), 1, rfunc), nrow = 2)
## else
## rfunc(as.matrix(resid))
## if (!is.matrix(ylim))
## ylim <- matrix(as.matrix(ylim), nrow = 2, ncol = nrow(as.matrix(resid)))
## attr(ylim, "split_vertical") <- rep(TRUE, sum(!split_vertical))
## attr(ylim, "dnames") <- dn[!split_vertical]
## class(ylim) <- "structable"
## if(is.null(xlim))
## xlim <- if (compress)
## matrix(c(-0.5, 0.5) %o% apply(as.matrix(sexpected), 2, max), nrow = 2)
## else
## c(-0.5, 0.5) * max(sexpected)
## if (!is.matrix(xlim))
## xlim <- matrix(as.matrix(xlim), nrow = 2, ncol = ncol(as.matrix(resid)))
## attr(xlim, "split_vertical") <- rep(TRUE, sum(split_vertical))
## attr(xlim, "dnames") <- dn[split_vertical]
## class(xlim) <- "structable"
## ## split workhorse
## split <- function(res, sexp, i, name, row, col) {
## v <- split_vertical[i]
## splitbase <- if (v) sexp else res
## splittab <- lapply(seq(dx[i]), function(j) splitbase[[j]])
## len <- sapply(splittab, function(x) sum(unclass(x)[1,] - unclass(x)[2,]))
## d <- dx[i]
## ## compute total cols/rows and build split layout
## dist <- unit.c(unit(len, "null"), spacing[[i]] + (1 * !v) * yspace)
## idx <- matrix(1:(2 * d), nrow = 2, byrow = TRUE)[-2 * d]
## layout <- if (v)
## grid.layout(ncol = 2 * d - 1, widths = dist[idx])
## else
## grid.layout(nrow = 2 * d - 1, heights = dist[idx])
## vproot <- viewport(layout.pos.col = col, layout.pos.row = row,
## layout = layout, name = remove_trailing_comma(name))
## ## next level: either create further splits, or final viewports
## name <- paste(name, dnn[i], "=", dn[[i]], ",", sep = "")
## rows <- cols <- rep.int(1, d)
## if (v) cols <- 2 * 1:d - 1 else rows <- 2 * 1:d - 1
## f <- if (i < dl) {
## if (v)
## function(m) split(res, splittab[[m]], i + 1, name[m], rows[m], cols[m])
## else
## function(m) split(splittab[[m]], sexp, i + 1, name[m], rows[m], cols[m])
## } else {
## if (v)
## function(m) viewport(layout.pos.col = cols[m], layout.pos.row = rows[m],
## name = remove_trailing_comma(name[m]),
## yscale = unclass(res)[,1],
## xscale = unclass(sexp)[,m], default.units = "null")
## else
## function(m) viewport(layout.pos.col = cols[m], layout.pos.row = rows[m],
## name = remove_trailing_comma(name[m]),
## yscale = unclass(res)[,m],
## xscale = unclass(sexp)[,1], default.units = "null")
## }
## vpleaves <- structure(lapply(1:d, f), class = c("vpList", "viewport"))
## vpTree(vproot, vpleaves)
## }
## ## start spltting on top, creates viewport-tree
## pushViewport(split(ylim, xlim, i = 1, name = paste(prefix, "cell:", sep = ""),
## row = 1, col = 1))
## ## draw tiles
## mnames <- paste(apply(expand.grid(dn), 1,
## function(i) paste(dnn, i, collapse = ",", sep = "=")
## )
## )
## for (i in seq_along(mnames)) {
## seekViewport(paste(prefix, "cell:", mnames[i], sep = ""))
## grid.lines(y = unit(0, "native"), gp = gp_axis)
## grid.rect(y = 0, x = 0,
## height = residuals[i],
## width = xscale * unit(sqrt(expected[i]), "native"),
## default.units = "native",
## gp = structure(lapply(gp, function(x) x[i]), class = "gpar"),
## just = c("center", "bottom"),
## name = paste(prefix, "rect:", mnames[i], sep = "")
## )
## }
## }
## class(struc_assoc2) <- "grapcon_generator"
struc_assoc <- function(compress = TRUE, xlim = NULL, ylim = NULL,
yspace = unit(0.5, "lines"), xscale = 0.9,
gp_axis = gpar(lty = 3))
function(residuals, observed = NULL, expected, spacing,
gp, split_vertical, prefix = "") {
if(is.null(expected)) stop("Need expected values.")
dn <- dimnames(expected)
dnn <- names(dn)
dx <- dim(expected)
dl <- length(dx)
## axis limits
resid <- structable(residuals, split_vertical = split_vertical)
sexpected <- structable(sqrt(expected), split_vertical = split_vertical)
rfunc <- function(x) c(min(x, 0), max(x, 0))
if (is.null(ylim))
ylim <- if (compress)
matrix(apply(as.matrix(resid), 1, rfunc), nrow = 2)
else
rfunc(as.matrix(resid))
if (!is.matrix(ylim))
ylim <- matrix(as.matrix(ylim), nrow = 2, ncol = nrow(as.matrix(resid)))
ylim[2,] <- ylim[2,] + .Machine$double.eps
attr(ylim, "split_vertical") <- rep(TRUE, sum(!split_vertical))
attr(ylim, "dnames") <- dn[!split_vertical]
class(ylim) <- "structable"
if(is.null(xlim))
xlim <- if (compress)
matrix(c(-0.5, 0.5) %o% apply(as.matrix(sexpected), 2, max), nrow = 2)
else
c(-0.5, 0.5) * max(sexpected)
if (!is.matrix(xlim))
xlim <- matrix(as.matrix(xlim), nrow = 2, ncol = ncol(as.matrix(resid)))
attr(xlim, "split_vertical") <- rep(TRUE, sum(split_vertical))
attr(xlim, "dnames") <- dn[split_vertical]
class(xlim) <- "structable"
## split workhorse
split <- function(res, sexp, i, name, row, col, index) {
v <- split_vertical[i]
d <- dx[i]
splitbase <- if (v) sexp else res
splittab <- lapply(seq(d), function(j) splitbase[[j]])
len <- abs(sapply(splittab, function(x) sum(unclass(x)[1,] - unclass(x)[2,])))
## compute total cols/rows and build split layout
dist <- if (d > 1)
unit.c(unit(len, "null"), spacing[[i]] + (1 * !v) * yspace)
else
unit(len, "null")
idx <- matrix(1:(2 * d), nrow = 2, byrow = TRUE)[-2 * d]
layout <- if (v)
grid.layout(ncol = 2 * d - 1, widths = dist[idx])
else
grid.layout(nrow = 2 * d - 1, heights = dist[idx])
pushViewport(viewport(layout.pos.col = col, layout.pos.row = row,
layout = layout, name = paste(prefix, "cell:",
remove_trailing_comma(name), sep = "")))
## next level: either create further splits, or final viewports
rows <- cols <- rep.int(1, d)
if (v) cols <- 2 * 1:d - 1 else rows <- 2 * 1:d - 1
for (m in 1:d) {
nametmp <- paste(name, dnn[i], "=", dn[[i]][m], ",", sep = "")
if (i < dl) {
if (v) sexp <- splittab[[m]] else res <- splittab[[m]]
split(res, sexp, i + 1, nametmp, rows[m], cols[m], cbind(index, m))
} else {
pushViewport(viewport(layout.pos.col = cols[m], layout.pos.row = rows[m],
name = paste(prefix, "cell:",
remove_trailing_comma(nametmp), sep = ""),
yscale = unclass(res)[,if (v) 1 else m],
xscale = unclass(sexp)[,if (v) m else 1],
default.units = "npc")
)
## draw tiles
grid.lines(y = unit(0, "native"), gp = gp_axis)
grid.rect(y = 0, x = 0,
height = residuals[cbind(index, m)],
width = xscale * unit(sqrt(expected[cbind(index, m)]), "native"),
default.units = "native",
gp = structure(lapply(gp, function(x) x[cbind(index,m)]),
class = "gpar"),
just = c("center", "bottom"),
name = paste(prefix, "rect:", remove_trailing_comma(nametmp), sep = "")
)
}
upViewport(1)
}
}
split(ylim, xlim, i = 1, name = "", row = 1, col = 1, index = cbind())
}
class(struc_assoc) <- "grapcon_generator"
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/assoc.R
|
assocstats <- function(x) {
if(!is.matrix(x)) {
l <- length(dim(x))
str <- apply(x, 3 : l, FUN = assocstats)
if (l == 3) {
names(str) <- paste(names(dimnames(x))[3], names(str), sep = ":")
} else {
dn <- dimnames(str)
dim(str) <- NULL
names(str) <-
apply(expand.grid(dn), 1,
function(x) paste(names(dn), x, sep = ":", collapse = "|"))
}
return(str)
}
tab <- summary(loglm(~1+2, x))$tests
phi <- sqrt(tab[2,1] / sum(x))
cont <- sqrt(phi^2 / (1 + phi^2))
cramer <- sqrt(phi^2 / min(dim(x) - 1))
structure(
list(table = x,
chisq_tests = tab,
phi = ifelse(all(dim(x) == 2L), phi, NA),
contingency = cont,
cramer = cramer),
class = "assocstats"
)
}
print.assocstats <- function(x,
digits = 3,
...)
{
print(x$chisq_tests, digits = 5, ...)
cat("\n")
cat("Phi-Coefficient :", round(x$phi, digits = digits), "\n")
cat("Contingency Coeff.:", round(x$contingency, digits = digits), "\n")
cat("Cramer's V :", round(x$cramer, digits = digits), "\n")
invisible(x)
}
summary.assocstats <- function(object, percentage = FALSE, ...) {
tab <- summary(object$table, percentage = percentage, ...)
tab$chisq <- NULL
structure(list(summary = tab,
object = object),
class = "summary.assocstats"
)
}
print.summary.assocstats <- function(x, ...) {
cat("\n")
print(x$summary, ...)
print(x$object, ...)
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/assocstats.R
|
binreg_plot <-
function(model, main = NULL, xlab = NULL, ylab = NULL,
xlim = NULL, ylim = NULL, pred_var = NULL, pred_range = c("data", "xlim"),
group_vars = NULL, base_level = NULL, subset,
type = c("response", "link"), conf_level = 0.95, delta = FALSE,
pch = NULL, cex = 0.6, jitter_factor = 0.1,
lwd = 5, lty = 1, point_size = 0, col_lines = NULL, col_bands = NULL,
legend = TRUE, legend_pos = NULL, legend_inset = c(0, 0.1),
legend_vgap = unit(0.5, "lines"),
labels = FALSE, labels_pos = c("right", "left"),
labels_just = c("left","center"),
labels_offset = c(0.01, 0),
gp_main = gpar(fontface = "bold", fontsize = 14),
gp_legend_frame = gpar(lwd = 1, col = "black"),
gp_legend_title = gpar(fontface = "bold"),
newpage = TRUE, pop = FALSE, return_grob = FALSE)
{
if (!inherits(model, "glm"))
stop("Method requires a model of class 'glm'.")
type <- match.arg(type)
labels_pos <- match.arg(labels_pos)
if (is.character(pred_range))
pred_range <- match.arg(pred_range)
## extract data from model
mod <- model.frame(model)
term <- terms(mod)
data.classes <- attr(term, "dataClasses")
nam <- names(data.classes)
## determine response
r <- attr(term, "response")
resp <- nam[r]
data.classes <- data.classes[-r]
nam <- nam[-r]
## determine numeric predictor (take first)
if (is.null(pred_var)) {
fac <- data.classes %in% c("factor","logical")
pred_var_model <- names(data.classes[!fac][1])
pred_var <-
names(unlist(sapply(all.vars(term),
grep, pred_var_model)))[1]
} else pred_var_model <- pred_var
## filter observed data using model (to account for models fitted with subset=...)
dat <- model$data[row.names(mod),]
## sort observations using order of numeric predictor
o <- order(dat[,pred_var,drop=TRUE])
mod <- mod[o,]
dat <- dat[o,]
## apply subset argument, if any
if (!missing(subset)) {
e <- substitute(subset)
i <- eval(e, dat, parent.frame())
i <- i & !is.na(i)
dat <- dat[i,]
mod <- mod[i,]
}
## determine conditioning variables. Remove all those with only one level observed.
if (is.null(group_vars)) {
group_vars <- nam[data.classes %in% "factor"]
sing <- na.omit(sapply(dat, function(i) all(i == i[1])))
if (any(sing))
group_vars <- setdiff(group_vars, names(sing)[sing])
if(length(group_vars) < 1)
group_vars <- NULL
} else
if (is.na(group_vars) || is.logical(group_vars) && !group_vars[1])
group_vars <- NULL
## set y axis limits - either probability or logit scale
if(is.null(ylim))
ylim <- if (type == "response")
c(0,1)
else
range(predict(model, dat, type = "link"))
## allow for some cosmetic extra space
ylimaxis <- ylim + c(-1, 1) * diff(ylim) * 0.04
if(is.null(xlim))
xlim <- if (is.numeric(pred_range))
range(pred_range)
else
range(dat[,pred_var])
xlimaxis <- xlim + c(-1, 1) * diff(xlim) * 0.04
## set default base level ("no effect") of response to first level/0
if (is.null(base_level))
base_level <- if(is.matrix(mod[,resp]))
2
else if(is.factor(mod[,resp]))
levels(mod[,resp])[1]
else
0
if (is.matrix(mod[,resp]) && is.character(base_level))
base_level <- switch(base_level, success =, Success = 1, failure =, Failure = 2)
## determine labels of conditioning variables, if any
if (is.null(group_vars)) {
labels <- legend <- FALSE
} else {
## compute cross-factors for more than two conditioning variables
if (length(group_vars) > 1) {
cross <- paste(group_vars, collapse = " x ")
dat[,cross] <- factor(apply(dat[,group_vars], 1, paste, collapse = " : "))
group_vars <- cross
}
lev <- levels(dat[,group_vars,drop=TRUE])
}
## set x- and y-lab
if (is.null(xlab))
xlab <- pred_var
if (is.null(ylab))
ylab <- if (type == "response") {
if (is.matrix(mod[,resp]))
paste0("P(",
c("Failure","Success")[base_level],
")")
else
paste0("P(", resp, ")")
} else {
if (is.matrix(mod[,resp]))
paste0("logit(",
c("Failure","Success")[base_level],
")")
else
paste0("logit(", resp, ")")
}
## rearrange default plot symbol palette
if (is.null(pch))
pch <- c(19,15,17, 1:14, 16, 18, 20:25)
## determine normal quantile for confidence band
quantile <- qnorm((1 + conf_level) / 2)
## determine default legend position, given the curve's slope
## (positive -> topleft, negative -> topright)
if (is.null(legend_pos))
legend_pos <-
if (coef(model)[grep(pred_var, names(coef(model)))[1]] > 0)
"topleft"
else
"topright"
## work horse for drawing points, fitted curve and confidence band
draw <- function(ind, colband, colline, pch, label) {
## plot observed data as points on top or bottom
ycoords <- if (is.matrix(mod[,resp])) {
tmp <- prop.table(mod[ind,resp], 1)[,switch(base_level, 2, 1)]
if (type == "link")
family(model)$linkfun(tmp)
else
tmp
} else
jitter(ylim[1 + (mod[ind, resp] != base_level)], jitter_factor)
if (cex > 0)
grid.points(unit(dat[ind, pred_var, drop = TRUE], "native"),
unit(ycoords, "native"),
pch = pch, size = unit(cex, "char"), gp = gpar(col = colline),
default.units = "native"
)
## confidence band and fitted values
typ <- if (type == "response" && !delta) "link" else type
if (is.character(pred_range)) {
if (pred_range == "data") {
D <- dat[ind,]
P <- D[,pred_var, drop = TRUE]
} else {
P <- seq(from = xlim[1L], to = xlim[2L], length.out = 100L)
D <- dat[ind,][rep(1L, length(P)),]
D[,pred_var] <- P
}
} else {
P <- pred_range
D <- dat[ind,][rep(1L, length(P)),]
D[,pred_var] <- P
}
pr <- predict(model, D, type = typ, se.fit = TRUE)
lower <- pr$fit - quantile * pr$se.fit
upper <- pr$fit + quantile * pr$se.fit
if (type == "response" && !delta) {
lower <- family(model)$linkinv(lower)
upper <- family(model)$linkinv(upper)
pr$fit <- family(model)$linkinv(pr$fit)
}
if (type == "response") { ## cut probs at unit interval
lower[lower < 0] <- 0
upper[upper > 1] <- 1
}
grid.polygon(unit(c(P, rev(P)), "native"),
unit(c(lower, rev(upper)), "native"),
gp = gpar(fill = colband, col = NA))
grid.lines(unit(P, "native"),
unit(pr$fit, "native"),
gp = gpar(col = colline, lwd = lwd, lty = lty))
if (point_size > 0)
grid.points(unit(P, "native"),
unit(pr$fit, "native"), pch = pch,
size = unit(point_size, "char"),
gp = gpar(col = colline))
## add labels, if any
if (labels) {
x = switch(labels_pos,
left = P[1],
right = P[length(P)])
y = switch(labels_pos,
left = pr$fit[1],
right = pr$fit[length(pr$fit)])
grid.text(x = unit(x, "native") + unit(labels_offset[1], "npc"),
y = unit(y, "native") + unit(labels_offset[2], "npc"),
label = label,
just = labels_just,
gp = gpar(col = colline))
}
}
## determine colors and plot symbols
llev <- if (is.null(group_vars)) 1 else length(lev)
pch <- rep(pch, length.out = llev)
if (is.null(col_bands))
col_bands <- colorspace::rainbow_hcl(llev, alpha = 0.2)
if (is.null(col_lines))
col_lines <- colorspace::rainbow_hcl(llev, l = 50)
## set up plot region, similar to plot.xy()
if (newpage) grid.newpage()
pushViewport(plotViewport(xscale = xlimaxis, yscale = ylimaxis, default.units = "native", name = "binreg_plot"))
grid.rect(gp = gpar(fill = "transparent"))
grid.xaxis()
grid.yaxis()
grid.text(xlab, y = unit(-3.5, "lines"))
grid.text(ylab, x = unit(-3, "lines"), rot = 90)
grid.text(main, y = unit(1, "npc") + unit(2, "lines"), gp = gp_main)
pushViewport(viewport(xscale = xlimaxis, yscale = ylimaxis, default.units = "native", clip = "on"))
## draw fitted curve(s)
if (is.null(group_vars)) {
## single curve
draw(1:nrow(dat),
col_bands,
col_lines,
pch[1])
} else {
## multiple curves
for (i in seq_along(lev)) {
ind <- dat[,group_vars,drop=TRUE] == lev[i]
draw(ind, col_bands[i], col_lines[i], pch[i], lev[i])
}
if (legend)
grid_legend(legend_pos,
labels = lev,
col = col_lines,
lty = "solid",
lwd = lwd,
vgap = legend_vgap,
gp_frame = gp_legend_frame,
inset = legend_inset,
title = group_vars,
gp_title = gp_legend_title)
}
if (pop) popViewport(2)
if (return_grob)
invisible(grid.grab())
else
invisible(NULL)
}
###########
grid_abline <- function(a, b, ...)
{
## taken from graphics::abline()
if (is.object(a) || is.list(a)) {
p <- length(coefa <- as.vector(coef(a)))
if (p > 2)
warning(gettextf("only using the first two of %d regression coefficients",
p), domain = NA)
islm <- inherits(a, "lm")
noInt <- if (islm)
!as.logical(attr(stats::terms(a), "intercept"))
else p == 1
if (noInt) {
a <- 0
b <- coefa[1L]
}
else {
a <- coefa[1L]
b <- if (p >= 2)
coefa[2L]
else 0
}
}
grid.abline(a, b, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/binregplot.R
|
cd_plot <- function(x, ...) {
UseMethod("cd_plot")
}
cd_plot.formula <- function(formula, data = list(),
plot = TRUE, ylab_tol = 0.05,
bw = "nrd0", n = 512, from = NULL, to = NULL,
main = "", xlab = NULL, ylab = NULL, margins = c(5.1, 4.1, 4.1, 3.1),
gp = gpar(), name = "cd_plot", newpage = TRUE, pop = TRUE,
return_grob = FALSE, ...)
{
## extract x, y from formula
mf <- model.frame(formula, data = data)
if(NCOL(mf) != 2) stop("`formula' should specify exactly two variables")
y <- mf[,1]
if(!is.factor(y)) stop("dependent variable should be a factor")
x <- mf[,2]
if(!is.numeric(x)) stop("explanatory variable should be numeric")
## graphical parameters
if(is.null(xlab)) xlab <- names(mf)[2]
if(is.null(ylab)) ylab <- names(mf)[1]
## call default interface
cd_plot(x, y,
plot = plot, ylab_tol = ylab_tol,
bw = bw, n = n, from = from, to = to,
main = main, xlab = xlab, ylab = ylab, margins = margins,
gp = gp, name = name, newpage = newpage, pop = pop, ...)
}
cd_plot.default <- function(x, y,
plot = TRUE, ylab_tol = 0.05,
bw = "nrd0", n = 512, from = NULL, to = NULL,
main = "", xlab = NULL, ylab = NULL, margins = c(5.1, 4.1, 4.1, 3.1),
gp = gpar(), name = "cd_plot", newpage = TRUE, pop = TRUE,
return_grob = FALSE, ...)
{
## check x and y
if(!is.numeric(x)) stop("explanatory variable should be numeric")
if(!is.factor(y)) stop("dependent variable should be a factor")
ny <- length(levels(y))
## graphical parameters
if(is.null(xlab)) xlab <- deparse(substitute(x))
if(is.null(ylab)) ylab <- deparse(substitute(y))
if(is.null(gp$fill)) gp$fill <- gray.colors(ny)
gp$fill <- rep(gp$fill, length.out = ny)
## unconditional density of x
dx <- if(is.null(from) & is.null(to)) density(x, bw = bw, n = n, ...)
else density(x, bw = bw, from = from, to = to, n = n, ...)
x1 <- dx$x
## setup conditional values
yprop <- cumsum(prop.table(table(y)))
y1 <- matrix(rep(0, n*(ny-1)), nrow = (ny-1))
## setup return value
rval <- list()
for(i in 1:(ny-1)) {
dxi <- density(x[y %in% levels(y)[1:i]], bw = dx$bw, n = n, from = min(dx$x), to = max(dx$x), ...)
y1[i,] <- dxi$y/dx$y * yprop[i]
rval[[i]] <- approxfun(x1, y1[i,], rule = 2)
}
names(rval) <- levels(y)[1:(ny-1)]
## use known ranges
y1 <- rbind(0, y1, 1)
y1 <- y1[,which(x1 >= min(x) & x1 <= max(x))]
x1 <- x1[x1 >= min(x) & x1 <= max(x)]
## plot polygons
if(plot) {
## setup
if(newpage) grid.newpage()
pushViewport(plotViewport(xscale = range(x1), yscale = c(0, 1),
default.units = "native", name = name, margins = margins, ...))
## polygons
for(i in 1:(NROW(y1)-1)) {
gpi <- gp
gpi$fill <- gp$fill[i]
grid.polygon(x = c(x1, rev(x1)), y = c(y1[i+1,], rev(y1[i,])), default.units = "native", gp = gpi)
}
## axes
grid.rect(gp = gpar(fill = "transparent"))
grid.xaxis()
grid.yaxis(main = FALSE)
equidist <- any(diff(y1[,1]) < ylab_tol)
yat <- if(equidist) seq(1/(2*ny), 1-1/(2*ny), by = 1/ny) else (y1[-1,1] + y1[-NROW(y1), 1])/2
grid.text(x = unit(-1.5, "lines"), y = unit(yat, "native"), label = levels(y),
rot = 90, check.overlap = TRUE)
## annotation
grid.text(xlab, y = unit(-3.5, "lines"))
grid.text(ylab, x = unit(-3, "lines"), rot = 90)
grid.text(main, y = unit(1, "npc") + unit(2, "lines"), gp = gpar(fontface = "bold"))
## pop
if(pop) popViewport()
}
## return conditional density functions
if (plot && return_grob)
invisible(structure(rval, grob = grid.grab()))
else
invisible(rval)
}
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/cd_plot.R
|
co_table <- function(x, margin, collapse = ".")
{
if (!is.array(x))
stop("x is not an array")
if("xtabs" %in% class(x)) attr(x, "call") <- NULL
dx <- dim(x)
idx <- lapply(dx, function(i) 1:i)
dn <- dimnames(x)
if(is.character(margin)) {
if(is.null(dn)) stop("margin must be an index when no dimnames are given")
margin <- which(names(dn) %in% margin)
}
idxm <- expand.grid(idx[margin])
cotab1 <- function(i) {
idx[margin] <- lapply(1:length(margin), function(j) idxm[i,j])
rval <- as.table(do.call("[", c(list(x), idx, list(drop = FALSE))))
if(length(dim(rval)) > 1) {
dim(rval) <- dim(x)[-margin]
dimnames(rval) <- dimnames(x)[-margin]
}
return(rval)
}
rval <- lapply(1:NROW(idxm), cotab1)
if(!is.null(dn)) names(rval) <- apply(expand.grid(dn[margin]), 1, function(z) paste(z, collapse = collapse))
return(rval)
}
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/co_table.R
|
coindep_test <- function(x, margin = NULL, n = 1000,
indepfun = function(x) max(abs(x)), aggfun = max,
alternative = c("greater", "less"),
pearson = TRUE)
{
DNAME <- deparse(substitute(x))
alternative <- match.arg(alternative)
if(is.null(margin)) {
rs <- rowSums(x)
cs <- colSums(x)
expctd <- rs %o% cs / sum(rs)
Pearson <- function(x) (x - expctd)/sqrt(expctd)
resids <- Pearson(x)
ff <- if(is.null(aggfun)) {
if(pearson) function(x) aggfun(indepfun(Pearson(x)))
else function(x) aggfun(indepfun(x))
} else {
if(pearson) function(x) indepfun(Pearson(x))
else function(x) indepfun(x)
}
if(length(dim(x)) > 2) stop("currently only implemented for (conditional) 2d tables")
dist <- sapply(r2dtable(n, rowSums(x), colSums(x)), ff)
STATISTIC <- ff(x)
} else {
ff <- if(pearson) function(x) indepfun(Pearson(x))
else function(x) indepfun(x)
cox <- co_table(x, margin)
nc <- length(cox)
if(length(dim(cox[[1]])) > 2) stop("currently only implemented for conditional 2d tables")
dist <- matrix(rep(0, n * nc), ncol = nc)
for(i in 1:nc) {
coxi <- cox[[i]]
cs <- colSums(coxi)
rs <- rowSums(coxi)
expctd <- rs %o% cs / sum(rs)
Pearson <- function(x) (x - expctd)/sqrt(expctd)
if(any(c(cs, rs) < 1)) warning("structural zeros") ## FIXME
dist[, i] <- sapply(r2dtable(n, rs, cs), ff)
}
dist <- apply(dist, 1, aggfun)
Pearson <- function(x) {
expctd <- rowSums(x) %o% colSums(x) / sum(x)
return((x - expctd)/sqrt(expctd))
}
STATISTIC <- aggfun(sapply(cox, ff))
## just for returning nicely formatted fitted values
## and residuals: fit once more with loglm()
vars <- names(dimnames(x))
condvars <- if(is.numeric(margin)) vars[margin] else margin
indvars <- vars[!(vars %in% condvars)]
coind.form <- as.formula(paste("~ (", paste(indvars, collapse = " + "),
") * ",
paste(condvars, collapse = " * "),
sep = ""))
fm <- loglm(coind.form, data = x, fitted = TRUE)
expctd <- fitted(fm)
resids <- residuals(fm, type = "pearson")
}
pdist <- function(x) sapply(x, function(y) mean(dist <= y))
qdist <- function(p) quantile(dist, p)
PVAL <- switch(alternative,
greater = mean(dist >= STATISTIC),
less = mean(dist <= STATISTIC))
METHOD <- "Permutation test for conditional independence"
names(STATISTIC) <- "f(x)"
rval <- list(statistic = STATISTIC,
p.value = PVAL,
method = METHOD,
data.name = DNAME,
observed = x,
expected = expctd,
residuals = resids,
margin = margin,
dist = dist,
qdist = qdist,
pdist = pdist)
class(rval) <- c("coindep_test", "htest")
return(rval)
}
fitted.coindep_test <- function(object, ...)
object$expected
## plot.coindep_test
## mosaic.coindep_test
## assoc.coindep_test
## difficult, depends on functionals...
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/coindep_test.R
|
cotabplot <- function(x, ...)
{
UseMethod("cotabplot")
}
cotabplot.formula <- function(formula, data = NULL, ...)
{
m <- match.call()
edata <- eval(m$data, parent.frame())
fstr <- deparse(formula)
fstr <- gsub("*", "+", fstr, fixed = TRUE)
fstr <- gsub("/", "+", fstr, fixed = TRUE)
fstr <- gsub("(", "", fstr, fixed = TRUE)
fstr <- gsub(")", "", fstr, fixed = TRUE)
fstr <- strsplit(paste(fstr, collapse = ""), "~")
vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+")
varnames <- vars[[1]]
condnames <- if(length(vars) > 1) vars[[2]] else NULL
if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) {
tab <- as.table(data)
if(all(varnames != ".")) {
ind <- match(varnames, names(dimnames(tab)))
if (any(is.na(ind)))
stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data))))
if (!is.null(condnames)) {
condind <- match(condnames, names(dimnames(tab)))
if (any(is.na(condind)))
stop(paste("Can't find", paste(condnames[is.na(condind)], collapse=" / "), "in", deparse(substitute(data))))
ind <- c(condind, ind)
}
tab <- margin.table(tab, ind)
}
} else {
tab <- if ("Freq" %in% colnames(data))
xtabs(formula(paste("Freq~", paste(c(condnames, varnames), collapse = " + "))),
data = data)
else
xtabs(formula(paste("~", paste(c(condnames, varnames), collapse = " + "))),
data = data)
}
tab <- margin.table(tab, match(c(varnames, condnames), names(dimnames(tab))))
cotabplot(tab, cond = condnames, ...)
}
cotabplot.default <- function(x, cond = NULL,
panel = cotab_mosaic, panel_args = list(),
margins = rep(1, 4), layout = NULL,
text_gp = gpar(fontsize = 12), rect_gp = gpar(fill = grey(0.9)),
pop = TRUE, newpage = TRUE, return_grob = FALSE, ...)
{
## coerce to table
x <- as.table(x)
## initialize newpage
if(newpage) grid.newpage()
## process default option
ldx <- length(dim(x))
if(is.null(cond)) {
indep <- if(ldx > 1) 1:2 else 1
if(ldx > 2) cond <- 3:ldx
} else {
if(is.character(cond)) cond <- match(cond, names(dimnames(x)))
cond <- as.integer(cond)
indep <- (1:ldx)[!(1:ldx %in% cond)]
}
## sort margins
x <- margin.table(x, c(indep, cond))
## convenience variables that describe conditioning variables
if(is.null(cond)) {
cond.n <- 0
cond.num <- cond.dnam <- cond.char <- NULL
} else {
cond.n <- length(cond) ## number of variables
cond.num <- (length(indep) + 1):ldx ## position in x
cond.dnam <- dimnames(x)[cond.num] ## corresponding dimnames
cond.char <- names(cond.dnam) ## names of variables
}
## create panel function (if necessary)
if(inherits(panel, "grapcon_generator"))
panel <- do.call("panel", c(list(x, cond.char), as.list(panel_args), list(...)))
if(cond.n < 1) panel(x, NULL) ## no conditioning variables
else {
cond.nlevels <- sapply(cond.dnam, length)
nplots <- prod(cond.nlevels)
condition <- as.matrix(expand.grid(cond.dnam))
## compute layout
#Z# needs fixing for more than two conditioning variables
if(is.null(layout)) {
layout <- c(1,1,1) ## rows, cols, pages
if(cond.n == 1) {
layout[2] <- ceiling(sqrt(floor(cond.nlevels)))
layout[1] <- ceiling(cond.nlevels/layout[2])
} else {
layout[1] <- cond.nlevels[1]
layout[2] <- cond.nlevels[2]
if(cond.n >= 3) layout[3] <- nplots/prod(cond.nlevels[1:2]) #Z# FIXME
if(layout[3] > 1) stop("multiple pages not supported yet")
}
} else {
layout <- c(rep(layout, length.out = 2), 1)
if(layout[1] * layout[2] < nplots) stop("number of panels specified in 'layout' is too small")
}
layout <- expand.grid(lapply(layout, function(x) 1:x))[1:nplots,]
## push basic grid of nr x nc cells
nr <- max(layout[,1])
nc <- max(layout[,2])
pushViewport(plotViewport(margins))
pushViewport(viewport(layout = grid.layout(nr, nc, widths = unit(1/nc, "npc"))))
strUnit <- unit(2 * ncol(condition), "strheight", "A")
cellport <- function(name) viewport(layout = grid.layout(2, 1,
heights = unit.c(strUnit, unit(1, "npc") - strUnit)),
name = name)
## go through each conditioning combination
for(i in 1:nrow(condition)) {
## conditioning information in ith cycle
condi <- as.vector(condition[i,])
names(condi) <- colnames(condition)
condistr <- paste(condi, collapse = ".")
condilab <- paste(cond.char, condi, sep = " = ")
## header
pushViewport(viewport(layout.pos.row = layout[i,1], layout.pos.col = layout[i,2]))
pushViewport(cellport(paste("cell", condistr, sep = ".")))
pushViewport(viewport(layout.pos.row = 1, name = paste("lab", condistr, sep = ".")))
grid.rect(gp = rect_gp)
grid.text(condilab, y = cond.n:1/cond.n - 1/(2*cond.n), gp = text_gp)
grid.segments(0, 0:cond.n/cond.n, 1, 0:cond.n/cond.n)
upViewport()
## main plot
pushViewport(viewport(layout.pos.row = 2, name = paste("plot", condistr, sep = ".")))
panel(x, condi)
upViewport(2)
grid.rect(gp = gpar(fill = "transparent"))
upViewport()
}
upViewport()
if(pop) popViewport() else upViewport()
}
if (return_grob)
invisible(structure(x, grob = grid.grab()))
else
invisible(x)
}
cotab_mosaic <- function(x = NULL, condvars = NULL, ...) {
function(x, condlevels) {
if(is.null(condlevels)) mosaic(x, newpage = FALSE, pop = FALSE, return_grob = FALSE, ...)
else mosaic(co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]],
newpage = FALSE, pop = FALSE, return_grob = FALSE,
prefix = paste("panel:", paste(names(condlevels), condlevels, sep = "=", collapse = ","), "|", sep = ""), ...)
}
}
class(cotab_mosaic) <- "grapcon_generator"
cotab_sieve <- function(x = NULL, condvars = NULL, ...) {
function(x, condlevels) {
if(is.null(condlevels)) sieve(x, newpage = FALSE, pop = FALSE, return_grob = FALSE, ...)
else sieve(co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]],
newpage = FALSE, pop = FALSE, return_grob = FALSE,
prefix = paste("panel:", paste(names(condlevels), condlevels, sep = "=", collapse = ","), "|", sep = ""), ...)
}
}
class(cotab_sieve) <- "grapcon_generator"
cotab_assoc <- function(x = NULL, condvars = NULL, ylim = NULL, ...) {
if(!is.null(x)) {
fm <- coindep_test(x, condvars, n = 1)
if(is.null(ylim)) ylim <- range(residuals(fm))
}
function(x, condlevels) {
if(is.null(condlevels)) assoc(x, newpage = FALSE, pop = FALSE, ylim = ylim, return_grob = FALSE, ...)
else assoc(co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]],
newpage = FALSE, pop = FALSE, return_grob = FALSE, ylim = ylim,
prefix = paste("panel:", paste(names(condlevels), condlevels, sep = "=", collapse = ","), "|", sep = ""), ...)
}
}
class(cotab_assoc) <- "grapcon_generator"
cotab_fourfold <- function (x = NULL, condvars = NULL, ...) {
function(x, condlevels) {
if (is.null(condlevels))
fourfold(x, newpage = FALSE, return_grob = FALSE, ...)
else
fourfold(co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]],
newpage = FALSE, return_grob = FALSE, ...)
}
}
class(cotab_fourfold) <- "grapcon_generator"
cotab_loddsratio <- function(x = NULL, condvars = NULL, ...) {
function(x, condlevels) {
if(is.null(condlevels)) {
plot(loddsratio(x, ...), newpage = FALSE, pop = FALSE, return_grob = FALSE, ...)
} else {
plot(loddsratio(co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]], ...),
newpage = FALSE, pop = FALSE, return_grob = FALSE,
prefix = paste("panel:", paste(names(condlevels), condlevels, sep = "=", collapse = ","), "|", sep = ""), ...)
}
upViewport(2)
}
}
class(cotab_loddsratio) <- "grapcon_generator"
cotab_agreementplot <- function(x = NULL, condvars = NULL, ...) {
function(x, condlevels) {
if(is.null(condlevels)) agreementplot(x, newpage = FALSE, pop = FALSE, return_grob = FALSE, ...)
else agreementplot(co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]], newpage = FALSE, pop = FALSE, return_grob = FALSE,
prefix = paste("panel:", paste(names(condlevels), condlevels, sep = "=", collapse = ","), "|", sep = ""), ...)
}
}
class(cotab_agreementplot) <- "grapcon_generator"
cotab_coindep <- function(x, condvars,
test = c("doublemax", "maxchisq", "sumchisq"),
level = NULL, n = 1000, interpolate = c(2, 4),
h = NULL, c = NULL, l = NULL, lty = 1,
type = c("mosaic", "assoc"),
legend = FALSE, ylim = NULL, ...)
{
if(is.null(condvars))
stop("at least one conditioning variable is required")
## set color defaults
if(is.null(h)) h <- c(260, 0)
if(is.null(c)) c <- c(100, 20)
if(is.null(l)) l <- c(90, 50)
## process conditional variables and get independent variables
## store some convenience information
ldx <- length(dim(x))
if(is.character(condvars)) condvars <- match(condvars, names(dimnames(x)))
condvars <- as.integer(condvars)
indep <- (1:ldx)[!(1:ldx %in% condvars)]
## sort margins
x <- margin.table(x, c(indep, condvars))
ind.n <- length(indep)
ind.num <- 1:ind.n
ind.dnam <- dimnames(x)[ind.num]
ind.char <- names(ind.dnam)
cond.n <- length(condvars)
cond.num <- (ind.n + 1):length(dim(x))
cond.dnam <- dimnames(x)[cond.num]
cond.char <- names(cond.dnam)
test <- match.arg(test)
switch(test,
"doublemax" = {
if(is.null(level)) level <- c(0.9, 0.99)
fm <- coindep_test(x, cond.num, n = n)
resids <- residuals(fm)
col.bins <- fm$qdist(sort(level))
gpfun <- shading_hcl(observed = NULL, residuals = NULL, expected = NULL, df = NULL,
h = h, c = c, l = l, interpolate = col.bins, lty = lty, p.value = fm$p.value)
},
"maxchisq" = {
if(is.null(level)) level <- 0.95
level <- level[1]
fm <- coindep_test(x, cond.num, n = n, indepfun = function(x) sum(x^2))
resids <- residuals(fm)
chisqs <- sapply(co_table(residuals(fm), fm$margin), function(x) sum(x^2))
pvals <- 1 - fm$pdist(chisqs)
gpfun <- sapply(pvals, function(p)
shading_hcl(observed = NULL, residuals = NULL, expected = NULL, df = NULL,
h = h, c = c, l = l, interpolate = interpolate, lty = lty, level = level, p.value = p))
},
"sumchisq" = {
if(is.null(level)) level <- 0.95
level <- level[1]
fm <- coindep_test(x, cond.num, n = n, indepfun = function(x) sum(x^2), aggfun = sum)
resids <- residuals(fm)
gpfun <- shading_hcl(observed = NULL, residuals = NULL, expected = NULL, df = NULL,
h = h, c = c, l = l, interpolate = interpolate, lty = lty, level = level, p.value = fm$p.value)
})
type <- match.arg(type)
if(type == "mosaic") {
rval <- function(x, condlevels) {
if(is.null(condlevels)) {
tab <- x
gp <- if(is.list(gpfun)) gpfun[[1]] else gpfun
} else {
tab <- co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]]
gp <- if(is.list(gpfun)) gpfun[[paste(condlevels, collapse = ".")]] else gpfun
}
mosaic(tab, newpage = FALSE, pop = FALSE, return_grob = FALSE, gp = gp, legend = legend,
prefix = paste("panel:", paste(names(condlevels), condlevels, sep = "=", collapse = ","), "|", sep = ""), ...)
}
} else {
if(is.null(ylim)) ylim <- range(resids)
rval <- function(x, condlevels) {
if(is.null(condlevels)) {
tab <- x
gp <- if(is.list(gpfun)) gpfun[[1]] else gpfun
} else {
tab <- co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]]
gp <- if(is.list(gpfun)) gpfun[[paste(condlevels, collapse = ".")]] else gpfun
}
assoc(tab, newpage = FALSE, pop = FALSE, return_grob = FALSE, gp = gp, legend = legend, ylim = ylim,
prefix = paste("panel:", paste(names(condlevels), condlevels, sep = "=", collapse = ","), "|", sep = ""), ...)
}
}
return(rval)
}
class(cotab_coindep) <- "grapcon_generator"
|
/scratch/gouwar.j/cran-all/cranData/vcd/R/cotabplot.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.