content
stringlengths
0
14.9M
filename
stringlengths
44
136
# Copyright 2010-2014 Google Inc. All Rights Reserved. # Author: [email protected] (Steve Scott) logit.spike <- function(formula, niter, data, subset, prior = NULL, na.action = options("na.action"), contrasts = NULL, drop.unused.levels = TRUE, initial.value = NULL, ping = niter / 10, nthreads = 0, clt.threshold = 2, mh.chunk.size = 10, proposal.df = 3, sampler.weights = c("DA" = .333, "RWM" = .333, "TIM" = .333), seed = NULL, ...) { ## Uses Bayesian MCMC to fit a logistic regression model with a ## spike-and-slab prior. ## ## Args: ## formula: model formula, as would be passed to 'glm', specifying the ## maximal model (i.e. the model with all predictors included). ## niter: desired number of MCMC iterations ## data: optional data.frame containing the data described in 'formula' ## subset: an optional vector specifying a subset of observations to be used ## in the fitting process. ## prior: an optional object inheriting from SpikeSlabGlmPrior. If missing, ## a prior will be constructed by calling LogitZellnerPrior with the ## remaining arguments. ## na.action: a function which indicates what should happen when the data ## contain ‘NA’s. The default is set by the ‘na.action’ setting of ## ‘options’, and is ‘na.fail’ if that is unset. The ‘factory-fresh’ ## default is ‘na.omit’. Another possible value is ‘NULL’, no action. ## Value ‘na.exclude’ can be useful. ## contrasts: an optional list. See the ‘contrasts.arg’ of ## ‘model.matrix.default’. An optional list. ## drop.unused.levels: should factor levels that are unobserved be dropped ## from the model? ## initial.value: Initial value of logistic regression coefficients for the ## MCMC algorithm. Can be given as a numeric vector, a 'logit.spike' ## object, or a 'glm' object. If a 'logit.spike' object is used for ## initialization, it is assumed to be a previous MCMC run to which ## 'niter' futher iterations should be added. If a 'glm' object is ## supplied, its coefficients will be used as the initial values in the ## MCMC simulation. ## ping: if positive, then print a status update every 'ping' MCMC ## iterations. ## nthreads: The number of threads to use when imputing latent data. ## clt.threshold: The smallest number of successes or failures needed to do ## use asymptotic data augmentation. ## mh.chunk.size: The largest number of parameters to draw together in a ## single Metropolis-Hastings proposal. A non-positive number means to ## use a single chunk. ## proposal.df: The degrees of freedom parameter for the multivariate T ## proposal distribution used for Metropolis-Hastings updates. A ## nonpositive number means to use a Gaussian proposal. ## sampler.weights: A 3-vector representing a discrete probability ## distribution. What fraction of the time should the sampler spend. The ## vector must have names "DA", "TIM", and "RWM" corresponding to data ## augmentation, tailored independence Metropolis, and random walk ## Metropolis. ## seed: Seed to use for the C++ random number generator. NULL or an int. ## If NULL, then the seed will be taken from the global .Random.seed ## object. ## ... : parameters to be passed to LogitZellnerPrior. ## ## Returns: ## An object of class 'logit.spike', which is a list containing the ## following values ## ## - beta: A 'niter' by 'ncol(X)' matrix of regression coefficients ## many of which may be zero. Each row corresponds to an MCMC ## iteration. ## - prior: The prior that was used to fit the model. ## ## In addition, the returned object contains sufficient details for ## the call to model.matrix in the predict.lm.spike method. stopifnot(is.numeric(sampler.weights), length(sampler.weights) == 3, "DA" %in% names(sampler.weights), "TIM" %in% names(sampler.weights), "RWM" %in% names(sampler.weights), all(sampler.weights >= 0), all(sampler.weights <= 1), abs(sum(sampler.weights) - 1.0) < .01) has.data <- !missing(data) cl <- match.call() mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L) mf <- mf[c(1L, m)] mf$drop.unused.levels <- drop.unused.levels mf[[1L]] <- as.name("model.frame") mf <- eval(mf, parent.frame()) mt <- attr(mf, "terms") response <- model.response(mf, "any") ## Unpack the vector of trials. If y is a 2-column matrix then the first ## column is the vector of success counts and the second is the vector of ## failure counts. Otherwise y is just a vector, and the vector of trials ## should just be a column of 1's. if (!is.null(dim(response)) && length(dim(response)) > 1) { stopifnot(length(dim(response)) == 2, ncol(response) == 2) ## If the user passed a formula like "cbind(successes, failures) ~ ## x", then y will be a two column matrix ny <- response[, 1] + response[, 2] response <- response[, 1] } else { ## The following line admits y's which are TRUE/FALSE, 0/1 or 1/-1. response <- response > 0 ny <- rep(1, length(response)) } design <- model.matrix(mt, mf, contrasts) if (is.null(prior)) { prior <- LogitZellnerPrior(design, response, ...) } stopifnot(inherits(prior, "SpikeSlabGlmPrior")) if (!is.null(initial.value)) { if (inherits(initial.value, "logit.spike")) { stopifnot(colnames(initial.value$beta) == colnames(design)) beta0 <- as.numeric(tail(initial.value$beta, 1)) } else if (inherits(initial.value, "glm")) { stopifnot(colnames(initial.value$beta) == colnames(design)) beta0 <- coef(initial.value) } else if (is.numeric(initial.value)) { stopifnot(length(initial.value) == ncol(design)) beta0 <- initial.value } else { stop("initial.value must be a 'logit.spike' object, a 'glm' object,", "or a numeric vector") } } else { ## No initial value was supplied beta0 <- prior$mu } stopifnot(is.matrix(design), nrow(design) == length(response), length(prior$mu) == ncol(design), length(prior$prior.inclusion.probabilities) == ncol(design), all(ny >= response), all(response >= 0)) if (is.null(prior$max.flips)) { prior$max.flips <- -1 } if (!is.null(seed)) { seed <- as.integer(seed) } ## Make sure the sampler weights are in the expected order. sampler.weights <- sampler.weights[c("DA", "RWM", "TIM")] ans <- .Call("logit_spike_slab_wrapper", as.matrix(design), as.integer(response), as.integer(ny), prior, as.integer(niter), as.integer(ping), as.integer(nthreads), beta0, as.integer(clt.threshold), as.integer(mh.chunk.size), sampler.weights, seed) ans$prior <- prior class(ans) <- c("logit.spike", "glm.spike") ## The stuff below will be needed by predict.logit.spike. ans$contrasts <- attr(design, "contrasts") ans$xlevels <- .getXlevels(mt, mf) ans$call <- cl ans$terms <- mt ## The next few entries are needed by some of the diagnostics plots and by ## summary.logit.spike. fitted.logits <- design %*% t(ans$beta) log.likelihood.contributions <- response * fitted.logits + ny * plogis(fitted.logits, log.p = TRUE, lower.tail = FALSE) ans$log.likelihood <- colSums(log.likelihood.contributions) sign <- rep(1, length(response)) sign[response / ny < 0.5] <- -1 ans$deviance.residuals <- sign * sqrt(rowMeans( -2 * log.likelihood.contributions)) p.hat <- sum(response) / sum(ny) ans$null.log.likelihood <- sum( response * log(p.hat) + (ny - response) * log(1 - p.hat)) fitted.probabilities <- plogis(fitted.logits) ans$fitted.probabilities <- rowMeans(fitted.probabilities) ans$fitted.logits <- rowMeans(fitted.logits) # Chop observed data into 10 buckets. Equal numbers of data points in each # bucket. Compare the average predicted success probability of the # observations in that bucket with the empirical success probability for that # bucket. # # dimension of fitted values is nobs x niter if (!is.null(initial.value) && inherits(initial.value, "logit.spike")) { ans$beta <- rbind(initial.value$beta, ans$beta) } ans$response <- response if (any(ny != 1)) { ans$trials <- ny } colnames(ans$beta) <- colnames(design) if (has.data) { ## Note, if a data.frame was passed as an argument to this function then ## saving the data frame will be cheaper than saving the model.frame. ans$training.data <- data } else { ## If the model was called with a formula referring to objects in another ## environment, then saving the model frame will capture these variables so ## they can be used to recreate the design matrix. ans$training.data <- mf } ## Make the answer a class, so that the right methods will be used. class(ans) <- c("logit.spike", "lm.spike", "glm.spike") return(ans) } predict.logit.spike <- function(object, newdata, burn = 0, type = c("prob", "logit", "link", "response"), na.action = na.pass, ...) { ## Prediction method for logit.spike ## Args: ## object: object of class "logit.spike" returned from the logit.spike ## function ## newdata: A data frame including variables with the same names as the data ## frame used to fit 'object'. ## burn: The number of MCMC iterations in 'object' that should be discarded. ## If burn < 0 then all iterations are kept. ## type: The type of prediction desired. If 'prob' then the prediction is ## returned on the probability scale. If 'logit' then it is returned on ## the logit scale (i.e. the scale of the linear predictor). Also accepts ## 'link' and 'response' for compatibility with predict.glm. ## ...: unused, but present for compatibility with generic predict(). ## ## Returns: ## A matrix of predictions, with each row corresponding to a row in newdata, ## and each column to an MCMC iteration. type <- match.arg(type) predictors <- GetPredictorMatrix(object, newdata, na.action = na.action, ...) beta <- object$beta if (burn > 0) { beta <- beta[-(1:burn), , drop = FALSE] } eta <- predictors %*% t(beta) if (type == "logit" || type == "link") return(eta) if (type == "prob" || type == "response") return(plogis(eta)) } plot.logit.spike <- function( x, y = c("inclusion", "coefficients", "scaled.coefficients", "fit", "residuals", "size", "help"), burn = SuggestBurnLogLikelihood(x$log.likelihood), ...) { ## S3 method for plotting logit.spike objects. ## Args: ## x: The object to be plotted. ## y: The type of plot desired. ## ...: Additional named arguments passed to the functions that ## actually do the plotting. y <- match.arg(y) if (y == "inclusion") { PlotMarginalInclusionProbabilities(x$beta, burn = burn, ...) } else if (y == "coefficients") { PlotLmSpikeCoefficients(x$beta, burn = burn, ...) } else if (y == "scaled.coefficients") { scale.factors <- apply(model.matrix(x), 2, sd) PlotLmSpikeCoefficients(x$beta, burn = burn, scale.factors = scale.factors, ...) } else if (y == "fit") { PlotLogitSpikeFitSummary(x, burn = burn, ...) } else if (y == "residuals") { PlotLogitSpikeResiduals(x, ...) } else if (y == "size") { PlotModelSize(x$beta, burn = burn, ...) } else if (y == "help") { help("plot.logit.spike", package = "BoomSpikeSlab", help_type = "html") } else { stop("Unrecognized option", y, "in plot.logit.spike") } } PlotLogitSpikeResiduals <- function(model, ...) { ## Args: ## model: An object of class logit.spike. ## ...: Optional named arguments passed to plot(). ## ## Details: ## ## The "deviance residuals" are defined as the signed square root each ## observation's contribution to log likelihood. The sign of the residual is ## positive if half or more of the trials associated with an observation are ## successes. The sign is negative otherwise. ## ## The "contribution to log likelihood" is taken to be the posterior mean of ## an observations log likelihood contribution, averaged over the life of the ## MCMC chain. ## ## The deviance residual is plotted against the fitted value, again averaged ## over the life of the MCMC chain. ## ## The plot also shows the .95 and .99 bounds from the square root of a ## chi-square(1) random variable. As a rough approximation, about 5% and 1% ## of the data should lie outside these bounds. residuals <- model$deviance.residuals fitted <- model$fitted.logits plot(fitted, residuals, pch = ifelse(residuals > 0, "+", "-"), col = ifelse(residuals > 0, "red", "blue"), xlab = "fitted logit", ylab = "deviance residual", ...) abline(h = 0) abline(h = c(-1, 1) * sqrt(qchisq(.95, df = 1)), lty = 2, col = "lightgray") abline(h = c(-1, 1) * sqrt(qchisq(.99, df = 1)), lty = 3, col = "lightgray") legend("topright", pch = c("+", "-"), col = c("red", "blue"), legend = c("success", "failure")) } PlotLogitSpikeFitSummary <- function( model, burn = 0, which.summary = c("both", "r2", "bucket"), scale = c("logit", "probability"), cutpoint.basis = c("sample.size", "equal.range"), number.of.buckets = 10, ...) { ## Args: ## model: An object of class logit.spike to be plotted. ## burn: A number of initial MCMC iterations to be discarded. ## which.summary: Which fit summaries should be plotted. ## scale: The scale on which to plot the 'bucket' summary. ## ...: Extra arguments passed to plot(). stopifnot(inherits(model, "logit.spike")) which.summary <- match.arg(which.summary) scale <- match.arg(scale) cutpoint.basis <- match.arg(cutpoint.basis) fit <- summary(model, burn = burn, cutpoint.scale = scale, cutpoint.basis = cutpoint.basis, number.of.buckets = number.of.buckets) if (which.summary == "both") { opar <- par(mfrow = c(1, 2)) on.exit(par(opar)) } if (which.summary %in% c("both", "r2")) { r2 <- fit$deviance.r2.distribution plot.ts(r2, xlab = "MCMC Iteration", ylab = "deviance R-square", main = "Deviance R-square", ...) } if (which.summary %in% c("both", "bucket")) { bucket.fit <- fit$predicted.vs.actual if (scale == "logit") { bucket.fit <- qlogis(bucket.fit) bucket.fit[!is.finite(bucket.fit)] <- NA x.label = "predicted logit" y.label = "observed logit" } else { x.label = "predicted probability" y.label = "observed probability" } if (any(is.na(bucket.fit))) { warning( "Some buckets were empty, or had empirical probabilities of 0 or 1.") } plot(bucket.fit, main = "Probabilities by decile", xlab = x.label, ylab = y.label, ...) if (length(attributes(bucket.fit)$cutpoints) > 1) { abline(v = attributes(bucket.fit)$cutpoints, lty = 3, col = "lightgray") } abline(a = 0, b = 1) } } summary.logit.spike <- function( object, burn = 0, order = TRUE, cutpoint.scale = c("probability", "logit"), cutpoint.basis = c("sample.size", "equal.range"), number.of.buckets = 10, coefficients = TRUE, ...) { ## Summary method for logit.spike coefficients ## ## Args: ## object: an object of class 'logit.spike' ## burn: an integer giving the number of MCMC iterations to discard as ## burn-in ## order: Logical indicating whether the output should be ordered according ## to posterior inclusion probabilities ## ## Returns: ## An object of class 'summary.logit.spike' that summarizes the model ## coefficients as in SummarizeSpikeSlabCoefficients. if (coefficients) { coefficient.table <- SummarizeSpikeSlabCoefficients(object$beta, burn, order) } else { coefficient.table <- NULL } deviance.r2 <- (object$null.log.likelihood - object$log.likelihood) / object$null.log.likelihood index <- seq_along(object$log.likelihood) if (burn > 0) { index <- index[-(1:burn)] } log.likelihood <- object$log.likelihood[index] response <- object$response trials <- object$trials if (is.null(object$trials)) { trials <- rep(1, length(response)) } cutpoint.scale <- match.arg(cutpoint.scale) if (cutpoint.scale == "probability") { fitted <- object$fitted.probabilities } else { fitted <- object$fitted.logits } cutpoint.basis = match.arg(cutpoint.basis) if (cutpoint.basis == "sample.size") { cutpoints <- quantile(fitted, (0:number.of.buckets) / number.of.buckets) } else if (cutpoint.basis == "equal.range") { fitted.range <- range(fitted, na.rm = TRUE) cutpoints <- seq(min(fitted.range), max(fitted.range), len = number.of.buckets + 1) } cutpoints <- unique(cutpoints) if (length(cutpoints) == 1) { ## Changing the type of "cutpoints" to keep R from choking on a ## "breaks" argument of length 1. cutpoints <- 2 } bucket.indicators <- cut(fitted, cutpoints) fitted.value.buckets <- split(fitted, bucket.indicators) bucket.predicted.means <- tapply(object$fitted.probabilities, bucket.indicators, mean) bucket.actual.means <- tapply(response / trials, bucket.indicators, mean) bucket.fit <- cbind(predicted = bucket.predicted.means, observed = bucket.actual.means) attributes(bucket.fit)$cutpoints <- cutpoints ans <- list(coefficients = coefficient.table, null.log.likelihood = object$null.log.likelihood, mean.log.likelihood = mean(log.likelihood), max.log.likelihood = max(log.likelihood), deviance.r2 = mean(deviance.r2[index]), deviance.r2.distribution = deviance.r2[index], predicted.vs.actual = bucket.fit) class(ans) <- "summary.logit.spike" return(ans) } print.summary.logit.spike <- function(x, ...) { ## print method for summary.logit.spike objects. cat("null log likelihood: ", x$null.log.likelihood, "\n") cat("posterior mean log likelihood: ", x$mean.log.likelihood, "\n") cat("posterior max log likelihood: ", x$max.log.likelihood, "\n") cat("mean deviance R-sq: ", x$deviance.r2, "\n") cat("\npredicted vs observed success rates, by decile:\n") fit <- x$predicted.vs.actual attributes(fit)$cutpoints <- NULL print(fit) if (!is.null(x$coefficients)) { cat("\nsummary of coefficients:\n") print.default(signif(x$coefficients, 3)) } }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/logit.spike.R
mlm.spike <- function(subject.formula, choice.formula = NULL, niter, data, choice.name.separator = ".", contrasts = NULL, subset, prior = NULL, ping = niter / 10, proposal.df = 3, rwm.scale.factor = 1, nthreads = 1, mh.chunk.size = 10, proposal.weights = c("DA" = .5, "RWM" = .25, "TIM" = .25), seed = NULL, ...) { ## Spike and slab regression for multinomial logit models. ## Extensive details about the model and MCMC algorithm are ## supplied below. ## ## Args: ## subject.formula: A model formula for the portion of the model ## relating the response to the subject level predictors. The ## response variable in this formula must be coercible to a ## factor. If only subject level intercepts are desired the ## formula should look like 'y ~ 1`. If subject level ## intercepts are not desired then `y ~ 0`. ## choice.formula: An optional formula relating the response ## variable to choice level characteristics. The response ## variable should be the same as in subject.formula (though ## technically it can be omitted). The variable names used in ## the formula should omit the choice levels (which are a ## required part of the variable names in the 'data' ## argument). Thus the formula should be 'y ~ MPG + HP', not ## 'y ~ MPG.Honda + HP.Honda'. ## niter: The desired number of MCMC iterations. ## data: A data frame containing the data referenced in the ## 'subject.formula' and 'choice.formula' arguments. If ## 'choice.formula' is NULL then this argument is optional, ## and variables will be pulled from the parent environment if ## it is omitted. If 'choice.formula' is non-NULL, then ## 'data' must be supplied. A variable measuring a choice ## characteristic must be present for each choice level in the ## response variable. The stem for the variable names ## measuring the same concept must be identical, and choice ## level must be appended as a suffix, separated by a "." ## character. Thus, if 'HP' is a variable to be considered, ## and the response levels are 'Toyota', 'Honda', 'Chevy', ## then the data must contain variables named 'HP.Toyota', ## 'HP.Honda', and 'HP.Chevy', measuring HP for the different ## choices, whether they were chosen or not. ## choice.name.separator: The character used to separate the ## predictor names from the choice values for the choice-level ## predictor variables in 'data'. ## contrasts: An optional list indicating how contrasts and ## dummy variables are to be coded in the design matrix. See ## the contrasts.arg argument of 'model.matrix.default'. ## subset: an optional vector specifying a subset of ## observations to be used in the fitting process. ## prior: An object of class IndependentSpikeSlabPrior ## specifying the prior distribution of coefficient vector. ## See 'details' for more explanation about how the model ## is parameterized. ## ping: The frequency with which status updates are printed to ## the console. Measured in MCMC iterations. ## proposal.df: The tail thickness ("degress of freedom") ## parameter for the T distribution used to make ## Metropolis-Hastings proposals. ## rwm.scale.factor: A positive scalar. The scale factor ## applied to the asymptotic variance estimate for random walk ## Metropolis proposals. Larger values produce proposals with ## larger variances, which will be accepted less often, but ## which will produce larger jumps. Values between 0 and 1 ## produce smaller jumps that will be accepted more often. ## nthreads: The number of threads to use during data ## augmentation. If the data size is very large then multiple ## threads can make data augmentation much faster, though they ## can actually slow things down in small problems. ## mh.chunk.size: The Metropolis-Hastings portions of the ## algorithm will operate on the model parameters a chunk at a ## time. ## proposal.weights: A vector of 3 probabilities (summing to 1) ## indicating the probability of each type of MH proposal ## during each iteration. ## seed: An integer to use as a seed for the C++ random number ## generator. If left NULL, the RNG will be seeded using the ## system clock. ## ...: Extra arguments passed to MultinomialLogitSpikeSlabPrior. ## These are ignored if 'prior' is non-NULL. ## ## Model details: ## A multinomial logit model has two sets of predictors: one measuring ## characterisitcs of the subject making the choice, and the other ## measuring characteristics of the items being chosen. The model ## can be written ## ## Pr(y[i] = m) \propto exp(beta.subject[, m] * x.subject[i, ] ## + beta.choice * x.choice[i, , m]) ## ## The coefficients in this model are beta.subject and beta.choice. ## beta.choice is a subject.xdim by ('nchoices' - 1) matrix. Each row ## multiplies the design matrix produced by subject.formula for a ## particular choice level, where the first choice level is omitted ## (logically set to zero) for identifiability. beta.choice is a ## vector multiplying the design matrix produced by choice.formula, ## and thre are 'nchoices' of such matrices. ## ## The coefficient vector 'beta' is the concatenation ## c(beta.subject, beta.choice), where beta.subject is vectorized ## by stacking its columns (in the usual R fashion). This means ## that the first contiguous region of beta contains the ## subject-level coefficients for choice level 2. ## ## MCMC details: ## The MCMC algorithm randomly moves between three tyes of updates: ## data augmentation (DA), random walk Metropolis (RWM), and ## tailored independence Metropolis (TIM). ## ## * DA: Each observation in the model is associated with a set of ## latent variables that renders the complete data posterior ## distribution conditionally Gaussian. The augmentation scheme ## is described in Tuchler (2008). The data augmentation ## algorithm conditions on the latent data, and integrates out ## the coefficients, to sample the inclusion vector (i.e. the ## vector of indicators showing which coefficients are nonzero) ## using Gibbs sampling. Then the coefficients are sampled given ## complete data conditional on inclusion. This is the only move ## that attemps a dimension change. ## ## * RWM: A chunk of the coefficient vector (up to mh.chunk.size) ## is selected. The proposal distribution is either ## multivariate normal or multivariate T (depending on ## 'proposal.df') centered on current values of this chunk. ## The precision parameter of the normal (or T) is the negative ## Hessian of the un-normalized log posterior, evaluated at the ## current value. The precision is divided by ## rwm.scale.factor. Only coefficients currently included in ## the model at the time of the proposal will be modified. ## ## * TIM: A chunk of the coefficient vector (up to mh.chunk.size) ## is selected. The proposal distribution is constructed by ## locating the posterior mode (using the current value as a ## starting point). The proposal is a Gaussian (or ## multivariate T) centered on the posterior mode, with ## precision equal to the negative Hessian evaluated at the ## mode. This is an expensive, but effective step. If the ## posterior mode finding fails (for numerical reasons) then a ## RWM proposal will be attempted instead. ## ## Value: ## Returns an object of class mlm.spike, which is a list containing ## beta: A matrix containing the MCMC draws of the model ## coefficients. Rows in the matrix correspond to MCMC draws. ## Columns correspond to different coefficients. ## prior: The prior distribution used to fit the model. ## MH.accounting: A summary of the amount of time spent, successes ## and failures for each move type. ## Create the model matrix for the subject predictors. function.call <- match.call(expand.dots = FALSE) important.arguments <- match(c("subject.formula", "data", "subset"), names(function.call), 0L) subject.frame.call <- function.call[c(1L, important.arguments)] subject.frame.call[[1L]] <- quote(stats::model.frame) names(subject.frame.call)[2] <- "formula" subject.frame.call[["drop.unused.levels"]] <- TRUE subject.frame <- eval(subject.frame.call, parent.frame()) subject.terms <- attr(subject.frame, "terms") subject.predictor.matrix <- model.matrix(subject.terms, subject.frame, contrasts) response <- as.factor(model.response(subject.frame)) if (!is.factor(response)) { stop("'", deparse(subject.formula[[2]]), "' is not a factor") } ## Create the model matrix for the choice predictors. choice.predictor.matrix <- NULL choice.predictor.subject.id <- NULL choice.predictor.choice.id <- NULL response.levels <- levels(response) if (!is.null(choice.formula)) { if (missing(data)) { stop("Choice predictors must be contained in a data frame ", "passed by the 'data' argument.") ## TODO(figure out a way to support data in the parent.frame) } pattern <- paste0(choice.name.separator, response.levels, collapse = "|") choice.predictor.names <- names(data)[grep(choice.name.separator, names(data), fixed = TRUE)] long.data <- reshape(data, varying = choice.predictor.names, times = response.levels, direction = "long", sep = choice.name.separator) names(long.data)[names(long.data) == "time"] <- "potential.choice" important.arguments <- match(c("choice.formula", "data", "subset"), names(function.call), 0L) choice.frame.call <- function.call[c(1L, important.arguments)] choice.frame.call[[1L]] <- quote(stats::model.frame) names(choice.frame.call)[2] <- "formula" choice.frame.call[["formula"]] <- update(as.formula(choice.frame.call[["formula"]]), ~ . -1) choice.frame.call[["data"]] <- quote(long.data) subject.frame.call[["drop.unused.levels"]] <- TRUE choice.frame <- eval(choice.frame.call) choice.terms <- attr(choice.frame, "terms") choice.predictor.matrix <- model.matrix(choice.terms, choice.frame, contrasts) } ## Setup the prior. if (is.null(prior)) { prior <- MultinomialLogitSpikeSlabPrior( response = response, subject.x = subject.predictor.matrix, choice.x = choice.predictor.matrix, ...) } stopifnot(inherits(prior, "IndependentSpikeSlabPrior")) ## Check the proposal weights. stopifnot(is.numeric(proposal.weights)) stopifnot(length(proposal.weights) == 3) if (any(proposal.weights < 0)) { stop("You can't have a negative proposal weight.") } proposal.weights.sum <- sum(proposal.weights) if (proposal.weights.sum <= 0) { stop("At least one entry in proposal.weights must be positive.") } proposal.weights <- proposal.weights / proposal.weights.sum proposal.weight.names <- names(proposal.weights) if (!is.null(proposal.weight.names)) { ## If the proposal weights were given, be sure they are in the ## right order. if (!all(c("DA", "RWM", "TIM") %in% proposal.weight.names)) { stop("Proposal weight names should include 'DA', 'RWM', and 'TIM'.") } proposal.weights <- c("DA" = proposal.weights["DA"], "RMW" = proposal.weights["RWM"], "TIM" = proposal.weights["TIM"]) } ## Run the sampler. ans<- .Call(analysis_common_r_multinomial_logit_spike_slab, response, subject.predictor.matrix, choice.predictor.matrix, choice.predictor.subject.id, choice.predictor.choice.id, prior, niter, ping, proposal.df, rwm.scale.factor, nthreads, mh.chunk.size, proposal.weights, seed) ans$prior <- prior subject.beta.names <- NULL if (length(subject.predictor.matrix) > 0) { subject.predictor.names <- colnames(subject.predictor.matrix) subject.beta.names <- outer(subject.predictor.names, response.levels[-1], FUN = paste, sep = ":") } choice.beta.names <- NULL if (length(choice.predictor.matrix) > 0) { choice.beta.names <- colnames(choice.predictor.matrix) } colnames(ans$beta) <- c(subject.beta.names, choice.beta.names) class(ans) <- c("mlm.spike", "logit.spike", "lm.spike") return(ans) } ##====================================================================== MultinomialLogitSpikeSlabPrior <- function( response, subject.x, expected.subject.model.size = 1, choice.x = NULL, expected.choice.model.size = 1, max.flips = -1, nchoices = length(levels(response)), subject.dim = ifelse(is.null(subject.x), 0, ncol(subject.x)), choice.dim = ifelse(is.null(choice.x), 0, ncol(choice.x))) { ## Build a prior distribution to be used with mlm.spike. ## ## Args: ## response: The response variable in the multinomial logistic ## regression. The response variable is optional if nchoices ## is supplied. If 'response' is provided then the prior ## means for the subject level intercpets will be chosen to ## match the empirical values of the response. ## subject.x: The design matrix for subject-level predictors. ## This can be NULL or of length 0 if no subject-level ## predictors are present. ## expected.subject.model.size: The expected number of non-zero ## coefficients -- per choice level -- in the subject specific ## portion of the model. All coefficients can be forced into ## the model by setting this to a negative number, or by setting ## it to be larger than the dimension of the subject-level ## predictors. ## choice.x: The design matrix for choice-level predictors. Each ## row of this matrix represents the characteristics of a choice ## in a choice occasion, so it takes 'nchoices' rows to encode ## one observation. This can be NULL or of length 0 if no ## choice-level predictors are present. ## expected.choice.model.size: The expected number of non-zero ## coefficients in the choice-specific portion of the model. ## All choice coefficients can be forced into the model by ## setting this to a negative number, or by setting it to be ## larger than the dimension of the choice-level predictors (for ## a single response level). ## max.flips: The maximum number of variable inclusion indicators ## the sampler will attempt to sample each iteration. If negative ## then all indicators will be sampled. ## nchoices: Tne number of potential response levels. ## subject.dim: The number of potential predictors in the ## subject-specific portion of the model. ## choice.dim: The number of potential predictors in the ## choice-specific portion of the model. ## ## Returns: ## An object of class IndependentSpikeSlabPrior, with elements ## arranged as expected by mlm.spike. subject.beta.dim <- (nchoices - 1) * subject.dim ##-------- Build prior.inclusion.probabilities --------- if (expected.subject.model.size > subject.dim || expected.subject.model.size < 0) { subject.prior.inclusion.probabilities <- rep(1, subject.beta.dim) expected.subject.model.size <- (nchoices - 1) * subject.dim } else { subject.prior.inclusion.probabilities <- rep(expected.subject.model.size / subject.dim, subject.beta.dim) } choice.prior.inclusion.probabilities <- numeric(0) if (choice.dim > 0) { if (expected.choice.model.size >= choice.dim || expected.choice.model.size < 0) { choice.prior.inclusion.probabilities <- rep(1, choice.dim) expected.choice.model.size <- choice.dim } else { choice.prior.inclusion.probabilities <- rep(expected.choice.model.size / choice.dim, choice.dim) } } prior.inclusion.probabilities <- c(subject.prior.inclusion.probabilities, choice.prior.inclusion.probabilities) ##------ Build prior.mean -------- subject.prior.mean <- matrix(0, nrow = subject.dim, ncol = nchoices - 1) choice.prior.mean <- rep(0, choice.dim) subject.intercept <- FALSE if (!missing(response) && !is.null(subject.x) && all.equal(subject.x[, 1], rep(1, nrow(subject.x)), check.attributes = FALSE) == TRUE) { ## If the response was supplied and the model has subject level ## intercepts, set the intercept prior means to correspond to ## the MAP estimate under a Jeffreys prior. That is, add 1 ## prior observation, evenly split among all levels. subject.intercept <- TRUE response.table <- table(response) response.table <- response.table + 1.0 / length(response.table) intercept.map.estimate <- response.table / length(response) logits <- log(intercept.map.estimate / intercept.map.estimate[1]) subject.prior.mean[1, ] <- logits[-1] } prior.mean <- c(subject.prior.mean, choice.prior.mean) ##------- Build prior.variance subject.prior.beta.sd <- numeric(0) choice.prior.beta.sd <- numeric(0) if (!is.null(subject.x)) { subject.x.sd <- sqrt(apply(subject.x, 2, var)) if (subject.intercept) { subject.x.sd[1] <- 1 } ## The prior is that the total variation in X * beta is something ## like -6..6, so the variance of X * beta is 4, and the variance of ## each x[i] * beta[i] will be 4 / (expected.model.size) subject.prior.beta.sd <- 2 / (subject.x.sd * expected.subject.model.size) subject.prior.beta.sd <- rep(subject.prior.beta.sd, nchoices - 1) } if (!is.null(choice.x)) { choice.x.sd <- sqrt(apply(choice.x, 2, var)) choice.prior.beta.sd <- 2 / (choice.x.sd * expected.choice.model.size) } prior.beta.sd <- c(subject.prior.beta.sd, choice.prior.beta.sd) ans <- IndependentSpikeSlabPrior( prior.inclusion.probabilities = prior.inclusion.probabilities, optional.coefficient.estimate = prior.mean, prior.beta.sd = prior.beta.sd, sdy = 1, mean.y = 1, expected.r2 = .5, prior.df = 1, number.of.observations = 0, number.of.variables = length(prior.mean), sdx = 1) ans$max.flips <- max.flips ## TODO(stevescott): should we give this object its own class, and ## keep the choice/subject information separate? return(ans) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/mlm.spike.R
GetPredictorMatrix <- function(object, newdata, na.action = na.omit, ...) { ## Obtain the design matrix for making predictions based on a glm.spike ## object. This function performs much the same role as model.matrix, but it ## allows for the 'newdata' argument to be a vector, matrix, or data frame. ## ## Args: ## object: An object of class glm.spike. The object must be a list with the ## following elements ## * beta: a matrix of MCMC draws, with rows representing draws, and ## columns representing coefficients. ## * xlevels: the levels of any contrasts present in the original training ## data. ## * contrasts: the "contrasts" attribute of the original design matrix ## used to train the model. ## * terms: the terms of the formula used to fit the original model. ## newdata: A data frame, matrix, or vector containing the predictors needed ## to make a prediction. If newdata is a matrix it must have the same ## number of columns as length(object$beta), unless it is off by one and ## the model contains an intercept, in which case an intercept term will ## be added. If length(object$beta) == 1 (or 2, with one element ## containing an intercept) then newdata can be a numeric vector. ## na.action: what to do about NA's. ## ...: extra arguments passed to model.matrix (if newdata is a data frame). ## ## Returns: ## A matrix of predictor variables suitable for multiplication by ## object$beta. stopifnot(inherits(object, "glm.spike")) beta.dimension <- ncol(object$beta) if (is.data.frame(newdata)) { tt <- terms(object) Terms <- delete.response(tt) m <- model.frame(Terms, newdata, na.action = na.action, xlev = object$xlevels) if (!is.null(cl <- attr(Terms, "dataClasses"))) .checkMFClasses(cl, m) X <- model.matrix(Terms, m, contrasts.arg = object$contrasts, ...) if (nrow(X) != nrow(newdata)) { warning("Some entries in newdata have missing values, and will", "be omitted from the prediction.") } } else if (is.matrix(newdata)) { X <- newdata if (ncol(X) == beta.dimension - 1) { if (attributes(object$terms)$intercept) { X <- cbind(1, X) warning("Implicit intercept added to newdata.") } } } else if (is.vector(newdata) && beta.dimension == 2) { if (attributes(object$terms)$intercept) { X <- cbind(1, newdata) } } else if (is.vector(newdata) && beta.dimension == 1) { X <- matrix(newdata, ncol=1) } else { stop("Argument 'newdata' must be a matrix or data.frame,", "unless dim(beta) <= 2, in which case it can be a vector") } if (ncol(X) != beta.dimension) { stop("The number of coefficients does not match the number", "of predictors in lm.spike") } return(X) } model.matrix.glm.spike <- function(object, data = NULL, ...) { ## S3 generic implementing model.matrix for glm.spike objects. ## ## Args: ## object: An object of class glm.spike. ## data: Either a data frame to use when building the model matrix, or NULL. ## If NULL then the training data from the original object will be used. ## ...: Extra arguments passed to model.matrix.default. ## ## Returns: ## The matrix of predictors used at training time, so long as the ## original data used to fit the model is available in the frame ## where this function is called. ## ## Details: ## glm.spike objects do not store the predictors used to fit the ## model. If the training data is modified between when 'object' ## is fit and when this function is called, the modifications will ## be reflected in the returned value. if (is.null(data)) { data = object$training.data } return(model.matrix.default(object, data = data)) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/model.matrix.R
NestedRegression <- function(response, predictors, group.id, residual.precision.prior = NULL, coefficient.prior = NULL, coefficient.mean.hyperprior = NULL, coefficient.variance.hyperprior = NULL, suf = NULL, niter, ping = niter / 10, sampling.method = c("ASIS", "DA"), seed = NULL) { ## Fits a Bayesian hierarchical regression model (with a Gaussian prior) to ## the data provided. ## ## Args: ## response: A numeric vector. The response variable to be modeled. ## predictors: A numeric matrix of predictor variables, including an ## intercept term if one is desired. The number of rows must match ## length(response). ## group.id: A factor (or object that can be converted using as.factor) ## naming the group to which each entry in 'response' belongs. ## residual.precision.prior: An object of type SdPrior describing the prior ## distribution of the residual standard deviation. ## coefficient.prior: An object of class MvnPrior, or NULL. If non-NULL ## this gives the initial values of the prior distribution of the ## regression coefficients in the nested regression model. This argument ## must be non-NULL if either 'coefficient.mean.hyperprior' or ## 'coefficient.variance.hyperprior' is NULL. ## coefficient.mean.hyperprior: An object of class MvnPrior, specifying the ## hyperprior distribution for the mean of 'coefficient.prior'. This ## argument can also be NULL, or FALSE. If NULL then a default prior will ## be used when learning the mean of the prior distribution. If FALSE ## then the mean of the prior distribution will not be learned; the mean ## of the 'coefficient.prior' distribution will be assumed instead. ## coefficient.variance.hyperprior: An object of class InverseWishartPrior, ## specifying the hyperprior distribution for the variance of ## 'coefficient.prior'. This argument can also be NULL, or FALSE. If ## NULL then a default prior will be used when learning the variance of ## the prior distribution. If FALSE then the variance of the prior ## distribution will not be learned; the variance of the ## 'coefficient.prior' distribution will be assumed instead. ## suf: A list, where each entry is of type RegressionSuf, giving the ## sufficient statistics for each group, or NULL. If NULL, then 'suf' ## will be computed from 'response', 'predictors', and 'group.id'. If ## non-NULL then these arguments will not be accessed, in which case they ## can be left unspecified. In 'big data' problems this can be a ## significant computational savings. ## niter: The desired number of MCMC iterations. ## ping: The frequency with which to print status updates. ## sampling.method: Use ASIS or standard data augmentation sampling. Both ## hyperpriors must be supplied to use ASIS. If either hyperprior is set ## to FALSE then the "DA" method will be used. ## seed: The integer-valued seed (or NULL) to use for the C++ random number ## generator. ## ## Returns: ## A list containing MCMC draws from the posterior distribution of model ## parameters. Each of the following is a vector, matrix, or array, with ## first index corresponding to MCMC draws, and later indices to distinct ## parameters. ## * coefficients: regression coefficients. ## * residual.sd: the residual standard deviation from the regression ## model. ## * prior.mean: The posterior distribution of the coefficient means across ## groups. ## * prior.variance: The posterior distribution of the variance matrix ## describing the distribution of regression coefficients across groups. if (is.null(suf)) { if (missing(response) || missing(predictors) || missing(group.id)) { stop("NestedRegression either needs a list of sufficient statistics,", " or a predictor matrix, response vector, and group indicators.") } suf <- .RegressionSufList(predictors, response, group.id) } stopifnot(is.list(suf)) stopifnot(length(suf) > 0) stopifnot(all(sapply(suf, inherits, "RegressionSuf"))) if (length(unique(sapply(suf, function(x) ncol(x$xtx)))) != 1) { stop("All RegressionSuf objects must have the same dimensions.") } xdim <- ncol(suf[[1]]$xtx) sampling.method <- match.arg(sampling.method) ##---------------------------------------------------------------------- ## Check that the priors are from the right families. if (is.null(residual.precision.prior)) { residual.precision.prior <- .DefaultNestedRegressionResidualSdPrior(suf) } stopifnot(inherits(residual.precision.prior, "SdPrior")) ##---------------------------------------------------------------------- if (is.logical(coefficient.mean.hyperprior) && coefficient.mean.hyperprior == FALSE) { sampling.method <- "DA" coefficient.mean.hyperprior <- NULL } else { if (is.null(coefficient.mean.hyperprior)) { coefficient.mean.hyperprior <- .DefaultNestedRegressionMeanHyperprior(suf) } stopifnot(inherits(coefficient.mean.hyperprior, "MvnPrior")) stopifnot(length(coefficient.mean.hyperprior$mean) == xdim) } ##---------------------------------------------------------------------- if (is.logical(coefficient.variance.hyperprior) && coefficient.variance.hyperprior == FALSE) { coefficient.variance.hyperprior <- NULL sampling.method <- "DA" } else if (is.null(coefficient.variance.hyperprior)) { coefficient.variance.hyperprior <- .DefaultNestedRegressionVarianceHyperprior(suf) stopifnot(inherits(coefficient.variance.hyperprior, "InverseWishartPrior"), ncol(coefficient.variance.hyperprior$variance.guess) == xdim) } ##-------------------------------------------------------------------------- ## If either hyperprior is non-NULL then coefficient.prior must be supplied. ## Otherwise, create a default value. if (!is.null(coefficient.mean.hyperprior) && !is.null(coefficient.variance.hyperprior)) { if (is.null(coefficient.prior)) { coefficient.prior <- MvnPrior(rep(0, xdim), diag(rep(1, xdim))) } } stopifnot(inherits(coefficient.prior, "MvnPrior")) ##---------------------------------------------------------------------- ## Check remaining arguments. stopifnot(is.numeric(niter), length(niter) == 1, niter > 0) stopifnot(is.numeric(ping), length(ping) == 1) if (!is.null(seed)) { seed <- as.integer(seed) } ##---------------------------------------------------------------------- ## Have C++ do the heavy lifting. ans <- .Call("boom_nested_regression_wrapper", suf, coefficient.prior, coefficient.mean.hyperprior, coefficient.variance.hyperprior, residual.precision.prior, as.integer(niter), as.integer(ping), sampling.method, seed) ans$priors <- list( coefficient.prior = coefficient.prior, coefficient.mean.hyperprior = coefficient.mean.hyperprior, coefficient.variance.hyperprior = coefficient.variance.hyperprior, residual.precision.prior = residual.precision.prior) ##---------------------------------------------------------------------- ## Slap on a class, and return the answer. class(ans) <- "NestedRegression" return(ans) } ###====================================================================== .RegressionSufList <- function(predictors, response, group.id) { ## Args: ## predictors: A matrix of predictor variables ## response: A numeric response variable with length matching ## nrow(predictors). ## group.id: A factor with length matching 'response'. ## ## Returns: ## A list of RegressionSuf objects, one for each unique value in group.id. ## Each list element contains the sufficient statistics for a regression ## model for the subset of data corresponding to that value of group.id. stopifnot(is.numeric(response)) stopifnot(is.matrix(predictors), nrow(predictors) == length(response)) group.id <- as.factor(group.id) stopifnot(length(group.id) == length(response)) MakeRegSuf <- function(data) { return(RegressionSuf(X = as.matrix(data[,-1]), y = as.numeric(data[,1]))) } return(by(as.data.frame(cbind(response, predictors)), group.id, MakeRegSuf)) } ###====================================================================== .CollapseRegressionSuf <- function(reg.suf.list) { ## Args: ## reg.suf.list: A list of objects of class RegressionSuf. Elements must be ## of the same dimension (i.e. all regressions must have the same number ## of predictors). ## Returns: ## A single RegressionSuf object formed by accumulating the sufficient ## statistics from each list element. stopifnot(is.list(reg.suf.list), length(reg.suf.list) > 0, all(sapply(reg.suf.list, inherits, "RegressionSuf"))) if (length(reg.suf.list) == 1){ return(reg.suf.list[[1]]) } xtx <- reg.suf.list[[1]]$xtx xty <- reg.suf.list[[1]]$xty yty <- reg.suf.list[[1]]$yty n <- reg.suf.list[[1]]$n xsum <- reg.suf.list[[1]]$xbar * n for (i in 2:length(reg.suf.list)) { xtx <- xtx + reg.suf.list[[i]]$xtx xty <- xty + reg.suf.list[[i]]$xty yty <- yty + reg.suf.list[[i]]$yty n <- n + reg.suf.list[[i]]$n xsum <- xsum + reg.suf.list[[i]]$xbar * reg.suf.list[[i]]$n } xbar <- xsum / n return(RegressionSuf(xtx = xtx, xty = xty, yty = yty, n = n, xbar = xbar)) } ###====================================================================== .ResidualVariance <- function(suf) { ## Args: ## suf: Sufficient statistics for a regression problem. ## Returns: ## The maximum likelihood (biased, but consistent) estimate of the residual ## variance in the regression problem. stopifnot(inherits(suf, "RegressionSuf")) sse <- as.numeric(suf$yty - t(suf$xty) %*% solve(suf$xtx, suf$xty)) df.model <- ncol(suf$xtx) return(sse / (suf$n - df.model)) } ###====================================================================== .DefaultNestedRegressionMeanHyperprior <- function(suf) { ## Args: ## suf: A list of RegressionSuf sufficient statistics. ## Returns: ## An object of class MvnPrior that can serve as the default prior for the ## prior mean parameters in a NestedRegression model. suf <- .CollapseRegressionSuf(suf) ## If xtx is full rank then center the prior on the OLS estimate beta-hat. beta.hat <- tryCatch(solve(suf$xtx, suf$xty)) if (is.numeric(beta.hat)) { ## If the OLS estimate is computable, use it to center and scale the prior ## mean for the prior mean parameters. return(MvnPrior(beta.hat, .ResidualVariance(suf) * solve(suf$xtx / suf$n))) } else { ## If the OLS estimate is not computable (because the xtx matrix is not full ## rank) then center the prior mean at zero with what is hopefully a big ## variance. xdim <- length(suf$xty) zero <- rep(0, xdim); V <- diag(rep(1000), xdim) return(MvnPrior(zero, V)) } } ###====================================================================== .DefaultNestedRegressionVarianceHyperprior <- function(suf) { ## Args: ## suf: A list of RegressionSuf sufficient statistics. ## Returns: ## An object of class InverseWishartPrior that can serve as the default ## prior for the prior variance parameters in a NestedRegression model. number.of.groups <- length(suf) suf <- .CollapseRegressionSuf(suf) ## Shrink the variance towards a small but realistic number. The variance of ## the grand mean is sigsq / X'X. It is also roughly Var(beta_g) / ## number.of.groups, so let's say the prior variance of beta_g is ## number.of.groups * sigsq / X'X. variance.guess <- .ResidualVariance(suf) * number.of.groups * solve(suf$xtx) variance.guess.weight <- ncol(variance.guess) + 1 return(InverseWishartPrior(variance.guess, variance.guess.weight)) } .DefaultNestedRegressionResidualSdPrior <- function(suf) { ## Args: ## suf: A list of RegressionSuf sufficient statistics. ## Returns: ## An object of class SdPrior that can serve as the default prior for the ## residual standard deviation in a NestedRegression model. ## Details: ## Shrinks (with one degree of freedom) the residual variance towards the ## residual variance from an OLS model based on pooled data. suf <- .CollapseRegressionSuf(suf) variance.guess <- .ResidualVariance(suf) return(SdPrior(sqrt(variance.guess), 1)) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/nested.regression.R
HiddenLayer <- function(number.of.nodes, prior = NULL, expected.model.size = Inf) { ## Specify the structure of a hidden layer to be used in a feedforward neural ## network. ## ## TODO(steve): Include an option for a 'bias' term. ## ## Args: ## number.of.nodes: The number of output nodes in this hidden layer. The ## number of inputs is determined by the preceding layer. ## prior: An MvnPrior or SpikeSlabGlmPrior to use for the coefficients of ## each of the logistic regression models comprising this hidden layer. ## All models will use the same prior. The dimension of the prior must ## match the inputs from the previous layer. ## ## Returns: ## An object (list) encoding the necessary information for the underlying ## C++ code to build the desired neural network model. check.scalar.integer(number.of.nodes) stopifnot(number.of.nodes > 0) stopifnot(is.null(prior) || inherits(prior, "MvnPrior") || inherits(prior, "SpikeSlabGlmPrior") || inherits(prior, "SpikeSlabGlmPriorDirect")) ans <- list(number.of.nodes = number.of.nodes, prior = prior, expected.model.size = expected.model.size) class(ans) <- c("HiddenLayerSpecification") return(ans) } ##=========================================================================== BayesNnet <- function(formula, hidden.layers, niter, data, subset, prior = NULL, expected.model.size = Inf, drop.unused.levels = TRUE, contrasts = NULL, ping = niter / 10, seed = NULL) { ## A Bayesian feed-forward neural network with logistic activation function ## and a Gaussian terminal layer. ## ## Args: ## formula: A model formula as one would pass to 'lm'. ## hidden.layers: A list of HiddenLayer objects defining the network ## structure. ## niter: The desired number of MCMC iterations. ## data: An optional data frame containing the variables used in 'formula'. ## subset: See 'lm'. ## prior: An object of class SpikeSlabPrior defining the prior distribution ## for the terminal layer. This includes the prior for the residual ## variance. ## drop.unused.levels: See 'lm'. ## contrasts: An optional list. See the 'contrasts.arg' of ## ‘model.matrix.default’. ## ping: The frequency with which to print status updates for the MCMC ## algorithm. Setting 'ping = 10' will print a status update message ## every 10 MCMC iterations. ## seed: The seed to use for the C++ random number generator. ## ## Returns: ## The MCMC draws for all the network coefficients. The return value also ## includes information needed by supporting methods (e.g. 'plot' and ## 'predict'). function.call <- match.call() frame <- match.call(expand.dots = FALSE) has.data <- !missing(data) name.positions <- match(c("formula", "data", "subset", "na.action"), names(frame), 0L) frame <- frame[c(1L, name.positions)] frame$drop.unused.levels <- drop.unused.levels frame[[1L]] <- as.name("model.frame") frame <- eval(frame, parent.frame()) model.terms <- attr(frame, "terms") response <- model.response(frame, "numeric") predictors <- model.matrix(model.terms, frame, contrasts) ## Check that each layer coheres with the preceding layer. hidden.layers <- .CheckHiddenLayers(predictors, hidden.layers) prior <- .EnsureTerminalLayerPrior( response = response, prior = prior, hidden.layers = hidden.layers, expected.model.size = expected.model.size) check.positive.scalar(niter) check.positive.scalar(ping) if (!is.null(seed)) { seed <- as.integer(seed) } ans <- .Call(analysis_common_r_do_feedforward, predictors, response, hidden.layers, prior, as.integer(niter), as.integer(ping), seed) ans$hidden.layer.specification <- hidden.layers ans$niter <- niter ans$contrasts <- attr(predictors, "contrasts") ans$xlevels <- .getXlevels(model.terms, frame) ans$call <- function.call ans$terms <- model.terms ans$response <- response if (has.data) { ans$training.data <- data } else { ans$training.data <- frame } dimnames(ans$hidden.layer.coefficients[[1]]) <- list(NULL, colnames(predictors), NULL) class(ans) <- c("BayesNnet") return(ans) } ##=========================================================================== plot.BayesNnet <- function(x, y = c("predicted", "residual", "structure", "partial", "help"), ...) { ## Match the 'y' argument against the supplied default values, or the data frame stopifnot(is.character(y)) which.function <- try(match.arg(y), silent = TRUE) which.variable <- "all" if (inherits(which.function, "try-error")) { which.function <- "partial" which.variable <- pmatch(y, names(x$training.data)) if (is.na(which.variable)) { err <- paste0("The 'y' argument ", y, " must either match one of the plot types", " or one of the predictor variable names.") stop(err) } } if (which.function == "predicted") { PlotBayesNnetPredictions(x, ...) } else if (which.function == "residual") { PlotBayesNnetResiduals(x, ...) } else if (which.function == "structure") { PlotNetworkStructure(x, ...) } else if (which.function == "help") { help("plot.BayesNnet", package = "BoomSpikeSlab", help_type = "html") } else if (which.function == "partial") { if (which.variable == "all") { varnames <- colnames(attributes(x$terms)$factors) nvars <- length(varnames) stopifnot(nvars >= 1) nr <- max(1, floor(sqrt(nvars))) nc <- ceiling(nvars / nr) original.pars <- par(mfrow = c(nr, nc)) on.exit(par(original.pars)) for (i in 1:nvars) { PartialDependencePlot(x, varnames[i], xlab = varnames[i], ...) } } else { PartialDependencePlot(x, y, ...) } } return(invisible(NULL)) } ##=========================================================================== SuggestBurn <- function(model) { return(SuggestBurnLogLikelihood(-1 * model$residual.sd)) } ##=========================================================================== PlotBayesNnetPredictions <- function(model, burn = SuggestBurn(model), ...) { pred <- predict(model, burn = burn) predicted <- colMeans(pred) actual <- model$response plot(predicted, actual, ...) abline(a = 0, b = 1) } ##=========================================================================== PlotBayesNnetResiduals <- function(model, burn = SuggestBurn(model), ...) { pred <- predict(model, burn = burn) predicted <- colMeans(pred) actual <- model$response residual <- actual - predicted plot(predicted, residual, ...) abline(h = 0) } ##=========================================================================== .HiddenLayerPriorMean <- function(prior) { ## Extract the mean of the prior distribution for hidden layer coefficients. if (inherits(prior, "SpikeSlabPriorBase")) { return(prior$mu) } else if (inherits(prior, "MvnPrior")) { return(prior$mean) } else { stop("Prior must be an MvnPrior or else inherit from SpikeSlabPriorBase") } } ##=========================================================================== .CheckHiddenLayers <- function(predictors, hidden.layers) { ## Check that the priors for each hidden layer are set and are of the ## appropriate dimension. Replace any NULL priors with default values. ## Return the updated list of hidden layers. ## ## Args: ## predictors: The matrix of predictors. ## hidden.layers: A list of HiddenLayerSpecification objects defining the ## hidden layers for the feed forward neural network model. ## ## Returns: ## hidden.layers, after checking that dimensions and priors are okay, and ## after replacing NULL priors with hopefully sensible defaults. stopifnot(is.list(hidden.layers), all(sapply(hidden.layers, inherits, "HiddenLayerSpecification"))) for (i in 1:length(hidden.layers)) { if (is.null(hidden.layers[[i]]$prior)) { expected.model.size <- hidden.layers[[i]]$expected.model.size if (is.null(expected.model.size)) { expected.model.size <- 10^10 } check.positive.scalar(expected.model.size) if (i == 1) { ## Logistic regression inputs are arbitrary. prior <- LogitZellnerPrior(predictors, prior.success.probability = .5, expected.model.size = expected.model.size) hidden.layers[[i]]$prior <- prior } else { ## Logistic regression inputs are all between 0 and 1. input.dimension <- hidden.layers[[i - 1]]$number.of.nodes prior <- SpikeSlabGlmPriorDirect( coefficient.mean = rep(0, input.dimension), coefficient.precision = diag(rep(1, input.dimension)), expected.model.size = expected.model.size) hidden.layers[[i]]$prior <- prior } } if (i == 1) { stopifnot(length(.HiddenLayerPriorMean(hidden.layers[[i]]$prior)) == ncol(predictors)) } else { stopifnot(length(.HiddenLayerPriorMean(hidden.layers[[i]]$prior)) == hidden.layers[[i - 1]]$number.of.nodes) } } return(hidden.layers) } ##=========================================================================== .EnsureTerminalLayerPrior <- function(response, hidden.layers, prior, expected.model.size, ...) { ## Args: ## response: The vector of 'y' values from the regression. ## hidden.layers: A list of objects inheriting from ## HiddenLayerSpecification. ## prior: The prior distribution for the model in the terminal layer. This ## must be of type SpikeSlabPrior, SpikeSlabPriorDirect, or NULL. If NULL ## a default prior will be created. ## ## Returns: ## The checked prior distribution. ## ## Effects: ## Checks that the dimension of the prior matches the number of outputs in the ## final hidden layer. dimension <- tail(hidden.layers, 1)[[1]]$number.of.nodes if (is.null(prior)) { precision <- diag(rep(1, dimension)) inclusion.probabilities <- rep(expected.model.size / dimension, dimension) inclusion.probabilities[inclusion.probabilities > 1] <- 1 inclusion.probabilities[inclusion.probabilities < 0] <- 0 prior <- SpikeSlabPriorDirect( coefficient.mean = rep(0, dimension), coefficient.precision = precision, prior.inclusion.probabilities = inclusion.probabilities, sigma.guess = sd(response, na.rm = TRUE) / 2, prior.df = 1) } stopifnot(inherits(prior, "SpikeSlabPrior") || inherits(prior, "SpikeSlabPriorDirect")) return(prior) } ##=========================================================================== predict.BayesNnet <- function(object, newdata = NULL, burn = 0, na.action = na.pass, mean.only = FALSE, seed = NULL, ...) { ## Prediction method for BayesNnet. ## Args: ## object: object of class "BayesNnet" returned from the BayesNnet function. ## newdata: Either NULL, or else a data frame, matrix, or vector containing ## the predictors needed to make the prediction. If 'newdata' is 'NULL' ## then the predictors are taken from the training data used to create the ## model object. Note that 'object' does not store its training data, so ## the data objects used to fit the model must be present for the training ## data to be recreated. If 'newdata' is a data.frame it must contain ## variables with the same names as the data frame used to fit 'object'. ## If it is a matrix, it must have the same number of columns as ## object$beta. (An intercept term will be implicitly added if the number ## of columns is one too small.) If the dimension of object$beta is 1 or ## 2, then newdata can be a vector. ## burn: The number of MCMC iterations in 'object' that should be discarded. ## If burn <= 0 then all iterations are kept. ## na.action: what to do about NA's. ## mean.only: Logical. If TRUE then return the posterior mean of the ## predictive distribution. If FALSE then return the entire distribution. ## seed: Seed for the C++ random number generator. ## ...: extra aguments ultimately passed to model.matrix (in the event that ## newdata is a data frame) ## Returns: ## A matrix of predictions, with each row corresponding to a row in newdata, ## and each column to an MCMC iteration. if (is.null(newdata)) { predictor.matrix <- model.matrix(object, data = object$training.data) } else { predictor.matrix <- model.matrix(object, data = newdata) } stopifnot(is.matrix(predictor.matrix), nrow(predictor.matrix) > 0) check.nonnegative.scalar(burn) check.scalar.boolean(mean.only) if (!is.null(seed)) { check.scalar.integer(seed) } ans <- .Call(analysis_common_r_feedforward_prediction, object, predictor.matrix, as.integer(burn), as.logical(mean.only), seed) class(ans) <- "BayesNnetPrediction" return(ans) } ##=========================================================================== PlotNetworkStructure <- function(model, ...) { ## Plot the nodes and edges of the neural network. Larger coefficients are ## thicker lines. ## ## Args: ## model: A model fit by BayesNnet. ## ...: Extra arguments passed to plot.igraph. ## ## NOTE: This function depends on having igraph installed. Igraph is a big ## package with lots of dependencies, so it is optional. If igraph is not ## installed then calling this function prints an error message. ok <- requireNamespace("igraph", quietly = TRUE) if (!ok) { warning("Plotting network structure requires the 'igraph' package. ", "Please install using 'install.packages'.") return(NULL) } input.names <- dimnames(model$hidden.layer.coefficients[[1]])[[2]] input.dimension <- length(input.names) input.nodes <- data.frame(id = input.names, layer = rep(0, length(input.names)), position.in.layer = 1:length(input.names)) number.of.hidden.layers <- length(model$hidden.layer.specification) hidden.node.counts <- sapply(model$hidden.layer.specification, function(x) x$number.of.nodes) ## Edge weights are the absolute values of the coefficients in each layer, ## normalized by that layer so that input and output nodes don't dominate ## because of scaling issues. layer <- rep(1:number.of.hidden.layers, times = hidden.node.counts) position.in.layer <- c(sapply(hidden.node.counts, function(x) 1:x)) hidden.nodes <- data.frame( id = paste("H", layer, position.in.layer, sep = "."), layer = rep(1:number.of.hidden.layers, times = hidden.node.counts), position.in.layer = position.in.layer) terminal.node <- data.frame( id = "terminal", layer = length(hidden.node.counts) + 1, position.in.layer = 1) nodes <- rbind(input.nodes, hidden.nodes, terminal.node) ##--------------------------------------------------------------------------- ## Compute the edges. first.hidden.layer <- hidden.nodes[hidden.nodes$layer == 1, , drop = FALSE] weights <- as.numeric(t(colMeans(model$hidden.layer.coefficients[[1]]))) nc <- max(abs(weights)) if (nc > 0) weights <- weights / nc input.layer.edges <- data.frame( from = as.character(rep(input.names, each = hidden.node.counts[1])), to = as.character(rep(first.hidden.layer$id, times = length(input.names))), weight = weights ) edges <- input.layer.edges if (number.of.hidden.layers >= 2) { for (layer in 2:number.of.hidden.layers) { current.layer <- nodes[nodes$layer == layer, , drop = FALSE] previous.layer <- nodes[nodes$layer == layer - 1, , drop = FALSE] weights <- as.numeric(t(colMeans(model$hidden.layer.coefficients[[layer]]))) nc <- max(abs(weights)) if (nc > 0) weights <- weights / nc edges <- rbind(edges, data.frame( from = as.character(rep(previous.layer$id, each = hidden.node.counts[layer])), to = as.character(rep(current.layer$id, times = nrow(previous.layer))), weight = weights )) } } final.hidden.layer <- nodes[nodes$layer == number.of.hidden.layers, , drop = FALSE] weights <- colMeans(model$terminal.layer.coefficients) nc <- max(abs(weights)) if (nc > 0) weights <- weights / nc edges <- rbind(edges, data.frame( from = as.character(final.hidden.layer$id), to = as.character(terminal.node$id), weight = weights )) ##--------------------------------------------------------------------------- ## Compute the layout for the plot. max.nodes <- max(nrow(input.nodes), hidden.node.counts) initial.layer.node.offset <- (max.nodes - nrow(input.nodes)) / 2 hidden.layer.node.offsets <- (max.nodes - hidden.node.counts) / 2 terminal.layer.offset <- (max.nodes - 1) / 2 input.layer.layout <- cbind("layer" = 0, "position.in.layer" = (1:nrow(input.nodes)) + initial.layer.node.offset) hidden.layer.layout <- cbind(hidden.nodes[, c("layer", "position.in.layer")]) hidden.layer.layout[,2] <- hidden.layer.layout[, 2] + hidden.layer.node.offsets[hidden.layer.layout[, 1]] terminal.layer.layout <- cbind("layer" = 1 + number.of.hidden.layers, "position.in.layer" = 1 + terminal.layer.offset) graph.layout <- rbind(input.layer.layout, hidden.layer.layout, terminal.layer.layout) ##--------------------------------------------------------------------------- ## Do the plotting. graph <- igraph::graph_from_data_frame(edges, vertices = NULL) plot(graph, layout = as.matrix(graph.layout), edge.color = edges$weight > 0, edge.width = 5 * abs(edges$weight), edge.arrow.size = 0, ...) return(invisible(list(nodes = nodes, input.layer.edges = input.layer.edges))) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/nnet.R
PartialDependencePlot <- function(model, which.variable, burn = SuggestBurn(model), data.fraction = .2, gridsize = 50, mean.only = FALSE, show.points = TRUE, xlab = NULL, ylab = NULL, ylim = NULL, report.time = FALSE, ...) { ## Args: ## model: A model with a suitably defined 'predict' method. See below for ## requirements. ## which.variable: Either the name of the variable for which a ## partial dependence plot is desired, or its index (column ## number) in the predictor matrix. ## burn: The number of initial MCMC iterations to discard as ## burn-in. ## data.fraction: The fraction of observations in the predictor ## matrix to use when constructing the partial dependence plot. ## A random sub-sample of this fraction will be taken (without ## replacement). ## mean.only: Logical. If TRUE then only the mean is plotted at ## each point. If FALSE then the posterior of the function ## value is plotted. ## show.points: If TRUE then the scatterplot of x vs y is added to ## the graph. Otherwise the points are left off. ## xlab: Label for the X axis. NULL produces a default label. ## Use "" for no label. ## ylab: Label for the Y axis. NULL produces a default label. ## Use "" for no label. ## ylim: Limits on the vertical axis. If NULL then the plot will ## default to its natural vertical limits. ## ...: Extra arguments are passed either to 'plot' (if mean.only ## is TRUE)' or 'PlotDynamicDistribution' (otherwise). ## ## Returns: ## Invisibly returns a list containing the posterior of the ## distribution function values at each 'x' value, and the x's ## where the distribution is calculated. stopifnot(inherits(model, "BayesNnet")) training.data <- model$training.data check.scalar.probability(data.fraction) if (data.fraction < 1) { rows <- sample(1:nrow(training.data), size = round(data.fraction * nrow(training.data))) training.data <- training.data[rows, , drop = FALSE] } if (report.time) { start.time <- Sys.time() cat("Starting at\t", format(start.time), "\n") } ## which.variable can either be a number or a name. If it is a name, convert ## it to a number. stopifnot(length(which.variable) == 1) if (is.character(which.variable)) { original.variable.name <- which.variable which.variable <- pmatch(which.variable, colnames(training.data)) if (is.na(which.variable)) { stop(original.variable.name, "was not uniquely matched in", colnames(model$training.data)) } } else { which.variable <- as.numeric(which.variable) original.variable.name <- colnames(training.data)[which.variable] } ## The training data defines a marginal distributions of the predictor ## variables other than which.variable. xvar <- model$training.data[, which.variable] if (is.factor(xvar) || is.character(xvar)) { xvar <- as.factor(xvar) grid <- as.factor(levels(xvar)) } else { xvar <- as.numeric(xvar) grid <- sort(unique(model$training.data[, which.variable])) if (length(grid) > gridsize) { endpoints <- range(grid) grid <- seq(endpoints[1], endpoints[2], length = 50) } } check.nonnegative.scalar(burn) if (burn > model$niter) { stop(paste0("'burn' cannot exceed the number of MCMC iterations ", "used to fit the model.")) } draws <- matrix(nrow = model$niter - burn, ncol = length(grid)) for (i in 1:length(grid)) { training.data[, which.variable] <- grid[i] prediction <- predict(model, newdata = training.data, burn = burn) draws[, i] <- rowMeans(prediction) } if (is.null(xlab)) { xlab = colnames(training.data)[which.variable] } if (mean.only) { if (is.null(ylab)) { ylab <- "Prediction" } pred <- colMeans(draws) if (is.null(ylim)) { if (show.points) { ylim <- range(pred, model$response) } else { ylim <- range(pred) } } plot(grid, pred, xlab = xlab, ylab = ylab, ylim = ylim, ...) } else { ## This branch plots the full predictive distribution. if (is.null(ylab)) { ylab <- as.character(model$call$formula[[2]]) } if (is.null(ylim)) { if (show.points) { ylim <- range(draws, model$response) } else { ylim <- range(draws) } } if (is.factor(grid)) { boxplot(draws, xlab = xlab, ylab = ylab, ylim = ylim, pch = 20, ...) if (show.points) { points(model$training.data[, which.variable], model$response, ...) } } else { if (show.points) { plot(model$training.data[, which.variable], model$response, xlab = xlab, ylab = ylab, ylim = ylim, ...) } PlotDynamicDistribution(draws, grid, xlab = xlab, ylab = ylab, ylim = ylim, add = show.points, ...) } } if (report.time) { stop.time <- Sys.time(); cat("Done at \t", format(stop.time), "\n") cat("Function took", difftime(stop.time, start.time, units = "secs"), "seconds.\n") } return(invisible(list(predictive.distribution = draws, x = grid))) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/partial-dependence.R
poisson.spike <- function( formula, exposure = 1, niter, data, subset, prior = NULL, na.action = options("na.action"), contrasts = NULL, drop.unused.levels = TRUE, initial.value = NULL, ping = niter / 10, nthreads = 4, seed = NULL, ...) { ## Uses Bayesian MCMC to fit a Poisson regression model with a ## spike-and-slab prior. ## ## Args: ## formula: model formula, as would be passed to 'glm', specifying ## the maximal model (i.e. the model with all predictors ## included). ## exposure: A vector of exposure durations of length matching ## nrow(data). A single-element vector will be recycled. ## niter: desired number of MCMC iterations ## ping: if positive, then print a status update every 'ping' MCMC ## iterations. ## nthreads: The number of threads to use when imputing latent data. ## data: optional data.frame containing the data described in 'formula' ## subset: an optional vector specifying a subset of observations ## to be used in the fitting process. ## prior: an optional list such as that returned from ## SpikeSlabPrior. If missing, SpikeSlabPrior ## will be called with the remaining arguments. ## na.action: a function which indicates what should happen when ## the data contain ‘NA’s. The default is set by the ## ‘na.action’ setting of ‘options’, and is ‘na.fail’ if that is ## unset. The ‘factory-fresh’ default is ‘na.omit’. Another ## possible value is ‘NULL’, no action. Value ‘na.exclude’ can ## be useful. ## contrasts: an optional list. See the ‘contrasts.arg’ of ## ‘model.matrix.default’. An optional list. ## drop.unused.levels: should factor levels that are unobserved be ## dropped from the model? ## initial.value: Initial value of Poisson regression ## coefficients for the MCMC algorithm. Can be given as a ## numeric vector, a 'poisson.spike' object, or a 'glm' object. ## If a 'poisson.spike' object is used for initialization, it is ## assumed to be a previous MCMC run to which 'niter' futher ## iterations should be added. If a 'glm' object is supplied, ## its coefficients will be used as the initial values in the ## MCMC simulation. ## seed: Seed to use for the C++ random number generator. NULL or ## an int. If NULL, then the seed will be taken from the global ## .Random.seed object. ## ... : parameters to be passed to SpikeSlabPrior ## ## Returns: ## An object of class 'poisson.spike', which is a list containing the ## following values ## beta: A 'niter' by 'ncol(X)' matrix of regression coefficients ## many of which may be zero. Each row corresponds to an MCMC ## iteration. ## prior: The prior that was used to fit the model. ## In addition, the returned object contains sufficient details for ## the call to model.matrix in the predict.lm.spike method. has.data <- !missing(data) cl <- match.call() mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L) mf <- mf[c(1L, m)] mf$drop.unused.levels <- drop.unused.levels mf[[1L]] <- as.name("model.frame") mf <- eval(mf, parent.frame()) mt <- attr(mf, "terms") y <- as.integer(model.response(mf, "any")) stopifnot(all(y[!is.na(y)] >= 0)) x <- model.matrix(mt, mf, contrasts) if (is.null(prior)) { prior <- SpikeSlabPrior(x, y, ...) } stopifnot(is.numeric(exposure)) stopifnot(all(exposure >= 0)) if (length(exposure) == 1) { exposure <- rep(exposure, length(y)) } stopifnot(length(exposure) == length(y)) if (!is.null(initial.value)) { if (inherits(initial.value, "poisson.spike")) { stopifnot(colnames(initial.value$beta) == colnames(x)) beta0 <- as.numeric(tail(initial.value$beta, 1)) } else if (inherits(initial.value, "glm")) { stopifnot(colnames(initial.value$beta) == colnames(x)) beta0 <- coef(initial.value) } else if (is.numeric(initial.value)) { stopifnot(length(initial.value) == ncol(x)) beta0 <- initial.value } else { stop("initial.value must be a 'poisson.spike' object, a 'glm' object,", "or a numeric vector") } } else { ## No initial value was supplied. The initial condition is set so ## that all slopes are zero. The intercept is set to the log of ## ybar, unless ybar is zero. If all y's are zero then the ## intercept is set to the value that would give probability .5 to ## the event of having all 0's in the data. beta0 <- rep(0, ncol(x)) if (all(x[, 1] == 1)) { ybar <- sum(y * exposure) / sum(exposure) if (ybar > 0) { beta0[1] <- log(ybar) } else { beta0[1] <- -log(.5) / sum(exposure) } } } ans <- .poisson.spike.fit(x = x, y = y, exposure = exposure, prior = prior, niter = niter, ping = ping, nthreads = nthreads, beta0 = beta0, seed = seed) ## The stuff below will be needed by predict.poisson.spike. ans$contrasts <- attr(x, "contrasts") ans$xlevels <- .getXlevels(mt, mf) ans$call <- cl ans$terms <- mt if (!is.null(initial.value) && inherits(initial.value, "poisson.spike")) { ans$beta <- rbind(initial.value$beta, ans$beta) } if (has.data) { ## Note, if a data frame was passed as an argument to this function then ## saving the data frame will be cheaper than saving the model.frame. ans$training.data <- data } else { ## If the model was called with a formula referring to objects in another ## environment, then saving the model frame will capture these variables so ## they can be used to recreate the design matrix. ans$training.data <- mf } ans$exposure <- exposure ## Make the answer a class, so that the right methods will be used. class(ans) <- c("poisson.spike", "glm.spike") return(ans) } predict.poisson.spike <- function(object, newdata = NULL, exposure = NULL, burn = 0, type = c("mean", "log", "link", "response"), na.action = na.pass, ...) { ## Prediction method for logit.spike ## Args: ## object: object of class "logit.spike" returned from the logit.spike ## function ## newdata: A data frame including variables with the same names as the data ## frame used to fit 'object'. If NULL then the predictors are taken from ## the training data. ## exposure: A vector of positive real numbers the same size as newdata, or ## NULL. If both newdata and exposure are NULL then exposure is taken to ## be the exposure from the training data. If newdata is supplied and ## exposure is null then exposure is taken to be 1 for all observations. ## burn: The number of MCMC iterations in 'object' that should be ## discarded. If burn < 0 then all iterations are kept. ## type: The type of prediction desired. If 'mean' then the ## prediction is returned on the scale of the original data. If ## 'log' then it is returned on the log scale (i.e. the scale of ## the linear predictor). Also accepts 'link' and 'response' ## for compatibility with predict.glm. ## na.action: what to do about NA's. See 'predict.lm'. ## ...: unused, but present for compatibility with generic predict(). ## Returns: ## A matrix of predictions, with each row corresponding to a row ## in newdata, and each column to an MCMC iteration. type <- match.arg(type) if (is.null(newdata)) { predictors <- model.matrix(object) if (is.null(exposure)) { exposure <- object$exposure } } else { predictors <- GetPredictorMatrix(object, newdata, na.action = na.action, ...) if (is.null(exposure)) { exposure <- rep(1, nrow(predictors)) } } beta <- object$beta if (burn > 0) { beta <- beta[-(1:burn), , drop = FALSE] } eta <- log(exposure) + predictors %*% t(beta) if (type == "log" || type == "link") { return(eta) } else { return(exp(eta)) } } .poisson.spike.fit <- function( x, y, exposure, prior, niter, ping, nthreads, beta0, seed) { ## Args: ## x: design matrix with 'n' rows corresponding to observations and ## 'p' columns corresponding to predictor variables. ## y: vector of integer responses (success counts) of length n ## exposure: A vector of exposure durations of length matching ## nrow(data). A single-element vector will be recycled. ## prior: a list structured like the return value from ## SpikeSlabPrior ## niter: the number of desired MCMC iterations ## ping: frequency with which to print MCMC status updates ## nthreads: number of threads to use when imputing latent data ## beta0: The initial value in the MCMC simulation. ## seed: Seed to use for the C++ random number generator. NULL or ## an int. ## ## Returns: ## An object of class poisson.spike, which is a list with the elements ## described in the 'poisson.spike' function. stopifnot(nrow(x) == length(y), length(exposure) == length(y), length(prior$mu) == ncol(x), length(prior$prior.inclusion.probabilities) == ncol(x), all(y >= 0)) if (is.null(prior$max.flips)) { prior$max.flips <- -1 } if (is.null(seed)) { ## Ensure that .Random.seed exists. tmp <- rnorm(1) seed <- .Random.seed[1] } ans <- .Call(analysis_common_r_poisson_regression_spike_slab, x, as.integer(y), exposure, prior, as.integer(niter), as.integer(ping), as.integer(nthreads), beta0, seed) if (!is.null(colnames(x))) { colnames(ans$beta) <- colnames(x) } ans$prior <- prior log.lambda <- x %*% t(ans$beta) log.exposure <- log(exposure) log.likelihood.contributions <- y * (log.lambda + log.exposure) - exp(log.lambda + log.exposure) ans$log.likelihood <- colSums(log.likelihood.contributions) class(ans) <- c("poisson.spike", "glm.spike", "lm.spike") return(ans) } plot.poisson.spike <- function( x, y = c("inclusion", "coefficients", "scaled.coefficients", "size", "help"), burn = SuggestBurnLogLikelihood(x$log.likelihood), ...) { y <- match.arg(y) if (y == "inclusion") { return(PlotMarginalInclusionProbabilities(x$beta, burn = burn, ...)) } else if (y == "coefficients") { return(PlotLmSpikeCoefficients(x$beta, burn = burn, ...)) } else if (y == "scaled.coefficients") { scale.factors <- apply(model.matrix(x), 2, sd) return(PlotLmSpikeCoefficients(x$beta, burn = burn, scale.factors = scale.factors, ...)) } else if (y == "size") { return(PlotModelSize(x$beta, ...)) } else if (y == "help") { help("plot.poisson.spike", package = "BoomSpikeSlab", help_type = "html") } }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/poisson.spike.R
# Copyright 2010-2014 Google Inc. All Rights Reserved. # Author: [email protected] (Steve Scott) probit.spike <- function(formula, niter, data, subset, prior = NULL, na.action = options("na.action"), contrasts = NULL, drop.unused.levels = TRUE, initial.value = NULL, ping = niter / 10, clt.threshold = 5, proposal.df = 3, sampler.weights = c(.5, .5), seed = NULL, ...) { ## Uses Bayesian MCMC to fit a probit regression model with a ## spike-and-slab prior. ## ## Args: ## formula: model formula, as would be passed to 'glm', specifying ## the maximal model (i.e. the model with all predictors ## included). ## niter: desired number of MCMC iterations ## data: optional data.frame containing the data described in 'formula' ## subset: an optional vector specifying a subset of observations ## to be used in the fitting process. ## prior: an optional object inheriting from ProbitPrior and ## SpikeSlabPriorBase. If missing, a prior will be constructed ## by calling LogitZellnerPrior with the remaining arguments. ## na.action: a function which indicates what should happen when ## the data contain ‘NA’s. The default is set by the ## ‘na.action’ setting of ‘options’, and is ‘na.fail’ if that is ## unset. The ‘factory-fresh’ default is ‘na.omit’. Another ## possible value is ‘NULL’, no action. Value ‘na.exclude’ can ## be useful. ## contrasts: an optional list. See the ‘contrasts.arg’ of ## ‘model.matrix.default’. An optional list. ## drop.unused.levels: should factor levels that are unobserved be ## dropped from the model? ## initial.value: Initial value of probit regression ## coefficients for the MCMC algorithm. Can be given as a ## numeric vector, a 'probit.spike' object, or a 'glm' object. ## If a 'probit.spike' object is used for initialization, it is ## assumed to be a previous MCMC run to which 'niter' futher ## iterations should be added. If a 'glm' object is supplied, ## its coefficients will be used as the initial values in the ## MCMC simulation. ## ping: if positive, then print a status update every 'ping' MCMC ## iterations. ## clt.threshold: The smallest number of successes or failures ## needed to do use asymptotic data augmentation. ## proposal.df: The degrees of freedom parameter for the ## multivariate T proposal distribution used for ## Metropolis-Hastings updates. A nonpositive number means to ## use a Gaussian proposal. ## sampler.weights: A two-element vector giving the probabilities ## of drawing from the two base sampling algorithm. The first ## element refers to the spike and slab algorithm. The second ## refers to the tailored independence Metropolis sampler. TIM ## is usually faster mixing, but cannot change model dimension. ## seed: Seed to use for the C++ random number generator. NULL or ## an int. If NULL, then the seed will be taken from the global ## .Random.seed object. ## ... : parameters to be passed to LogitZellnerPrior. ## ## Returns: ## An object of class 'probit.spike', which is a list containing the ## following values ## beta: A 'niter' by 'ncol(X)' matrix of regression coefficients ## many of which may be zero. Each row corresponds to an MCMC ## iteration. ## prior: The prior that was used to fit the model. ## In addition, the returned object contains sufficient details for ## the call to model.matrix in the predict.lm.spike method. has.data <- !missing(data) cl <- match.call() mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L) mf <- mf[c(1L, m)] mf$drop.unused.levels <- drop.unused.levels mf[[1L]] <- as.name("model.frame") mf <- eval(mf, parent.frame()) mt <- attr(mf, "terms") response <- model.response(mf, "any") ## Unpack the vector of trials. If y is a 2-column matrix then the ## first column is the vector of success counts and the second is ## the vector of failure counts. Otherwise y is just a vector, and ## the vector of trials should just be a column of 1's. if (!is.null(dim(response)) && length(dim(response)) > 1) { stopifnot(length(dim(response)) == 2, ncol(response) == 2) ## If the user passed a formula like "cbind(successes, failures) ~ ## x", then y will be a two column matrix ny <- response[, 1] + response[, 2] response <- response[, 1] } else { ## The following line admits y's which are TRUE/FALSE, 0/1 or 1/-1. response <- response > 0 ny <- rep(1, length(response)) } design <- model.matrix(mt, mf, contrasts) if (is.null(prior)) { prior <- LogitZellnerPrior(design, response, ...) } stopifnot(inherits(prior, "SpikeSlabPriorBase")) stopifnot(inherits(prior, "LogitPrior")) if (!is.null(initial.value)) { if (inherits(initial.value, "probit.spike")) { stopifnot(colnames(initial.value$beta) == colnames(design)) beta0 <- as.numeric(tail(initial.value$beta, 1)) } else if (inherits(initial.value, "glm")) { stopifnot(colnames(initial.value$beta) == colnames(design)) beta0 <- coef(initial.value) } else if (is.numeric(initial.value)) { stopifnot(length(initial.value) == ncol(design)) beta0 <- initial.value } else { stop("initial.value must be a 'probit.spike' object, a 'glm' object,", "or a numeric vector") } } else { ## No initial value was supplied beta0 <- prior$mu } stopifnot(is.matrix(design), nrow(design) == length(response), length(prior$mu) == ncol(design), length(prior$prior.inclusion.probabilities) == ncol(design), all(response >= 0)) if (is.null(prior$max.flips)) { prior$max.flips <- -1 } if (!is.null(seed)) { seed <- as.integer(seed) } stopifnot(is.numeric(proposal.df), length(proposal.df) == 1) stopifnot(is.numeric(sampler.weights), length(sampler.weights) == 2, sum(sampler.weights) == 1.0) ans <- .Call("probit_spike_slab_wrapper", as.matrix(design), as.integer(response), as.integer(ny), prior, as.integer(niter), as.integer(ping), beta0, as.integer(clt.threshold), proposal.df, sampler.weights, seed) ans$prior <- prior class(ans) <- c("probit.spike", "glm.spike") ## The stuff below will be needed by predict.probit.spike. ans$contrasts <- attr(design, "contrasts") ans$xlevels <- .getXlevels(mt, mf) ans$call <- cl ans$terms <- mt ## The next few entries are needed by some of the diagnostics plots ## and by summary.probit.spike. fitted.probits <- design %*% t(ans$beta) log.probs <- pnorm(fitted.probits, log.p = TRUE) log.failure.probs <- pnorm(fitted.probits, log.p = TRUE, lower.tail = FALSE) log.likelihood.contributions <- response * log.probs + (ny - response) * log.failure.probs ans$log.likelihood <- colSums(log.likelihood.contributions) sign <- rep(1, length(response)) sign[response / ny < 0.5] <- -1 ans$deviance.residuals <- sign * sqrt(rowMeans( -2 * log.likelihood.contributions)) p.hat <- sum(response) / sum(ny) ans$null.log.likelihood <- sum( response * log(p.hat) + (ny - response) * log(1 - p.hat)) fitted.probabilities <- exp(log.probs) ans$fitted.probabilities <- rowMeans(fitted.probabilities) ans$fitted.probits <- rowMeans(fitted.probits) # Chop observed data into 10 buckets. Equal numbers of data points # in each bucket. Compare the average predicted success probability # of the observations in that bucket with the empirical success # probability for that bucket. # # dimension of fitted values is nobs x niter if (!is.null(initial.value) && inherits(initial.value, "probit.spike")) { ans$beta <- rbind(initial.value$beta, ans$beta) } ans$response <- response if (any(ny != 1)) { ans$trials <- ny } colnames(ans$beta) <- colnames(design) if (has.data) { ## Note, if a data.frame was passed as an argument to this function ## then saving the data frame will be cheaper than saving the ## model.frame. ans$training.data <- data } else { ## If the model was called with a formula referring to objects in ## another environment, then saving the model frame will capture ## these variables so they can be used to recreate the design ## matrix. ans$training.data <- mf } ## Make the answer a class, so that the right methods will be used. class(ans) <- c("probit.spike", "lm.spike", "glm.spike") return(ans) } predict.probit.spike <- function(object, newdata, burn = 0, type = c("prob", "probit", "link", "response"), na.action = na.pass, ...) { ## Prediction method for probit.spike ## Args: ## object: object of class "probit.spike" returned from the probit.spike ## function ## newdata: A data frame including variables with the same names ## as the data frame used to fit 'object'. ## burn: The number of MCMC iterations in 'object' that should be ## discarded. If burn < 0 then all iterations are kept. ## type: The type of prediction desired. If 'prob' then the ## prediction is returned on the probability scale. If 'probit' ## then it is returned on the probit scale (i.e. the scale of the ## linear predictor). Also accepts 'link' and 'response' for ## compatibility with predict.glm. ## ...: unused, but present for compatibility with generic predict(). ## Returns: ## A matrix of predictions, with each row corresponding to a row ## in newdata, and each column to an MCMC iteration. type <- match.arg(type) predictors <- GetPredictorMatrix(object, newdata, na.action = na.action, ...) beta <- object$beta if (burn > 0) { beta <- beta[-(1:burn), , drop = FALSE] } eta <- predictors %*% t(beta) if (type == "probit" || type == "link") return(eta) if (type == "prob" || type == "response") return(pnorm(eta)) } plot.probit.spike <- function( x, y = c("inclusion", "coefficients", "scaled.coefficients", "fit", "residuals", "size", "help"), burn = SuggestBurnLogLikelihood(x$log.likelihood), ...) { ## S3 method for plotting probit.spike objects. ## Args: ## x: The object to be plotted. ## y: The type of plot desired. ## ...: Additional named arguments passed to the functions that ## actually do the plotting. y <- match.arg(y) if (y == "inclusion") { PlotMarginalInclusionProbabilities(x$beta, burn = burn, ...) } else if (y == "coefficients") { PlotLmSpikeCoefficients(x$beta, burn = burn, ...) } else if (y == "scaled.coefficients") { scale.factors <- apply(model.matrix(x), 2, sd) PlotLmSpikeCoefficients(x$beta, burn = burn, scale.factors = scale.factors, ...) } else if (y == "fit") { PlotProbitSpikeFitSummary(x, burn = burn, ...) } else if (y == "residuals") { PlotProbitSpikeResiduals(x, ...) } else if (y == "size") { PlotModelSize(x$beta, burn = burn, ...) } else if (y == "help") { help("plot.probit.spike", package = "BoomSpikeSlab", help_type = "html") } else { stop("Unrecognized option", y, "in plot.probit.spike") } } PlotProbitSpikeResiduals <- function(model, ...) { ## Args: ## model: An object of class probit.spike. ## ...: Optional named arguments passed to plot(). ## ## Details: ## ## The "deviance residuals" are defined as the signed square root ## each observation's contribution to log likelihood. The sign of ## the residual is positive if half or more of the trials associated ## with an observation are successes. The sign is negative ## otherwise. ## ## The "contribution to log likelihood" is taken to be the posterior ## mean of an observations log likelihood contribution, averaged ## over the life of the MCMC chain. ## ## The deviance residual is plotted against the fitted value, again ## averaged over the life of the MCMC chain. ## ## The plot also shows the .95 and .99 bounds from the square root ## of a chi-square(1) random variable. As a rough approximation, ## about 5% and 1% of the data should lie outside these bounds. residuals <- model$deviance.residuals fitted <- model$fitted.probits plot(fitted, residuals, pch = ifelse(residuals > 0, "+", "-"), col = ifelse(residuals > 0, "red", "blue"), xlab = "fitted probit", ylab = "deviance residual", ...) abline(h = 0) abline(h = c(-1, 1) * sqrt(qchisq(.95, df = 1)), lty = 2, col = "lightgray") abline(h = c(-1, 1) * sqrt(qchisq(.99, df = 1)), lty = 3, col = "lightgray") legend("topright", pch = c("+", "-"), col = c("red", "blue"), legend = c("success", "failure")) } PlotProbitSpikeFitSummary <- function( model, burn = 0, which.summary = c("both", "r2", "bucket"), scale = c("probit", "probability"), cutpoint.basis = c("sample.size", "equal.range"), number.of.buckets = 10, ...) { ## Args: ## model: An object of class probit.spike to be plotted. ## burn: A number of initial MCMC iterations to be discarded. ## which.summary: Which fit summaries should be plotted. ## scale: The scale on which to plot the 'bucket' summary. ## ...: Extra arguments passed to plot(). stopifnot(inherits(model, "probit.spike")) which.summary <- match.arg(which.summary) scale <- match.arg(scale) cutpoint.basis <- match.arg(cutpoint.basis) fit <- summary(model, burn = burn, cutpoint.scale = scale, cutpoint.basis = cutpoint.basis, number.of.buckets = number.of.buckets) if (which.summary == "both") { opar <- par(mfrow = c(1, 2)) on.exit(par(opar)) } if (which.summary %in% c("both", "r2")) { r2 <- fit$deviance.r2.distribution plot.ts(r2, xlab = "MCMC Iteration", ylab = "deviance R-square", main = "Deviance R-square", ...) } if (which.summary %in% c("both", "bucket")) { bucket.fit <- fit$predicted.vs.actual if (scale == "probit") { bucket.fit <- qnorm(bucket.fit) bucket.fit[!is.finite(bucket.fit)] <- NA x.label = "predicted probit" y.label = "observed probit" } else { x.label = "predicted probability" y.label = "observed probability" } if (any(is.na(bucket.fit))) { warning( "Some buckets were empty, or had empirical probabilities of 0 or 1.") } plot(bucket.fit, main = "Probabilities by decile", xlab = x.label, ylab = y.label, ...) if (length(attributes(bucket.fit)$cutpoints) > 1) { abline(v = attributes(bucket.fit)$cutpoints, lty = 3, col = "lightgray") } abline(a = 0, b = 1) } } summary.probit.spike <- function( object, burn = 0, order = TRUE, cutpoint.scale = c("probability", "probit"), cutpoint.basis = c("sample.size", "equal.range"), number.of.buckets = 10, coefficients = TRUE, ...) { ## Summary method for probit.spike coefficients ## Args: ## object: an object of class 'probit.spike' ## burn: an integer giving the number of MCMC iterations to ## discard as burn-in ## order: Logical indicating whether the output should be ordered ## according to posterior inclusion probabilities ## Returns: ## An object of class 'summary.probit.spike' that summarizes the ## model coefficients as in SummarizeSpikeSlabCoefficients. if (coefficients) { coefficient.table <- SummarizeSpikeSlabCoefficients(object$beta, burn, order) } else { coefficient.table <- NULL } deviance.r2 <- (object$null.log.likelihood - object$log.likelihood) / object$null.log.likelihood index <- seq_along(object$log.likelihood) if (burn > 0) { index <- index[-(1:burn)] } log.likelihood <- object$log.likelihood[index] response <- object$response trials <- object$trials if (is.null(object$trials)) { trials <- rep(1, length(response)) } cutpoint.scale <- match.arg(cutpoint.scale) if (cutpoint.scale == "probability") { fitted <- object$fitted.probabilities } else { fitted <- object$fitted.probits } cutpoint.basis = match.arg(cutpoint.basis) if (cutpoint.basis == "sample.size") { cutpoints <- quantile(fitted, (0:number.of.buckets) / number.of.buckets) } else if (cutpoint.basis == "equal.range") { fitted.range <- range(fitted, na.rm = TRUE) cutpoints <- seq(min(fitted.range), max(fitted.range), len = number.of.buckets + 1) } cutpoints <- unique(cutpoints) if (length(cutpoints) == 1) { ## Changing the type of "cutpoints" to keep R from choking on a ## "breaks" argument of length 1. cutpoints <- 2 } bucket.indicators <- cut(fitted, cutpoints) fitted.value.buckets <- split(fitted, bucket.indicators) bucket.predicted.means <- tapply(object$fitted.probabilities, bucket.indicators, mean) bucket.actual.means <- tapply(response / trials, bucket.indicators, mean) bucket.fit <- cbind(predicted = bucket.predicted.means, observed = bucket.actual.means) attributes(bucket.fit)$cutpoints <- cutpoints ans <- list(coefficients = coefficient.table, null.log.likelihood = object$null.log.likelihood, mean.log.likelihood = mean(log.likelihood), max.log.likelihood = max(log.likelihood), deviance.r2 = mean(deviance.r2[index]), deviance.r2.distribution = deviance.r2[index], predicted.vs.actual = bucket.fit) class(ans) <- "summary.probit.spike" return(ans) } print.summary.probit.spike <- function(x, ...) { ## print method for summary.probit.spike objects. cat("null log likelihood: ", x$null.log.likelihood, "\n") cat("posterior mean log likelihood: ", x$mean.log.likelihood, "\n") cat("posterior max log likelihood: ", x$max.log.likelihood, "\n") cat("mean deviance R-sq: ", x$deviance.r2, "\n") cat("\npredicted vs observed success rates, by decile:\n") fit <- x$predicted.vs.actual attributes(fit)$cutpoints <- NULL print(fit) if (!is.null(x$coefficients)) { cat("\nsummary of coefficients:\n") print.default(signif(x$coefficients, 3)) } }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/probit.spike.R
CheckFunction <- function(u, quantile) { stopifnot(is.numeric(u)) stopifnot(is.numeric(quantile), length(quantile) == 1, quantile > 0, quantile < 1) negative <- u < 0 ans <- quantile * u ans[negative] <- -(1 - quantile) * u[negative] return(ans) } qreg.spike <- function( formula, quantile, niter, ping = niter / 10, nthreads = 0, data, subset, prior = NULL, na.action = options("na.action"), contrasts = NULL, drop.unused.levels = TRUE, initial.value = NULL, seed = NULL, ...) { ## Uses Bayesian MCMC to fit a quantile regression model with a ## spike-and-slab prior. ## ## Args: ## formula: Model formula, as would be passed to 'glm', specifying ## the maximal model (i.e. the model with all predictors ## included). ## quantile: The quantile of the response variable to be targeted ## by the regression. A scalar between 0 and 1. ## niter: desired number of MCMC iterations ## ping: If positive, then print a status update every 'ping' MCMC ## iterations. ## nthreads: The number of threads to use when imputing latent data. ## data: optional data.frame containing the data described in 'formula' ## subset: an optional vector specifying a subset of observations ## to be used in the fitting process. ## prior: An optional list such as that returned from ## SpikeSlabPrior. If missing, SpikeSlabPrior ## will be called with the remaining arguments. ## na.action: A function which indicates what should happen when ## the data contain ‘NA’s. The default is set by the ## ‘na.action’ setting of ‘options’, and is ‘na.fail’ if that is ## unset. The ‘factory-fresh’ default is ‘na.omit’. Another ## possible value is ‘NULL’, no action. Value ‘na.exclude’ can ## be useful. ## contrasts: An optional list. See the ‘contrasts.arg’ of ## ‘model.matrix.default’. An optional list. ## drop.unused.levels: should factor levels that are unobserved be ## dropped from the model? ## initial.value: Initial value of quantile regression ## coefficients for the MCMC algorithm. Can be given as a ## numeric vector, a 'qreg.spike' object, or a 'glm' object. ## If a 'qreg.spike' object is used for initialization, it is ## assumed to be a previous MCMC run to which 'niter' futher ## iterations should be added. If a 'glm' object is supplied, ## its coefficients will be used as the initial values in the ## MCMC simulation. ## seed: Seed to use for the C++ random number generator. NULL or ## an int. If NULL, then the seed will be taken from the global ## .Random.seed object. ## ... : parameters to be passed to SpikeSlabPrior ## ## Returns: ## An object of class 'qreg.spike', which is a list containing the ## following values: ## beta: A 'niter' by 'ncol(X)' matrix of regression coefficients ## many of which may be zero. Each row corresponds to an MCMC ## iteration. ## prior: The prior that was used to fit the model. ## In addition, the returned object contains sufficient details for ## the call to model.matrix in the predict.qreg.spike method. quantile.arg <- quantile stopifnot(is.numeric(quantile.arg), length(quantile.arg) == 1, quantile.arg > 0, quantile.arg < 1) has.data <- !missing(data) cl <- match.call() mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L) mf <- mf[c(1L, m)] mf$drop.unused.levels <- drop.unused.levels mf[[1L]] <- as.name("model.frame") mf <- eval(mf, parent.frame()) mt <- attr(mf, "terms") response <- model.response(mf, "numeric") predictor.matrix <- model.matrix(mt, mf, contrasts) if (is.null(prior)) { prior <- SpikeSlabPrior(predictor.matrix, response, ...) } if (!is.null(initial.value)) { if (inherits(initial.value, "qreg.spike")) { stopifnot(colnames(initial.value$beta) == colnames(predictor.matrix)) beta0 <- as.numeric(tail(initial.value$beta, 1)) } else if (inherits(initial.value, "glm")) { stopifnot(colnames(initial.value$beta) == colnames(predictor.matrix)) beta0 <- coef(initial.value) } else if (is.numeric(initial.value)) { stopifnot(length(initial.value) == ncol(predictor.matrix)) beta0 <- initial.value } else { stop("initial.value must be a 'qreg.spike' object, a 'glm' object,", "or a numeric vector") } } else { ## No initial value was supplied. The initial condition is set so ## that all slopes are zero. The intercept is set to the targeted ## quantile of the response variable. beta0 <- rep(0, ncol(predictor.matrix)) beta0[1] <- quantile(response, quantile, na.rm = TRUE) } if (!is.null(seed)) { seed <- as.integer(seed) stopifnot(length(seed) == 1) } ans <- .Call("analysis_common_r_quantile_regression_spike_slab", predictor.matrix, response, quantile.arg, prior, as.integer(niter), as.integer(ping), as.integer(nthreads), beta0, seed) variable.names <- colnames(predictor.matrix) if (!is.null(variable.names)) { colnames(ans$beta) <- variable.names } ans$prior <- prior ## The stuff below will be needed by predict.qreg.spike. ans$contrasts <- attr(predictor.matrix, "contrasts") ans$xlevels <- .getXlevels(mt, mf) ans$call <- cl ans$terms <- mt if (!is.null(initial.value) && inherits(initial.value, "qreg.spike")) { ans$beta <- rbind(initial.value$beta, ans$beta) } ## (niter x p) %*% (p x n) prediction.distribution <- ans$beta %*% t(predictor.matrix) residual.distribution <- matrix(rep(response, each = nrow(ans$beta)), nrow = nrow(ans$beta)) - prediction.distribution ans$log.likelihood <- -.5 * rowSums(CheckFunction(residual.distribution, quantile)) if (has.data) { ## Note, if a data.frame was passed as an argument to this function ## then saving the data frame will be cheaper than saving the ## model.frame. ans$training.data <- data } else { ## If the model was called with a formula referring to objects in ## another environment, then saving the model frame will capture ## these variables so they can be used to recreate the design ## matrix. ans$training.data <- mf } ## Make the answer a class, so that the right methods will be used. class(ans) <- c("qreg.spike", "glm.spike", "lm.spike") return(ans) } predict.qreg.spike <- function(object, newdata, burn = 0, na.action = na.pass, ...) { ## Prediction method for qreg.spike. ## Args: ## object: object of class "qreg.spike" returned from the ## qreg.spike function ## newdata: A data frame including variables with the same names ## as the data frame used to fit 'object'. ## burn: The number of MCMC iterations in 'object' that should be ## discarded. If burn < 0 then all iterations are kept. ## ...: unused, but present for compatibility with generic predict(). ## Returns: ## A matrix of predictions, with each row corresponding to a row ## in newdata, and each column to an MCMC iteration. predictors <- GetPredictorMatrix(object, newdata, na.action = na.action, ...) beta <- object$beta if (burn > 0) { beta <- beta[-(1:burn), , drop = FALSE] } return(predictors %*% t(beta)) } plot.qreg.spike <- function( x, y = c("inclusion", "coefficients", "scaled.coefficients", "size", "help"), burn = SuggestBurnLogLikelihood(x$log.likelihood), ...) { y <- match.arg(y) if (y == "inclusion") { return(PlotMarginalInclusionProbabilities(x$beta, burn = burn, ...)) } else if (y == "coefficients") { return(PlotLmSpikeCoefficients(x$beta, burn = burn, ...)) } else if (y == "scaled.coefficients") { scale.factors <- apply(model.matrix(x), 2, sd) if (abs(scale.factors[1]) < 1e-8 && names(scale.factors)[1] == "(Intercept)") { scale.factors[1] <- 1.0 } return(PlotLmSpikeCoefficients(x$beta, burn = burn, scale.factors = scale.factors, ...)) } else if (y == "size") { return(PlotModelSize(x$beta, ...)) } else if (y == "help") { help("plot.qreg.spike", package = "BoomSpikeSlab", help_type = "html") } }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/qreg.spike.R
ShrinkageRegression <- function(response, predictors, coefficient.groups, residual.precision.prior = NULL, suf = NULL, niter, ping = niter / 10, seed = NULL) { ## Fit a Bayesian regression model with a shrinkage prior on the coefficient. ## The model is ## ## y[i] ~ N(x[i,] %*% beta, sigma^2) ## 1 / sigma^2 ~ Gamma(df/2, ss/2) ## group(beta, 1) ~ N(b1, v1) ## group(beta, 2) ~ N(b2, v2) ## .... ## ## In this notation, group(beta, k) ~ N(bk, vk) indicates that the subset of ## coefficients in group k are a priori independent draws from the specified ## normal distribution. In addition, each subset-level prior may include a ## hyperprior, in which case the subset-level prior parameters will be ## updated as part of the MCMC. The hyperprior has the form of independent ## priors on the mean and precision parameters. ## ## bi ~ N(prior.mean, prior.variance) ## 1.0 / vi ~ Chisq(df, guess.at.sd) ## ## Args: ## response: The numeric vector of responses. ## predictors: The matrix of predictors, including an intercept term, if ## desired. ## coefficient.groups: A list of objects of type CoefficientGroup, defining ## the pattern in which the coefficients should be shrunk together. Each ## coefficient must belong to exactly one CoefficientGroup. ## residual.precision.prior: An object of type SdPrior describing the prior ## distribution of the residual standard deviation. ## suf: An object of class RegressionSuf containing the sufficient ## statistics for the regression model. If this is NULL then it will be ## computed from 'response' and 'predictors'. If it is supplied then ## 'response' and 'predictors' are not used and can be left missing. ## niter: The desired number of MCMC iterations. ## ping: The frequency with which to print status updates. ## seed: The integer-valued seed (or NULL) to use for the C++ random number ## generator. ## ## Returns: ## A list containing MCMC draws from the posterior distribution of model ## parameters. Each of the following is a matrix, with rows corresponding ## to MCMC draws, and columns to distinct parameters. ## * coefficients: regression coefficients. ## * residual.sd: the residual standard deviation from the regression ## model. ## * group.means: The posterior distribution of the mean of each ## coefficient group. If no mean hyperprior was assigned to a ## particular group, then the value here will be a constant (the values ## supplied by the 'prior' argument to 'CoefficientGroup' for that ## group). ## * group.sds: The posterior distribution of the standard deviation of ## each coefficient group. If no sd.hyperprior was assigned to a ## particular group, then the value here will be a constant (the values ## supplied by the 'prior' argument to 'CoefficientGroup' for that ## group). if (is.null(suf)) { ## No need to touch response or predictors if sufficient statistics are ## supplied directly. stopifnot(is.numeric(response)) stopifnot(is.matrix(predictors), nrow(predictors) == length(response)) stopifnot(is.list(coefficient.groups), all(sapply(coefficient.groups, inherits, "CoefficientGroup"))) suf <- RegressionSuf(X = predictors, y = response) } stopifnot(inherits(suf, "RegressionSuf")) stopifnot(is.list(coefficient.groups)) all.indices <- sort(unlist(lapply(coefficient.groups, function(x) x$indices))) xdim <- ncol(suf$xtx) if (any(all.indices != 1:xdim)) { if (any(all.indices > xdim)) { stop("One or more indices were larger than the available ", "number of predictors.") } else if (any(all.indices <= 0)) { stop("All indices must be 1 or larger.") } else if (all.indices != unique(all.indices)) { stop("Each index can only appear in one group.") } else { omitted <- !(all.indices %in% 1:xdim) omitted.indices <- all.indices[omitted] if (length(omitted.indices) > 10) { msg <- paste("There were ", length(omitted.indices), " indices omitted from index groups.") stop(msg) } else if (length(omitted.indices > 1)) { msg <- paste("The following indices were omitted from a ", "coefficient groups: \n") msg <- paste(msg, paste(omitted.indices, collapse = " "), "\n") stop(msg) } else { msg <- paste("Index ", omitted.indices, " was not present in any coefficient groups.\n") stop(msg) } } } ## done checking index groups if (is.null(residual.precision.prior)) { residual.precision.prior <- SdPrior(1, 1) } stopifnot(inherits(residual.precision.prior, "SdPrior")) stopifnot(is.numeric(niter), length(niter) == 1, niter > 0) stopifnot(is.numeric(ping), length(ping) == 1) if (!is.null(seed)) { seed <- as.integer(seed) } ans <- .Call("boom_shrinkage_regression_wrapper", suf, coefficient.groups, residual.precision.prior, as.integer(niter), as.integer(ping), seed) class(ans) <- "ShrinkageRegression" return(ans) } CoefficientGroup <- function(indices, mean.hyperprior = NULL, sd.hyperprior = NULL, prior = NULL) { ## Args: ## indices: A vector of integers giving the positions of the regression ## coefficients that should be viewed as exchangeable. ## mean.hyperprior: A NormalPrior object describing the hyperprior ## distribution for the average coefficient. ## sd.hyperprior: An SdPrior object describing the hyperprior distribution ## for the standard deviation of the coefficients. ## prior: An object of type NormalPrior giving the initial value of the ## distribution describing the collection of coefficients in this group. ## If either hyperprior is NULL then the corresponding prior parameter ## will not be updated. If both hyperpriors are non-NULL then this ## parameter can be left unspecified. ## ## Returns: ## An object (list) containing the arguments, with values checked for ## legality, and with names as expected by the underlying C++ code. ## ## Details: ## The model for the coefficients in this group is that they are independent ## draws from N(b0, sigma^2 / kappa), where sigma^2 is the residual variance ## from the regression model. The hyperprior distribution for this model is ## b0 ~ mean.hyperprior and kappa ~ shrinkage.hyperprior, independently. stopifnot(is.numeric(indices), length(unique(indices)) == length(indices), all(indices >= 1)) if (!is.null(mean.hyperprior)) { stopifnot(inherits(mean.hyperprior, "NormalPrior")) } if (!is.null(sd.hyperprior)) { stopifnot(inherits(sd.hyperprior, "SdPrior")) } if (is.null(prior) && (is.null(mean.hyperprior) || is.null(sd.hyperprior))) { stop("If either hyperprior is NULL, then an initial prior distribution ", "must be supplied.") } if (!is.null(prior)) { stopifnot(inherits(prior, "NormalPrior")) } ans <- list(indices = as.integer(indices), mean.hyperprior = mean.hyperprior, sd.hyperprior = sd.hyperprior, prior = prior) class(ans) <- "CoefficientGroup" return(ans) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/shrinkage.regression.R
SpikeSlabPriorBase <- function(number.of.variables, expected.r2 = .5, prior.df = .01, expected.model.size = 1, optional.coefficient.estimate = NULL, mean.y, sdy, prior.inclusion.probabilities = NULL, sigma.upper.limit = Inf) { ## Computes information that is shared by the different implementation of ## spike and slab priors. Currently, the only difference between the ## different priors is the prior variance on the regression coefficients. ## When that changes, change this function accordingly, and change all the ## classes that inherit from it. ## ## Args: ## number.of.variables: The number of columns in the design matrix for the ## regression begin modeled. The maximum size of the coefficient vector. ## expected.r2: The R^2 statistic that the model is expected to achieve. ## Used along with 'sdy' to derive a prior distribution for the residual ## variance. ## prior.df: The number of observations worth of weight to give to the guess ## at the residual variance. ## expected.model.size: The expected number of nonzero coefficients in the ## model. This number is used to set prior.inclusion.probabilities to ## expected.model.size / number.of.variables. If expected.model.size is ## either negative or larger than number.of.variables then all elements of ## prior.inclusion.probabilities will be set to 1.0 and the model will be ## fit with all available coefficients. ## optional.coefficient.estimate: A vector of length number.of.variables to ## use as the prior mean of the regression coefficients. This can also be ## NULL, in which case the prior mean for the intercept will be set to ## mean.y, and the prior mean for all slopes will be 0. ## mean.y: The mean of the response variable. Used to create a sensible ## default prior mean for the regression coefficients when ## optional.coefficient.estimate is NULL. ## sdy: Used along with expected.r2 to create a prior guess at the residual ## variance. ## prior.inclusion.probabilities: A vector of length number.of.variables ## giving the prior inclusion probability of each coefficient. Each ## element must be between 0 and 1, inclusive. If left as NULL then a ## default value will be created with all elements set to ## expected.model.size / number.of.variables. ## sigma.upper.limit: The largest acceptable value for the residual standard ## deviation. A non-positive number is interpreted as Inf. ## ## Returns: ## An object of class SpikeSlabPriorBase, which is a list with the ## following elements: ## *) prior.inclusion.probabilities: A vector giving the prior inclusion ## probability of each coefficient. ## *) mu: A vector giving the prior mean of each coefficient given ## inclusion. ## *) sigma.guess: A prior estimate of the residual standard deviation. ## *) prior.df: A number of observations worth of weight to assign to ## sigma.guess. ## Compute prior.inclusion.probabilities, the prior inclusion probability if (is.null(prior.inclusion.probabilities)) { stopifnot(is.numeric(expected.model.size)) stopifnot(length(expected.model.size) == 1) stopifnot(expected.model.size > 0) if (expected.model.size < number.of.variables) { prior.inclusion.probabilities <- rep(expected.model.size / number.of.variables, number.of.variables) } else { prior.inclusion.probabilities <- rep(1, number.of.variables) } } stopifnot(length(prior.inclusion.probabilities) == number.of.variables) stopifnot(all(prior.inclusion.probabilities >= 0)) stopifnot(all(prior.inclusion.probabilities <= 1)) ## Compute sigma.guess (guess at the residual standard deviation) stopifnot(is.numeric(expected.r2)) stopifnot(length(expected.r2) == 1) stopifnot(expected.r2 < 1, expected.r2 > 0) stopifnot(is.numeric(sdy), length(sdy) == 1, sdy > 0) sigma.guess <- sqrt((1 - expected.r2)) * sdy ## Compute mu, the conditional prior mean of beta (given nonzero) if (!is.null(optional.coefficient.estimate)) { mu <- optional.coefficient.estimate if (length(mu) != number.of.variables) { stop("The vector of estimated coefficients has length", length(mu), "but the design matrix has", number.of.variables, "columns.") } } else { ## The default behavior is to set the prior mean of all slopes to ## zero, and the prior mean of the intercept to ybar. mu <- rep(0, number.of.variables) mu[1] <- mean.y } stopifnot(is.numeric(prior.df), length(prior.df) == 1, prior.df >= 0) stopifnot(is.numeric(sigma.upper.limit), length(sigma.upper.limit) == 1) if (sigma.upper.limit <= 0) { sigma.upper.limit <- Inf } ans <- list(prior.inclusion.probabilities = prior.inclusion.probabilities, mu = mu, sigma.guess = sigma.guess, prior.df = prior.df, sigma.upper.limit = sigma.upper.limit) class(ans) <- c("SpikeSlabPriorBase", "Prior") return(ans) } ###====================================================================== SpikeSlabPriorDirect <- function(coefficient.mean, coefficient.precision, prior.inclusion.probabilities, prior.df, sigma.guess, max.flips = -1, sigma.upper.limit = Inf) { check.positive.scalar(sigma.guess) check.positive.scalar(prior.df) stopifnot(is.numeric(sigma.upper.limit), length(sigma.upper.limit) == 1) ans <- SpikeSlabGlmPriorDirect( coefficient.mean = coefficient.mean, coefficient.precision = coefficient.precision, prior.inclusion.probabilities = prior.inclusion.probabilities, max.flips = max.flips) ans$prior.df <- prior.df ans$sigma.guess <- sigma.guess ans$sigma.upper.limit <- sigma.upper.limit class(ans) <- c("SpikeSlabPriorDirect", "SpikeSlabPrior", class(ans)) return(ans) } ###====================================================================== SpikeSlabPrior <- function(x, y = NULL, expected.r2 = .5, prior.df = .01, expected.model.size = 1, prior.information.weight = .01, diagonal.shrinkage = .5, optional.coefficient.estimate = NULL, max.flips = -1, mean.y = mean(y, na.rm = TRUE), sdy = sd(as.numeric(y), na.rm = TRUE), prior.inclusion.probabilities = NULL, sigma.upper.limit = Inf) { ## Produces a list containing the prior distribution needed for ## lm.spike. This is Zellner's g-prior, where ## ## 1 / sigsq ~ Ga(prior.weight, prior.sumsq) ## beta | gamma ~ N(b, sigsq * V) ## gamma ~ Independent Bernoulli(prior.inclusion.probabilities) ## ## with V^{-1} = prior.information.weight * ## ((1 - diagonal.shrinkage) * xtx / n ## + (diagonal.shrinkage) * diag(diag(xtx / n))) ## and prior.sumsq = prior.df * (1 - expected.r2) * sdy^2 ## ## Args: ## x: The design matrix in the regression problem ## y: The vector of responses in the regression problem ## expected.r2: A positive scalar less than 1. The expected ## R-squared statistic in the regression. Used to obtain the ## prior distribution for the residual variance. ## prior.df: A positive scalar representing the prior 'degrees of ## freedom' for estimating the residual variance. This can be ## thought of as the amount of weight (expressed as an ## observation count) given to the expected.r2 argument. ## expected.model.size: A positive number less than ncol(x), ## representing a guess at the number of significant predictor ## variables. Used to obtain the 'spike' portion of the spike ## and slab prior. ## prior.information.weight: A positive scalar. Number of ## observations worth of weight that should be given to the ## prior estimate of beta. ## diagonal.shrinkage: The conditionally Gaussian prior for beta ## (the "slab") starts with a precision matrix equal to the ## information in a single observation. However, this matrix ## might not be full rank. The matrix can be made full rank by ## averaging with its diagonal. diagonal.shrinkage is the ## weight given to the diaonal in this average. Setting this to ## zero gives Zellner's g-prior. ## optional.coefficient.estimate: If desired, an estimate of the ## regression coefficients can be supplied. In most cases this ## will be a difficult parameter to specify. If omitted then a ## prior mean of zero will be used for all coordinates except ## the intercept, which will be set to mean(y). ## max.flips: The maximum number of variable inclusion indicators ## the sampler will attempt to sample each iteration. If negative ## then all indicators will be sampled. ## mean.y: The mean of the response variable. ## sdy: The standard deviation of the response variable. ## prior.inclusion.probabilities: A vector giving the prior ## probability of inclusion for each variable. ## sigma.upper.limit: The largest acceptable value for the residual ## standard deviation. A non-positive number is interpreted as ## Inf. ## Returns: ## A list with the values needed to run lm.spike ## Details: ## Let gamma be a logical vector with length ncol(x), where ## gamma[i] == TRUE means beta[i] != 0. The prior is: ## ## Pr(beta[i] != 0) = pi ## p(beta[gamma] | x, sigma) ## = N(b[gamma], sigma^2 * Omega[gamma, gamma]) ## p(1/sigma^2) = Gamma(prior.df / 2, prior.sum.of.squares / 2) ## ## The parameters are set as follows: ## prior.inclusion.probabilities = expected.model.size / ncol(x) ## b is a vector of zeros, except for the intercept (first term), ## which is set to mean(y) ## Omega^{-1} = [(1 - diagonal.srhinkage) * x^Tx + ## diagonal.shrinkage * diag(x^Tx)] ## * prior.information.weight / n ## prior.sum.of.squares = var(y) * (1 - expected.r2) * prior.df ans <- SpikeSlabPriorBase( number.of.variables = ncol(x), expected.r2 = expected.r2, prior.df = prior.df, expected.model.size = expected.model.size, optional.coefficient.estimate = optional.coefficient.estimate, mean.y = mean.y, sdy = sdy, prior.inclusion.probabilities = prior.inclusion.probabilities, sigma.upper.limit = sigma.upper.limit) ans$max.flips <- max.flips p <- length(ans$mu) n <- nrow(x) ## Compute siginv, solve(siginv) times the residual variance is the ## prior variance of beta, conditional on nonzero elements. w <- diagonal.shrinkage if (w < 0 || w > 1) { stop("Illegal value of diagonal shrinkage: ", w, "(must be between 0 and 1)") } xtx <- crossprod(x) / n if (p == 1) { d <- xtx } else { d <- diag(diag(xtx)) } xtx <- w * d + (1 - w) * xtx xtx <- xtx * prior.information.weight ans$siginv <- xtx class(ans) <- c("SpikeSlabPrior", class(ans)) return(ans) } ###====================================================================== StudentSpikeSlabPrior <- function( predictor.matrix, response.vector = NULL, expected.r2 = .5, prior.df = .01, expected.model.size = 1, prior.information.weight = .01, diagonal.shrinkage = .5, optional.coefficient.estimate = NULL, max.flips = -1, mean.y = mean(response.vector, na.rm = TRUE), sdy = sd(as.numeric(response.vector), na.rm = TRUE), prior.inclusion.probabilities = NULL, sigma.upper.limit = Inf, degrees.of.freedom.prior = UniformPrior(.1, 100)) { ans <- SpikeSlabPrior( x = predictor.matrix, y = response.vector, expected.r2 = expected.r2, prior.df = prior.df, expected.model.size = expected.model.size, prior.information.weight = prior.information.weight, diagonal.shrinkage = diagonal.shrinkage, optional.coefficient.estimate = optional.coefficient.estimate, max.flips = max.flips, mean.y = mean.y, sdy = sdy, prior.inclusion.probabilities = prior.inclusion.probabilities, sigma.upper.limit = sigma.upper.limit) stopifnot(inherits(degrees.of.freedom.prior, "DoubleModel")) ans$degrees.of.freedom.prior <- degrees.of.freedom.prior class(ans) <- c("StudentSpikeSlabPrior", class(ans)) return(ans) } ###====================================================================== IndependentSpikeSlabPrior <- function( x = NULL, y = NULL, expected.r2 = .5, prior.df = .01, expected.model.size = 1, prior.beta.sd = NULL, optional.coefficient.estimate = NULL, mean.y = mean(y, na.rm = TRUE), sdy = sd(as.numeric(y), na.rm = TRUE), sdx = apply(as.matrix(x), 2, sd, na.rm = TRUE), prior.inclusion.probabilities = NULL, number.of.observations = nrow(x), number.of.variables = ncol(x), scale.by.residual.variance = FALSE, sigma.upper.limit = Inf) { ## This version of the spike and slab prior assumes ## ## 1.0 / sigsq ~ Ga(prior.weight, prior.sumsq), ## beta | gamma ~ N(b, V), ## gamma ~ Independent Bernoulli(prior.inclusion.probabilities) ## ## where V is a diagonal matrix. ## ## Args: ## See SpikeSlabPriorBase. ## Additional args: ## prior.beta.sd: A vector of positive numbers giving the prior ## standard deviation of each model coefficient, conditionl on ## inclusion. If NULL it will be set to 10 * the ratio of sdy / ## sdx. ## scale.by.residual.variance: If TRUE the prior variance is ## sigma_sq * V, where sigma_sq is the residual variance of the ## linear regression modeled by this prior. Otherwise the prior ## variance is V, unscaled. stopifnot(is.logical(scale.by.residual.variance), length(scale.by.residual.variance) == 1) ans <- SpikeSlabPriorBase( number.of.variables = number.of.variables, expected.r2 = expected.r2, prior.df = prior.df, expected.model.size = expected.model.size, optional.coefficient.estimate = optional.coefficient.estimate, mean.y = mean.y, sdy = sdy, prior.inclusion.probabilities = prior.inclusion.probabilities, sigma.upper.limit = sigma.upper.limit) ## If any columns of x have zero variance (e.g. the intercept) then ## don't normalize by their standard deviation. sdx[sdx == 0] <- 1 stopifnot(length(sdy) == 1) stopifnot(is.numeric(sdy)) stopifnot(sdy > 0) stopifnot(is.numeric(sdx)) stopifnot(all(sdx > 0)) ## Each 1 sd change in x could have up to a 10 sd change in y. That's BIG if (is.null(prior.beta.sd)) { prior.beta.sd <- 10 * sdy / sdx } ans$prior.variance.diagonal <- prior.beta.sd^2 ans$scale.by.residual.variance <- scale.by.residual.variance class(ans) <- c("IndependentSpikeSlabPrior", class(ans)) return(ans) } ##=========================================================================== StudentIndependentSpikeSlabPrior <- function( predictor.matrix = NULL, response.vector = NULL, expected.r2 = .5, prior.df = .01, expected.model.size = 1, prior.beta.sd = NULL, optional.coefficient.estimate = NULL, mean.y = mean(response.vector, na.rm = TRUE), sdy = sd(as.numeric(response.vector), na.rm = TRUE), sdx = apply(as.matrix(predictor.matrix), 2, sd, na.rm = TRUE), prior.inclusion.probabilities = NULL, number.of.observations = nrow(predictor.matrix), number.of.variables = ncol(predictor.matrix), scale.by.residual.variance = FALSE, sigma.upper.limit = Inf, degrees.of.freedom.prior = UniformPrior(.1, 100)) { ans <- IndependentSpikeSlabPrior( x = predictor.matrix, y = response.vector, expected.r2 = expected.r2, prior.df = prior.df, expected.model.size = expected.model.size, prior.beta.sd = prior.beta.sd, optional.coefficient.estimate = optional.coefficient.estimate, mean.y = mean.y, sdy = sdy, sdx = sdx, prior.inclusion.probabilities = prior.inclusion.probabilities, number.of.observations = number.of.observations, number.of.variables = number.of.variables, scale.by.residual.variance = scale.by.residual.variance, sigma.upper.limit = sigma.upper.limit) stopifnot(inherits(degrees.of.freedom.prior, "DoubleModel")) ans$degrees.of.freedom.prior <- degrees.of.freedom.prior class(ans) <- c("StudentIndependentSpikeSlabPrior", class(ans)) return(ans) } ###====================================================================== SpikeSlabGlmPrior <- function( predictors, weight, mean.on.natural.scale, expected.model.size, prior.information.weight, diagonal.shrinkage, optional.coefficient.estimate, max.flips, prior.inclusion.probabilities) { ## A spike and slab prior for generalized linear models, like ## poisson and logit. The model is ## ## beta | gamma ~ N(b, V), ## gamma ~ Independent Bernoulli(prior.inclusion.probabilities) ## ## where V^{-1} = alpha * diag(V0) + (1 - alpha) * V0 with V0 = ## kappa * X' W X / n. In this formula X is the matrix of ## predictors, W is a diagonal matrix of weights, and n is the ## sample size, and both kappa and alpha are scalar tuning ## parameters. ## ## Args: ## predictors: A matrix of predictor variables, also known as the ## design matrix, or just X. ## weight: A vector of length nrow(predictors) giving the prior ## weight assigned to each observation in X. This should ## ideally match the weights from the Fisher information (e.g. p ## * (1-p) for logistic regression, or lambda for poisson ## regression, but that depends on the model, so a typical thing ## to do is to set all the weights the same. ## mean.on.natural.scale: Used to set the prior mean for the ## intercept. The mean of the response, expressed on the ## natural scale. This is logit(p-hat) for logits and log(ybar) ## for poissons. ## expected.model.size: A positive number less than ncol(x), ## representing a guess at the number of significant predictor ## variables. Used to obtain the 'spike' portion of the spike ## and slab prior. ## diagonal.shrinkage: The conditionally Gaussian prior for beta ## (the "slab") starts with a precision matrix equal to the ## information in a single observation. However, this matrix ## might not be full rank. The matrix can be made full rank by ## averaging with its diagonal. diagonal.shrinkage is the ## weight given to the diaonal in this average. Setting this to ## zero gives Zellner's g-prior. ## optional.coefficient.estimate: If desired, an estimate of the ## regression coefficients can be supplied. In most cases this ## will be a difficult parameter to specify. If omitted then a ## prior mean of zero will be used for all coordinates except ## the intercept, which will be set to mean(y). ## max.flips: The maximum number of variable inclusion indicators ## the sampler will attempt to sample each iteration. If negative ## then all indicators will be sampled. ## prior.inclusion.probabilities: A vector giving the prior ## probability of inclusion for each variable. dimension <- ncol(predictors) ans <- SpikeSlabPriorBase( number.of.variables = dimension, expected.model.size = expected.model.size, mean.y = mean.on.natural.scale, sdy = 1, optional.coefficient.estimate = optional.coefficient.estimate, prior.inclusion.probabilities = prior.inclusion.probabilities) ans$max.flips <- max.flips sample.size <- nrow(predictors) if (length(weight) == 1) { weight <- rep(weight, sample.size) } xtwx <- crossprod(sqrt(weight) * predictors) / sample.size stopifnot(is.numeric(diagonal.shrinkage), length(diagonal.shrinkage) == 1, diagonal.shrinkage >= 0, diagonal.shrinkage <= 1) if (dimension == 1) { d <- xtwx } else { d <- diag(diag(xtwx)) } xtwx <- diagonal.shrinkage * d + (1 - diagonal.shrinkage) * xtwx xtwx <- xtwx * prior.information.weight ans$siginv <- xtwx class(ans) <- c("SpikeSlabGlmPrior", "Prior", class(ans)) return(ans) } ##=========================================================================== SpikeSlabGlmPriorDirect <- function(coefficient.mean, coefficient.precision, prior.inclusion.probabilities = NULL, expected.model.size = NULL, max.flips = -1) { ## A spike and slab prior for problems where you want to specify the ## parameters directly, rather than in terms of the predictors and response. ## The model is beta | gamma ~ N(mean[gamma], precision[gamma, gamma]), where ## the elements of gamma are independent Bernoulli. ## ## Args: ## coefficient.mean: The mean of the 'slab' portion of the distribution if ## all variables were included. ## coefficient.precision: The precision (inverse variance) of the 'slab' ## portion of the distribution if all variables were included. ## prior.inclusion.probabilities: The probability that each variable is ## included. ## max.flips: The maximum number of include / exclude decsisions to explore ## in each MCMC iteration. If max.flips <= 0 or if max.flips exceeds the ## dimension of beta then each element of gamma is sampled each iteration. ## ## Returns: ## A spike and slab prior that can be used for probit, logit, and Poisson ## models. stopifnot(length(coefficient.mean) == nrow(coefficient.precision), nrow(coefficient.precision) == ncol(coefficient.precision)) if (is.null(prior.inclusion.probabilities)) { if (is.null(expected.model.size)) { stop(paste0( "Either 'expected.model.size' or 'prior.inclusion.probabilities' ", "must be specified.")) } check.positive.scalar(expected.model.size) xdim <- length(coefficient.mean) prior.inclusion.probabilities <- rep(expected.model.size / xdim, xdim) prior.inclusion.probabilities[prior.inclusion.probabilities > 1] <- 1 prior.inclusion.probabilities[prior.inclusion.probabilities < 0] <- 0 } check.scalar.integer(max.flips) ans <- list(mu = coefficient.mean, siginv = coefficient.precision, prior.inclusion.probabilities = prior.inclusion.probabilities, max.flips = max.flips) class(ans) <- c("SpikeSlabGlmPriorDirect", "SpikeSlabPriorBase", "Prior") return(ans) } ###====================================================================== ConditionalZellnerPrior <- function(xdim, optional.coefficient.estimate = NULL, expected.model.size = 1, prior.information.weight = .01, diagonal.shrinkage = .5, max.flips = -1, prior.inclusion.probabilities = NULL) { ## A Zellner-style prior where the predictor matrix, and potentially the ## residual variance parameter, will be obtained elsewhere. C++ code that ## takes this prior object must know where the X information comes from. ## ## Args: ## optional.coefficient.estimate: If desired, an estimate of the ## regression coefficients can be supplied. In most cases this ## will be a difficult parameter to specify. If omitted then a ## prior mean of zero will be used for all coordinates except ## the intercept, which will be set to mean(y). ## expected.model.size: A positive number less than ncol(x), ## representing a guess at the number of significant predictor ## variables. Used to obtain the 'spike' portion of the spike ## and slab prior. ## prior.information.weight: A positive scalar. Number of observations ## worth of weight that should be given to the prior estimate of beta. ## diagonal.shrinkage: The conditionally Gaussian prior for beta (the ## "slab") starts with a precision matrix equal to the information in a ## single observation. However, this matrix might not be full rank. The ## matrix can be made full rank by averaging with its diagonal. ## diagonal.shrinkage is the weight given to the diaonal in this average. ## Setting this to zero gives Zellner's g-prior. ## max.flips: The maximum number of variable inclusion indicators the ## sampler will attempt to sample each iteration. If negative then all ## indicators will be sampled. ## prior.inclusion.probabilities: A vector of length number.of.variables ## giving the prior inclusion probability of each coefficient. Each ## element must be between 0 and 1, inclusive. If left as NULL then a ## default value will be created with all elements set to ## expected.model.size / number.of.variables. stopifnot(check.positive.scalar(diagonal.shrinkage)) stopifnot(check.positive.scalar(prior.information.weight)) if (!is.null(optional.coefficient.estimate)) { xdim <- length(optional.coefficient.estimate) } stopifnot(xdim > 0) if (is.null(optional.coefficient.estimate)) { optional.coefficient.estimate <- rep(0, xdim) } if (is.null(prior.inclusion.probabilities)) { stopifnot(check.positive.scalar(expected.model.size)) prior.inclusion.probabilities <- rep(expected.model.size / xdim, xdim) prior.inclusion.probabilities[prior.inclusion.probabilities > 1] <- 1 prior.inclusion.probabilities[prior.inclusion.probabilities < 0] <- 0 } stopifnot(check.scalar.integer(max.flips)) ans <- list( prior.mean = optional.coefficient.estimate, prior.information.weight = prior.information.weight, diagonal.shrinkage = diagonal.shrinkage, max.flips = as.integer(max.flips), prior.inclusion.probabilities = prior.inclusion.probabilities) class(ans) <- c("ConditionalZellnerPrior", "Prior") return(ans) } ###====================================================================== LogitZellnerPrior <- function( predictors, successes = NULL, trials = NULL, prior.success.probability = NULL, expected.model.size = 1, prior.information.weight = .01, diagonal.shrinkage = .5, optional.coefficient.estimate = NULL, max.flips = -1, prior.inclusion.probabilities = NULL) { ## A Zellner-style spike and slab prior for logistic regression. ## ## beta | gamma ~ N(b, V), ## gamma ~ Independent Bernoulli(prior.inclusion.probabilities) ## ## with V^{-1} = prior.information.weight * ## ((1 - diagonal.shrinkage) * x^Twx / n ## + (diagonal.shrinkage) * diag(x^Twx / n)) ## ## The 'weight' in the information matrix x^Twx is p * (1 - p), ## where p is prior.success.probability. ## ## Args: ## predictors: The design matrix for the regression problem. No ## missing data is allowed. ## successes: The vector of responses, which can be binary or counts. If ## binary they can be 0/1, TRUE/FALSE, or 1/-1. If counts, then the ## 'trials' argument must be specified as well. This is only used to ## obtain the empirical overall success rate, so it can be left NULL if ## prior.success.probability is specified. ## trials: A vector of the same length as successes, giving the number of ## trials for each success count (trials cannot be less than successes). ## If successes is binary (or NULL) then this can be NULL as well, ## signifying that there was only one trial per experiment. ## prior.success.probability: An a priori (scalar) guess at the overall ## frequency of successes. Used in two places: to set the prior mean of ## the intercept (if optional.coefficient.estimate is NULL) and to weight ## the information matrix in the "slab" portion of the prior. ## expected.model.size: A positive number less than ncol(x), representing a ## guess at the number of significant predictor variables. Used to obtain ## the 'spike' portion of the spike and slab prior. ## prior.information.weight: A positive scalar. Number of observations ## worth of weight that should be given to the prior estimate of beta. ## diagonal.shrinkage: The conditionally Gaussian prior for beta (the ## "slab") starts with a precision matrix equal to the information in a ## single observation. However, this matrix might not be full rank. The ## matrix can be made full rank by averaging with its diagonal. ## diagonal.shrinkage is the weight given to the diaonal in this average. ## Setting this to zero gives Zellner's g-prior. ## optional.coefficient.estimate: If desired, an estimate of the regression ## coefficients can be supplied. In most cases this will be a difficult ## parameter to specify. If omitted then a prior mean of zero will be ## used for all coordinates except the intercept, which will be set to ## logit(prior.success.probability). ## max.flips: The maximum number of variable inclusion indicators the ## sampler will attempt to sample each iteration. If negative then all ## indicators will be sampled. ## prior.inclusion.probabilities: A vector of length number.of.variables ## giving the prior inclusion probability of each coefficient. Each ## element must be between 0 and 1, inclusive. If left as NULL then a ## default value will be created with all elements set to ## expected.model.size / number.of.variables. if (is.null(prior.success.probability)) { if (is.null(trials)) { prior.success.probability <- mean(successes > 0, na.rm = TRUE) } else { stopifnot(length(trials) == length(successes)) prior.success.probability <- sum(successes, na.rm = TRUE) / sum(trials, na.rm = TRUE) } } stopifnot(is.numeric(prior.success.probability), length(prior.success.probability) == 1, prior.success.probability >= 0.0, prior.success.probability <= 1.0) if (prior.success.probability == 0) { prior.success.probability = 1.0 / (2.0 + nrow(predictors)) warning("Fudging around the fact that prior.success.probability is zero. ", "Setting it to ", round(prior.success.probability, 5), "\n") } else if (prior.success.probability == 1.0) { nx <- nrow(predictors) prior.success.probability = (1.0 + nx) / (2.0 + nx) warning("Fudging around the fact that prior.success.probability is 1.", " Setting it to ", round(prior.success.probability, 5), "\n") } prior.logit <- qlogis(prior.success.probability) dimension <- ncol(predictors) ans <- SpikeSlabGlmPrior( predictors = predictors, weight = prior.success.probability * (1 - prior.success.probability), mean.on.natural.scale = prior.logit, expected.model.size = expected.model.size, prior.information.weight = prior.information.weight, diagonal.shrinkage = diagonal.shrinkage, optional.coefficient.estimate = optional.coefficient.estimate, max.flips = max.flips, prior.inclusion.probabilities = prior.inclusion.probabilities) ## All LogitPrior objects will have a 'prior.success.probability' ## field. ans$prior.success.probability = prior.success.probability class(ans) <- c("LogitZellnerPrior", "LogitPrior", class(ans)) return(ans) } ##=========================================================================== PoissonZellnerPrior <- function( predictors, counts = NULL, exposure = NULL, prior.event.rate = NULL, expected.model.size = 1, prior.information.weight = .01, diagonal.shrinkage = .5, optional.coefficient.estimate = NULL, max.flips = -1, prior.inclusion.probabilities = NULL) { ## A Zellner-style spike and slab prior for Poisson regression. ## ## beta | gamma ~ N(b, V), ## gamma ~ Independent Bernoulli(prior.inclusion.probabilities) ## ## with V^{-1} = prior.information.weight * ## ((1 - diagonal.shrinkage) * x^Twx / n ## + (diagonal.shrinkage) * diag(x^Twx / n)) ## ## The 'weight' in the information matrix x^Twx is exposure[i] * ## exp(beta^Tx[i]), which the mean of y[i]. ## ## Args: ## predictors: The design matrix for the regression problem. No ## missing data is allowed. ## counts: The vector of responses, This is only used to obtain ## the empirical overall event rate, so it can be left NULL if ## prior.event.rate is specified. ## exposure: A vector of the same length as counts, giving the ## "exposure time" for each experiment. This can also be NULL, ## signifying that exposure = 1.0 for each observation. ## prior.event.rate: An a priori guess at the overall frequency of ## successes. Used in two places: to set the prior mean of the ## intercept (if optional.coefficient.estimate is NULL) and to ## weight the information matrix in the "slab" portion of the ## prior. ## expected.model.size: A positive number less than ncol(x), ## representing a guess at the number of significant predictor ## variables. Used to obtain the 'spike' portion of the spike ## and slab prior. ## prior.information.weight: A positive scalar. Number of ## observations worth of weight that should be given to the ## prior estimate of beta. ## diagonal.shrinkage: The conditionally Gaussian prior for beta ## (the "slab") starts with a precision matrix equal to the ## information in a single observation. However, this matrix ## might not be full rank. The matrix can be made full rank by ## averaging with its diagonal. diagonal.shrinkage is the ## weight given to the diaonal in this average. Setting this to ## zero gives Zellner's g-prior. ## optional.coefficient.estimate: If desired, an estimate of the ## regression coefficients can be supplied. In most cases this ## will be a difficult parameter to specify. If omitted then a ## prior mean of zero will be used for all coordinates except ## the intercept, which will be set to log(prior.event.rate). ## max.flips: The maximum number of variable inclusion indicators ## the sampler will attempt to sample each iteration. If negative ## then all indicators will be sampled. ## prior.inclusion.probabilities: A vector of length ## number.of.variables giving the prior inclusion probability of ## each coefficient. Each element must be between 0 and 1, ## inclusive. If left as NULL then a default value will be ## created with all elements set to expected.model.size / ## number.of.variables. if (is.null(prior.event.rate)) { if (is.null(exposure)) { prior.event.rate <- mean(counts, na.rm = TRUE) } else { stopifnot(length(exposure) == length(counts), all(exposure > 0, na.rm = TRUE)) prior.event.rate = sum(counts, na.rm = TRUE) / sum(exposure, na.rm = TRUE) } } ## TODO(stevescott): Another really good choice here is to set ## prior.event.rate = 1 + y / exposure. That solves the weight ## problem for the precision matrix, but does not help for the ## intercept term. stopifnot(is.numeric(prior.event.rate), length(prior.event.rate) == 1, prior.event.rate >= 0.0) if (prior.event.rate == 0) { prior.event.rate = 1.0 / (2.0 + nrow(predictors)) warning("Fudging around the fact that prior.event.rate is zero. ", "Setting it to ", round(prior.event.rate, 5), "\n") } prior.log.event.rate <- log(prior.event.rate) dimension <- ncol(predictors) ans <- SpikeSlabGlmPrior( predictors = predictors, weight = prior.event.rate, mean.on.natural.scale = prior.log.event.rate, expected.model.size = expected.model.size, prior.information.weight = prior.information.weight, diagonal.shrinkage = diagonal.shrinkage, optional.coefficient.estimate = optional.coefficient.estimate, max.flips = max.flips, prior.inclusion.probabilities = prior.inclusion.probabilities) ## All PoissonPrior objects have a 'prior.event.rate' field. ans$prior.event.rate <- prior.event.rate class(ans) <- c("PoissonZellnerPrior", "PoissonPrior", class(ans)) return(ans) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/spike.slab.prior.R
.MakeKnots <- function(x, numknots) { ## Return a vector of quantiles of x of length numknots, equally space in ## quantile space. stopifnot(is.numeric(numknots), length(numknots) == 1, numknots > 0) stopifnot(is.numeric(x), !any(is.na(x))) knot.quantiles <- seq(1/numknots, 1 - 1/numknots, length = numknots) knots <- quantile(x, knot.quantiles) return(knots) } BsplineBasis <- function(x, knots = NULL, numknots = 3) { ## Args: ## x: A nummeric vector to be expanded. ## knots: A vector of knots. ## numknots: If 'knots' is supplied this is ignored. stopifnot(is.numeric(x), !any(is.na(x))) if (is.null(knots)) { knots <- .MakeKnots(x, numknots) } stopifnot(is.numeric(knots)) knots <- sort(knots) ans <- .Call("boom_spike_slab_Bspline_basis", x, knots) attr(ans, "knots") <- knots class(ans) <- c("BsplineBasis", "SplineBasis") return(ans) } MsplineBasis <- function(x, knots = NULL, numknots = 3) { ## Args: ## x: A nummeric vector to be expanded. ## knots: A vector of knots. stopifnot(is.numeric(x), !any(is.na(x))) if (is.null(knots)) { knots <- .MakeKnots(x, numknots) } stopifnot(is.numeric(knots)) knots <- sort(knots) ans <- .Call(boom_spike_slab_Mspline_basis, x, knots) attr(ans, "knots") <- knots class(ans) <- c("MsplineBasis", "SplineBasis") return(ans) } IsplineBasis <- function(x, knots = NULL, numknots = 3) { ## Args: ## x: A nummeric vector to be expanded. ## knots: A vector of knots. stopifnot(is.numeric(x), !any(is.na(x))) if (is.null(knots)) { knots <- .MakeKnots(x, numknots) } stopifnot(is.numeric(knots)) knots <- sort(knots) ans <- .Call("boom_spike_slab_Ispline_basis", x, knots) attr(ans, "knots") <- knots class(ans) <- c("IsplineBasis", "SplineBasis") return(ans) } knots <- function(Fn, ...) { UseMethod("knots") } knots.SplineBasis <- function(Fn, ...) { ## Args: ## Fn: A BOOM spline basis matrix. ## ...: Unused. Required to match the signature of the 'knots' generic function. ## ## Returns: ## The 'knots' attribute of Fn. return(attr(Fn, "knots")) }
/scratch/gouwar.j/cran-all/cranData/BoomSpikeSlab/R/splines.R
BoostMLR <- function(x, tm, id, y, Time_Varying = TRUE, BS_Time = TRUE, nknots_t = 10, d_t = 3, All_RawX = TRUE, RawX_Names, nknots_x = 7, d_x = 3, M = 200, nu = 0.05, Mod_Grad = TRUE, Shrink = FALSE, VarFlag = TRUE, lower_perc = 0.25, upper_perc = 0.75, NLambda = 100, Verbose = TRUE, Trace = FALSE, lambda = 0, setting_seed = FALSE, seed_value = 100L, ...) { if(missing(y)){ stop("y is missing") } if(is.data.frame(y)){ y <- data.matrix(y) } if(!is.vector(y) && !is.matrix(y) ){ stop("y must be a vector or matrix") } else { if(is.vector(y) && is.atomic(y)) { y <- matrix(y,ncol = 1) } } if(missing(tm) && missing(x)){ stop("tm and x both missing") } if(!missing(tm) && missing(id)){ stop("id is missing") } CrossSectional <- FALSE if(missing(tm) && !missing(x) ){ if(!missing(id)){ if(!(length(sort(unique(id))) == nrow(y)) ){ stop("tm is missing") } } else { id <- 1:nrow(y) } tm <- rep(0, nrow(y)) nknots_t <- 1 d_t <- 0 CrossSectional <- TRUE VarFlag <- FALSE } if(missing(x) && !missing(tm)){ x_miss <- TRUE All_RawX <- TRUE x <- cbind(rep(1,nrow(y))) if(length(sort(unique(id))) == nrow(y) ){ CrossSectional <- TRUE VarFlag <- FALSE } }else { x_miss <- FALSE } if(nknots_t <= 0 && BS_Time == TRUE){ stop("nknots_t must be > 0") } if(All_RawX == FALSE && any(nknots_x <= 0) ){ stop("nknots_x must be > 0") } if(missing(tm) && Time_Varying == TRUE){ Time_Varying <- FALSE } if(!BS_Time){ nknots_t <- 1 d_t <- 0 } #if(!missing(tm) && Time_Varying == FALSE && CrossSectional == FALSE){ # if(x_miss){ # x <- tm # } # nknots_t <- 1 # d_t <- 0 #} if ( any(is.na(id)) ) { stop("missing values encountered in id: remove observations with missing values") } Time_Unmatch <- rep(FALSE,ncol(x)) N <- nrow(y) user.option <- list(...) Lambda_Scale <- 1 rho <- is.hidden.rho(user.option) phi <- is.hidden.phi(user.option) Lambda_Ridge <- lambda Ridge_Penalty <- FALSE dt_Add <- is.hidden.dt_Add(user.option) if(!is.null(dt_Add)){ if(!is.list(dt_Add)){ stop("dt_Add must be a list") } K_Add <- length(dt_Add) nullObj <- lapply(1:K_Add,function(kk){ nc_K_Add <- ncol(dt_Add[[kk]]) if(nc_K_Add != 3){ stop("Each element of dt_Add must be a dataset with 3 columns arrange in order of id, time, x") } NULL }) Ord_id_tm <- Order_Time(ID = id,Time = tm) id <- id[Ord_id_tm] tm <- tm[Ord_id_tm] x <- x[Ord_id_tm,,drop = FALSE] y <- y[Ord_id_tm,,drop = FALSE] x_Add_New <- matrix(NA,nrow = N,ncol = K_Add) x_Names_Add <- rep(NA,K_Add) Time_Add_New <- matrix(NA,nrow = N,ncol = K_Add) Time_Names_Add <- rep(NA,K_Add) for(kk in 1:K_Add){ Ord_id_tm_Add <- Order_Time(ID = dt_Add[[kk]][,1],Time = dt_Add[[kk]][,2]) dt_Add[[kk]] <- dt_Add[[kk]][Ord_id_tm_Add,,drop = FALSE] id_Add <- dt_Add[[kk]][,1] x_Names_Add[kk] <- names(dt_Add[[kk]][,3,drop = FALSE]) Time_Names_Add[kk] <- names(dt_Add[[kk]][,2,drop = FALSE]) if(any(is.na(id_Add))){ stop("Missing values observed for id in dt_Add") } unq_id_Add <- unique(id_Add) n_Add <- length(unq_id_Add) nullObj <- unlist(lapply(1:n_Add,function(i){ Which_id <- which(unq_id_Add[i] == id) ni <- length(Which_id) if(ni > 0){ Which_id_Add <- which(id_Add == unq_id_Add[i]) ni_Add <- length(Which_id_Add) tm_Add <- dt_Add[[kk]][Which_id_Add,2] x_Add <- dt_Add[[kk]][Which_id_Add,3] for(j in 1:ni){ for(jj in 1:ni_Add){ if((!is.na(tm_Add[jj]) && !is.na(tm[Which_id[j]]))){ if(tm_Add[jj] <= tm[Which_id[j]]){ x_Add_New[Which_id[j], kk] <<- x_Add[jj] Time_Add_New[Which_id[j], kk] <<- tm_Add[jj] } } } } } NULL })) } colnames(x_Add_New) <- x_Names_Add x <- cbind(x,x_Add_New) Time_Unmatch <- c(Time_Unmatch,rep(TRUE, ncol(x_Add_New))) colnames(Time_Add_New) <- Time_Names_Add } else { Time_Add_New <- matrix(0,nrow = N,ncol = 1) colnames(Time_Add_New) <- "Time_Add" } #---------------------------------------------------------------------------------- # Date: 12/11/2020 # In the following codes, if the id is character or factor, we convert into numeric # without changing the values. #---------------------------------------------------------------------------------- if(is.character(id)){ id <- as.numeric(id) } if(is.factor(id)){ id <- as.numeric(levels(id))[id] } #---------------------------------------------------------------------------------- # Date: 12/11/2020 # while working on BoostMLR manuscript, I realized that the function Order_Time # works only when Dt_Add is non-null. We need this in every situation so that # I can plot beta coefficient as a function of time. This is done in the following # codes. Note that I have modified the Order_Time function in the utilities file. #---------------------------------------------------------------------------------- sort_id <- is.hidden.sort_id(user.option) if(sort_id){ unq_id <- sort_unique_C_NA(id) } else { unq_id <- unique_C_NA(id) } Ord_id_tm <- Order_Time(ID = id,Time = tm,unq_id = unq_id) id <- id[Ord_id_tm] tm <- tm[Ord_id_tm] x <- x[Ord_id_tm,,drop = FALSE] y <- y[Ord_id_tm,,drop = FALSE] if(!is.matrix(x)){ x <- data.matrix(x) } K <- ncol(x) L <- ncol(y) x_Names <- colnames(x) y_Names <- colnames(y) if(is.null(x_Names)){ x_Names <- paste("x",1:K,sep="") } if(is.null(y_Names)){ y_Names <- paste("y",1:L,sep="") } if( ( is.null(rho) && !is.null(phi) ) || ( !is.null(rho) && is.null(phi) ) ){ stop("rho or phi is null") } if( !is.null(rho) && !is.null(phi) ){ VarFlag <- FALSE if(! ( (length(rho) == 1 || length(rho) == L) && (length(phi) == 1 || length(phi) == L) ) ){ stop("Length of rho and phi must be 1 or L") } if( any(rho < -1) || any(rho > 1) || any(phi <= 0) ){ stop("rho should be between -1 and 1 and phi should be > 0") } if(length(rho) == 1 && length(phi) == 1){ rho <- rep(rho,L) phi <- rep(phi,L) } Rho <- matrix(rep(rho,M),nrow = M,byrow = TRUE) Phi <- matrix(rep(phi,M),nrow = M,byrow = TRUE) } else { rho <- rep(0,L) phi <- rep(1,L) Rho <- matrix(rep(rho,M),nrow = M,byrow = TRUE) Phi <- matrix(rep(phi,M),nrow = M,byrow = TRUE) } unq_x <- lapply(1:K,function(k){ sort_unique_C_NA(x[,k,drop = TRUE]) }) n_unq_x <- unlist(lapply(1:K,function(k){ length(unq_x[[k]]) })) if( !(length(nknots_x) == 1 || length(nknots_x) == K) ){ stop( paste("Length of nknots_x should be either 1 or",K,sep = " ") ) } if( !(length(d_x) == 1 || length(d_x) == K) ){ stop( paste("Length of d_x should be either 1 or",K,sep = " ") ) } if(length(nknots_x) == 1){ nknots_x <- rep(nknots_x,K) } if(length(d_x) == 1){ d_x <- rep(d_x,K) } Unique_Limit <- unlist(lapply(1:K,function(k){ nknots_x[k] + d_x[k] })) Categorical_x <- x_Names[which(unlist(lapply(1:K,function(k){ (n_unq_x[k] < Unique_Limit[k]) })))] if(length(Categorical_x) > 0){ if(missing(RawX_Names)){ RawX_Names <- Categorical_x }else { RawX_Names <- union(RawX_Names,Categorical_x) } } if(All_RawX){ UseRaw <- rep(TRUE,K) }else { if(missing(RawX_Names) ){ UseRaw <- rep(FALSE,K) }else { UseRaw <- (!is.na(match(x_Names,RawX_Names))) if(all(UseRaw == FALSE)){ stop("RawX.names do not match with the variables names from x") } } } ProcessedData <- DataProcessing_C(x, y, id, tm, unq_id, x_miss, Trace) Org_x <- ProcessedData$Data$Org_x Org_y <- ProcessedData$Data$Org_y id <- ProcessedData$Data$id tm <- ProcessedData$Data$tm x <- ProcessedData$Data$x y <- ProcessedData$Data$y if(!is.matrix(Org_x)){ Org_x <- data.matrix(Org_x) } if(!is.matrix(Org_y)){ Org_y <- data.matrix(Org_y) } if(!is.matrix(x)){ x <- data.matrix(x) } if(!is.matrix(y)){ y <- data.matrix(y) } x_Mean <- ProcessedData$Data$x_Mean x_Std_Error <- ProcessedData$Data$x_Std_Error y_Mean <- ProcessedData$Data$y_Mean y_Std_Error <- ProcessedData$Data$y_Std_Error unq_id <- ProcessedData$Index$unq_id id_index <- ProcessedData$Index$id_index n <- ProcessedData$Dimensions$n K <- ProcessedData$Dimensions$K L <- ProcessedData$Dimensions$L ni <- ProcessedData$Dimensions$ni N <- ProcessedData$Dimensions$N if(all(ni == 1)){ VarFlag <- FALSE } H <- nknots_t + d_t unq_tm <- sort_unique_C_NA(tm) n_unq_tm <- length(unq_tm) if( (n_unq_tm < H) && (BS_Time == TRUE) ){ H <- n_unq_tm } if(CrossSectional == TRUE || Time_Varying == FALSE){ Bt <- cbind(rep(1,n_unq_tm)); }else { if(BS_Time){ Bt <- bs(x = unq_tm,df = H,degree = d_t,intercept = TRUE) }else { Bt <- cbind(unq_tm) } } unq_x <- lapply(1:K,function(k){ if(UseRaw[k]){ NA }else { sort_unique_C_NA(x[,k,drop = TRUE]) } }) n_unq_x <- unlist(lapply(1:K,function(k){ if(UseRaw[k]){ NA }else { length(unq_x[[k]]) } })) Dk <- unlist(lapply(1:K,function(k){ if(UseRaw[k]){ out <- 1 }else { Dk_Temp <- nknots_x[k] + d_x[k] if(n_unq_x[k] < Dk_Temp){ out <- n_unq_x[k] }else { out <- Dk_Temp } } out })) count <- 0 Bx <- lapply(1:K,function(k){ if(UseRaw[k]){ if(Time_Unmatch[k]){ count <<- count + 1 x[,k,drop = FALSE]*Time_Add_New[ , count, drop = FALSE] } else { x[,k,drop = FALSE] } }else { bs(x = unq_x[[k]],df = Dk[k],degree = d_x[k],intercept = TRUE) } }) Bx_Scale <- lapply(1:K,function(k){ if(UseRaw[k]){ 1 }else { rep(1,Dk[k]) } }) Lambda_Ridge_Vec <- unlist(lapply(1:K,function(k){ Lambda_Ridge })) if(M < 10){ Verbose <- FALSE } obj_C <- BoostMLR_C(Org_x, Org_y, id, tm, x, y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, K, L, H, Dk, ni, N, unq_id, unq_tm, unq_x, id_index, Bt, Bx, Bx_Scale, Time_Add_New, Time_Unmatch, nu, M, Mod_Grad, UseRaw, Lambda_Ridge_Vec, Ridge_Penalty, Shrink, lower_perc, upper_perc, Lambda_Scale, NLambda, VarFlag, rho, phi, setting_seed, seed_value, Verbose, Trace) Tm_Beta <- lapply(1:obj_C$Dimensions$L,function(l){ Out <- matrix(unlist(lapply(1:obj_C$Dimensions$K,function(k){ if(!UseRaw[k]){ rep(NA, obj_C$Dimensions$N) }else { Reduce("+",lapply(1:obj_C$Dimensions$H,function(h){ unlist(lapply(1:obj_C$Dimensions$n,function(i){ obj_C$Beta_Estimate$Tm_Beta_C[[k]][[1]][[h]][[l]][[i]] })) })) } })),ncol = obj_C$Dimensions$K,byrow = FALSE) colnames(Out) <- x_Names Out }) #---------------------------------------------------------------------------------- # Date: 12/11/2020 # It was realized that it makes more sense to show plots of beta on the standardized # scale rather than on the original scale. Therefore, along with Tm_Beta, I # have calculated Tm_Beta_Std in the following codes. #---------------------------------------------------------------------------------- Tm_Beta_Std <- lapply(1:obj_C$Dimensions$L,function(l){ Out <- matrix(unlist(lapply(1:obj_C$Dimensions$K,function(k){ if(!UseRaw[k]){ rep(NA, obj_C$Dimensions$N) }else { Reduce("+",lapply(1:obj_C$Dimensions$H,function(h){ unlist(lapply(1:obj_C$Dimensions$n,function(i){ obj_C$Beta_Estimate$Tm_Beta_Std_C[[k]][[1]][[h]][[l]][[i]] })) })) } })),ncol = obj_C$Dimensions$K,byrow = FALSE) colnames(Out) <- x_Names Out }) if(Time_Varying == FALSE){ Tm_Beta <- lapply(1:obj_C$Dimensions$L,function(l){ Tm_Beta[[l]][1,,drop = TRUE] }) } names(Tm_Beta) <- y_Names #---------------------------------------------------------------------------------- # Date: 12/11/2020 # Added Tm_Beta_Std as a part of Beta_Estimate #---------------------------------------------------------------------------------- if(Time_Varying == FALSE){ Tm_Beta_Std <- lapply(1:obj_C$Dimensions$L,function(l){ Tm_Beta_Std[[l]][1,,drop = TRUE] }) } names(Tm_Beta_Std) <- y_Names Beta_Estimate <- obj_C$Beta_Estimate Beta_Estimate$Tm_Beta <- Tm_Beta #---------------------------------------------------------------------------------- # Date: 12/11/2020 # Added Tm_Beta_Std as a part of Beta_Estimate #---------------------------------------------------------------------------------- Beta_Estimate$Tm_Beta_Std <- Tm_Beta_Std Rho <- Phi <- matrix(NA,nrow = M,ncol = L) colnames(Phi) <- y_Names colnames(Rho) <- y_Names Error_Rate <- obj_C$Error_Rate colnames(Error_Rate) <- y_Names if(FALSE){ if(VarFlag){ NullObj <- lapply(1:L,function(l){ lapply(1:M,function(m){ Residual_Data <- data.frame(y = (obj_C$Data$Org_y[,l] - obj_C$mu_List[[m]][,l]) ,tm = obj_C$Data$tm, id = obj_C$Data$id, obj_C$Data$Org_x) gls.obj <- tryCatch({gls(y ~ ., data = Residual_Data, correlation = corCompSymm(form = ~ 1 | id))}, error = function(ex){NULL}) if (is.null(gls.obj)) { gls.obj <- tryCatch({gls(y ~ 1, data = Residual_Data, correlation = corCompSymm(form = ~ 1 | id))}, error = function(ex){NULL}) } if (!is.null(gls.obj)) { phi_Temp <- gls.obj$sigma^2 Phi[m,l] <<- ifelse(phi_Temp == 0,1,phi_Temp) rho_Temp <- as.numeric(coef(gls.obj$modelStruct$corStruc, unconstrained = FALSE)) Rho[m,l] <<- max(min(0.999, rho_Temp, na.rm = TRUE), -0.999) Result <- c(phi_Temp,rho_Temp) } NULL }) NULL }) } } x <- obj_C$Data$Org_x y <- obj_C$Data$Org_y id <- obj_C$Data$id tm <- obj_C$Data$tm M <- obj_C$Regulate$M nu <- obj_C$Regulate$nu mu <- obj_C$mu_List[[M]] if(VarFlag){ phi <- obj_C$Phi[M,] rho <- obj_C$Rho[M,] } Grow_Object <- list(Data = obj_C$Data, Dimensions = obj_C$Dimensions, Index = obj_C$Index, BS = obj_C$BS, Regulate = obj_C$Regulate, Beta_Estimate = Beta_Estimate, mu = obj_C$mu, mu_List = obj_C$mu_List, mu_zero = obj_C$mu_zero, Vec_zero = obj_C$Vec_zero, Mod_Grad = Mod_Grad, sort_id = sort_id, phi = phi, rho = rho, Time_Unmatch = Time_Unmatch, setting_seed = setting_seed, seed_value = seed_value, Time_Add_New = if(is.null(dt_Add)) NULL else Time_Add_New) Variable_Select = (obj_C$Variable_Select + 1) Response_Select = (obj_C$Response_Select + 1) Variable_Select[Variable_Select == 0] <- NA Response_Select[Response_Select == 0] <- NA Phi <- obj_C$Phi Rho <- obj_C$Rho colnames(Phi) <- colnames(Rho) <- y_Names obj <- list(x = x, id = id, tm = tm, y = y, UseRaw = UseRaw, x_Names = x_Names, y_Names = y_Names, M = M, nu = nu, Tm_Beta = Tm_Beta, mu = mu, Error_Rate = Error_Rate, Variable_Select = Variable_Select, Response_Select = Response_Select, VarFlag = VarFlag, Time_Varying = Time_Varying, Phi = Phi, Rho = Rho, Lambda_List = obj_C$Lambda_List, Grow_Object = Grow_Object) class(obj) <- c("BoostMLR", "grow") invisible(obj) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/BoostMLR.R
#-------------------------------------------------- # BoostMLR news BoostMLR.news <- function(...) { newsfile <- file.path(system.file(package="BoostMLR"), "NEWS") file.show(newsfile) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/BoostMLR.news.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 Sum_C <- function(x) { .Call(`_BoostMLR_Sum_C`, x) } Sum_C_NA <- function(x) { .Call(`_BoostMLR_Sum_C_NA`, x) } length_C_NA <- function(x) { .Call(`_BoostMLR_length_C_NA`, x) } Mean_C <- function(x) { .Call(`_BoostMLR_Mean_C`, x) } Mean_C_NA <- function(x) { .Call(`_BoostMLR_Mean_C_NA`, x) } Which_C <- function(x, x_set) { .Call(`_BoostMLR_Which_C`, x, x_set) } Which_C_NA <- function(x, x_set) { .Call(`_BoostMLR_Which_C_NA`, x, x_set) } Which_Min_C <- function(x) { .Call(`_BoostMLR_Which_Min_C`, x) } Which_Min_C_NA <- function(x) { .Call(`_BoostMLR_Which_Min_C_NA`, x) } Which_Max_C <- function(x) { .Call(`_BoostMLR_Which_Max_C`, x) } Which_Max_C_NA <- function(x) { .Call(`_BoostMLR_Which_Max_C_NA`, x) } StdVar_C <- function(MyMat) { .Call(`_BoostMLR_StdVar_C`, MyMat) } StdVar_C_NA <- function(MyMat) { .Call(`_BoostMLR_StdVar_C_NA`, MyMat) } Match_C <- function(x_subset, x_set) { .Call(`_BoostMLR_Match_C`, x_subset, x_set) } Match_C_NA <- function(x_subset, x_set) { .Call(`_BoostMLR_Match_C_NA`, x_subset, x_set) } Approx_Match_C <- function(x, y) { .Call(`_BoostMLR_Approx_Match_C`, x, y) } Approx_Match_C_NA <- function(x, y) { .Call(`_BoostMLR_Approx_Match_C_NA`, x, y) } Diag_Matrix_C <- function(x) { .Call(`_BoostMLR_Diag_Matrix_C`, x) } Matrix_Sum_C <- function(x, y) { .Call(`_BoostMLR_Matrix_Sum_C`, x, y) } Matrix_Sum_C_NA <- function(x, y) { .Call(`_BoostMLR_Matrix_Sum_C_NA`, x, y) } l2Dist_Vector_C <- function(x1, x2, ID) { .Call(`_BoostMLR_l2Dist_Vector_C`, x1, x2, ID) } l2Dist_Vector_C_NA <- function(x1, x2, ID) { .Call(`_BoostMLR_l2Dist_Vector_C_NA`, x1, x2, ID) } set_seed <- function(seed) { invisible(.Call(`_BoostMLR_set_seed`, seed)) } randomShuffle <- function(x, size, setting_seed, seed_value, replace = FALSE, p = NULL) { .Call(`_BoostMLR_randomShuffle`, x, size, setting_seed, seed_value, replace, p) } int_randomShuffle <- function(x, size, setting_seed, seed_value, replace = FALSE, p = NULL) { .Call(`_BoostMLR_int_randomShuffle`, x, size, setting_seed, seed_value, replace, p) } Reverse_Ordering <- function(a) { .Call(`_BoostMLR_Reverse_Ordering`, a) } RemoveNA <- function(x) { .Call(`_BoostMLR_RemoveNA`, x) } stl_sort <- function(x) { .Call(`_BoostMLR_stl_sort`, x) } stl_sort_NA <- function(x) { .Call(`_BoostMLR_stl_sort_NA`, x) } stl_sort_reverse <- function(x) { .Call(`_BoostMLR_stl_sort_reverse`, x) } stl_sort_reverse_NA <- function(x) { .Call(`_BoostMLR_stl_sort_reverse_NA`, x) } unique_C <- function(x) { .Call(`_BoostMLR_unique_C`, x) } unique_C_NA <- function(x) { .Call(`_BoostMLR_unique_C_NA`, x) } sort_unique_C <- function(x) { .Call(`_BoostMLR_sort_unique_C`, x) } sort_unique_C_NA <- function(x) { .Call(`_BoostMLR_sort_unique_C_NA`, x) } Which_Max_Matrix <- function(x) { .Call(`_BoostMLR_Which_Max_Matrix`, x) } Which_Max_Matrix_NA <- function(x) { .Call(`_BoostMLR_Which_Max_Matrix_NA`, x) } rowSums_C <- function(x) { .Call(`_BoostMLR_rowSums_C`, x) } rowSums_C_NA <- function(x) { .Call(`_BoostMLR_rowSums_C_NA`, x) } isNA <- function(x) { .Call(`_BoostMLR_isNA`, x) } Rho_Inv_C <- function(Rho_Value, N_Value) { .Call(`_BoostMLR_Rho_Inv_C`, Rho_Value, N_Value) } MatrixInversion_Equicorrelation_C <- function(N_Value, phi, rho) { .Call(`_BoostMLR_MatrixInversion_Equicorrelation_C`, N_Value, phi, rho) } Matrix_Vector_Multiplication_C <- function(x, y) { .Call(`_BoostMLR_Matrix_Vector_Multiplication_C`, x, y) } DataProcessing_C <- function(Org_x, Org_y, id, tm, unq_id, x_miss, Trace) { .Call(`_BoostMLR_DataProcessing_C`, Org_x, Org_y, id, tm, unq_id, x_miss, Trace) } BoostMLR_C <- function(Org_x, Org_y, id, tm, x, y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, K, L, H, Dk, ni, N, unq_id, unq_tm, unq_x, id_index, Bt, Bx, Bx_Scale, Time_Add_New, Time_Unmatch, nu, M, Mod_Grad, UseRaw, Lambda_Ridge_Vec, Ridge_Penalty, Shrink, lower_perc, upper_perc, Lambda_Scale, NLambda, VarFlag, rho, phi, setting_seed, seed_value, Verbose, Trace) { .Call(`_BoostMLR_BoostMLR_C`, Org_x, Org_y, id, tm, x, y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, K, L, H, Dk, ni, N, unq_id, unq_tm, unq_x, id_index, Bt, Bx, Bx_Scale, Time_Add_New, Time_Unmatch, nu, M, Mod_Grad, UseRaw, Lambda_Ridge_Vec, Ridge_Penalty, Shrink, lower_perc, upper_perc, Lambda_Scale, NLambda, VarFlag, rho, phi, setting_seed, seed_value, Verbose, Trace) } update_BoostMLR_C <- function(Org_x, Org_y, id, tm, x, y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, K, L, H, Dk, ni, N, unq_id, unq_tm, unq_x, id_index, tm_index, x_index, Bt, Bx, Bt_H, Bx_K, Bxt, Bx_Scale, nu, M, M_New, UseRaw, Shrink, Ridge_Penalty, Lambda_Ridge_Vec, Lambda_Scale, NLambda, lower_perc, upper_perc, Lambda_List, mu, mu_List, mu_zero, Vec_zero, Error_Rate, Variable_Select, Response_Select, Beta_Hat_List, Sum_Beta_Hat_List, Beta, Beta_Hat_List_Iter, lower_Beta_Hat_Noise, upper_Beta_Hat_Noise, List_Trace_Bxt_gm, Mod_Grad, VarFlag, phi, rho, Phi, Rho, setting_seed, seed_value, Verbose) { .Call(`_BoostMLR_update_BoostMLR_C`, Org_x, Org_y, id, tm, x, y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, K, L, H, Dk, ni, N, unq_id, unq_tm, unq_x, id_index, tm_index, x_index, Bt, Bx, Bt_H, Bx_K, Bxt, Bx_Scale, nu, M, M_New, UseRaw, Shrink, Ridge_Penalty, Lambda_Ridge_Vec, Lambda_Scale, NLambda, lower_perc, upper_perc, Lambda_List, mu, mu_List, mu_zero, Vec_zero, Error_Rate, Variable_Select, Response_Select, Beta_Hat_List, Sum_Beta_Hat_List, Beta, Beta_Hat_List_Iter, lower_Beta_Hat_Noise, upper_Beta_Hat_Noise, List_Trace_Bxt_gm, Mod_Grad, VarFlag, phi, rho, Phi, Rho, setting_seed, seed_value, Verbose) } predict_BoostMLR_C <- function(Org_x, tm, id, Org_y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, K, L, H, Dk, unq_id, unq_tm, unq_x, Bt, Bx, UseRaw, Time_Add_New, Time_Unmatch, Beta, Beta_Hat_List, testFlag, M, nu, Time_Varying, vimpFlag, vimpFlag_Coef, eps, setting_seed, seed_value) { .Call(`_BoostMLR_predict_BoostMLR_C`, Org_x, tm, id, Org_y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, K, L, H, Dk, unq_id, unq_tm, unq_x, Bt, Bx, UseRaw, Time_Add_New, Time_Unmatch, Beta, Beta_Hat_List, testFlag, M, nu, Time_Varying, vimpFlag, vimpFlag_Coef, eps, setting_seed, seed_value) } vimp_BoostMLR_C <- function(Org_x, Org_y, tm, id, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, ni, N, L, K, p, H, Dk, n_unq_tm, UseRaw, id_index, tm_index, unq_x_New, Index_Bt, vimp_set, joint, Bt, Bt_H, Bx, Bxt, Bx_K, Beta_Hat_List, Mopt, nu, rmse, Time_Varying, Vec_zero, mu_zero_vec, setting_seed, seed_value) { .Call(`_BoostMLR_vimp_BoostMLR_C`, Org_x, Org_y, tm, id, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, ni, N, L, K, p, H, Dk, n_unq_tm, UseRaw, id_index, tm_index, unq_x_New, Index_Bt, vimp_set, joint, Bt, Bt_H, Bx, Bxt, Bx_K, Beta_Hat_List, Mopt, nu, rmse, Time_Varying, Vec_zero, mu_zero_vec, setting_seed, seed_value) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/RcppExports.R
#------------------------------------------------------------------------------------------- # Partial plot function partial.BoostMLR <- function(Object, xvar.name, n.x = 10, n.tm = 10, x.unq = NULL, tm.unq = NULL, Mopt, plot.it = TRUE, path_saveplot = NULL, Verbose = TRUE, ...) { if (missing(Object)) { stop("Object is missing") } x <- Object$x tm <- Object$tm id <- Object$id if (missing(xvar.name)) { stop("xvar.name is missing" ) } if(length(xvar.name) > 1){ stop("Use single covariate in xvar.name") } x_Names <- Object$x_Names xvar.name <- intersect(xvar.name, x_Names) if (length(xvar.name) == 0) { stop("xvar.name do not match original variable names") } user.option <- list(...) prob_min <- is.hidden.prob_min(user.option) prob_max <- is.hidden.prob_max(user.option) if( is.null(x.unq) ){ xvar <- x[,xvar.name,drop = TRUE] n.x.unq <- length(unique(xvar)) if(n.x.unq <= n.x){ x.unq <- sort(unique(xvar)) } else { x.unq <- sort(unique(xvar))[unique(as.integer(quantile(1: n.x.unq ,probs = seq(prob_min,prob_max,length.out = min(n.x,n.x.unq) ))))] } } n.x <- length(x.unq) if( is.null(tm.unq) ){ n.tm.unq <- length(unique(tm)) if(n.tm.unq <= n.tm){ tm.unq <- sort(unique(tm)) } else { tm.unq <- sort(unique(tm))[unique(as.integer(quantile(1: length(unique(tm)) ,probs = seq(0,0.9,length.out = min(n.tm,n.tm.unq) ))))] } } n.tm <- length(tm.unq) if(missing(Mopt)){ Mopt <- Object$M } L <- Object$Grow_Object$Dimensions$L p.obj <- lapply(1:n.x,function(i){ new_x <- x new_x[,xvar.name] <- x.unq[i] lapply(1:n.tm,function(j){ tm <- rep(tm.unq[j],nrow(x)) colMeans(predictBoostMLR(Object = Object,x = new_x,tm = tm,id = id,M = Mopt,importance = FALSE)$mu,na.rm = TRUE) }) }) pList <- lapply(1:L,function(l){ pMat <- matrix(NA,nrow = n.x,ncol = n.tm) for(i in 1:n.x){ for(j in 1:n.tm){ pMat[i,j] <- p.obj[[i]][[j]][l] } } pMat }) sList <- lapply(1:L,function(l){ sMat <- matrix(NA,nrow = n.x,ncol = n.tm) for(i in 1:n.x){ y.lo <- lowess(x = tm.unq,y = pList[[l]][i,,drop = TRUE] )$y sMat[i,] <- y.lo } sMat }) if(plot.it){ if(is.null(path_saveplot)){ path_saveplot <- tempdir() } pdf(file = paste(path_saveplot,"/","PartialPlot.pdf",sep=""),width = 14,height = 14) for(l in 1:L){ filled.contour(x = tm.unq, y = x.unq, z = t(sList[[l]]), xlim = range(tm.unq, finite = TRUE) + c(-0, 0), ylim = range(x.unq, finite = TRUE) + c(-0, 0), color.palette = colorRampPalette(c("yellow", "red")), xlab = "Time", ylab = "x", main = "PartialPlot", cex.main = 2, cex.lab = 1.5, plot.axes = { axis(1,cex.axis = 1.5) axis(2,cex.axis = 1.5)}) } dev.off() if(Verbose){ cat("Plot will be saved at:",path_saveplot,sep = "") } } obj <- list(x.unq = x.unq, tm.unq = tm.unq, pList = pList, sList = sList) invisible(obj) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/partial.BoostMLR.R
plot.Variable_Select <- function(Variable_Select,K,plot.it = FALSE,N_R = 2,N_C = 2){ H <- ncol(Variable_Select) M <- nrow(Variable_Select) List_Proportion_Variable_Select <- lapply(1:H,function(h){ prop.var.full <- matrix(unlist(lapply(1:K,function(i){ unlist(lapply(1:M,function(j){ sum(Variable_Select[1:j,h] == i,na.rm = TRUE)/j })) })),nrow = M,byrow = FALSE) prop.var.full <- cbind(prop.var.full[,1:4],rowMeans(prop.var.full[,5:K]) ) }) if(plot.it){ oldpar <- par("mfrow", "mar") on.exit(par(oldpar)) par(mfrow=c(N_R,N_C)) for(h in 1:H){ plot(range(1:M),range(List_Proportion_Variable_Select[[h]]),type = "n",xlab = "m",ylab = "Proportion of Selected Variables") K <- ncol(List_Proportion_Variable_Select[[h]]) for(i in 1:K){ if(i <= 4){ lines(1:M,List_Proportion_Variable_Select[[h]][,i],type = "l",lwd = 3,col = i) }else { lines(1:M,List_Proportion_Variable_Select[[h]][,i],type = "l",lwd = 3,col = "gray") } } } } List_Proportion_Variable_Select }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/plot.Variable_Select.R
#-------------------------------------------------- # Colors for plotting ColorPlot <- c("black","red3","green4","blue","pink4","magenta2","orange") #-------------------------------------------------- # Plot rho, phi, or error rate plotBoostMLR <- function(Result,xlab = "",ylab = "",legend_fraction_x = 0.10,legend_fraction_y = 0,...){ if(is.vector(Result)){ Result <- matrix(Result,ncol = 1) } nr <- nrow(Result) nc <- ncol(Result) Range_x <- c(0,nr) x_lim <- c(0, (nr + round(legend_fraction_x*nr,0)) ) Range_y <- range(c(Result),na.rm = TRUE) y_lim <- c(Range_y[1], ifelse(Range_y[2] > 0, Range_y[2] + legend_fraction_y*Range_y[2], Range_y[2] + legend_fraction_y*abs(Range_y[2]))) plot(1:nr,Result[,1],type = "n",xlab = xlab,ylab = ylab,xlim = x_lim,ylim = y_lim,cex.lab = 1.5,frame.plot=FALSE,tck = 0,cex.axis = 1,xaxt = "n",yaxt = "n") axis(1,lwd = 2,at = seq(Range_x[1],Range_x[2],length.out = 5),tick = TRUE,cex = 0.5,font.axis = 2) axis(2,lwd = 2,at = seq(Range_y[1],Range_y[2],length.out = 5),labels = round(seq(Range_y[1],Range_y[2],length.out = 5),2),tick = TRUE,cex = 0.5,font.axis = 2) for(i in 1:nc){ lines(1:nr,Result[,i],type = "l",lwd = 2,col = ColorPlot[i]) } # q3 <- quantile(Result,probs = 0.75) # legend(nr,q3,col = ColorPlot[1:nc],lwd = 3,lty = 1,box.col = "white",colnames(Result)) legend(Range_x[2],Range_y[2],col = ColorPlot[1:nc],lwd = 3,lty = 1,box.col = "white",colnames(Result)) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/plotBoostMLR.R
plotVIMP <- function(vimp_Object, xvar.names = NULL, cex.xlab = NULL, ymaxlim = 0, yminlim = 0, main = "Variable Importance (%)", col = grey(.80), cex.lab = 1.5, ylbl = NULL, legend_placement = NULL, plot.it = TRUE, path_saveplot = NULL, Verbose = TRUE) { ymaxtimelim <- 0 subhead.cexval <- 1 yaxishead <- NULL xaxishead <- NULL subhead.labels <- c("Time-Interactions Effects","Main Effects") Adj <- -0.5 cex.main <- 1 seplim <- NULL if(missing(vimp_Object) ){ stop("vimp is not provided") } if(is.list(vimp_Object)){ L <- length(vimp_Object) } else { stop("vimp_Object must be a list of length equal to number of response variables") } vimp <- matrix(unlist(lapply(1:L,function(l){ vimp_Object[[l]][,1] })),ncol = L,byrow = FALSE) colnames(vimp) <- names(vimp_Object) if(is.null(xvar.names)){ xvar.names <- rownames(vimp_Object[[1]]) } MainEffect <- TRUE vimp <- vimp*100 if(plot.it){ if(is.null(path_saveplot)){ path_saveplot <- tempdir() } pdf(file = paste(path_saveplot,"/","VIMP.pdf",sep=""),width = 14,height = 14) if(MainEffect){ for(l in 1:L){ if(is.null(ylbl)){ ylbl <- "" } ylim <- range(vimp[,l]) + c(yminlim,ymaxlim) yaxs <- pretty(ylim) yat <- abs(yaxs) bp <- barplot(as.matrix(vimp[,l]),beside=T,col=col,ylim=ylim,yaxt="n",ylab = ylbl,main = main,cex.main = cex.main,cex.lab=cex.lab) text(c(bp), if(is.null(legend_placement)) pmax(as.matrix(vimp[,l]),0) else legend_placement, rep(xvar.names, 3),srt=90,adj=Adj,cex= if(!is.null(cex.xlab)) cex.xlab else 1 ) axis(2,yaxs,yat) } } else { p <- 1 n.vimp <- 1 for(l in 1:L){ vimp.x <- vimp[1:p,l] vimp.time <- vimp[-c(1:p),l] ylim <- max(c(vimp.x,vimp.time)) * c(-1, 1) + c(-ymaxtimelim,ymaxlim) yaxs <- pretty(ylim) yat <- abs(yaxs) if(is.null(yaxishead)){ yaxishead <- c(-ylim[1],ylim[2]) } if(is.null(xaxishead)){ xaxishead <- c(floor(n.vimp/4),floor(n.vimp/4)) } bp1 <- barplot(pmax(as.matrix(vimp.x),0),beside=T,col=col,ylim=ylim,yaxt="n",ylab = "",cex.lab=cex.lab, main = main,cex.main = cex.main) text(c(bp1), pmax(as.matrix(vimp.x),0), rep(xvar.names, 3),srt=90,adj=Adj,cex=if(!is.null(cex.xlab)) cex.xlab else 1) text(xaxishead[2],yaxishead[2],labels = subhead.labels[2],cex = subhead.cexval) bp2 <- barplot(-pmax(as.matrix(vimp.time),0),beside=T,col=col,add=TRUE,yaxt="n") text(c(bp2), -pmax(as.matrix(vimp.time),0), rep(xvar.names, 3),srt=90,adj=Adj,yaxt="n",cex=if(!is.null(cex.xlab)) cex.xlab else 1) text(xaxishead[1],-yaxishead[1],labels = subhead.labels[1],cex = subhead.cexval) axis(2,yaxs,yat) } } dev.off() if(Verbose){ cat("Plot will be saved at:",path_saveplot,sep = "") } } }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/plotVIMP.R
predictBoostMLR <- function(Object, x, tm, id, y, M, importance = FALSE, eps = 1e-5, setting_seed = FALSE, seed_value = 100L, ...) { user.option <- list(...) dt_Add <- is.hidden.predict.dt_Add(user.option) importance_Coef <- is.hidden.importance_Coef(user.option) if(missing(tm) && missing(x)){ stop("tm and x both missing") } if(!missing(tm) && missing(id)){ stop("id is missing") } CrossSectional <- FALSE if(missing(tm) && !missing(x) ){ if(!missing(id)){ if(!(length(sort(unique(id))) == nrow(x)) ){ stop("tm is missing") } }else { id <- 1:nrow(x) } tm <- rep(0, length(x)) CrossSectional <- TRUE } if(missing(x) && !missing(tm)){ x_miss <- TRUE All_RawX <- TRUE x <- cbind(rep(1,length(tm))) if(length(sort(unique(id))) == nrow(x) ){ CrossSectional <- TRUE } }else { x_miss <- FALSE } Time_Varying <- Object$Time_Varying if(!missing(tm) && Time_Varying == FALSE && CrossSectional == FALSE){ if(x_miss){ x <- tm }else { x <- x #cbind(x,tm) } } if (any(is.na(id))) { stop("missing values encountered in id: remove observations with missing values") } if (!missing(y)) { if ( any(is.na(y)) ) { #stop("missing values encountered in y: remove observations with missing values") } testFlag <- TRUE y_Names <- colnames(y) } else{ testFlag <- FALSE L <- Object$Grow_Object$Dimensions$L y <- matrix(0, nrow = nrow(x),ncol = L) y_Names <- paste("y",1:L,sep="") } if(!is.matrix(y)){ y <- data.matrix(y) } Time_Unmatch <- Object$Grow_Object$Time_Unmatch N <- nrow(x) if(!is.null(dt_Add)){ if(!is.list(dt_Add)){ stop("dt_Add must be a list") } K_Add <- length(dt_Add) nullObj <- lapply(1:K_Add,function(kk){ nc_K_Add <- ncol(dt_Add[[kk]]) if(nc_K_Add != 3){ stop("Each element of dt_Add must be a dataset with 3 columns arrange in order of id, time, x") } NULL }) Ord_id_tm <- Order_Time(ID = id,Time = tm) id <- id[Ord_id_tm] tm <- tm[Ord_id_tm] x <- x[Ord_id_tm,,drop = FALSE] y <- y[Ord_id_tm,,drop = FALSE] x_Add_New <- matrix(NA,nrow = N,ncol = K_Add) x_Names_Add <- rep(NA,K_Add) Time_Add_New <- matrix(NA,nrow = N,ncol = K_Add) Time_Names_Add <- rep(NA,K_Add) for(kk in 1:K_Add){ Ord_id_tm_Add <- Order_Time(ID = dt_Add[[kk]][,1],Time = dt_Add[[kk]][,2]) dt_Add[[kk]] <- dt_Add[[kk]][Ord_id_tm_Add,,drop = FALSE] id_Add <- dt_Add[[kk]][,1] x_Names_Add[kk] <- names(dt_Add[[kk]][,3,drop = FALSE]) Time_Names_Add[kk] <- names(dt_Add[[kk]][,2,drop = FALSE]) if(any(is.na(id_Add))){ stop("Missing values observed for id in dt_Add") } unq_id_Add <- unique(id_Add) n_Add <- length(unq_id_Add) nullObj <- unlist(lapply(1:n_Add,function(i){ Which_id <- which(unq_id_Add[i] == id) ni <- length(Which_id) if(ni > 0){ Which_id_Add <- which(id_Add == unq_id_Add[i]) ni_Add <- length(Which_id_Add) tm_Add <- dt_Add[[kk]][Which_id_Add,2] x_Add <- dt_Add[[kk]][Which_id_Add,3] for(j in 1:ni){ for(jj in 1:ni_Add){ if((!is.na(tm_Add[jj]) && !is.na(tm[Which_id[j]]))){ if(tm_Add[jj] <= tm[Which_id[j]]){ x_Add_New[Which_id[j], kk] <<- x_Add[jj] Time_Add_New[Which_id[j], kk] <<- tm_Add[jj] } } } } } NULL })) } colnames(x_Add_New) <- x_Names_Add x <- cbind(x,x_Add_New) colnames(Time_Add_New) <- Time_Names_Add } else { Time_Add_New <- matrix(0,nrow = N,ncol = 1) colnames(Time_Add_New) <- "Time_Add" } #---------------------------------------------------------------------------------- # Date: 12/17/2020 # In the following codes, if the id is character or factor, we convert into numeric # without changing the values. #---------------------------------------------------------------------------------- if(is.character(id)){ id <- as.numeric(id) } if(is.factor(id)){ id <- as.numeric(levels(id))[id] } #---------------------------------------------------------------------------------- # Date: 12/17/2020 # while working on BoostMLR manuscript, I realized that the function Order_Time # works only when Dt_Add is non-null. We need this in every situation so that # I can plot beta coefficient as a function of time. This is done in the following # codes. Note that I have modified the Order_Time function in the utilities file. #---------------------------------------------------------------------------------- sort_id <- is.hidden.sort_id(user.option) if(sort_id){ unq_id <- sort_unique_C_NA(id) } else { unq_id <- unique_C_NA(id) } Ord_id_tm <- Order_Time(ID = id,Time = tm,unq_id = unq_id) id <- id[Ord_id_tm] tm <- tm[Ord_id_tm] x <- x[Ord_id_tm,,drop = FALSE] y <- y[Ord_id_tm,,drop = FALSE] if(!is.matrix(x)){ x <- data.matrix(x) } x_Names <- colnames(x) K <- ncol(x) if(is.null(x_Names)){ x_Names <- paste("x",1:K,sep="") } if(!identical(x_Names , Object$x_Names) ){ stop("Covariate from grow and predict function are not matching") } if(missing(M)){ M <- Object$Grow_Object$Regulate$M } L <- ncol(y) if(is.null(y_Names)){ y_Names <- paste("y",1:L,sep="") } H <- Object$Grow_Object$Dimensions$H Dk <- Object$Grow_Object$Dimensions$Dk x_Mean <- Object$Grow_Object$Data$x_Mean x_Std_Error <- Object$Grow_Object$Data$x_Std_Error y_Mean <- Object$Grow_Object$Data$y_Mean y_Std_Error <- Object$Grow_Object$Data$y_Std_Error unq_tm <- Object$Grow_Object$Index$unq_tm unq_x <- Object$Grow_Object$Index$unq_x Bt <- Object$Grow_Object$BS$Bt Bx <- Object$Grow_Object$BS$Bx nu <- Object$Grow_Object$Regulate$nu Beta <- Object$Grow_Object$Beta_Estimate$Beta Beta_Hat_List <- Object$Grow_Object$Beta_Estimate$Beta_Hat_List UseRaw <- Object$UseRaw vimpFlag <- (importance == TRUE && testFlag == TRUE) vimpFlag_Coef <- (importance_Coef == TRUE && testFlag == TRUE) obj_C <- predict_BoostMLR_C(x, tm, id, y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, K, L, H, Dk, unq_id, unq_tm, unq_x, Bt, Bx, UseRaw, Time_Add_New, Time_Unmatch, Beta, Beta_Hat_List, testFlag, M, nu, Time_Varying, vimpFlag, vimpFlag_Coef, eps, setting_seed, seed_value) Error_Rate <- obj_C$Error_Rate colnames(Error_Rate) <- y_Names vimp <- obj_C$vimp vimp_Coef <- obj_C$vimp_Coef if(vimpFlag){ names(vimp) <- y_Names for(l in 1:L){ rownames(vimp[[l]]) <- x_Names if(H == 1){ vimp[[l]] <- vimp[[l]][,1,drop = FALSE] } if(H == 1){ colnames(vimp[[l]]) <- "Main_Eff" } else { colnames(vimp[[l]]) <- c("Main_Eff",paste("Int_Eff.",1:H,sep="")) } } } if(vimpFlag_Coef){ names(vimp_Coef) <- y_Names for(l in 1:L){ rownames(vimp_Coef[[l]]) <- x_Names if(H == 1){ vimp_Coef[[l]] <- vimp_Coef[[l]][,1,drop = FALSE] } if(H == 1){ colnames(vimp_Coef[[l]]) <- "Main_Eff" } else { colnames(vimp_Coef[[l]]) <- c("Main_Eff",paste("Int_Eff.",1:H,sep="")) } } } mu <- obj_C$Org_mu colnames(mu) <- y_Names if(testFlag) { mu_Mopt <- obj_C$Org_mu_Mopt colnames(mu_Mopt) <- y_Names } else { mu_Mopt <- NA } Pred_Object <- obj_C$Pred_Object Pred_Object$Dimensions = obj_C$Dimensions Pred_Object$Index = obj_C$Index Pred_Object$BS = obj_C$BS Pred_Object$UseRaw = UseRaw Pred_Object$Time_Varying = Time_Varying Pred_Object$Beta_Hat_List = Beta_Hat_List obj <- list(Data = obj_C$Data, x_Names = x_Names, y_Names = y_Names, mu = mu, mu_Mopt = mu_Mopt, Error_Rate = Error_Rate, Mopt = obj_C$Mopt, nu = nu, rmse = obj_C$rmse, vimp = vimp, vimp_Coef = vimp_Coef, Pred_Object = Pred_Object) class(obj) <- c("BoostMLR", "predict") invisible(obj) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/predictBoostMLR.R
simLong <- function(n = 100, ntest = 0, N = 5, rho = 0.8, model = c(1, 2), phi = 1, q_x = 0, q_y = 0, type = c("corCompSym", "corAR1", "corSymm", "iid")) { dta <- data.frame(do.call("rbind", lapply(1:(n+ntest), function(i) { Ni <- round(runif(1, 1, 3 * N)) type <- match.arg(type, c("corCompSym", "corAR1", "corSymm", "iid")) if (type == "corCompSym") { corr.mat <- matrix(rho, nrow=Ni, ncol=Ni) diag(corr.mat) <- 1 } if (type == "corAR1") { corr.mat <- diag(rep(1, Ni)) if (Ni > 1) { for (ii in 1:(Ni - 1)) { corr.mat[ii, (ii + 1):Ni] <- rho^(1:(Ni - ii)) } ind <- lower.tri(corr.mat) corr.mat[ind] <- t(corr.mat)[ind] } } if (type == "iid") { corr.mat <- diag(rep(1, Ni)) } tm <- sort(sample((1:(3 * N))/N, size = Ni, replace = TRUE)) if (model == 1) { x1 <- rnorm(Ni) x2 <- rnorm(Ni) x3 <- rnorm(Ni) x4 <- rnorm(Ni) x <- cbind(x1, x2, x3, x4) p <- ncol(x) if (q_x > 0) { xnoise <- matrix(rnorm(Ni*q_x),ncol = q_x) x <- cbind(x, xnoise) } eps1 <- sqrt(phi) * t(chol(corr.mat)) %*% rnorm(Ni) eps2 <- sqrt(phi) * t(chol(corr.mat)) %*% rnorm(Ni) eps3 <- sqrt(phi) * t(chol(corr.mat)) %*% rnorm(Ni) y1 <- 1.5 + 1.5 * x1 + 1 * x4 + eps1 y2 <- 1.5 + 1.5 * x2 + 1 * x4 + eps2 y3 <- 1.5 + 1.5 * x3 + 1 * x4 + eps3 y <- cbind(y1,y2,y3) if (q_y > 0) { ynoise <- matrix(rnorm(Ni*q_y),ncol = q_y) y <- cbind(y,ynoise) } } if (model == 2) { x1 <- rnorm(Ni) x2 <- rnorm(Ni) x3 <- rnorm(Ni) x4 <- rnorm(Ni) x <- cbind(x1, x2, x3, x4) p <- ncol(x) if (q_x > 0) { xnoise <- matrix(rnorm(Ni*q_x),ncol = q_x) x <- cbind(x, xnoise) } eps <- sqrt(phi) * t(chol(corr.mat)) %*% rnorm(Ni) b.x1 <- ifelse(tm < 1.5, 0, 1.5 * x1 ) y1 <- 1.5 + b.x1 - 0.65 * (x2^2) * (tm^2) - 2.5 * x3 - 1.5 * exp(x4) + eps y <- cbind(y1) if (q_y > 0) { ynoise <- matrix(rnorm(Ni*q_y),ncol = q_y) y <- cbind(y,ynoise) } } if (model == 3) { x1 <- sort(rnorm(Ni)) x2_Temp <- sort(runif(n = Ni,min = 0,max = 1)) x2 <- unlist(lapply(1:Ni,function(ii){ if(tm[ii] > 1 && tm[ii] < 2) -1*x2_Temp[ii] else x2_Temp[ii] })) x3 <- rnorm(1) x4 <- rnorm(1) x <- cbind(x1, x2, x3, x4) B1 <- 2 B2 <- tm^2 B3 <- exp(tm) B4 <- 1 p <- ncol(x) if (q_x > 0) { xnoise <- matrix(rnorm(Ni*q_x),ncol = q_x) x <- cbind(x, xnoise) } eps <- sqrt(phi) * t(chol(corr.mat)) %*% rnorm(Ni) y1 <- 1.5 + B1 * x1 + B2 * x2 + B3 * x3 + B4 * x4 + eps y <- cbind(y1) if (q_y > 0) { ynoise <- matrix(rnorm(Ni*q_y),ncol = q_y) y <- cbind(y,ynoise) } } cbind(x,tm, rep(i, Ni), y) }))) d_x <- q_x + 4 if(model == 1){ d_y <- q_y + 3 } if(model == 2){ d_y <- q_y + 1 } if(model == 3){ d_y <- q_y + 1 } colnames(dta) <- c(paste("x", 1:d_x, sep = ""), "time", "id", paste("y", 1:d_y, sep = "")) dtaL <- list(features = dta[, 1:d_x], time = dta$time, id = dta$id, y = dta[, -c(1:(d_x+2)) ]) trn <- c(1:sum(dta$id <= n)) return(invisible(list(dtaL = dtaL, dta = dta, trn = trn))) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/simLong.R
updateBoostMLR <- function(Object,M_Add,Verbose = TRUE,...){ n <- Object$Grow_Object$Dimensions$n K <- Object$Grow_Object$Dimensions$K L <- Object$Grow_Object$Dimensions$L H <- Object$Grow_Object$Dimensions$H Dk <- Object$Grow_Object$Dimensions$Dk ni <- Object$Grow_Object$Dimensions$ni N <- Object$Grow_Object$Dimensions$N Org_x <- Object$Grow_Object$Data$Org_x Org_y <- Object$Grow_Object$Data$Org_y id <- Object$Grow_Object$Data$id tm <- Object$Grow_Object$Data$tm x <- Object$Grow_Object$Data$x y <- Object$Grow_Object$Data$y x_Mean <- Object$Grow_Object$Data$x_Mean x_Std_Error <- Object$Grow_Object$Data$x_Std_Error y_Mean <- Object$Grow_Object$Data$y_Mean y_Std_Error <- Object$Grow_Object$Data$y_Std_Error unq_id <- Object$Grow_Object$Index$unq_id unq_tm <- Object$Grow_Object$Index$unq_tm unq_x <- Object$Grow_Object$Index$unq_x id_index <- Object$Grow_Object$Index$id_index tm_index <- Object$Grow_Object$Index$tm_index x_index <- Object$Grow_Object$Index$x_index Bt <- Object$Grow_Object$BS$Bt Bx <- Object$Grow_Object$BS$Bx Bt_H <- Object$Grow_Object$BS$Bt_H Bx_K <- Object$Grow_Object$BS$Bx_K Bxt <- Object$Grow_Object$BS$Bxt Bx_Scale <- Object$Grow_Object$BS$Bx_Scale nu <- Object$Grow_Object$Regulate$nu M <- Object$Grow_Object$Regulate$M Lambda_Ridge_Vec <- Object$Grow_Object$Regulate$Lambda_Ridge_Vec Shrink <- Object$Grow_Object$Regulate$Shrink Ridge_Penalty <- Object$Grow_Object$Regulate$Ridge_Penalty Lambda_Scale <- Object$Grow_Object$Regulate$Lambda_Scale NLambda <- Object$Grow_Object$Regulate$NLambda lower_perc <- Object$Grow_Object$Regulate$lower_perc upper_perc <- Object$Grow_Object$Regulate$upper_perc Mod_Grad <- Object$Grow_Object$Mod_Grad Error_Rate <- Object$Error_Rate Variable_Select <- (Object$Variable_Select - 1) Response_Select <- (Object$Response_Select - 1) mu_List <- Object$Grow_Object$mu_List mu <- Object$Grow_Object$mu mu_zero <- Object$Grow_Object$mu_zero Vec_zero <- Object$Grow_Object$Vec_zero UseRaw <- Object$UseRaw VarFlag <- Object$VarFlag Time_Varying <- Object$Time_Varying x_Names <- Object$x_Names y_Names <- Object$y_Names Lambda_List <- Object$Lambda_List Phi <- Object$Phi Rho <- Object$Rho phi <- Object$Grow_Object$phi rho <- Object$Grow_Object$rho Beta <- Object$Grow_Object$Beta_Estimate$Beta Beta_Hat_List <- Object$Grow_Object$Beta_Estimate$Beta_Hat_List Beta_Hat_List_Iter <- Object$Grow_Object$Beta_Estimate$Beta_Hat_List_Iter Sum_Beta_Hat_List <- Object$Grow_Object$Beta_Estimate$Sum_Beta_Hat_List lower_Beta_Hat_Noise <- Object$Grow_Object$Beta_Estimate$lower_Beta_Hat_Noise upper_Beta_Hat_Noise <- Object$Grow_Object$Beta_Estimate$upper_Beta_Hat_Noise List_Trace_Bxt_gm <- Object$Grow_Object$Beta_Estimate$List_Trace_Bxt_gm setting_seed <- Object$Grow_Object$setting_seed seed_value <- Object$Grow_Object$seed_value M_New <- M + M_Add if(M_Add < 10){ Verbose <- FALSE } obj_C <- update_BoostMLR_C(Org_x, Org_y, id, tm, x, y, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, K, L, H, Dk, ni, N, unq_id, unq_tm, unq_x, id_index, tm_index, x_index, Bt, Bx, Bt_H, Bx_K, Bxt, Bx_Scale, nu, M, M_New, UseRaw, Shrink, Ridge_Penalty, Lambda_Ridge_Vec, Lambda_Scale, NLambda, lower_perc, upper_perc, Lambda_List, mu, mu_List, mu_zero, Vec_zero, Error_Rate, Variable_Select, Response_Select, Beta_Hat_List, Sum_Beta_Hat_List, Beta, Beta_Hat_List_Iter, lower_Beta_Hat_Noise, upper_Beta_Hat_Noise, List_Trace_Bxt_gm, Mod_Grad, VarFlag, phi, rho, Phi, Rho, setting_seed, seed_value, Verbose) Tm_Beta <- lapply(1:obj_C$Dimensions$L,function(l){ Out <- matrix(unlist(lapply(1:obj_C$Dimensions$K,function(k){ if(!UseRaw[k]){ rep(NA, obj_C$Dimensions$N) }else { Reduce("+",lapply(1:obj_C$Dimensions$H,function(h){ unlist(lapply(1:obj_C$Dimensions$n,function(i){ obj_C$Beta_Estimate$Tm_Beta_C[[k]][[1]][[h]][[l]][[i]] })) })) } })),ncol = obj_C$Dimensions$K,byrow = FALSE) colnames(Out) <- x_Names Out }) #---------------------------------------------------------------------------------- # Date: 12/11/2020 # It was realized that it makes more sense to show plots of beta on the standardized # scale rather than on the original scale. Therefore, along with Tm_Beta, I # have calculated Tm_Beta_Std in the following codes. #---------------------------------------------------------------------------------- Tm_Beta_Std <- lapply(1:obj_C$Dimensions$L,function(l){ Out <- matrix(unlist(lapply(1:obj_C$Dimensions$K,function(k){ if(!UseRaw[k]){ rep(NA, obj_C$Dimensions$N) }else { Reduce("+",lapply(1:obj_C$Dimensions$H,function(h){ unlist(lapply(1:obj_C$Dimensions$n,function(i){ obj_C$Beta_Estimate$Tm_Beta_Std_C[[k]][[1]][[h]][[l]][[i]] })) })) } })),ncol = obj_C$Dimensions$K,byrow = FALSE) colnames(Out) <- x_Names Out }) if(Time_Varying == FALSE){ Tm_Beta <- lapply(1:obj_C$Dimensions$L,function(l){ Tm_Beta[[l]][1,,drop = TRUE] }) } names(Tm_Beta) <- y_Names #---------------------------------------------------------------------------------- # Date: 12/11/2020 # Added Tm_Beta_Std as a part of Beta_Estimate #---------------------------------------------------------------------------------- if(Time_Varying == FALSE){ Tm_Beta_Std <- lapply(1:obj_C$Dimensions$L,function(l){ Tm_Beta_Std[[l]][1,,drop = TRUE] }) } names(Tm_Beta_Std) <- y_Names Beta_Estimate <- obj_C$Beta_Estimate Beta_Estimate$Tm_Beta <- Tm_Beta #---------------------------------------------------------------------------------- # Date: 12/11/2020 # Added Tm_Beta_Std as a part of Beta_Estimate #---------------------------------------------------------------------------------- Beta_Estimate$Tm_Beta_Std <- Tm_Beta_Std Rho <- Phi <- matrix(NA,nrow = M_New,ncol = L) colnames(Phi) <- y_Names colnames(Rho) <- y_Names Error_Rate <- obj_C$Error_Rate colnames(Error_Rate) <- y_Names if(FALSE){ if(VarFlag){ Rho[1:M, ] <- Object$Rho Phi[1:M, ] <- Object$Phi NullObj <- lapply(1:L,function(l){ lapply( (M+1) : M_New,function(m){ Residual_Data <- data.frame(y = (obj_C$Data$Org_y[,l] - obj_C$mu_List[[m]][,l]) ,tm = obj_C$Data$tm, id = obj_C$Data$id, obj_C$Data$Org_x) gls.obj <- tryCatch({gls(y ~ ., data = Residual_Data, correlation = corCompSymm(form = ~ 1 | id))}, error = function(ex){NULL}) if (is.null(gls.obj)) { gls.obj <- tryCatch({gls(y ~ 1, data = Residual_Data, correlation = corCompSymm(form = ~ 1 | id))}, error = function(ex){NULL}) } if (!is.null(gls.obj)) { phi_Temp <- gls.obj$sigma^2 Phi[m,l] <<- ifelse(phi_Temp == 0,1,phi_Temp) rho_Temp <- as.numeric(coef(gls.obj$modelStruct$corStruc, unconstrained = FALSE)) Rho[m,l] <<- max(min(0.999, rho_Temp, na.rm = TRUE), -0.999) Result <- c(phi_Temp,rho_Temp) } NULL }) NULL }) } } x <- obj_C$Data$Org_x y <- obj_C$Data$Org_y id <- obj_C$Data$id tm <- obj_C$Data$tm M <- obj_C$Regulate$M nu <- obj_C$Regulate$nu mu <- obj_C$mu_List[[M]] if(VarFlag){ phi <- obj_C$Phi[M,] rho <- obj_C$Rho[M,] } Grow_Object <- list(Data = obj_C$Data, Dimensions = obj_C$Dimensions, Index = obj_C$Index, BS = obj_C$BS, Regulate = obj_C$Regulate, Beta_Estimate = Beta_Estimate, mu = obj_C$mu, mu_List = obj_C$mu_List, mu_zero = obj_C$mu_zero, Vec_zero = obj_C$Vec_zero, Mod_Grad = Mod_Grad, phi = phi, rho = rho, Time_Unmatch = Object$Grow_Object$Time_Unmatch, setting_seed = setting_seed, seed_value = seed_value, Time_Add_New = Object$Grow_Object$Time_Add_New) Variable_Select = (obj_C$Variable_Select + 1) Response_Select = (obj_C$Response_Select + 1) Variable_Select[Variable_Select == 0] <- NA Response_Select[Response_Select == 0] <- NA Phi <- obj_C$Phi Rho <- obj_C$Rho colnames(Phi) <- colnames(Rho) <- y_Names obj <- list(x = x, id = id, tm = tm, y = y, UseRaw = UseRaw, x_Names = x_Names, y_Names = y_Names, M = M, nu = nu, Tm_Beta = Tm_Beta, mu = mu, Error_Rate = Error_Rate, Variable_Select = Variable_Select, Response_Select = Response_Select, VarFlag = VarFlag, Time_Varying = Time_Varying, Phi = Phi, Rho = Rho, Lambda_List = obj_C$Lambda_List, Grow_Object = Grow_Object) class(obj) <- c("BoostMLR", "update") invisible(obj) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/updateBoostMLR.R
##------------------------------------------------------------------------ # Date: 12/11/2020 # This is replaced by earlier function which has only the first two arguments. # Arrange the longitudinal data in the order to time for each subject. # Also user can request to sort the ID in ascending order. ##------------------------------------------------------------------------ is.hidden.sort_id <- function (user.option) { if ( is.null(user.option$sort_id) ) { TRUE } else { user.option$sort_id } } ##------------------------------------------------------------------------ # Date: 12/11/2020 # Below we replace unique(x) and sort(unique(x)) function from R to # the following C functions. That way when we calculate unq_id in # DataProcessing_C function, the result matches. ##------------------------------------------------------------------------ Order_Time <- function(ID,Time,unq_id){ n <- length(unq_id) ID_index <- unlist(lapply(1:n,function(i){ Temp_index <- which(ID == unq_id[i]) Temp_time <- Time[Temp_index] Ord_time <- order(Temp_time) Temp_index <- Temp_index[Ord_time] Temp_index })) return(ID_index) } #-------------------------------------------------- # Plot beta coefficient on the original scale plotBeta <- function(Object, N_Row = 1, N_Column = 1, plot.it = TRUE, path_saveplot = NULL, Verbose = TRUE){ Raw_Variables <- which(Object$UseRaw == TRUE) K <- length(Raw_Variables) if(K == 0){ stop("Variables not provided for plotting") } x_Names_plot <- Object$x_Names[Raw_Variables] L <- Object$Grow_Object$Dimensions$L tm <- Object$tm Ord_tm <- order(tm) if(plot.it){ if(is.null(path_saveplot)){ path_saveplot <- tempdir() } pdf(file = paste(path_saveplot,"/","Beta_Estimate.pdf",sep=""),width = 14,height = 14) for(l in 1:L){ count <- 0 oldpar <- par("mfrow", "mar") on.exit(par(oldpar)) par(mfrow = c(N_Row,N_Column)) for(k in Raw_Variables){ count <- count + 1 plot(tm[Ord_tm], Object$Tm_Beta[[ l ]][,k,drop = TRUE][Ord_tm],type = "l",xlab = "Time",ylab = "Beta Estimate",main = x_Names_plot[count],lwd = 3) } } dev.off() if(Verbose){ cat("Plot will be saved at:",path_saveplot,sep = "") } } } #-------------------------------------------------- # Plot mu and y on the original scale plotMu <- function(Object,smooth_plot = TRUE,overall_mean = FALSE,y_range = NULL,plot.it = TRUE,path_saveplot = NULL,Verbose = TRUE){ mu <- Object$mu n <- Object$Grow_Object$Dimensions$n id_index <- Object$Grow_Object$Index$id_index y <- Object$y tm <- Object$tm L <- Object$Grow_Object$Dimensions$L y_Names <- Object$y_Names if(plot.it){ if(is.null(path_saveplot)){ path_saveplot <- tempdir() } pdf(file = paste(path_saveplot,"/","PredictedMu.pdf",sep=""),width = 14,height = 14) for(l in 1:L){ if( is.null(y_range) ){ y_range <- range( c(mu[,l,drop = TRUE], y[,l,drop = TRUE]) ) } plot(tm, y[,l,drop = TRUE],type = "n",ylim = y_range,xlab = "Time",ylab = "Predicted Y",main = y_Names[l]) if(!overall_mean){ for(i in 1:n){ tm_subject <- tm[ id_index[[i]] ] Ord_tm <- order(tm_subject) mu_subject <- mu[ id_index[[i]], l, drop = TRUE ] y_subject <- y[ id_index[[i]], l, drop = TRUE ] lines(tm_subject[Ord_tm], y_subject[Ord_tm],type = "p",lwd = 1,col = "gray") if(smooth_plot){ fit.lo <- tryCatch({loess(mu_subject ~ tm_subject,span = 0.75)}, error = function(ex){NULL}) if(!is.null(fit.lo)){ predict.lo <- tryCatch({predict(fit.lo,newdata = tm_subject)}, error = function(ex){NULL}) } if( !is.null(predict.lo) ){ lines(tm_subject[Ord_tm],predict.lo[Ord_tm],lwd = 1,col = 2,type = "l") }else { lines(tm_subject[Ord_tm], mu_subject[Ord_tm],type = "l",lwd = 1,col = 2) } }else { lines(tm_subject[Ord_tm], mu_subject[Ord_tm],type = "l",lwd = 1,col = 2) } } }else { tm_unique <- sort(unique(tm))[unique(as.integer(quantile(1: length(unique(tm)) ,probs = seq(0,0.9,length.out = 15))))] tm.q <- cut(tm,breaks = tm_unique,labels = tm_unique[-1],include.lowest = TRUE) y_Mean <- tapply(y[,l,drop = TRUE],tm.q,mean,na.rm = TRUE) mu_Mean <- tapply(mu[,l,drop = TRUE],tm.q,mean,na.rm = TRUE) tm_Mean <- as.numeric(levels(sort(unique(tm.q)))) lo.mu <- lowess(tm_Mean,mu_Mean)$y lines(tm_Mean,y_Mean,type = "p",pch = 19) lines(tm_Mean,lo.mu,type = "l",lwd = 3,col = 1) } } dev.off() if(Verbose){ cat("Plot will be saved at:",path_saveplot,sep = "") } } } is.hidden.dt_Add <- function (user.option) { if (is.null(user.option$dt_Add)) { NULL } else { user.option$dt_Add } } is.hidden.predict.dt_Add <- function (user.option) { if (is.null(user.option$dt_Add)) { NULL } else { user.option$dt_Add } } is.hidden.rho <- function (user.option) { if (is.null(user.option$rho)) { NULL } else { user.option$rho } } is.hidden.phi <- function (user.option) { if (is.null(user.option$phi)) { NULL } else { user.option$phi } } is.hidden.prob_min <- function (user.option) { if (is.null(user.option$prob_min)) { 0.1 } else { user.option$prob_min } } is.hidden.prob_max <- function (user.option) { if (is.null(user.option$prob_max)) { 0.9 } else { user.option$prob_max } } is.hidden.importance_Coef <- function (user.option) { if (is.null(user.option$importance_Coef)) { FALSE } else { TRUE } }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/utilities.R
vimp.BoostMLR <- function(Object,xvar.names = NULL,joint = FALSE,setting_seed = FALSE, seed_value = 100L){ if(sum(inherits(Object, c("BoostMLR", "predict"), TRUE) == c(1, 2)) != 2) { stop("This function only works for objects of class `(BoostMLR, predict)'") } x <- Object$Data$Org_x P <- ncol(x) x_Names <- Object$x_Names y_Names <- Object$y_Names if(is.null(xvar.names)){ vimp_set <- (1:P) - 1 x_Names <- x_Names if(joint){ x_Names <- "joint_vimp" } }else { n.x.names <- length(xvar.names) vimp_set <- (match(xvar.names,x_Names)) - 1 if(any(is.na( vimp_set ))){ stop("xvar.names do not match with variable names from original data") } if(joint){ x_Names <- "joint_vimp" }else { x_Names <- xvar.names } } if(joint) { p <- 1 } else { p <- length(vimp_set) } Org_x <- Object$Data$Org_x Org_y <- Object$Data$Org_y id <- Object$Data$id tm <- Object$Data$tm x_Mean <- Object$Data$x_Mean x_Std_Error <- Object$Data$x_Std_Error y_Mean <- Object$Data$y_Mean y_Std_Error <- Object$Data$y_Std_Error n <- Object$Pred_Object$Dimensions$n ni <- Object$Pred_Object$Dimensions$ni N <- Object$Pred_Object$Dimensions$N L <- Object$Pred_Object$Dimensions$L K <- Object$Pred_Object$Dimensions$K Dk <- Object$Pred_Object$Dimensions$Dk H <- Object$Pred_Object$Dimensions$H n_unq_tm <- Object$Pred_Object$Dimensions$n_unq_tm unq_id <- Object$Pred_Object$Index$unq_id unq_tm <- Object$Pred_Object$Index$unq_tm unq_x <- Object$Pred_Object$Index$unq_x id_index <- Object$Pred_Object$Index$id_index tm_index <- Object$Pred_Object$Index$tm_index x_index <- Object$Pred_Object$Index$x_index unq_x_New <- Object$Pred_Object$Index$unq_x_New Index_Bt <- Object$Pred_Object$Index$Index_Bt Bt <- Object$Pred_Object$BS$Bt Bxt <- Object$Pred_Object$BS$Bxt Bx_K <- Object$Pred_Object$BS$Bx_K Bt_H <- Object$Pred_Object$BS$Bt_H Bx <- Object$Pred_Object$BS$Bx UseRaw <- Object$Pred_Object$UseRaw Beta_Hat_List <- Object$Pred_Object$Beta_Hat_List Mopt <- Object$Mopt rmse <- Object$rmse nu <- Object$nu Vec_zero <- Object$Pred_Object$Vec_zero mu_zero_vec <- Object$Pred_Object$mu_zero_vec Time_Varying <- Object$Pred_Object$Time_Varying obj_C <- vimp_BoostMLR_C(Org_x, Org_y, tm, id, x_Mean, x_Std_Error, y_Mean, y_Std_Error, n, ni, N, L, K, p, H, Dk, n_unq_tm, UseRaw, id_index, tm_index, unq_x_New, Index_Bt, vimp_set, joint, Bt, Bt_H, Bx, Bxt, Bx_K, Beta_Hat_List, Mopt, nu, rmse, Time_Varying, Vec_zero, mu_zero_vec, setting_seed, seed_value) vimp <- obj_C$vimp names(vimp) <- y_Names for(l in 1:L){ rownames(vimp[[l]]) <- x_Names if(H == 1){ vimp[[l]] <- vimp[[l]][,1,drop = FALSE] } if(H == 1){ colnames(vimp[[l]]) <- "Main_Eff" } else { colnames(vimp[[l]]) <- c("Main_Eff",paste("Int_Eff.",1:H,sep="")) } } obj <- vimp invisible(obj) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/vimp.BoostMLR.R
.onAttach <- function(libname, pkgname) { BoostMLR.version <- read.dcf(file=system.file("DESCRIPTION", package=pkgname), fields="Version") packageStartupMessage(paste("\n", pkgname, BoostMLR.version, "\n", "\n", "Type BoostMLR.news() to see new features, changes, and bug fixes.", "\n", "\n")) }
/scratch/gouwar.j/cran-all/cranData/BoostMLR/R/zzz.R
#########################################BootMRMR package############################## ##############################Dependent Packages##################################### library(stats) #######################Gene selection using F-score algorithm ######################## geneslect.f <- function(x, y, s) { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } cls <- as.vector(y) ###class information### genenames <- rownames(x) g <- as.matrix(x) n <- nrow(g) ###number of genes#### M <- ncol(x) ###number of samples### idx <- which(cls==1) # indexing of positive samples idy <- which(cls==-1) # indexing of negative samples B=vector(mode="numeric", n) for(i in 1:n){ f.mes <-(((mean(g[i, idx])-mean(g[i, ]))^2)+ ((mean(g[i, idy])-mean(g[i, ]))^2))/(var(g[i, idx])+var(g[i, idy])) #####F-Score B[i] <- f.mes } ranking <- sort(-B, index.return = TRUE)$ix temp <- ranking[1:s] selectgenes <- genenames[temp] class(selectgenes) <- "Informative geneset" return(selectgenes) } ####################################################################################### # Gene selection using MRMR algorithm # ####################################################################################### Weights.mrmr <- function(x, y) { ###x is gene expression data matrix, y is vector of class labels### this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } cls <- as.numeric(y) ###class information### g <- as.matrix(x) genes <- rownames(x) n <- nrow(g) ###number of genes#### m <- ncol(x) ###number of samples### GeneRankedList <- vector(length=n) qsi <- as.vector((apply(abs(cor(t(g), method="pearson",use="p")-diag(n)), 1, sum))/(n-1)) idx <- which(cls==1) ###indexing of positive samples idy <- which(cls==-1) ###indexing of negative samples B <- vector(mode="numeric", n) for(i in 1:n){ f.mes <-(((mean(g[i, idx])-mean(g[i, ]))^2)+ ((mean(g[i, idy])-mean(g[i, ]))^2))/(var(g[i, idx])+var(g[i, idy])) #####F-Score B[i] <- f.mes } rsi <- abs(B) rankingCriteria <- rsi/qsi names(rankingCriteria) <- genes class(rankingCriteria) <- "MRMR weights" return(rankingCriteria) } ################################Gene subset selection################################## mrmr.cutoff <- function (x, y, n) { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(n < 0 & n > nrow(x)) { warning(" n must be numeric and less than total number of genes in gene space") } weights <- as.vector(Weights.mrmr (x, y)) gene.id <- sort(-weights, index.return=TRUE)$ix temp <- gene.id [1:n] genes <- rownames(x) select.gene <- genes[temp] class(select.gene) <- "Informative geneset" return (select.gene) } ####################################Ends here######################################### ###################################################################################### # Boot-MRMR technique of gene selection # ###################################################################################### ######################Gene Selection using Modified Bootstrap procedure############### weight.mbmr <- function(x, y, m, s, plot=TRUE) ### x is the gene expression data matrix, y is class vector, m is bootstrap sample size, n is number of bootstraps tob e drawn# { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(m < 0 & m > ncol(x)) { warning("m must be numeric and less than total number of samples in the input GE data") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } cls <- as.numeric(y) ### class information### genes <- rownames(x) g <- as.matrix(x) nn <- nrow(g) ### number of genes#### M <- ncol(x) ### number of samples### #if(missing(m)) #m <- trunc(0.9*M) ### Fix the size of bootstrap sample### GeneRankedList <- vector(length=nn) M1 <- matrix(0, nn, s) for (j in 1:s) { samp <- sample(M, m, replace=TRUE) ###select bootstrap sample ##### x1 <- g[, samp] y1 <- cls[samp] qsi <- as.vector((apply(abs(cor(t(x1), method="pearson",use="p")-diag(nrow(x1))), 1, sum))/(nrow(x1)-1)) idx <- which(y1==1) # indexing of positive samples idy <- which(y1==-1) # indexing of negative samples B=vector(mode="numeric", nn) for(i in 1:nrow(x1)){ f.mes <-(((mean(x1[i, idx])-mean(x1[i, ]))^2)+ ((mean(x1[i, idy])-mean(x1[i, ]))^2))/(var(x1[i, idx])+var(x1[i, idy])) #####F-Score B[i] <- f.mes } rsi <- abs(B) rankingCriteria <- rsi/qsi GeneRankedList <- sort(-rankingCriteria, index.return = TRUE)$ix rankvalue <- sort(GeneRankedList, index.return=TRUE)$ix rankscore <- (nn+1-rankvalue)/(nn) M1[,j] <- as.vector(rankscore) #print(rankscore) } rownames(M1) <- genes rankingcriteria <- as.vector(rowSums((M1), na.rm = FALSE, dims = 1)) names(rankingcriteria) <- genes if (plot==TRUE) { wgs <- as.vector(rankingcriteria) ranks <- sort(wgs, decreasing=TRUE, index.return=TRUE)$ix wgs_sort <- wgs[ranks] plot(1:length(ranks), wgs_sort, main="Gene selection plot", type="p", xlab="Genes", ylab="Weights") } class( rankingcriteria) <- "MBootMRMR weights" return(rankingcriteria) } #####################################Gene set selection using Boot-MRMR weights######## mbmr.weight.cutoff <- function (x, y, m, s, n) { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(m < 0 & m > ncol(x)) { warning("m must be numeric and less than total number of samples in the input GE data") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } if(n > nrow(x)) { stop("Number of informative genes to be selected must be less than total number of genes") } weights <- weight.mbmr(x, y, m, s, plot=FALSE) genes <- rownames(x) w1 <- as.vector(weights) gene.id <- sort(-w1, index.return=TRUE)$ix temp <- gene.id [1:n] select.gene <- genes[temp] class(select.gene) <- "Informative geneset" return (select.gene) } ####################Computation of Boot-MRMR statistical significance values########### pval.mbmr <- function(x, y, m, s, Q, plot=TRUE) { if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(m < 0 & m > ncol(x)) { warning("m must be numeric and less than total number of samples in the input GE data") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } if(Q < 0 & Q > 1) { warning("Q is the quartile value of rank scores and must be within 0 and 1") } if (missing (Q)) { Q <- 0.5 } cls <- as.numeric(y) ### class information### genes <- rownames(x) g <- as.matrix(x) n1 <- nrow(g) ### number of genes#### M <- ncol(x) ### number of samples### if(missing(m)) { m <- trunc(0.9*M) }### Fix the size of bootstrap sample### GeneRankedList <- vector(length=n1) M1 <- matrix(0, n1, s) ##if(missing(s)) for (j in 1:s) { samp <- sample(M, m, replace=TRUE) ###select bootstrap sample ##### x1 <- g[, samp] y1 <- cls[samp] qsi <- as.vector((apply(abs(cor(t(x1), method="pearson",use="p")-diag(nrow(x1))), 1, sum))/(nrow(x1)-1)) idx <- which(y1==1) # indexing of positive samples idy <- which(y1==-1) # indexing of negative samples B=vector(mode="numeric", n1) for(i in 1:nrow(x1)){ f.mes <-(((mean(x1[i, idx])-mean(x1[i, ]))^2)+ ((mean(x1[i, idy])-mean(x1[i, ]))^2))/(var(x1[i, idx])+var(x1[i, idy])) #####F-Score B[i] <- f.mes } rsi <- abs(B) rankingCriteria <- rsi/qsi GeneRankedList <- sort(-rankingCriteria, index.return = TRUE)$ix rankvalue <- sort(GeneRankedList, index.return=TRUE)$ix rankscore <- (n1+1-rankvalue)/(n1) M1[,j] <- as.vector(rankscore) } rankscore <- as.matrix(M1) # Raw scores obtained from SVM-RFE mu <- Q # value under null hypothesis #if (missing (Q)) R <- rankscore - mu # Transformed score of MRMR under H0 sam <- nrow (R) # number of genes pval.vec <- vector(mode="numeric", length=nrow(rankscore)) for (i in 1:sam) { z <- R[i,] z <- z[z != 0] n11 <- length(z) r <- rank(abs(z)) tplus <- sum(r[z > 0]) etplus <- n11 * (n11 + 1) / 4 vtplus <- n11 * (n11 + 1) * (2 * n11 + 1) / 24 p.value=pnorm(tplus, etplus, sqrt(vtplus), lower.tail=FALSE) pval.vec[i]=p.value } names( pval.vec) <- genes if (plot==TRUE) { pval <- as.vector(pval.vec) ranks <- sort(pval, decreasing=FALSE, index.return=TRUE)$ix pval_sort <- pval[ranks] plot(1:length(ranks), pval_sort, main="Gene selection plot", type="p", xlab="Genes", ylab="p-values") } class(pval.vec) <- "p value" return(pval.vec) } ######################Gene set selection using statistical significance values ######## mbmr.pval.cutoff <- function (x, y, m, s, Q, n) { if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(m < 0 & m > ncol(x)) { warning("m must be numeric and less than total number of samples in the input GE data") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } if(Q < 0 & Q > 1) { warning("Q is the quartile value of rank scores and must be within 0 and 1") } if (missing (Q)) { Q <- 0.5 } if(n > nrow(x)) { stop("Number of informative genes to be selected must be less than total number of genes") } pvalue <- pval.mbmr (x, y, m, s, Q, plot=FALSE) genes <- rownames(x) w11 <- as.vector(pvalue) gene.id <- sort(w11, index.return=TRUE)$ix temp <- gene.id [1:n] select.gene <- genes[temp] class(select.gene) <- "Informative geneset" return (select.gene) } ######################Gene Selection using Standard Bootstrap procedure############### bootmr.weight <- function(x, y, s, plot=TRUE) ### x is the gene expression data matrix, y is class vector, m is bootstrap sample size, n is number of bootstraps tob e drawn# { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } cls <- as.numeric(y) ### class information### genes <- rownames(x) g <- as.matrix(x) n1 <- nrow(g) ### number of genes#### M <- ncol(x) ### number of samples### GeneRankedList <- vector(length=n1) M1 <- matrix(0, n1, s) ##if(missing(s)) for (j in 1:s) { samp <- sample(M, M, replace=TRUE) ###select bootstrap sample ##### x1 <- g[, samp] y1 <- cls[samp] qsi <- as.vector((apply(abs(cor(t(x1), method="pearson",use="p")-diag(n1)), 1, sum))/(n1-1)) idx <- which(y1==1) # indexing of positive samples idy <- which(y1==-1) # indexing of negative samples B=vector(mode="numeric", n1) for(i in 1:nrow(x1)){ f.mes <-(((mean(x1[i, idx])-mean(x1[i, ]))^2)+ ((mean(x1[i, idy])-mean(x1[i, ]))^2))/(var(x1[i, idx])+var(x1[i, idy])) #####F-Score B[i] <- f.mes } rsi <- abs(B) rankingCriteria <- rsi/qsi GeneRankedList <- sort(-rankingCriteria, index.return = TRUE)$ix rankvalue <- sort(GeneRankedList, index.return=TRUE)$ix rankscore <- (n1+1-rankvalue)/(n1) M1[,j] <- as.vector(rankscore) } rankingcriteria <- as.vector(rowSums((M1), na.rm = FALSE, dims = 1)) names(rankingcriteria) <- genes if (plot==TRUE) { wgs <- as.vector(rankingcriteria) ranks <- sort(wgs, decreasing=TRUE, index.return=TRUE)$ix wgs_sort <- wgs[ranks] plot(1:length(ranks), wgs_sort, main="Gene selection plot", type="p", xlab="Genes", ylab="Weights") } class(rankingcriteria) <- "Boot-MRMR weights" return(rankingcriteria) } #####################################Gene set selection using Boot-MRMR weights######## bmrmr.weight.cutoff <- function (x, y, s, n) { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } if(n > nrow(x)) { stop("Number of informative genes to be selected must be less than total number of genes") } weights <- bootmr.weight(x, y, s, plot=FALSE) genes <- names(weights) w1 <- as.vector(weights) gene.id <- sort(-w1, index.return=TRUE)$ix temp <- gene.id [1:n] select.gene <- genes[temp] class(select.gene) <- "Informative geneset" return (select.gene) } ####################Computation of Boot-MRMR statistical significance values########### pval.bmrmr <- function(x, y, s, Q, plot=TRUE) { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } if(Q < 0 & Q > 1) { warning("Q is the quartile value of rank scores and must be within 0 and 1") } if (missing (Q)) { Q <- 0.5 } cls <- as.numeric(y) ### class information### genes <- rownames(x) g <- as.matrix(x) n1 <- nrow(g) ### number of genes#### M <- ncol(x) ### number of samples### GeneRankedList <- vector(length=n1) M1 <- matrix(0, n1, s) ##if(missing(s)) for (j in 1:s) { samp <- sample(M, M, replace=TRUE) ###select bootstrap sample ##### x1 <- g[, samp] y1 <- cls[samp] qsi <- as.vector((apply(abs(cor(t(x1), method="pearson",use="p")-diag(n1)), 1, sum))/(n1-1)) idx <- which(y1==1) # indexing of positive samples idy <- which(y1==-1) # indexing of negative samples B=vector(mode="numeric", n1) for(i in 1:nrow(x1)){ f.mes <-(((mean(x1[i, idx])-mean(x1[i, ]))^2)+ ((mean(x1[i, idy])-mean(x1[i, ]))^2))/(var(x1[i, idx])+var(x1[i, idy])) #####F-Score B[i] <- f.mes } rsi <- abs(B) rankingCriteria <- rsi/qsi GeneRankedList <- sort(-rankingCriteria, index.return = TRUE)$ix rankvalue <- sort(GeneRankedList, index.return=TRUE)$ix rankscore <- (n1+1-rankvalue)/(n1) M1[,j] <- as.vector(rankscore) } rankscore <- as.matrix(M1) # Raw scores obtained from SVM-RFE mu <- Q # value under null hypothesis R <- rankscore - mu # Transformed score of MRMR under H0 sam <- nrow (R) # number of genes pval.vec <- vector(mode="numeric", length=nrow(rankscore)) for (i in 1:sam) { z <- R[i,] z <- z[z != 0] n11 <- length(z) r <- rank(abs(z)) tplus <- sum(r[z > 0]) etplus <- n11 * (n11 + 1) / 4 vtplus <- n11 * (n11 + 1) * (2 * n11 + 1) / 24 p.value=pnorm(tplus, etplus, sqrt(vtplus), lower.tail=FALSE) pval.vec[i]=p.value } names( pval.vec) <- genes if (plot==TRUE) { pval <- as.vector(pval.vec) ranks <- sort(pval, decreasing=FALSE, index.return=TRUE)$ix pval_sort <- pval[ranks] plot(1:length(ranks), pval_sort, main="Gene selection plot", type="p", xlab="Genes", ylab="p-values") } class(pval.vec) <- "p values" return(pval.vec) } ######################Gene set selection using statistical significance values ######## bmrmr.pval.cutoff <- function (x, y, s, Q, n) { this.call = match.call() if ((!class(x)=="data.frame")) { warning("x must be a data frame and rows as gene names") } if ((!class(y)=="numeric")) { warning("y must be a vector of 1/-1's for two class problems") } if (!length(y)==ncol(x)) { warning("Number of samples in x must have same number of sample labels in y") } if(s < 0 & s <= 50) { warning("s must be numeric and sufficiently large") } if(Q < 0 & Q > 1) { warning("Q is the quartile value of rank scores and must be within 0 and 1") } if (missing (Q)) { Q <- 0.5 } if(n > nrow(x)) { stop("Number of informative genes to be selected must be less than total number of genes") } pvalue <- pval.bmrmr(x, y, s, Q, plot=FALSE) genes <- names(pvalue) w11 <- as.vector(pvalue) gene.id <- sort(w11, index.return=TRUE)$ix temp <- gene.id [1:n] select.gene <- genes[temp] class(select.gene) <- "Informative geneset" return (select.gene) } ########################Booot-MRMR Ends Here########################################## ##################################################################################### # Technique for Order of Preference by Similarity to Ideal Solution # ##################################################################################### topsis.meth <- function (x) { if(!class(x)=="data.frame") { warning("x must be a data frame and rows as methods and columns as criteria") } dat <- as.matrix(x) methods <- rownames(x) criteria <- colnames(x) #####Calculation of weights############## dat.sum <- apply(dat, 2, sum) dat.norm <- t(t(dat)/(dat.sum)) #####Decission matrix to Normalized mode##### dat.norm1 <- dat.norm*log(dat.norm) m <- nrow(dat) ###number of methods### n <- ncol(dat) ### number of criterias### a <- 1/log(m) dat.entr <- (-a)*apply(dat.norm1, 2, sum) dat.diver <- 1-dat.entr weights <- dat.diver/sum(dat.diver) ##########Topsis MCDM############ dat.seq <- dat^2 dat.sum <- (apply(dat.seq, 2, sum))^0.5 R.norm <- t(t(dat)/(dat.sum)) V.norm <- t(t(R.norm)*weights) V.pos <- vector(mode="numeric", length=n) V.neg <- vector(mode="numeric", length=n) for (j in 1:n){ V.pos[j] <- max(V.norm[,j]) } for (j in 1:n){ V.neg[j] <- min(V.norm[,j]) } D.p <- t(t(V.norm)-V.pos) d.pos <- (apply((D.p)^2, 1, sum))^0.5 D.n <- t(t(V.norm)-V.neg) d.neg <- (apply((D.n)^2, 1, sum))^0.5 d.tot <- d.pos+d.neg C.Score <-d.neg/(d.pos+d.neg) C.rank <- rank(-C.Score) D.topsis <- cbind(d.pos, d.neg, C.Score, C.rank) colnames(D.topsis) <- c("di+", "di-", "Topsis Score", "Rank") rownames(D.topsis) <- methods class(D.topsis) <- "TOPSIS" return(D.topsis) } ###############Ends here###############################################
/scratch/gouwar.j/cran-all/cranData/BootMRMR/R/BoootMRMR.R
AR.Fore <- function(x,b,h) { n <- nrow(x) p <- length(b)-1 b1 <- b[p+1] b2 <- b[1:p] rx <- x[(n-p+1):n,1] for( i in 1:h) { f <- b1 + sum( b2 * rx[length(rx):(length(rx)-p+1)]) rx <- c(rx,f) } f <- rx[(p+1):(p+h)] return(as.matrix(f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/AR.Fore.R
AR.ForeB <- function(x,b,h,e,p1) { n <- nrow(x) p <- length(b)-1 b1 <- b[p+1] b2 <- b[1:p] rx <- x[(n-p+1):n,1] for( i in 1:h) { f <- b1 + sum( b2 * rx[length(rx):(length(rx)-p+1)]) + e[as.integer(runif(1, min=1, max=nrow(e)))] rx <- c(rx,f) } f <- rx[(p+1):(p+h)] return(f) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/AR.ForeB.R
AR.order <- function(x,pmax) { n <- nrow(x) tem <- numeric(0) for( i in 1:pmax) { e <- LSM(x,i)$resid aic <- log( sum(e^2)/n ) + (2/n) * (i+1) bic <- log( sum(e^2)/n )+ (log(n)/n) * (i+1) hq <- log(sum(e^2)/n ) + (2*log(log(n))/n) * (i+1) tem <- rbind(tem,cbind(i,aic,bic,hq)) } paic <- tem[tem[,2] == min(tem[,2]),1] pbic <- tem[tem[,3] == min(tem[,3]),1] phq <- tem[tem[,4] == min(tem[,4]),1] return(list(ARorder=cbind(paic,pbic,phq),Criteria=tem[,2:4])) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/AR.order.R
ART.Fore <- function(x,b,h) { n <- nrow(x) p <- length(b)-2 tm <- (n+1):(n+h) b1 <- b[p+1] b2 <- b[p+2] b3 <- b[1:p] rx <- x[(n-p+1):n,1] for( i in 1:h) { f <- b1 + b2*tm[i] + sum( b3 * rx[length(rx):(length(rx)-p+1)]) rx <- c(rx,f) } f <- rx[(p+1):(p+h)] return(as.matrix(f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ART.Fore.R
ART.ForeB <- function(x,b,h,e,p1) { n <- nrow(x) p <- length(b)-2 tm <- (n+1):(n+h) b1 <- b[p+1] b2 <- b[p+2] b3 <- b[1:p] rx <- x[(n-p+1):n,1] for( i in 1:h) { f <- b1 + b2*tm[i] + sum( b3 * rx[length(rx):(length(rx)-p+1)]) +e[as.integer(runif(1, min=1, max=nrow(e)))] rx <- c(rx,f) } f <- rx[(p+1):(p+h)] return(f) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ART.ForeB.R
ART.order <- function(x,pmax) { n <- nrow(x) tem <- numeric(0) for( i in 1:pmax) { e <- LSMT(x,i)$resid aic <- log( sum(e^2)/n ) + (2/n) * (i+2) bic <- log( sum(e^2)/n )+ (log(n)/n) * (i+2) hq <- log(sum(e^2)/n ) + (2*log(log(n))/n) * (i+2) tem <- rbind(tem,cbind(i,aic,bic,hq)) } paic <- tem[tem[,2] == min(tem[,2]),1] pbic <- tem[tem[,3] == min(tem[,3]),1] phq <- tem[tem[,4] == min(tem[,4]),1] return(list(ARorder=cbind(paic,pbic,phq),Criteria=tem[,2:4])) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ART.order.R
ARnames <- function(p,type) {tem1 <- paste("AR",1:p,sep="") if(type=="const") tem2 <- c(tem1,"const") if(type=="const+trend") tem2 <- c(tem1,"const","trend") return(tem2) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ARnames.R
ARnames2 <- function(p,type) { if(p==1) tem1 <- "AR" if(p>1) tem1 <- c("AR",paste("phi",1:(p-1),sep="")) if(type=="const") tem2 <- c(tem1,"const") if(type=="const+trend") tem2 <- c(tem1,"const","trend") return(tem2) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ARnames2.R
ARorder <- function(x,pmax,type) { x<-as.matrix(x) if (type=="const") M <- AR.order(x,pmax) if (type=="const+trend") M <- ART.order(x,pmax) rownames(M$Criteria) <- paste("",1:pmax,sep="") rownames(M$ARorder) <- "p*"; colnames(M$ARorder) <- c("aic","bic","hq") return(list(ARorder=M$ARorder,Criteria=M$Criteria)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ARorder.R
Andrews.Chen <- function(x,p,h,type) { x<-as.matrix(x) if (type=="const") M <- Andrews.Chen1(x,p,h) if (type=="const+trend") M <- Andrews.Chen2(x,p,h) rownames(M$coef) <- ARnames(p,type); colnames(M$coef) <- "coefficients" rownames(M$ecmcoef) <- ARnames2(p,type); colnames(M$coef) <- "coefficients" colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(coef=M$coef,ecm.coef=M$ecmcoef,resid=M$resid,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Andrews.Chen.R
Andrews.Chen1 <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- LSE(x,p)$coef alphau <- alpha.u0(b,p,n) if(p == 1 & alphau == 1) newb <- rbind(1,0) else newb <- rbind(alphau,estmf0(x,p,alphau)) tem1 <- newb[1] tem <- newb; tem[1,1] <- b[1,1] { if(p == 1 | alphau == 1) newb2 <- newb else { for( i in 1:10) { alphau <- alpha.u0(tem,p,n) newb2 <- rbind(alphau,estmf0(x,p,alphau)) tem2 <- newb2[1] { if (abs(tem1-tem2) < 0.01) break else tem1 <- tem2; tem <- newb2; tem[1,1] <- b[1]} } } } b<-arlevel(newb2,p) e <- RESID(x,b) f <- {} if(h > 0) f <- AR.Fore(x,b,h) return(list(coef=b,ecmcoef=newb2,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Andrews.Chen1.R
Andrews.Chen2 <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- LSET(x,p)$coef alphau <- alpha.u(b,p,n) newb <- rbind(alphau,estmf(x,p,alphau)) tem1 <- newb[1] tem <- newb; tem[1,1] <- b[1,1] { if(p == 1 | alphau == 1) newb2 <- newb else { for( i in 1:10) { alphau <- alpha.u(tem,p,n) newb2 <- rbind(alphau,estmf(x,p,alphau)) tem2 <- newb2[1] { if (abs(tem1-tem2) < 0.01) break else tem1 <- tem2; tem <- newb2; tem[1,1] <- b[1]} } } } b<-arlevel(newb2,p) e <- RESIDT(x,b) f <- {} if(h > 0) f <- ART.Fore(x,b,h) return(list(coef=b,ecmcoef=newb2,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Andrews.Chen2.R
Boot.PI <- function(x,p,h,nboot,prob) { set.seed(12345) n <- nrow(x) B <- OLS.AR(x,p,h,prob) bb <- LSMB(x,p)$coef eb <- sqrt( (n-p) / ( (n-p)-length(bb)))*LSMB(x,p)$resid ef <- sqrt( (n-p) / ( (n-p)-length(bb)))*LSM(x,p)$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysb(x, bb, es) bs <- LSM(xs,p)$coef fore[i,] <- AR.ForeB(xs,bs,h,ef,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=B$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Boot.PI.R
BootAfterBoot.PI <- function(x,p,h,nboot,prob) { set.seed(12345) n <- nrow(x) B <- OLS.AR(x,p,h,prob) BBC <- Bootstrap(x,p,h,200) BBCB <- BootstrapB(x,p,h,200) bb <- BBCB$coef eb <- sqrt( (n-p) / ( (n-p)-length(bb)))*BBCB$resid bias <- B$coef - BBC$coef ef <- sqrt( (n-p) / ( (n-p)-length(bb)))*BBC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysb(x, bb, es) bs <- LSM(xs,p)$coef bsc <- bs-bias bsc <- adjust(bs,bsc,p) if(sum(bsc) != sum(bs)) bsc[p+1] <- mean(xs)*(1-sum(bsc[1:p])) fore[i,] <- AR.ForeB(xs,bsc,h,ef,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BBC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootAfterBoot.PI.R
BootAfterBootPI <- function(x,p,h,nboot,prob,type) {x<-as.matrix(x) if (type=="const") M <- BootAfterBoot.PI(x,p,h,nboot,prob) if (type=="const+trend") M <- BootAfterBootT.PI(x,p,h,nboot,prob) colnames(M$PI) <- paste(prob*100,"%",sep="");rownames(M$PI) <- paste("h",1:h,sep="") colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(PI=M$PI,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootAfterBootPI.R
BootAfterBootT.PI <- function(x,p,h,nboot,prob) { set.seed(12345) n <- nrow(x) B <- OLS.ART(x,p,h,prob) BBC <- BootstrapT(x,p,h,200) BBCB <- BootstrapTB(x,p,h,200) bb <- BBCB$coef eb <- sqrt( (n-p) / ( (n-p)-length(bb)))*BBCB$resid bias <- B$coef - BBC$coef ef <- sqrt( (n-p) / ( (n-p)-length(bb)))*BBC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysbT(x, bb, es) bs <- LSMT(xs,p)$coef bsc <- bs-bias bsc <- adjust(bs,bsc,p) if(sum(bsc) != sum(bs)) bsc[(p+1):(p+2),] <- RE.LSMT(xs,p,bsc) fore[i,] <- ART.ForeB(xs,bsc,h,ef,length(bs)-2) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BBC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootAfterBootT.PI.R
BootBC <- function(x,p,h,nboot,type) {x<-as.matrix(x) if (type=="const") M <- Bootstrap(x,p,h,nboot) if (type=="const+trend") M <- BootstrapT(x,p,h,nboot) rownames(M$coef) <- ARnames(p,type); colnames(M$coef) <- "coefficients" colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(coef=M$coef,resid=M$resid,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootBC.R
BootPI <- function(x,p,h,nboot,prob,type) {x<-as.matrix(x) if (type=="const") M <- Boot.PI(x,p,h,nboot,prob) if (type=="const+trend") M <- BootT.PI(x,p,h,nboot,prob) colnames(M$PI) <- paste(prob*100,"%",sep="");rownames(M$PI) <- paste("h",1:h,sep="") colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(PI=M$PI,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootPI.R
BootT.PI <- function(x,p,h,nboot,prob) { set.seed(12345) n <- nrow(x) B <- OLS.ART(x,p,h,prob) bb <- LSMBT(x,p)$coef eb <- sqrt( (n-p) / ( (n-p)-length(bb)))*LSMBT(x,p)$resid ef <- sqrt( (n-p) / ( (n-p)-length(bb)))*LSMT(x,p)$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysbT(x, bb, es) bs <- LSMT(xs,p)$coef fore[i,] <- ART.ForeB(xs,bs,h,ef,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=B$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootT.PI.R
Bootstrap <- function(x,p,h,nboot) { set.seed(12345) B <- LSM(x,p) n <- nrow(x) b <- B$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*B$resid btem1 <- numeric(length(b)) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ys(x, b, es) btem1 <- btem1 + OLS.AR(xs,p,0,0)$coef/nboot } bc <- 2*b-btem1 bc <- adjust(b,bc,p) if(sum(b) != sum(bc)) bc[p+1] <- mean(x)*(1-sum(bc[1:p])) e <- RESID(x,bc) f <- {} if(h > 0) f <- AR.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Bootstrap.R
BootstrapB <- function(x,p,h,nboot) { set.seed(12345) B <- LSMB(x,p) n <- nrow(x) b <- B$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*B$resid btem1 <- numeric(length(b)) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ysb(x, b, es) btem1 <- btem1 + LSMB(xs,p)$coef/nboot } bc <- 2*b-btem1 bc <- adjust(b,bc,p) if(sum(b) != sum(bc)) bc[p+1] <- mean(x)*(1-sum(bc[1:p])) e <- RESID(x,bc) f <- {} if(h > 0) f <- AR.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootstrapB.R
BootstrapT <- function(x,p,h,nboot) { set.seed(12345) B <- LSMT(x,p) n <- nrow(x) b <- B$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*B$resid btem1 <- numeric(p+2) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ysT(x, b, es) btem1 <- btem1 + OLS.ART(xs,p,0,0)$coef/nboot } bc <- 2*b-btem1 bc <- adjust(b,bc,p) if(sum(b) != sum(bc)) bc[(p+1):(p+2),] <- RE.LSMT(x,p,bc) e <- RESIDT(x,bc) if(h > 0) f <- ART.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootstrapT.R
BootstrapTB <- function(x,p,h,nboot) { set.seed(12345) B <- LSMBT(x,p) n <- nrow(x) b <- B$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*B$resid btem1 <- numeric(length(b)) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ysbT(x, b, es) btem1 <- btem1 + LSMBT(xs,p)$coef/nboot } bc <- 2*b-btem1 bc <- adjust(b,bc,p) if(sum(b) != sum(bc)) bc[(p+1):(p+2),] <- RE.LSMTB(x,p,bc) e <- RESIDT(x,bc) if(h > 0) f <- ART.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/BootstrapTB.R
FFuller <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- fuller(x,p) e <- RESID(x,b) f <- {} if(h > 0) f <- AR.Fore(x,b,h) return(list(coef=b,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/FFuller.R
FFullerT <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- fullerT(x,p) e <- RESIDT(x,b) f <- {} if(h > 0) f <- ART.Fore(x,b,h) return(list(coef=b,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/FFullerT.R
LS.AR <- function(x,p,h,type,prob) { x<-as.matrix(x) if (type=="const") M <- OLS.AR(x,p,h,prob) if (type=="const+trend") M <- OLS.ART(x,p,h,prob) rownames(M$coef) <- ARnames(p,type); colnames(M$coef) <- "coefficients" colnames(M$PI) <- paste(prob*100,"%",sep="");rownames(M$PI) <- paste("h",1:h,sep="") colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(coef=M$coef,resid=M$resid,forecast=M$forecast,PI=M$PI)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/LS.AR.R
LSE <- function(x,p) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(NA,nrow=n-p,ncol=p+1) xmat[,1] <- x[p:(n-1),1] if(p > 1) { z <- x[2:n,1] - x[1:(n-1),1] for(i in 1:(p-1)) xmat[,i+1] <- z[(p-i):(n-1-i)] } xmat[,p+1] <- cbind(rep(1,n-p)) y <- x[(p+1):n,1] b <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y e <- y - xmat %*% b #return(list(coef=arlevel(b,p),resid=e)) return(list(coef=b,resid=e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/LSE.R
LSET <- function(x,p) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(NA,nrow=n-p,ncol=p+2) xmat[,1] <- x[p:(n-1),1] if(p > 1) { z <- x[2:n,1] - x[1:(n-1),1] for(i in 1:(p-1)) xmat[,i+1] <- z[(p-i):(n-1-i)] } xmat[,(p+1):(p+2)] <- cbind(rep(1,n-p),(p+1):n) y <- x[(p+1):n,1] b <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y e <- y - xmat %*% b #return(list(coef=arlevel(b,p),resid=e)) return(list(coef=b,resid=e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/LSET.R
LSM <- function(x,p) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(1,nrow=n-p,ncol=p+1) index <- p:(n-1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index-1 } y <- x[(p+1):n,1] b <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y e <- y - xmat %*% b return(list(coef=b,resid=e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/LSM.R
LSMB <- function(x,p) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(1,nrow=n-p,ncol=p+1) index <- 2:(n-p+1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index+1 } y <- x[1:(n-p),1] b <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y e <- y - xmat %*% b return(list(coef=b,resid=e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/LSMB.R
LSMBT <- function(x,p) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(1,nrow=n-p,ncol=p+2) xmat[,p+2] <- 1:(n-p) index <- 2:(n-p+1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index+1 } y <- x[1:(n-p),1] b <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y e <- y - xmat %*% b return(list(coef=b,resid=e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/LSMBT.R
LSMT <- function(x,p) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(1,nrow=n-p,ncol=p+2) xmat[,p+2] <- (p+1):n index <- p:(n-1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index-1 } y <- x[(p+1):n,1] b <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y e <- y - xmat %*% b return(list(coef=b,resid=e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/LSMT.R
OLS.AR <- function(x,p,h,prob) { x <- as.matrix(x) n <- nrow(x) B <- LSM(x,p) b <- B$coef e <- B$resid f <- {}; PImat <- {} if(h > 0) { f <- AR.Fore(x,b,h) s2 <- sum(e^2)/(nrow(x)-length(b)) mf <- mainf(b,h-1,p) se <- as.matrix(sqrt(s2*cumsum(mf^2))) PImat <- matrix(NA,ncol=length(prob),nrow=h) for( i in 1:length(prob)) {PImat[,i] <- f + qnorm(prob[i])*se } } return(list(coef=b,resid=e,forecast=f,PI=PImat)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/OLS.AR.R
OLS.ART <- function(x,p,h,prob) { x <- as.matrix(x) n <- nrow(x) B <- LSMT(x,p) b <- B$coef e <- B$resid f <- {}; PImat <- {} if(h > 0) { f <- ART.Fore(x,b,h) s2 <- sum(e^2)/(nrow(x)-length(b)) mf <- mainf(b,h-1,p) se <- as.matrix(sqrt(s2*cumsum(mf^2))) PImat <- matrix(NA,ncol=length(prob),nrow=h) for( i in 1:length(prob)) {PImat[,i] <- f + qnorm(prob[i])*se } } return(list(coef=b,resid=e,forecast=f,PI=PImat)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/OLS.ART.R
Plot.Fore <- function(x,fore,start,end,frequency) { x=ts(x,start,end,frequency) if(frequency==1) d2=end+1 if (frequency>1){ d2=end;d2[2]=d2[2]+1; if(d2[2] > frequency) { d2[1]=d2[1]+1; d2[2]=d2[2]-frequency} } f=ts(fore,start=d2,frequency=frequency) ts.plot(x,f,lwd=c(1,2),col=c(1,4)) title(main="Time Plot and Point Forecasts",sub="blue = point forecasts", col.sub=4) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Plot.Fore.R
Plot.PI <- function(x,fore,Interval,start,end,frequency){ x=ts(x,start,end,frequency) if(frequency==1) d2=end+1 if (frequency>1){ d2=end;d2[2]=d2[2]+1; if(d2[2] > frequency) { d2[1]=d2[1]+1; d2[2]=d2[2]-frequency} } y1=ts(fore,start=d2,frequency=frequency) y2=ts(Interval,start=d2,frequency=frequency) ts.plot(x,y1,y2,lwd=c(1,rep(2,1+ncol(Interval))),col=c(1,4,rep(2,ncol(Interval)))) title(main="Time Plot and Prediction Intervals",sub="red = prediction quantiles; blue = point forecasts", col.sub=2) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Plot.PI.R
RE.LSMT <- function(x,p,b) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(1,nrow=n-p,ncol=p+2) xmat[,p+2] <- (p+1):n index <- p:(n-1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index-1 } y <- x[(p+1):n,1] x1 <- as.matrix(xmat[,1:p]) x2 <- xmat[,(p+1):(p+2)] tem1 <- y-x1 %*% b[1:p,1] tem2 <- solve( t(x2) %*% x2) %*% t(x2) %*% tem1 return(tem2) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RE.LSMT.R
RE.LSMTB <- function(x,p,b) { x <- as.matrix(x) n <- nrow(x) xmat <- matrix(1,nrow=n-p,ncol=p+2) xmat[,p+2] <- 1:(n-p) index <- 2:(n-p+1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index+1 } y <- x[1:(n-p),1] x1 <- as.matrix(xmat[,1:p]) x2 <- xmat[,(p+1):(p+2)] tem1 <- y-x1 %*% b[1:p,1] tem2 <- solve( t(x2) %*% x2) %*% t(x2) %*% tem1 return(tem2) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RE.LSMTB.R
RESID <- function(x,b) { x <- as.matrix(x) n <- nrow(x) p <- length(b)-1 xmat <- matrix(1,nrow=n-p,ncol=p+1) index <- p:(n-1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index-1 } y <- x[(p+1):n,1] e <- y - xmat %*% b return(e-mean(e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RESID.R
RESIDT <- function(x,b) { x <- as.matrix(x) n <- nrow(x) p <- length(b)-2 xmat <- matrix(1,nrow=n-p,ncol=p+2) xmat[,p+2] <- (p+1):n index <- p:(n-1) for(i in 1:p) {xmat[,i] <- x[index,1] index <- index-1 } y <- x[(p+1):n,1] e <- y - xmat %*% b return(e-mean(e)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RESIDT.R
Roy.Fuller <- function(x,p,h,type) { x<-as.matrix(x) if (type=="const") M <- FFuller(x,p,h) if (type=="const+trend") M <- FFullerT(x,p,h) rownames(M$coef) <- ARnames(p,type); colnames(M$coef) <- "coefficients" colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(coef=M$coef,resid=M$resid,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Roy.Fuller.R
RoyFuller.PI <- function(x,p,h,nboot,prob,type,pmax) { x<-as.matrix(x) if (type=="const" & pmax==0) M <- RoyFuller1.PI(x,p,h,nboot,prob,"const") if (type=="const+trend" & pmax==0) M <- RoyFuller1T.PI(x,p,h,nboot,prob,"const+trend") if (type=="const" & pmax > 0) M <- RoyFuller2.PI(x,p,h,nboot,prob,"const",pmax) if (type=="const+trend" & pmax > 0) M <- RoyFuller2T.PI(x,p,h,nboot,prob,"const+trend",pmax) colnames(M$PI) <- paste(prob*100,"%",sep="");rownames(M$PI) <- paste("h",1:h,sep="") colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(PI=M$PI,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RoyFuller.PI.R
RoyFuller1.PI <- function(x,p,h,nboot,prob,type) { set.seed(12345) n <- nrow(x) BC <- Roy.Fuller(x,p,h,type) b <- BC$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ys(x, b, es) { if( p ==1 & b[1] == 1) bs <- rbind(1,0) if( p > 1 & sum(b[1:p]) == 1) {as <- rbind(1,estmf0(xs,p,1)) bs <- arlevel(as,p)} else bs <- Roy.Fuller(xs,p,h,type)$coef } fore[i,] <- AR.ForeB(xs,bs,h,e,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RoyFuller1.PI.R
RoyFuller1T.PI <- function(x,p,h,nboot,prob,type) { set.seed(12345) n <- nrow(x) BC <- Roy.Fuller(x,p,h,type) b <- BC$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ysT(x, b, es) { if( sum(b[1:p]) == 1) {as <- rbind(1,estmf(xs,p,1)) bs <- arlevel(as,p)} else bs <- Roy.Fuller(xs,p,h,type)$coef } fore[i,] <- ART.ForeB(xs,bs,h,e,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RoyFuller1T.PI.R
RoyFuller2.PI <- function(x,p,h,nboot,prob,type,pmax) { set.seed(12345) n <- nrow(x) BC <- Roy.Fuller(x,p,h,type) b <- BC$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ys(x, b, es) ps <- AR.order(xs,pmax)$ARorder[1] { if( ps ==1 & b[1] == 1) bs <- rbind(1,0) if( ps > 1 & sum(b[1:p]) == 1) {as <- rbind(1,estmf0(xs,ps,1)) bs <- arlevel(as,ps)} else bs <- Roy.Fuller(xs,ps,h,type)$coef } fore[i,] <- AR.ForeB(xs,bs,h,e,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RoyFuller2.PI.R
RoyFuller2T.PI <- function(x,p,h,nboot,prob,type,pmax) { set.seed(12345) n <- nrow(x) BC <- Roy.Fuller(x,p,h,type) b <- BC$coef e <- sqrt( (n-p) / ( (n-p)-length(b)))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(e))) es <- e[index,1] xs <- ysT(x, b, es) ps <- ART.order(xs,pmax)$ARorder[1] { if( sum(b[1:p]) == 1) {as <- rbind(1,estmf(xs,ps,1)) bs <- arlevel(as,ps)} else bs <- Roy.Fuller(xs,ps,h,type)$coef } fore[i,] <- ART.ForeB(xs,bs,h,e,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/RoyFuller2T.PI.R
Shaman.Stine <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- LSM(x,p)$coef bc <- c(Stine(b,n,p),b[p+1]) bc <- adjust(b,bc,p) bc[p+1] <- mean(x)*(1-sum(bc[1:p])) e <- RESID(x,bc) f <- {} if(h > 0) f <- AR.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Shaman.Stine.R
Shaman.StineB <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- LSMB(x,p)$coef bc <- c(Stine(b,n,p),b[p+1]) bc <- adjust(b,bc,p) bc[p+1] <- mean(x)*(1-sum(bc[1:p])) e <- RESID(x,bc) f <- {} if(h > 0) f <- AR.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Shaman.StineB.R
Shaman.StineBT <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- LSMBT(x,p)$coef bc <- c(StineT(b,n,p),b[p+1],b[p+2]) bc <- adjust(b,bc,p) bc[(p+1):(p+2),] <- RE.LSMTB(x,p,bc) e <- RESIDT(x,bc) f <- {} if(h > 0) f <- ART.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Shaman.StineBT.R
Shaman.StineT <- function(x,p,h) { x <- as.matrix(x) n <- nrow(x) b <- LSMT(x,p)$coef bc <- c(StineT(b,n,p),b[p+1],b[p+2]) bc <- adjust(b,bc,p) bc[(p+1):(p+2),] <- RE.LSMT(x,p,bc) e <- RESIDT(x,bc) f <- {} if(h > 0) f <- ART.Fore(x,bc,h) return(list(coef=bc,resid=e,forecast=f)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Shaman.StineT.R
ShamanStine.PI <- function(x,p,h,nboot,prob,type,pmax) { x<-as.matrix(x) if (type=="const" & pmax==0) M <- ShamanStine1.PI(x,p,h,nboot,prob) if (type=="const+trend" & pmax==0) M <- ShamanStine1T.PI(x,p,h,nboot,prob) if (type=="const" & pmax > 0) M <- ShamanStine2.PI(x,p,h,nboot,prob,pmax) if (type=="const+trend" & pmax > 0) M <- ShamanStine2T.PI(x,p,h,nboot,prob,pmax) colnames(M$PI) <- paste(prob*100,"%",sep="");rownames(M$PI) <- paste("h",1:h,sep="") colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(PI=M$PI,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ShamanStine.PI.R
ShamanStine1.PI <- function(x,p,h,nboot,prob) { set.seed(12345) n <- nrow(x) BC <- Shaman.Stine(x,p,h) BCB <- Shaman.StineB(x,p,h) bb <- BCB$coef eb <- sqrt( (n-p) / ( (n-p)-length(bb)))*BCB$resid ef <- sqrt( (n-p) / ( (n-p)-length(bb)))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysb(x, bb, es) bs <- Shaman.Stine(xs,p,h)$coef fore[i,] <- AR.ForeB(xs,bs,h,ef,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ShamanStine1.PI.R
ShamanStine1T.PI <- function(x,p,h,nboot,prob) { set.seed(12345) n <- nrow(x) BC <- Shaman.StineT(x,p,h) BCB <- Shaman.StineBT(x,p,h) bb <- BCB$coef eb <- sqrt( (n-p) / ( (n-p)-length(bb)))*BCB$resid ef <- sqrt( (n-p) / ( (n-p)-length(bb)))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysbT(x, bb, es) bs <- Shaman.StineT(xs,p,h)$coef fore[i,] <- ART.ForeB(xs,bs,h,ef,length(bs)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ShamanStine1T.PI.R
ShamanStine2.PI <- function(x,p,h,nboot,prob,pmax) { set.seed(12345) n <- nrow(x) BC <- Shaman.Stine(x,p,h) BCB <- Shaman.StineB(x,p,h) bb <- BCB$coef eb <- sqrt( (n-p) / ( (n-p)-p-1))*BCB$resid ef <- sqrt( (n-p) / ( (n-p)-p-1))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysb(x, bb, es) ps <- AR.order(xs,pmax)$ARorder[1] bs <- Shaman.Stine(xs,ps,h)$coef fore[i,] <- AR.ForeB(xs,bs,h,ef,length(bb)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ShamanStine2.PI.R
ShamanStine2T.PI <- function(x,p,h,nboot,prob,pmax) { set.seed(12345) n <- nrow(x) BC <- Shaman.StineT(x,p,h) BCB <- Shaman.StineBT(x,p,h) bb <- BCB$coef eb <- sqrt( (n-p) / ( (n-p)-p-1))*BCB$resid ef <- sqrt( (n-p) / ( (n-p)-p-1))*BC$resid fore <- matrix(NA,nrow=nboot,ncol=h) for(i in 1:nboot) { index <- as.integer(runif(n-p, min=1, max=nrow(eb))) es <- eb[index,1] xs <- ysbT(x, bb, es) ps <- ART.order(xs,pmax)$ARorder[1] bs <- Shaman.StineT(xs,ps,h)$coef fore[i,] <- ART.ForeB(xs,bs,h,ef,length(bb)-1) } Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob)) for( i in 1:h) Interval[i,] <- quantile(fore[,i],probs=prob) return(list(PI=Interval,forecast=BC$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ShamanStine2T.PI.R
Stine <- function(bb,n,p) { a <- c(1,bb[1:p]) { if (p == 1) { b <- rbind(c(0,0),c(1,3)) } else { value <- 0.5*p - as.integer(0.5*p) b1 <- matrix(0,nrow=p+1,ncol=p+1) diag(b1) <- 0:p b21 <- matrix(0,nrow=p+1,ncol=1) b22 <- matrix(0,nrow=p+1,ncol=1) b2 <- matrix(0,nrow=p+1,ncol=1) if (value == 0) { for (i in 0:(0.5*p-1)) { e <- matrix(0,nrow=p+1,ncol=1) index <- seq(i+3,length.out=(0.5*p-i),by = 2) e[index] <- matrix(1,nrow=(0.5*p-i),ncol=1) b21 <- cbind(b21,-e) b22 <- cbind(e,b22) } b2 <- cbind(b21[,2:(0.5*p+1)],b2,b22[,1:(0.5*p)]) } else { for (i in 0:(0.5*(p-1)) ) { d <- matrix(0,nrow=p+1,ncol=1) index <- seq(i+2,length.out=( 0.5*(p-1)+1-i ),by = 2) d[index] <- matrix(1,nrow=( 0.5*(p-1)+1-i ),ncol=1) b21 <- cbind(b21,-d) b22 <- cbind(d,b22) } b2 <- cbind(b21[,3:(0.5*(p-1)+2)],b2,b22[,1:(0.5*(p-1)+1)]) } b3 <- matrix(0,nrow=p+1,ncol=p+1) for (i in 1:(p+1)) { for (j in 1:(p+1)) { if (j < i & i <= p-j+2) b3[i,j] <- -1 if (p-j+2< i & i <= j) b3[i,j] <- 1 } } b <- b1+b2+b3 b[,1] <- -b[,1] } } bmat <- -b/n; bmat1 <- bmat[2:(p+1),1] bmat2 <- bmat[2:(p+1),2:(p+1)] eye <- matrix(0,nrow=p,ncol=p) diag(eye) <- rep(1,p) ahat <- solve(eye+bmat2) %*% (a[2:(p+1)]-bmat1) return(ahat) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Stine.R
Stine.Shaman <- function(x,p,h,type) { x<-as.matrix(x) if (type=="const") M <- Shaman.Stine(x,p,h) if (type=="const+trend") M <- Shaman.StineT(x,p,h) rownames(M$coef) <- ARnames(p,type); colnames(M$coef) <- "coefficients" colnames(M$forecast) <- "forecasts"; rownames(M$forecast) <- paste("h",1:h,sep="") return(list(coef=M$coef,resid=M$resid,forecast=M$forecast)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/Stine.Shaman.R
StineT <- function(bb,n,p) { a <- c(1,bb[1:p]) { if (p == 1) { b <- rbind(c(0,0),c(2,4)) } else { value <- 0.5*p - as.integer(0.5*p) b1 <- matrix(0,nrow=p+1,ncol=p+1) diag(b1) <- 0:p b21 <- matrix(0,nrow=p+1,ncol=1) b22 <- matrix(0,nrow=p+1,ncol=1) b2 <- matrix(0,nrow=p+1,ncol=1) if (value == 0) { for (i in 0:(0.5*p-1)) { e <- matrix(0,nrow=p+1,ncol=1) index <- seq(i+3,length.out=(0.5*p-i),by = 2) e[index] <- matrix(1,nrow=(0.5*p-i),ncol=1) b21 <- cbind(b21,-e) b22 <- cbind(e,b22) } b2 <- cbind(b21[,2:(0.5*p+1)],b2,b22[,1:(0.5*p)]) } else { for (i in 0:(0.5*(p-1)) ) { d <- matrix(0,nrow=p+1,ncol=1) index <- seq(i+2,length.out=( 0.5*(p-1)+1-i ),by = 2) d[index] <- matrix(1,nrow=( 0.5*(p-1)+1-i ),ncol=1) b21 <- cbind(b21,-d) b22 <- cbind(d,b22) } b2 <- cbind(b21[,3:(0.5*(p-1)+2)],b2,b22[,1:(0.5*(p-1)+1)]) } b3 <- matrix(0,nrow=p+1,ncol=p+1) for (i in 1:(p+1)) { for (j in 1:(p+1)) { if (j < i & i <= p-j+2) b3[i,j] <- -1 if (p-j+2< i & i <= j) b3[i,j] <- 1 } } b <- b1+b2+2*b3 b[,1] <- -b[,1] } } bmat <- -b/n; bmat1 <- bmat[2:(p+1),1] bmat2 <- bmat[2:(p+1),2:(p+1)] eye <- matrix(0,nrow=p,ncol=p) diag(eye) <- rep(1,p) ahat <- solve(eye+bmat2) %*% (a[2:(p+1)]-bmat1) return(ahat) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/StineT.R
adjust <- function(b,btem1,p) { bias <- b - btem1 bs1 <- b - bias delta3 <- min(Mod(polyroot(c(1,-bs1[1:p])))) if(delta3 > 1) return(bs1) delta1 <- 1 while(delta3 <= 1) { delta1 <- delta1-0.01 bias <- delta1*bias bs2 <- b - bias if (sum(as.numeric(is.infinite(bs2))) > 0) {bs2 <- bs1; break} delta3 <- min(Mod(polyroot(c(1,-bs2[1:p])))) } return(bs2) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/adjust.R
alpha.u <- function(b,p,n) { alphavec <- c(-0.99,seq(-0.9,1,0.1)) stat <- matrix(NA,nrow=length(alphavec),ncol=2) for( i in 1:length(alphavec) ) {alpha <- alphavec[i] stat[i,] <- cbind(alpha,alphas(alpha,b,p,n))} if( stat[nrow(stat),2] < b[1] ) alphau <- 1 if( stat[1,2] >= b[1]) alphau <- -1 if( stat[1,2] < b[1] & stat[nrow(stat),2] >= b[1]) { for (i in 2:length(alphavec)) {low <- stat[i-1,2]; high <- stat[i,2] if(low < b[1] & high > b[1]) stat1 <- stat[(i-1):i,] } base1 <- stat1[1,2]; base2 <- stat1[1,1] slope <- (stat1[2,1]-stat1[1,1])/(stat1[2,2]-stat1[1,2]) alphau <- (b[1] - base1)*slope+base2 } return(alphau) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/alpha.u.R
alpha.u0 <- function(b,p,n) { alphavec <- c(-0.99,seq(-0.9,1,0.1)) stat <- matrix(NA,nrow=length(alphavec),ncol=2) for( i in 1:length(alphavec) ) {alpha <- alphavec[i] stat[i,] <- cbind(alpha,alphas0(alpha,b,p,n))} if( stat[nrow(stat),2] < b[1] ) alphau <- 1 if( stat[1,2] >= b[1]) alphau <- -1 if( stat[1,2] < b[1] & stat[nrow(stat),2] >= b[1]) { for (i in 2:length(alphavec)) {low <- stat[i-1,2]; high <- stat[i,2] if(low < b[1] & high > b[1]) stat1 <- stat[(i-1):i,] } base1 <- stat1[1,2]; base2 <- stat1[1,1] slope <- (stat1[2,1]-stat1[1,1])/(stat1[2,2]-stat1[1,2]) alphau <- (b[1] - base1)*slope+base2 } return(alphau) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/alpha.u0.R
alphas <- function(alpha,b,p,n) {set.seed(12345) b[1,1] <- alpha a <- arlevel(b,p) stat <- matrix(NA,nrow=500) for(ii in 1:500) { nob <- n+50 u <- rnorm(nob) y <- matrix(0,nrow=p) for( i in (p+1):nob) {tem <- sum( a[1:p,1] * y[(i-1):(i-p),1] ) + u[i] y <- rbind(y,tem)} xs <- y[(nob-n+1):nob,1] bs <- LSET(xs,p)$coef stat[ii,1] <- bs[1] } return(median(stat)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/alphas.R
alphas0 <- function(alpha,b,p,n) {set.seed(12345) b[1,1] <- alpha a <- arlevel(b,p) stat <- matrix(NA,nrow=500) for(ii in 1:500) { nob <- n+50 u <- rnorm(nob) y <- matrix(0,nrow=p) for( i in (p+1):nob) {tem <- sum( a[1:p,1] * y[(i-1):(i-p),1] ) + u[i] y <- rbind(y,tem)} xs <- y[(nob-n+1):nob,1] bs <- LSE(xs,p)$coef stat[ii,1] <- bs[1] } return(median(stat)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/alphas0.R
arlevel <- function(b,p) { a <- numeric(0) if(p == 1) a <- b[1] else { for(i in 1:p) { if(i == 1) a <- c(a, b[1]+b[2]) else a <- c(a, -b[i]+b[i+1]) if(i == p) a[p] <- -b[i] } } a <- c(a,b[(p+1):length(b)]) return(as.matrix(a)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/arlevel.R
estmf <- function(x,p,alphau) { x <- as.matrix(x) n <- nrow(x) y <- x[(p+1):n,1]- alphau*x[p:(n-1),1] { if( alphau == 1){ xmat <- matrix(1,nrow=n-p) if(p > 1){ z<- x[2:n,1]-x[(1:n-1),1] index <- (p-1):(n-2) for(i in 1:(p-1)){ xmat <- cbind(xmat,z[index]) index <- index -1} xmat <- cbind(xmat[,2:ncol(xmat)],xmat[,1]) } btem <- rbind( solve( t(xmat) %*% xmat) %*% t(xmat) %*% y , 0) } else{ xmat <- cbind(rep(1,(n-p)),(p+1):n) if(p > 1){ z<- x[2:n,1]-x[(1:n-1),1] index <- (p-1):(n-2) for(i in 1:(p-1)){ xmat <- cbind(xmat,z[index]) index <- index -1} xmat <- cbind(xmat[,3:ncol(xmat)],xmat[,1:2]) } btem <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y } } return(btem) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/estmf.R
estmf0 <- function(x,p,alphau) { x <- as.matrix(x) n <- nrow(x) y <- x[(p+1):n,1]- alphau*x[p:(n-1),1] { if( alphau == 1){ xmat <- numeric() if(p > 1){ z<- x[2:n,1]-x[(1:n-1),1] index <- (p-1):(n-2) for(i in 1:(p-1)){ xmat <- cbind(xmat,z[index]) index <- index -1} } btem <- rbind( solve( t(xmat) %*% xmat) %*% t(xmat) %*% y , 0) } else{ xmat <- matrix(1,nrow=n-p) if(p > 1){ z<- x[2:n,1]-x[(1:n-1),1] index <- (p-1):(n-2) for(i in 1:(p-1)){ xmat <- cbind(xmat,z[index]) index <- index -1} xmat <- cbind(xmat[,2:ncol(xmat)],xmat[,1]) } btem <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y } } return(btem) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/estmf0.R
fuller <- function(x,p) { y <- as.matrix(x) n <- nrow(y) x <- matrix(1,nrow=n) e <- y - x %*% solve(t(x) %*% x) %*% t(x) %*% y M1 <- fuller1(e,p) tau <- M1$tau r <- 1; K <- 5; dn <- 0.1111; an <- 0.0467; bn <- 0.0477; taumed <- -1.57 k1 <- (r+1)*n/(0.5*(p+1)) k2 <- ( (1+(0.5*(p+1)/n)) * taumed*(taumed-K))^(-1)*( (r+1)-(0.5*(p+1)/n)*taumed^2) if(tau <= -sqrt(k1)) c <- 0 if(tau > -sqrt(k1) & tau <= -K) c <- 0.5*(p+1)/n*tau - (r+1)/tau if(tau > -K & tau <= taumed) c <- 0.5*(p+1)/n*tau - (r+1)*(tau+k2*(tau+K))^(-1) if(tau >= taumed) c <- -taumed + dn*(tau-taumed) b1 <- M1$coef[1,1] + c*M1$se b2 <- min(c(b1,1)) { if( p ==1 & b2 == 1) newb <- rbind(b2,0) else { newb <- rbind(b2,estmf0(y,p,b2)) newb <- arlevel(newb,p)} } return(newb) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/fuller.R
fuller1 <- function(x,p) { x <- as.matrix(x) n <- nrow(x) y <- x[(p+1):n,1] xmat <- as.matrix(x[p:(n-1),1]) if(p > 1) { z <- x[2:n,1]-x[(1:n-1),1] index1 <- (p-1):(n-2) for( i in 1:(p-1)) {xmat <- cbind(xmat,z[index1]) index1 <- index1-1} } b <- solve( t(xmat) %*% xmat) %*% t(xmat) %*% y e <- y - xmat %*% b s2 <- sum(e^2)/(n-p) cov <- solve(t(xmat) %*% xmat)*s2 se <- sqrt(cov[1,1]) tau <- (b[1,1]-1)/se return(list(coef=b,se=se,tau=tau)) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/fuller1.R
fullerT <- function(x,p) { y <- as.matrix(x) n <- nrow(y) k <-5; dn<-0.290; an<-0; bn<-0.080; taumed <- -2.18; x <- cbind(rep(1,n),1:n) e <- y - x %*% solve(t(x) %*% x) %*% t(x) %*% y ip <- as.integer( 0.5*(p+1)) sk <- (3*n-taumed^2*(ip+n))*(taumed*(k+taumed)*(ip+n))^(-1) M1 <- fuller1(e,p) tau <- M1$tau if( tau > taumed) c <- -taumed + dn*(tau-taumed) if( tau > -k & tau <= taumed) c <- ip*(tau/n) - 3/(tau+sk*(tau+k)) if( tau > -sqrt(3*n) & tau <= -k) c <- ip*(tau/n) - 3/tau if( tau <= -sqrt(3*n)) c <- 0 b1 <- M1$coef[1,1] + c*M1$se b2 <- min(c(b1,1)) newb <- rbind(b2,estmf(y,p,b2)) newb <- arlevel(newb,p) return(newb) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/fullerT.R
mainf <- function(b,h,p) { mf <- c(1, b[1], rep(0,h-1)) for(i in 2:h) { idx <- 1:min(i,p) mf[i+1] <- sum(b[idx] * rev(mf[1:i])[idx]) } return(mf) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/mainf.R
ys <- function(x,b,e) { p <- length(b)-1 n <- nrow(x) y <- x for(i in (p+1):n) y[i,1] <- b[p+1,1] + sum(b[1:p,1]*y[(i-1):(i-p),1]) + e[i-p] return(y) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ys.R
ysT <- function(x,b,e) { p <- length(b)-2 n <- nrow(x) tm <- 1:n y <- x for(i in (p+1):n) y[i,1] <- b[p+1,1] + b[p+2,1]*tm[i] + sum(b[1:p,1]*y[(i-1):(i-p),1]) + e[i-p] return(y) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ysT.R
ysb <- function(x,b,e) { p <- length(b)-1 n <- nrow(x) y <- x for(i in (n-p):1) y[i,1] <- b[p+1,1] + sum(b[1:p,1]*y[(i+1):(i+p),1]) + e[i] return(y) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ysb.R
ysbT <- function(x,b,e) { p <- length(b)-2 n <- nrow(x) tm <- 1:n y <- x for(i in (n-p):1) y[i,1] <- b[p+1,1] + b[p+2,1]*tm[i] + sum(b[1:p,1]*y[(i+1):(i+p),1]) + e[i] return(y) }
/scratch/gouwar.j/cran-all/cranData/BootPR/R/ysbT.R