content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
summary.BANOVA.Poisson <-
function(object, ...){
res <- list(anova.table = object$anova.table,
coef.table = object$coef.tables$full_table,
pvalue.table = object$pvalue.table, conv = object$conv, full_object = object, call = object$call)
class(res) <- "summary.BANOVA.Poisson"
res
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.Poisson.R |
summary.BANOVA <- function(object, ...){
if(object$model_name == "BANOVA.ordMultinomial"){
res <- list(anova.table = object$anova.table,
coef.table = rbind(object$coef.tables$full_table, object$coef.tables$cutp_table),
pvalue.table = object$pvalue.table, conv = object$conv, R2 = object$R2, full_object = object,
single_level = object$single_level, model_name = object$model_name, call = object$call)
}else{
res <- list(anova.table = object$anova.table,
coef.table = object$coef.tables$full_table,
pvalue.table = object$pvalue.table, conv = object$conv, R2 = object$R2, full_object = object,
single_level = object$single_level, model_name = object$model_name, call = object$call)
}
class(res) <- "summary.BANOVA"
res
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.R |
summary.BANOVA.T <-
function(object, ...){
res <- list(anova.table = object$anova.table,
coef.table = object$coef.tables$full_table,
pvalue.table = object$pvalue.table, conv = object$conv, full_object = object, call = object$call)
class(res) <- "summary.BANOVA.T"
res
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.T.R |
summary.BANOVA.ordMultinomial <-
function(object, ...){
res <- list(anova.table = object$anova.table,
coef.table = rbind(object$coef.tables$full_table, object$coef.tables$cutp_table),
pvalue.table = object$pvalue.table, conv = object$conv, full_object = object, call = object$call)
class(res) <- "summary.BANOVA.ordMultinomial"
res
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/summary.BANOVA.ordMultinomial.R |
table.ANCOVA <-
function(samples_l1_param,
X,
Z,
samples_l2_param,
y_val = NULL,
error = NULL, # for Poisson, bernoulli binomial and multinomial case, sigle level, need to fix here
multi = F, # multinomial
n_cat = 0,
choice = 0,
l1_error = 0, # variance of the level 1 error
num_trials = 0,
model = NULL
){
eff_digits = 3
if (length(attr(Z, 'varNames')) >= 1){
if(!is.null(error)){ #for bernoulli Poisson, binomial and multinomial case, single level
num_l1_v <- ncol(X) # should be the same with num_l1
num_l2_v <- length(attr(Z, 'varNames')) - 1# Not include intercept
num_id <- nrow(Z)
ancova_table <- data.frame(matrix(NA, nrow = num_l1_v, ncol = num_l2_v + 1 + 2)) # 1: intercept
rownames(ancova_table) <- colnames(X) #attr(X, 'varNames')
colnames(ancova_table) <- c(attr(Z, 'varNames'), 'Residuals', 'Total')
effect_table <- data.frame(matrix(NA, nrow = num_l1_v, ncol = num_l2_v + 1)) # 1: intercept
rownames(effect_table) <- colnames(X) #attr(X, 'varNames')
colnames(effect_table) <- c(attr(Z, 'varNames'))
X_assign <- attr(X, 'assign')
Z_assign <- attr(Z, 'assign')
if (multi)
Z_factor_index <- 1:(num_l2_v+1)
else
Z_factor_index <- 0:num_l2_v # include intercept here
n_f <- length(Z_factor_index)
n_sample <- nrow(samples_l2_param)
X_names <- colnames(X)
Z_names <- colnames(Z)
num_l1 <- length(X_assign)
num_l2 <- length(Z_assign)
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_sample), dimnames = list(X_names, Z_names, NULL))
for (i in 1:num_l1){
for (j in 1:n_sample)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
for (i in 1:num_l1){
# TODO: compute the error(finite-sample) for each factor
factor_SS <- array(0, dim = c(1, n_f))
factor_SS_numeric <- array(0, dim = c(1, n_f))
effect_size <- array(0, dim = c(1, n_f))
# get the new design matrix according to Z_assign and Z_factor_index
newassign <- array(0, dim = 0)
index_of_factors <- array(0, dim = 0)
for (i_z in 1:n_f){
newassign <- c(newassign, Z_assign[Z_assign == Z_factor_index[i_z]])
index_of_factors <- c(index_of_factors, which(Z_assign == Z_factor_index[i_z]))
}
newdesign_matrix <- Z[, index_of_factors]
if (length(index_of_factors) > 1){
if(!multi)
if (qr(newdesign_matrix)$rank < length(index_of_factors)) stop ('Colinearity in design matrix, model is unidentified!')
}
pred_full <- array(0 , dim = c(num_id, n_sample))
for (j in 1:n_sample){
pred_full[ , j] <- est_matrix[i, , j] %*% t(newdesign_matrix)
}
# v1.1.5
y = array(0 , dim = c(num_id, n_sample))
for (s in 1:n_sample){
y[ , s] = y_val
}
if (model == "Binomial" || model == "Bernoulli"){
pred_full = exp(pred_full) / (1 + exp(pred_full))
e = 2 * (y * log(y / pmax(num_trials * pred_full, 0.000001) + 0.000001) +
(num_trials - y) * log (pmax((num_trials - y) / pmax(num_trials - num_trials * pred_full, 0.000001), 0.000001)))
error <- pmax(e, 0)
} else if (model == "Poisson"){
pred_full = exp(pred_full)
e = 2 * (y * log(pmax(y / pmax(pred_full, 0.000001), 0.000001)) - (y - pred_full))
error <- pmax(e, 0)
}
if (model == "Multinomial" || model == "ordMultinomial")
error <- array(error, dim = c(num_id, n_sample))
var_error <- colSums(error) / num_id * (num_id - 1)
e_error <- max(mean(var_error), 0)
var_pred_full <- colSums(pred_full^2) / num_id * (num_id - 1)
pred_full_center <- scale(pred_full, scale = F)
var_pred_full_center <- colSums(pred_full_center^2) / num_id * (num_id - 1)
ancova_table[i,'Residuals'] <- format(round(e_error, digits = 4), nsmall = 4)
if (multi){
if (n_f >= (n_cat - 1) && choice > 0){
# calculate the effect of the intercept
factor_SS[choice] <- round(max(mean(var_pred_full - var_pred_full_center), 0), digits = 4)
factor_SS_numeric[choice] <- factor_SS[choice]
effect_size[choice] <- round(max(mean((var_pred_full - var_pred_full_center)/(var_pred_full - var_pred_full_center + var_error)), 0), digits = 4)
#print(format(round(quantile(y_square - y_var, c(0.05, 0.95)),digits = 4),nsmall = 2))
if (factor_SS[choice] > 0){
#factor_SS[1] <- paste(format(factor_SS[1], nsmall = 4), " (", paste(pmax(round(quantile(y_square - y_var, c(0.05, 0.95)),digits = 2), 0), collapse = ","), ")", sep = "")
factor_SS[choice] <- format(factor_SS[choice], nsmall = 4)
#effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(pmax(round(quantile((y_square - y_var)/(y_square - y_var + var_error), c(0.05, 0.95)),digits = 2), 0), collapse = ","), ")", sep = "")
effect_size[choice] <- paste(format(effect_size[choice], nsmall = 4), " (", paste(round(quantile((var_pred_full - var_pred_full_center)/(var_pred_full - var_pred_full_center + var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}else{
#factor_SS[1] <- paste(format(factor_SS[1], nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
factor_SS[choice] <- format(factor_SS[choice], nsmall = 4)
#effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
effect_size[choice] <- paste(format(effect_size[choice], nsmall = 4), " (", paste(round(quantile((var_pred_full - var_pred_full_center)/(var_pred_full - var_pred_full_center + var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}
#factor_SS[1] <- round(error, digits = 4)
#paste(round(SS_full, digits = 5), ' (', round((SS_full)/SS_TO*100, digits = 2), '%)', sep="")
}
if (n_f >= n_cat){
for (i_2 in n_cat:n_f){
factor_index_i_2 <- which(newassign == Z_factor_index[i_2])
design_matrix_i_2 <- newdesign_matrix
design_matrix_i_2[, -factor_index_i_2] <- 0
pred_i_2 <- array(0 , dim = c(num_id, n_sample))
for (j in 1:n_sample){
pred_i_2[ , j] <- est_matrix[i, , j] %*% t(design_matrix_i_2)
}
pred_i_2_center <- scale(pred_i_2, scale = F)
error_pred_i_2_center <- colSums(pred_i_2_center^2) / num_id * (num_id - 1)
var_error_i_2 <- error_pred_i_2_center + e_error
var_error_i_2_type3 <- error_pred_i_2_center
e_error_i_2 <- max(mean(var_error_i_2_type3), 0)
factor_SS_numeric[i_2] <- e_error_i_2
effect_i_2 <- max(mean(var_error_i_2_type3/var_error_i_2), 0)
if (e_error_i_2 > 0){
#factor_SS[i_2] <- paste(format(round(e_error_i_2, digits = 4), nsmall = 4), " (", paste(pmax(round(quantile(var_error_i_2_type3, c(0.05, 0.95)),digits = 2),0), collapse = ","), ")", sep = "")
factor_SS[i_2] <- format(round(e_error_i_2, digits = 4), nsmall = 4)
#effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(pmax(round(quantile(var_error_i_2_type3/var_error_i_2, c(0.05, 0.95)),digits = 2),0), collapse = ","), ")", sep = "")
effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(round(quantile(var_error_i_2_type3/var_error_i_2, c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}else{
#factor_SS[i_2] <- paste(format(round(e_error_i_2, digits = 4), nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
factor_SS[i_2] <- format(round(e_error_i_2, digits = 4), nsmall = 4)
#effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(round(quantile(var_error_i_2_type3/var_error_i_2, c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}
#paste(round(SS_full - SS_i, digits = 5), ' (',round((SS_full - SS_i)/SS_TO*100, digits = 2),'%)',sep = '')
}
}
ancova_table[i, 1:n_f] = factor_SS
ancova_table[i,'Total'] <- format(round(sum(factor_SS_numeric) + e_error, digits = 4), nsmall = 4)
effect_table[i, 1:n_f] = effect_size
}else{
if (n_f >= 1){
# calculate the effect of the intercept
factor_SS[1] <- round(max(mean(var_pred_full - var_pred_full_center), 0), digits = 4)
factor_SS_numeric[1] <- factor_SS[1]
effect_size[1] <- round(max(mean((var_pred_full - var_pred_full_center)/(var_pred_full - var_pred_full_center + var_error)), 0), digits = 4)
#print(format(round(quantile(y_square - y_var, c(0.05, 0.95)),digits = 4),nsmall = 2))
if (factor_SS[1] > 0){
#factor_SS[1] <- paste(format(factor_SS[1], nsmall = 4), " (", paste(pmax(round(quantile(y_square - y_var, c(0.05, 0.95)),digits = 2), 0), collapse = ","), ")", sep = "")
factor_SS[1] <- format(factor_SS[1], nsmall = 4)
#effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(pmax(round(quantile((y_square - y_var)/(y_square - y_var + var_error), c(0.05, 0.95)),digits = 2), 0), collapse = ","), ")", sep = "")
effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(round(quantile((var_pred_full - var_pred_full_center)/(var_pred_full - var_pred_full_center + var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}else{
#factor_SS[1] <- paste(format(factor_SS[1], nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
factor_SS[1] <- format(factor_SS[1], nsmall = 4)
#effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(round(quantile((var_pred_full - var_pred_full_center)/(var_pred_full - var_pred_full_center + var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}
#factor_SS[1] <- round(error, digits = 4)
#paste(round(SS_full, digits = 5), ' (', round((SS_full)/SS_TO*100, digits = 2), '%)', sep="")
}
if (n_f >= 2){
for (i_2 in 2:n_f){
factor_index_i_2 <- which(newassign == Z_factor_index[i_2])
design_matrix_i_2 <- newdesign_matrix
design_matrix_i_2[, -factor_index_i_2] <- 0
pred_i_2 <- array(0 , dim = c(num_id, n_sample))
for (j in 1:n_sample){
pred_i_2[ , j] <- est_matrix[i, , j] %*% t(design_matrix_i_2)
}
pred_i_2_center <- scale(pred_i_2, scale = F)
error_pred_i_2_center <- colSums(pred_i_2_center^2) / num_id * (num_id - 1)
var_error_i_2 <- error_pred_i_2_center + e_error
var_error_i_2_type3 <- error_pred_i_2_center
e_error_i_2 <- max(mean(var_error_i_2_type3), 0)
factor_SS_numeric[i_2] <- e_error_i_2
effect_i_2 <- max(mean(var_error_i_2_type3/var_error_i_2), 0)
if (e_error_i_2 > 0){
#factor_SS[i_2] <- paste(format(round(e_error_i_2, digits = 4), nsmall = 4), " (", paste(pmax(round(quantile(var_error_i_2_type3, c(0.05, 0.95)),digits = 2),0), collapse = ","), ")", sep = "")
factor_SS[i_2] <- format(round(e_error_i_2, digits = 4), nsmall = 4)
#effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(pmax(round(quantile(var_error_i_2_type3/var_error_i_2, c(0.05, 0.95)),digits = 2),0), collapse = ","), ")", sep = "")
effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(round(quantile(var_error_i_2_type3/var_error_i_2, c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}else{
#factor_SS[i_2] <- paste(format(round(e_error_i_2, digits = 4), nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
factor_SS[i_2] <- format(round(e_error_i_2, digits = 4), nsmall = 4)
#effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(round(quantile(var_error_i_2_type3/var_error_i_2, c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}
#paste(round(SS_full - SS_i, digits = 5), ' (',round((SS_full - SS_i)/SS_TO*100, digits = 2),'%)',sep = '')
}
}
ancova_table[i, 1:n_f] = factor_SS
ancova_table[i,'Total'] <- format(round(sum(factor_SS_numeric) + e_error, digits = 4), nsmall = 4)
effect_table[i, 1:n_f] = effect_size
}
}
}else{
num_l1_v <- ncol(X) # should be the same with num_l1
num_l2_v <- length(attr(Z, 'varNames')) - 1# Not include intercept
num_id <- nrow(Z)
ancova_table <- data.frame(matrix(NA, nrow = num_l1_v, ncol = num_l2_v + 1 + 2)) # 1: intercept
rownames(ancova_table) <- colnames(X) #attr(X, 'varNames')
colnames(ancova_table) <- c(attr(Z, 'varNames'), 'Residuals', 'Total')
effect_table <- data.frame(matrix(NA, nrow = num_l1_v, ncol = num_l2_v + 1)) # 1: intercept
rownames(effect_table) <- colnames(X) #attr(X, 'varNames')
colnames(effect_table) <- c(attr(Z, 'varNames'))
X_assign <- attr(X, 'assign')
Z_assign <- attr(Z, 'assign')
Z_factor_index <- 0:num_l2_v # include intercept here
n_f <- length(Z_factor_index)
n_sample <- nrow(samples_l2_param)
X_names <- colnames(X)
Z_names <- colnames(Z)
num_l1 <- length(X_assign)
num_l2 <- length(Z_assign)
est_matrix <- array(0 , dim = c(num_l1, num_l2, n_sample), dimnames = list(X_names, Z_names, NULL))
for (i in 1:num_l1){
for (j in 1:n_sample)
est_matrix[i,,j] <- samples_l2_param[j,((i-1)*num_l2+1):((i-1)*num_l2+num_l2)]
}
for (i in 1:num_l1){
if (is.null(y_val))
y <- t(as.matrix(samples_l1_param)[1:n_sample,((i-1)*num_id +1) : (i*num_id)])
else
y <- y_val
# TODO: compute the error(finite-sample) for each factor
factor_SS <- array(NA, dim = c(1, n_f))
effect_size <- array(NA, dim = c(1, n_f))
# get the new design matrix according to Z_assign and Z_factor_index
newassign <- array(0, dim = 0)
index_of_factors <- array(0, dim = 0)
for (i_z in 1:n_f){
newassign <- c(newassign, Z_assign[Z_assign == Z_factor_index[i_z]])
index_of_factors <- c(index_of_factors, which(Z_assign == Z_factor_index[i_z]))
}
newdesign_matrix <- Z[, index_of_factors]
if (length(index_of_factors) > 1)
if (qr(newdesign_matrix)$rank < length(index_of_factors)) stop ('Colinearity in level 2 design matrix, model is unidentified!')
pred_full <- array(0 , dim = c(num_id, n_sample))
for (j in 1:n_sample){
pred_full[ , j] <- est_matrix[i, , j] %*% t(newdesign_matrix)
}
l1error <- array(l1_error, dim = c(num_id, n_sample))
l1_var_error <- colSums(l1error) / num_id * (num_id - 1)
if (!is.null(y_val)){
error <- array(0 , dim = c(num_id, n_sample))
for (p_col in 1:ncol(pred_full))
error[, p_col] <- y_val - pred_full[, p_col]
}else{
error <- y - pred_full
}
error_center <- scale(error, scale = F)
y_center <- scale(y, scale = F)
var_error <- colSums(error_center^2) / num_id * (num_id - 1)
e_error <- max(mean(var_error), 0)
y_var <- colSums(y_center^2) / num_id * (num_id - 1)
e_y_var <- mean(y_var)
y_square <- colSums(y^2)
#ancova_table[i,'Residuals'] <- paste(format(round(e_error, digits = 4), nsmall = 4), " (", paste(pmax(round(quantile(var_error, c(0.05, 0.95)),digits = 2),0), collapse = ","), ")", sep = "")
#ancova_table[i,'Total'] <- paste(format(round(e_y_var, digits = 4), nsmall = 4), " (", paste(round(quantile(y_var, c(0.05, 0.95)),digits = 2), collapse = ","), ")", sep = "")
ancova_table[i,'Residuals'] <- format(round(e_error, digits = 4), nsmall = 4)
ancova_table[i,'Total'] <- format(round(mean(y_square), digits = 4), nsmall = 4)
if (n_f >= 1){
# calculate the effect of the intercept
factor_SS[1] <- round(max(mean(y_square - y_var), 0), digits = 4)
effect_size[1] <- round(max(mean((y_square - y_var)/(y_square - y_var + var_error + l1_var_error)), 0), digits = 4)
#print(format(round(quantile(y_square - y_var, c(0.05, 0.95)),digits = 4),nsmall = 2))
if (factor_SS[1] > 0){
#factor_SS[1] <- paste(format(factor_SS[1], nsmall = 4), " (", paste(pmax(round(quantile(y_square - y_var, c(0.05, 0.95)),digits = 2), 0), collapse = ","), ")", sep = "")
factor_SS[1] <- format(factor_SS[1], nsmall = 4)
#effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(pmax(round(quantile((y_square - y_var)/(y_square - y_var + var_error), c(0.05, 0.95)),digits = 2), 0), collapse = ","), ")", sep = "")
effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(round(quantile((y_square - y_var)/(y_square - y_var + var_error + l1_var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}else{
#factor_SS[1] <- paste(format(factor_SS[1], nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
factor_SS[1] <- format(factor_SS[1], nsmall = 4)
#effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
effect_size[1] <- paste(format(effect_size[1], nsmall = 4), " (", paste(round(quantile((y_square - y_var)/(y_square - y_var + var_error + l1_var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}
#factor_SS[1] <- round(error, digits = 4)
#paste(round(SS_full, digits = 5), ' (', round((SS_full)/SS_TO*100, digits = 2), '%)', sep="")
}
if (n_f >= 2){
for (i_2 in 2:n_f){
factor_index_i_2 <- which(newassign == Z_factor_index[i_2])
design_matrix_i_2 <- newdesign_matrix
design_matrix_i_2[, -factor_index_i_2] <- 0
pred_i_2 <- array(0 , dim = c(num_id, n_sample))
for (j in 1:n_sample){
pred_i_2[ , j] <- est_matrix[i, , j] %*% t(design_matrix_i_2)
}
#print(head(design_matrix_i_2))
error_i_2 <- error + pred_i_2
error_i_2_center <- scale(error_i_2, scale = F)
var_error_i_2 <- colSums(error_i_2_center^2) / num_id * (num_id - 1)
var_error_i_2_type3 <- var_error_i_2 - var_error
e_error_i_2 <- max(mean(var_error_i_2_type3), 0)
effect_i_2 <- max(mean(var_error_i_2_type3/(var_error_i_2 + l1_var_error)), 0)
if (e_error_i_2 > 0){
#factor_SS[i_2] <- paste(format(round(e_error_i_2, digits = 4), nsmall = 4), " (", paste(pmax(round(quantile(var_error_i_2_type3, c(0.05, 0.95)),digits = 2),0), collapse = ","), ")", sep = "")
factor_SS[i_2] <- format(round(e_error_i_2, digits = 4), nsmall = 4)
#effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(pmax(round(quantile(var_error_i_2_type3/var_error_i_2, c(0.05, 0.95)),digits = 2),0), collapse = ","), ")", sep = "")
effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(round(quantile(var_error_i_2_type3/(var_error_i_2 + l1_var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}else{
#factor_SS[i_2] <- paste(format(round(e_error_i_2, digits = 4), nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
factor_SS[i_2] <- format(round(e_error_i_2, digits = 4), nsmall = 4)
#effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(c(0,0), collapse = ","), ")", sep = "")
effect_size[i_2] <- paste(format(round(effect_i_2, digits = 4), nsmall = 4), " (", paste(round(quantile(var_error_i_2_type3/(var_error_i_2 + l1_var_error), c(0.025, 0.975)),digits = eff_digits), collapse = ","), ")", sep = "")
}
#paste(round(SS_full - SS_i, digits = 5), ' (',round((SS_full - SS_i)/SS_TO*100, digits = 2),'%)',sep = '')
}
}
ancova_table[i, 1:n_f] = factor_SS
effect_table[i, 1:n_f] = effect_size
}
}
#return(data.frame(ancova_table))
sol <- list(ancova_table = ancova_table, effect_table = effect_table)
class(sol) <- 'ancova.effect'
return(sol)
}else
return(NA)
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/table.ANCOVA.R |
table.ANOVA <-
function(samples_l1_param, X, Z){
if (length(attr(Z, 'varNames')) > 1){
num_l1_v <- ncol(X)
#make sure to exclude the numeric variables
numeric_index <- which(attr(Z,'dataClasses') == 'numeric' | attr(Z,'dataClasses') == 'integer')
factor_index <- which(attr(Z,'dataClasses') == 'factor')
temp_names <- attr(attr(Z,'dataClasses'), 'names')
numeric_names <- temp_names[numeric_index]
numeric_index_in_Vnames <- array(dim = 0)
if (length(numeric_index) > 0)
for(i in 1:length(numeric_index))
numeric_index_in_Vnames <- c(numeric_index_in_Vnames, which(attr(Z, 'varNames') == numeric_names[i]))
#num_l2_v <- length(attr(Z, 'varNames')) - 1 - length(numeric_index) # exclude the intercept and numeric variables
num_l2_v <- length(factor_index) + length(attr(Z,'interactions_index'))
if (num_l2_v > 0){
num_id <- nrow(Z)
anova_table <- matrix(NA, nrow = num_l1_v, ncol = num_l2_v+2)
rownames(anova_table) <- colnames(X)
#colnames(anova_table) <- c(attr(Z, 'varNames')[-c(1, numeric_index_in_Vnames)], 'Residuals', 'Total') # exclude the intercept and numerics
temp_full_names <- attr(Z, 'varNames')[-1] # exclude intercept
colnames(anova_table) <- c(temp_names[factor_index], temp_full_names[attr(Z,'interactions_index')], 'Residuals', 'Total')
assign <- attr(Z, 'assign')
Z_factor_index <- c(factor_index, attr(Z,'interactions_index'))
for (i in 1:num_l1_v){
y <- array(0, dim = c(num_id, 1))
for (j in 1:num_id)
y[j] <- mean(samples_l1_param[,(i-1)*num_id + j])
SS <- ssquares(y, Z, assign, Z_factor_index)
anova_table[i,] <- c(SS$factor_SS, SS$SSE, SS$SS_TO)
}
return(data.frame(anova_table))
}else
return(NA)
}else
return(NA)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/table.ANOVA.R |
table.coefficients <-
function (samples_l2_param, l2_parameters, X_names, Z_names, X_assign, Z_assign, samples_cutp_param = array(dim = 0)){
n_p <- length(l2_parameters)
row_names <- array(NA, dim = c(n_p,1))
row_indices <- matrix(NA, nrow = length(X_names)*length(Z_names), ncol = 2) # store indices (corresponding to level 1 and 2 variables) of each row in coefficient table, used for p-value table
for (i in 1:length(X_names))
for (j in 1:length(Z_names)){
temp <- (i - 1)*length(Z_names) + j
if (X_names[i] == " "){
row_names[temp] <- Z_names[j]
}else{
row_names[temp] <- paste(X_names[i]," : ", Z_names[j])
}
row_indices[temp, 1] <- X_assign[i]
row_indices[temp, 2] <- Z_assign[j]
}
result_table <- data.frame(matrix(NA, nrow = n_p, ncol = 1+1+2+1+1)) # the table stores statistics of coefficients
rownames(result_table) <- row_names
colnames(result_table) <- c("mean","SD","Quantile0.025","Quantile0.975","p-value","Signif.codes")
for (i in 1:n_p){
result_table[i,1] <- round(mean(samples_l2_param[,i]), digits = 4)
result_table[i,2] <- round(as.numeric(sd(samples_l2_param[,i])), digits = 4)
result_table[i,3:4] <- round(as.numeric(quantile(samples_l2_param[,i],c(0.025,0.975))), digits = 4)
}
p_values <- pValues(samples_l2_param)
#result_table <- round(result_table, digits = 4)
result_table[,5] <- round(p_values, digits = 4)
coeff_table <- result_table[, c(1,3,4,5)]
#result_table <- round(result_table, digits = 4)
result_table <- format(result_table, nsmall = 4)
for (i in 1:n_p){
if (p_values[i] <= 0.001) {
result_table[i,6] <- '***'
if (p_values[i] == 0) result_table[i,5] <- '<0.0001'
}
else if (p_values[i] <= 0.01 & p_values[i] > 0.001 ) result_table[i,6] <- '**'
else if (p_values[i] <= 0.05 & p_values[i] > 0.01 ) result_table[i,6] <- '*'
else if (p_values[i] <= 0.1 & p_values[i] > 0.05 ) result_table[i,6] <- '.'
else if (p_values[i] <= 1 & p_values[i] > 0.1 ) result_table[i,6] <- ' '
}
# for multinomial cutpoint model
if (length(samples_cutp_param) != 0){
rn_cutpresults <- array(NA,ncol(samples_cutp_param))
for (i in 1:ncol(samples_cutp_param))
rn_cutpresults[i] <- paste('Cutpoint[',i+1,']', sep="")
cutpresults <- matrix(NA,nrow = ncol(samples_cutp_param), ncol = 6)
rownames(cutpresults) <- rn_cutpresults
colnames(cutpresults) <- colnames(result_table)
for (i in 1:ncol(samples_cutp_param)){
cutpresults[i,1] <- round(mean(samples_cutp_param[,i]),4)
cutpresults[i,2] <- round(sd(samples_cutp_param[,i]),4)
cutpresults[i,3:4] <- round(quantile(samples_cutp_param[,i],c(0.025,0.975)),4)
}
}
#full_table <- as.table(result_table)
results <- list()
results$row_indices <- row_indices
results$full_table <- result_table
results$coeff_table <- data.frame(coeff_table)
if (length(samples_cutp_param) != 0)
results$cutp_table <- cutpresults
return(results) # return the coefficient table with mean and quantiles for table of means computation
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/table.coefficients.R |
table.predictions <-
function(x){
if (x$single_level){
if(x$model_name %in% c('BANOVA.Normal', 'BANOVA.T', 'BANOVA.truncNormal')){
l2_values <- attr(x$dMatrice$X, 'varValues')
l2_values[[1]] <- NULL # remove y var
l2_interactions <- attr(x$dMatrice$X, 'interactions')
if (length(l2_interactions) > 0)
for (i in 1: length(l2_interactions))
l2_interactions[[i]] <- l2_interactions[[i]] - 1
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l1_param, X_names = colnames(x$dMatrice$Z),
X_assign = attr(x$dMatrice$Z, 'assign'),
Z_names = colnames(x$dMatrice$X),
Z_assign = attr(x$dMatrice$X, 'assign'),
Z_classes = attr(x$dMatrice$X, 'dataClasses'),
l2_values = l2_values,
l2_interactions = l2_interactions,
l2_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
numeric_index_in_Z = attr(x$dMatrice$X, 'numeric_index'),
model = 'NormalNormal', contrast = x$contrast)
}else if (x$model_name == 'BANOVA.Poisson'){
l2_values <- attr(x$dMatrice$X, 'varValues')
l2_values[[1]] <- NULL # remove y var
l2_interactions <- attr(x$dMatrice$X, 'interactions')
if (length(l2_interactions) > 0)
for (i in 1: length(l2_interactions))
l2_interactions[[i]] <- l2_interactions[[i]] - 1
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l1_param, X_names = colnames(x$dMatrice$Z),
X_assign = attr(x$dMatrice$Z, 'assign'),
Z_names = colnames(x$dMatrice$X),
Z_assign = attr(x$dMatrice$X, 'assign'),
Z_classes = attr(x$dMatrice$X, 'dataClasses'),
l2_values = l2_values,
l2_interactions = l2_interactions,
l2_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
numeric_index_in_Z = attr(x$dMatrice$X, 'numeric_index'),
model = 'PoissonNormal', contrast = x$contrast)
}else if (x$model_name == 'BANOVA.Bernoulli' || x$model_name == 'BANOVA.Binomial' ){
l2_values <- attr(x$dMatrice$X, 'varValues')
l2_values[[1]] <- NULL # remove y var
l2_interactions <- attr(x$dMatrice$X, 'interactions')
if (length(l2_interactions) > 0)
for (i in 1: length(l2_interactions))
l2_interactions[[i]] <- l2_interactions[[i]] - 1
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l1_param, X_names = colnames(x$dMatrice$Z),
X_assign = attr(x$dMatrice$Z, 'assign'),
Z_names = colnames(x$dMatrice$X),
Z_assign = attr(x$dMatrice$X, 'assign'),
Z_classes = attr(x$dMatrice$X, 'dataClasses'),
l2_values = l2_values,
l2_interactions = l2_interactions,
l2_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
numeric_index_in_Z = attr(x$dMatrice$X, 'numeric_index'),
model = 'BernNormal',
n_trials = x$num_trials, contrast = x$contrast)
}else if (x$model_name == 'BANOVA.ordMultinomial'){
l2_values <- attr(x$dMatrice$X, 'varValues')
l2_values[[1]] <- NULL # remove y var
l2_interactions <- attr(x$dMatrice$X, 'interactions')
if (length(l2_interactions) > 0)
for (i in 1: length(l2_interactions))
l2_interactions[[i]] <- l2_interactions[[i]] - 1
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l1_param, X_names = colnames(x$dMatrice$Z),
X_assign = attr(x$dMatrice$Z, 'assign'),
Z_names = colnames(x$dMatrice$X),
Z_assign = attr(x$dMatrice$X, 'assign'),
Z_classes = attr(x$dMatrice$X, 'dataClasses'),
l2_values = l2_values,
l2_interactions = l2_interactions,
l2_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
numeric_index_in_Z = attr(x$dMatrice$X, 'numeric_index'),
samples_cutp_param = x$samples_cutp_param,
model = 'MultinomialordNormal', contrast = x$contrast)
}else if (x$model_name == 'BANOVA.Multinomial'){
# TODO: X_full[[1]] values must all be 1
# factors are the same across all alternatives,
# which means different levels of the same factor has the same probability estimation. cancelled in prob/sum
#
sol_tables <- NULL
# sol_tables <- multi.print.table.means (x$coef.tables$coeff_table,
# n_choice = x$n_categories,
# x$samples_l1_param,
# X_names = colnames(x$dMatrice$X_full[[1]]),
# X_assign = attr(x$dMatrice$X_full[[1]], 'assign'),
# X_classes = attr(x$dMatrice$X_full[[1]], 'dataClasses'),
# Z_names = colnames(x$dMatrice$Z),
# Z_assign = attr(x$dMatrice$Z, 'assign'),
# l1_values = attr(x$dMatrice$X_full[[1]], 'varValues'),
# l1_interactions = attr(x$dMatrice$X_full[[1]], 'interactions'),
# l1_interactions_index = attr(x$dMatrice$X_full[[1]], 'interactions_index'),
# numeric_index_in_X = attr(x$dMatrice$X_full[[1]], 'numeric_index'),
# single_level = T)
} else if (x$model_name == 'BANOVA.multiNormal'){
l2_values <- attr(x$dMatrice$X, 'varValues')
l2_values[[1]] <- NULL # remove y var
l2_interactions <- attr(x$dMatrice$X, 'interactions')
if (length(l2_interactions) > 0)
for (i in 1: length(l2_interactions))
l2_interactions[[i]] <- l2_interactions[[i]] - 1
sol_tables <- list()
for (i in 1:x$num_depenent_variables){
name <- x$names_of_dependent_variables[i]
title <- paste0("\nPredictions for ", name,"\n")
cat(title)
sol_tables[[title]] <- print.table.means(x$coef.tables.list[[i]]$coeff_table, x$samples_l1.list[[i]],
X_names = colnames(x$dMatrice$Z),
X_assign = attr(x$dMatrice$Z, 'assign'),
Z_names = colnames(x$dMatrice$X),
Z_assign = attr(x$dMatrice$X, 'assign'),
Z_classes = attr(x$dMatrice$X, 'dataClasses'),
l2_values = l2_values,
l2_interactions = l2_interactions,
l2_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
numeric_index_in_Z = attr(x$dMatrice$X, 'numeric_index'),
model = 'NormalNormal', contrast = x$contrast)
# coeff_table = x$coef.tables.list[[i]]$coeff_table
# samples_l2_param = x$samples_l1.list[[i]]
# X_names = colnames(x$dMatrice$Z)
# X_assign = attr(x$dMatrice$Z, 'assign')
# X_classes = character(0)
# Z_names = colnames(x$dMatrice$X)
# Z_assign = attr(x$dMatrice$X, 'assign')
# Z_classes = attr(x$dMatrice$X, 'dataClasses')
# l1_values = list()
# l1_interactions = list()
# l1_interactions_index = array(dim = 0)
# l2_values = l2_values
# l2_interactions = l2_interactions
# l2_interactions_index = attr(x$dMatrice$X, 'interactions_index')
# numeric_index_in_Z = attr(x$dMatrice$X, 'numeric_index')
# samples_cutp_param = NA
# model = 'NormalNormal'
# l2_sd = NULL
# n_trials = NULL
# contrast = x$contrast
}
}
}else{
if(x$model_name %in% c('BANOVA.Normal', 'BANOVA.T', 'BANOVA.truncNormal')){
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l2_param, colnames(x$dMatrice$X), X_assign = attr(x$dMatrice$X, 'assign'),
X_classes = attr(x$dMatrice$X, 'dataClasses'), colnames(x$dMatrice$Z), Z_assign = attr(x$dMatrice$Z, 'assign'),
Z_classes = attr(x$dMatrice$Z, 'dataClasses'), l1_values = attr(x$dMatrice$X, 'varValues'),
l1_interactions = attr(x$dMatrice$X, 'interactions'), l1_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
l2_values = attr(x$dMatrice$Z, 'varValues'), l2_interactions = attr(x$dMatrice$Z, 'interactions'),
l2_interactions_index = attr(x$dMatrice$Z, 'interactions_index'), numeric_index_in_X = attr(x$dMatrice$X, 'numeric_index'),
numeric_index_in_Z = attr(x$dMatrice$Z, 'numeric_index'), model = 'NormalNormal', contrast = x$contrast)
}else if (x$model_name == 'BANOVA.Poisson'){
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l2_param, colnames(x$dMatrice$X), X_assign = attr(x$dMatrice$X, 'assign'),
X_classes = attr(x$dMatrice$X, 'dataClasses'), colnames(x$dMatrice$Z), Z_assign = attr(x$dMatrice$Z, 'assign'),
Z_classes = attr(x$dMatrice$Z, 'dataClasses'), l1_values = attr(x$dMatrice$X, 'varValues'),
l1_interactions = attr(x$dMatrice$X, 'interactions'), l1_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
l2_values = attr(x$dMatrice$Z, 'varValues'), l2_interactions = attr(x$dMatrice$Z, 'interactions'),
l2_interactions_index = attr(x$dMatrice$Z, 'interactions_index'), numeric_index_in_X = attr(x$dMatrice$X, 'numeric_index'),
numeric_index_in_Z = attr(x$dMatrice$Z, 'numeric_index'), model = 'PoissonNormal', l2_sd = x$samples_l2_sigma_param, contrast = x$contrast)
}else if (x$model_name == 'BANOVA.Bernoulli' || x$model_name == 'BANOVA.Binomial' ){
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l2_param, colnames(x$dMatrice$X), X_assign = attr(x$dMatrice$X, 'assign'),
X_classes = attr(x$dMatrice$X, 'dataClasses'), colnames(x$dMatrice$Z), Z_assign = attr(x$dMatrice$Z, 'assign'),
Z_classes = attr(x$dMatrice$Z, 'dataClasses'), l1_values = attr(x$dMatrice$X, 'varValues'),
l1_interactions = attr(x$dMatrice$X, 'interactions'), l1_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
l2_values = attr(x$dMatrice$Z, 'varValues'), l2_interactions = attr(x$dMatrice$Z, 'interactions'),
l2_interactions_index = attr(x$dMatrice$Z, 'interactions_index'), numeric_index_in_X = attr(x$dMatrice$X, 'numeric_index'),
numeric_index_in_Z = attr(x$dMatrice$Z, 'numeric_index'), model = 'BernNormal', n_trials = x$num_trials, contrast = x$contrast)
}else if (x$model_name == 'BANOVA.ordMultinomial'){
sol_tables <- print.table.means(x$coef.tables$coeff_table, x$samples_l2_param, colnames(x$dMatrice$X), X_assign = attr(x$dMatrice$X, 'assign'),
X_classes = attr(x$dMatrice$X, 'dataClasses'), colnames(x$dMatrice$Z), Z_assign = attr(x$dMatrice$Z, 'assign'),
Z_classes = attr(x$dMatrice$Z, 'dataClasses'), l1_values = attr(x$dMatrice$X, 'varValues'),
l1_interactions = attr(x$dMatrice$X, 'interactions'), l1_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
l2_values = attr(x$dMatrice$Z, 'varValues'), l2_interactions = attr(x$dMatrice$Z, 'interactions'),
l2_interactions_index = attr(x$dMatrice$Z, 'interactions_index'), numeric_index_in_X = attr(x$dMatrice$X, 'numeric_index'),
numeric_index_in_Z = attr(x$dMatrice$Z, 'numeric_index'), samples_cutp_param = x$samples_cutp_param, model = 'MultinomialordNormal', contrast = x$contrast)
}else if (x$model_name == 'BANOVA.Multinomial'){
sol_tables <- multi.print.table.means (x$coef.tables$coeff_table, n_choice = x$n_categories, x$samples_l2_param, colnames(x$dMatrice$X_full[[1]]), X_assign = attr(x$dMatrice$X_full[[1]], 'assign'),
X_classes = attr(x$dMatrice$X_full[[1]], 'dataClasses'), colnames(x$dMatrice$Z), Z_assign = attr(x$dMatrice$Z, 'assign'),
Z_classes = attr(x$dMatrice$Z, 'dataClasses'), l1_values = attr(x$dMatrice$X_full[[1]], 'varValues'),
l1_interactions = attr(x$dMatrice$X_full[[1]], 'interactions'), l1_interactions_index = attr(x$dMatrice$X_full[[1]], 'interactions_index'),
l2_values = attr(x$dMatrice$Z, 'varValues'), l2_interactions = attr(x$dMatrice$Z, 'interactions'),
l2_interactions_index = attr(x$dMatrice$Z, 'interactions_index'), numeric_index_in_X = attr(x$dMatrice$X_full[[1]], 'numeric_index'),
numeric_index_in_Z = attr(x$dMatrice$Z, 'numeric_index'), contrast = x$contrast)
} else if (x$model_name == 'BANOVA.multiNormal'){
sol_tables <- list()
for (i in 1:x$num_depenent_variables){
name <- x$names_of_dependent_variables[i]
title <- paste0("\nPredictions for ", name,"\n")
cat(title)
sol_tables[[title]] <- print.table.means(x$coef.tables.list[[i]]$coeff_table, x$samples_l2.list[[i]],
colnames(x$dMatrice$X), X_assign = attr(x$dMatrice$X, 'assign'),
X_classes = attr(x$dMatrice$X, 'dataClasses'),
colnames(x$dMatrice$Z), Z_assign = attr(x$dMatrice$Z, 'assign'),
Z_classes = attr(x$dMatrice$Z, 'dataClasses'),
l1_values = attr(x$dMatrice$X, 'varValues'),
l1_interactions = attr(x$dMatrice$X, 'interactions'),
l1_interactions_index = attr(x$dMatrice$X, 'interactions_index'),
l2_values = attr(x$dMatrice$Z, 'varValues'),
l2_interactions = attr(x$dMatrice$Z, 'interactions'),
l2_interactions_index = attr(x$dMatrice$Z, 'interactions_index'),
numeric_index_in_X = attr(x$dMatrice$X, 'numeric_index'),
numeric_index_in_Z = attr(x$dMatrice$Z, 'numeric_index'),
model = 'NormalNormal', contrast = x$contrast)
}
}
}
invisible(sol_tables)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/table.predictions.R |
table.pvalue <-
function (coeff_table, row_indices, l1_names, l2_names){
if (length(l1_names) == 1 && length(l2_names) == 1) coeff_table <- data.frame(matrix(coeff_table, nrow = 1)) # the case that there is only one intercept
n_l1_p <- length(l1_names)
n_l2_p <- length(l2_names)
ptable <- data.frame(matrix(NA, nrow = n_l1_p, ncol = n_l2_p))
for (i in 1:n_l1_p)
for (j in 1:n_l2_p){
# find rows in coeff_table corresponding to each factor or interaction
rows <- which(row_indices[,1] == i & row_indices[,2] == j)
# find the min and max of the means among these rows
temp_mean <- coeff_table[rows, 1]
temp_pvalues <- coeff_table[rows, 4]
# find the p-values of corresponding variables with min and max mean
p_min <- temp_pvalues[which.min(temp_mean)]
p_max <- temp_pvalues[which.max(temp_mean)]
ptable[i, j] <- round(min(p_min, p_max), digits = 4)
if (ptable[i, j] == 0) ptable[i, j] <- '<0.0001' else ptable[i, j] <- format(as.numeric(ptable[i, j]), nsmall = 4)
}
rownames(ptable) <- l1_names
colnames(ptable) <- l2_names
return(ptable)
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/table.pvalue.R |
table.pvalues <-
function(x){
x$pvalue.table
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/table.pvalues.R |
trace.plot <-
function(x, save = FALSE){
if (class(x) %in% c('BANOVA', 'BANOVA.Binomial','BANOVA.Bernoulli',
'BANOVA.Normal', 'BANOVA.T', 'BANOVA.Multinomial','BANOVA.ordMutinomial')){
if (!x$single_level){
if (x$model_name == 'BANOVA.Multinomial')
traceplot(x$samples_l2_param, colnames(x$dMatrice$X_full[[1]]), colnames(x$dMatrice$Z), save)
else
traceplot(x$samples_l2_param, colnames(x$dMatrice$X), colnames(x$dMatrice$Z), save)
}else{
if (x$model_name == 'BANOVA.Multinomial')
traceplot(x$samples_l1_param, Z_names = colnames(x$dMatrice$X_full[[1]]), save = save)
else
traceplot(x$samples_l1_param, Z_names = colnames(x$dMatrice$X), save = save)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/trace.plot.R |
traceplot <-
function (samples_l2_param, X_names = " ", Z_names, save = FALSE){
row_names <- array(NA, dim = c(ncol(samples_l2_param),1))
for (i in 1:length(X_names))
for (j in 1:length(Z_names)){
temp <- (i - 1)*length(Z_names) + j
if (X_names[i] == " ")
row_names[temp] <- Z_names[j]
else
row_names[temp] <- paste(X_names[i]," : ", Z_names[j])
}
plot_data <- samples_l2_param
colnames(plot_data) <- row_names
if (save == TRUE){
pdf('traceplot.pdf')
plot(mcmc(plot_data))
dev.off()
}else
plot(mcmc(plot_data))
}
| /scratch/gouwar.j/cran-all/cranData/BANOVA/R/traceplot.R |
assign_contrast <- function(data, # a data frame
contrast # must be a list of matrix
){
if (!is.null(contrast)){
c_names = attr(contrast, 'names')
for (c_name in c_names){
# check the dim of each contrast
if (is.null(dim(contrast[[c_name]]))){
d = 1
}else{
d = dim(contrast[[c_name]])[2]
}
if (c_name %in% colnames(data))
contrasts(data[[c_name]], d) = contrast[[c_name]]
}
}
return(data)
}
# for table of predictions
assign_contrast_factor <- function(factor, # factor value
name, # factor name
contrast # must be a list of matrix
){
if (!is.null(contrast)){
c_names = attr(contrast, 'names')
if (name %in% c_names){
# check the dim of each contrast
if (is.null(dim(contrast[[name]]))){
d = 1
}else{
d = dim(contrast[[name]])[2]
}
contrasts(factor, d) = contrast[[name]]
}
}
return(factor)
}
# for mediation/floodlight effects using effect coding
#
#
# create idmap new_id -> old_id
idmap <- function(old_id, new_id){
# new_id is from 1,2,3,...
# old_id is any character string
res <- rep("", length(unique(new_id)))
for (i in 1:length(new_id)){
if (res[new_id[i]] == "")
res[new_id[i]] = old_id[i]
}
return(res)
} | /scratch/gouwar.j/cran-all/cranData/BANOVA/R/util.R |
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ---- message=FALSE-----------------------------------------------------------
library(BANOVA)
data(colorad)
head(colorad)
## ---- message=FALSE, eval=FALSE-----------------------------------------------
# library(rstan)
# set.seed(700)
# model <- BANOVA.model(model_name = 'Binomial')
# banova_fit <- BANOVA.build(model)
# res <- BANOVA.run(y~typic, ~color*blur, data = colorad, fit = banova_fit,
# id = 'id', num_trials = as.integer(16), iter = 1000, thin = 1, chains = 2)
## ---- message=FALSE, eval=FALSE-----------------------------------------------
# res_alt <- BANOVA.run(y~typic, ~color*blur, data = colorad, model_name = 'Binomial',
# id = 'id', num_trials = as.integer(16), iter = 1000, thin = 1, chains = 2)
## ---- message=FALSE, eval=FALSE-----------------------------------------------
# summary(res)
# #> Call:
# #> BANOVA.run(l1_formula = y ~ typic, l2_formula = ~color * blur,
# #> fit = banova_fit, data = colorad, id = 'id', iter = 1000,
# #> num_trials = as.integer(16), thin = 1, chains = 2)
# #>
# #> Convergence diagnostics:
# #> Geweke Diag. & Heidelberger and Welch's Diag.
# #> Geweke stationarity test
# #> (Intercept) : (Intercept) passed
# #> (Intercept) : color1 passed
# #> (Intercept) : blur passed
# #> (Intercept) : color1:blur passed
# #> typic1 : (Intercept) passed
# #> typic1 : color1 passed
# #> typic1 : blur passed
# #> typic1 : color1:blur passed
# #> Geweke convergence p value
# #> (Intercept) : (Intercept) 0.1409
# #> (Intercept) : color1 0.9288
# #> (Intercept) : blur 0.4537
# #> (Intercept) : color1:blur 0.9024
# #> typic1 : (Intercept) 0.9642
# #> typic1 : color1 0.9105
# #> typic1 : blur 0.1451
# #> typic1 : color1:blur 0.4603
# #> H. & W. stationarity test
# #> (Intercept) : (Intercept) passed
# #> (Intercept) : color1 passed
# #> (Intercept) : blur passed
# #> (Intercept) : color1:blur passed
# #> typic1 : (Intercept) passed
# #> typic1 : color1 passed
# #> typic1 : blur passed
# #> typic1 : color1:blur passed
# #> H. & W. convergence p value
# #> (Intercept) : (Intercept) 0.4819
# #> (Intercept) : color1 0.6041
# #> (Intercept) : blur 0.7871
# #> (Intercept) : color1:blur 0.4488
# #> typic1 : (Intercept) 0.8005
# #> typic1 : color1 0.8028
# #> typic1 : blur 0.1004
# #> typic1 : color1:blur 0.6634
# #>
# #> The Chain has converged.
# #>
# #> Table of sum of squares & effect sizes:
# #>
# #> Table of sum of squares:
# #> (Intercept) color blur color:blur Residuals Total
# #> (Intercept) 59.5532 2.3591 26.1587 9.0749 138.4249 229.8047
# #> typic1 21.9510 1.9610 5.4139 7.0553 20.1769 50.6221
# #>
# #> Table of effect sizes (95% credible interval):
# #> (Intercept) color
# #> (Intercept) 0.3014 (0.249,0.358) 0.0159 (-0.015,0.104)
# #> typic1 0.5215 (0.402,0.638) 0.0781 (-0.015,0.34)
# #> blur color:blur
# #> (Intercept) 0.1590 (0.108,0.21) 0.0581 (-0.006,0.199)
# #> typic1 0.2114 (0.088,0.362) 0.2352 (0.006,0.521)
# #>
# #> Table of p-values (Multidimensional):
# #> (Intercept) color blur color:blur
# #> (Intercept) <0.0001 0.9560 <0.0001 0.1400
# #> typic <0.0001 0.4180 <0.0001 0.0280
# #>
# #> Table of coefficients:
# #> mean SD Quantile0.025 Quantile0.975
# #> (Intercept) : (Intercept) 0.4975 0.0572 0.3881 0.6101
# #> (Intercept) : color1 -0.0069 0.1245 -0.2605 0.2413
# #> (Intercept) : blur -0.1716 0.0307 -0.2333 -0.1133
# #> (Intercept) : color1:blur 0.0410 0.0291 -0.0171 0.1001
# #> typic1 : (Intercept) 0.3011 0.0313 0.2374 0.3580
# #> typic1 : color1 -0.0596 0.0736 -0.2062 0.0781
# #> typic1 : blur -0.0767 0.0170 -0.1087 -0.0439
# #> typic1 : color1:blur 0.0384 0.0178 0.0052 0.0733
# #> p.value Signif.codes
# #> (Intercept) : (Intercept) <0.0001 ***
# #> (Intercept) : color1 0.9560
# #> (Intercept) : blur <0.0001 ***
# #> (Intercept) : color1:blur 0.1400
# #> typic1 : (Intercept) <0.0001 ***
# #> typic1 : color1 0.4180
# #> typic1 : blur <0.0001 ***
# #> typic1 : color1:blur 0.0280 *
# #> ---
# #> Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
# #>
# #> Multiple R-squared: 0.0664
# #>
# #> Table of predictions:
# #>
# #> Grand mean:
# #> 9.95
# #> 2.5% 97.5%
# #> 9.5332 10.3673
# #>
# #>
# #> typic mean 2.5% 97.5%
# #> 0 11.035 10.5818 11.4579
# #> 1 8.7829 8.2705 9.2933
# #>
# #>
# #> color mean 2.5% 97.5%
# #> 0 9.924 8.7817 10.9414
# #> 1 9.9759 9.0196 10.8926
# #>
# #>
# #> typic color mean 2.5% 97.5%
# #> 0 0 10.8042 9.4812 11.9297
# #> 0 1 11.26 10.202 12.271
# #> 1 0 8.9913 7.7188 10.2174
# #> 1 1 8.5735 7.4431 9.6343
## ---- message=FALSE, eval=FALSE-----------------------------------------------
# library(rstan)
# set.seed(900)
# res_fac <- BANOVA.run(y~typic, ~color*blurfac, data = colorad, fit = banova_fit,
# id = 'id', num_trials = as.integer(16), iter = 2000, thin = 1, chains = 2)
## ---- message=FALSE, eval=FALSE-----------------------------------------------
# summary(res_fac)
# #> Call:
# #> BANOVA.run(l1_formula = y ~ typic, l2_formula = ~color * blurfac,
# #> fit = banova_fit, data = colorad, id = 'id', iter = 2000,
# #> num_trials = as.integer(16), thin = 1, chains = 2)
# #>
# #> Convergence diagnostics:
# #> Geweke Diag. & Heidelberger and Welch's Diag.
# #> Geweke stationarity test
# #> (Intercept) : (Intercept) passed
# #> (Intercept) : color1 passed
# #> (Intercept) : blurfac1 passed
# #> (Intercept) : blurfac2 passed
# #> (Intercept) : blurfac3 passed
# #> (Intercept) : blurfac4 passed
# #> (Intercept) : color1:blurfac1 passed
# #> (Intercept) : color1:blurfac2 passed
# #> (Intercept) : color1:blurfac3 passed
# #> (Intercept) : color1:blurfac4 passed
# #> typic1 : (Intercept) passed
# #> typic1 : color1 passed
# #> typic1 : blurfac1 passed
# #> typic1 : blurfac2 passed
# #> typic1 : blurfac3 passed
# #> typic1 : blurfac4 passed
# #> typic1 : color1:blurfac1 passed
# #> typic1 : color1:blurfac2 passed
# #> typic1 : color1:blurfac3 passed
# #> typic1 : color1:blurfac4 passed
# #> Geweke convergence p value
# #> (Intercept) : (Intercept) 0.0217
# #> (Intercept) : color1 0.4861
# #> (Intercept) : blurfac1 0.7050
# #> (Intercept) : blurfac2 0.5498
# #> (Intercept) : blurfac3 0.4843
# #> (Intercept) : blurfac4 0.6209
# #> (Intercept) : color1:blurfac1 0.9840
# #> (Intercept) : color1:blurfac2 0.6900
# #> (Intercept) : color1:blurfac3 0.2931
# #> (Intercept) : color1:blurfac4 0.7919
# #> typic1 : (Intercept) 0.0159
# #> typic1 : color1 0.5622
# #> typic1 : blurfac1 0.0594
# #> typic1 : blurfac2 0.1408
# #> typic1 : blurfac3 0.0534
# #> typic1 : blurfac4 0.3087
# #> typic1 : color1:blurfac1 0.3151
# #> typic1 : color1:blurfac2 0.4267
# #> typic1 : color1:blurfac3 0.1776
# #> typic1 : color1:blurfac4 0.8341
# #> H. & W. stationarity test
# #> (Intercept) : (Intercept) passed
# #> (Intercept) : color1 passed
# #> (Intercept) : blurfac1 passed
# #> (Intercept) : blurfac2 passed
# #> (Intercept) : blurfac3 passed
# #> (Intercept) : blurfac4 passed
# #> (Intercept) : color1:blurfac1 passed
# #> (Intercept) : color1:blurfac2 passed
# #> (Intercept) : color1:blurfac3 passed
# #> (Intercept) : color1:blurfac4 passed
# #> typic1 : (Intercept) passed
# #> typic1 : color1 passed
# #> typic1 : blurfac1 passed
# #> typic1 : blurfac2 passed
# #> typic1 : blurfac3 passed
# #> typic1 : blurfac4 passed
# #> typic1 : color1:blurfac1 passed
# #> typic1 : color1:blurfac2 passed
# #> typic1 : color1:blurfac3 passed
# #> typic1 : color1:blurfac4 passed
# #> H. & W. convergence p value
# #> (Intercept) : (Intercept) 0.2829
# #> (Intercept) : color1 0.8963
# #> (Intercept) : blurfac1 0.5252
# #> (Intercept) : blurfac2 0.8212
# #> (Intercept) : blurfac3 0.5227
# #> (Intercept) : blurfac4 0.9169
# #> (Intercept) : color1:blurfac1 0.5844
# #> (Intercept) : color1:blurfac2 0.4926
# #> (Intercept) : color1:blurfac3 0.7559
# #> (Intercept) : color1:blurfac4 0.8684
# #> typic1 : (Intercept) 0.0515
# #> typic1 : color1 0.0775
# #> typic1 : blurfac1 0.2471
# #> typic1 : blurfac2 0.1948
# #> typic1 : blurfac3 0.0845
# #> typic1 : blurfac4 0.0610
# #> typic1 : color1:blurfac1 0.1983
# #> typic1 : color1:blurfac2 0.2473
# #> typic1 : color1:blurfac3 0.2181
# #> typic1 : color1:blurfac4 0.8831
# #>
# #> The Chain has converged.
# #>
# #> Table of sum of squares & effect sizes:
# #>
# #> Table of sum of squares:
# #> (Intercept) color blurfac color:blurfac Residuals Total
# #> (Intercept) 59.3470 5.1145 29.5136 1.0276 136.9923 231.8971
# #> typic1 21.3932 2.0202 13.6640 1.9275 16.7336 55.6143
# #>
# #> Table of effect sizes (95% credible interval):
# #> (Intercept) color blurfac
# #> (Intercept) 0.3028 (0.25,0.36) 0.0361 (0.01,0.066) 0.1774 (0.123,0.232)
# #> typic1 0.5602 (0.444,0.67) 0.1075 (0.017,0.231) 0.4476 (0.315,0.585)
# #> color:blurfac
# #> (Intercept) 0.0075 (-0.028,0.038)
# #> typic1 0.1023 (0.009,0.231)
# #>
# #> Table of p-values (Multidimensional):
# #> (Intercept) color blurfac color:blurfac
# #> (Intercept) <0.0001 0.0100 <0.0001 0.1590
# #> typic <0.0001 0.0010 <0.0001 0.0200
# #>
# #> Table of coefficients:
# #> mean SD Quantile0.025 Quantile0.975
# #> (Intercept) : (Intercept) 0.4981 0.0574 0.3840 0.6115
# #> (Intercept) : color1 0.1532 0.0567 0.0404 0.2683
# #> (Intercept) : blurfac1 0.5591 0.1139 0.3470 0.7807
# #> (Intercept) : blurfac2 0.0554 0.1168 -0.1731 0.2883
# #> (Intercept) : blurfac3 0.0193 0.1036 -0.1775 0.2226
# #> (Intercept) : blurfac4 -0.0565 0.1094 -0.2689 0.1672
# #> (Intercept) : color1:blurfac1 -0.1586 0.1146 -0.3897 0.0724
# #> (Intercept) : color1:blurfac2 0.1137 0.1162 -0.1094 0.3347
# #> (Intercept) : color1:blurfac3 -0.0774 0.1096 -0.2961 0.1376
# #> (Intercept) : color1:blurfac4 0.0125 0.1114 -0.2098 0.2329
# #> typic1 : (Intercept) 0.3092 0.0318 0.2481 0.3742
# #> typic1 : color1 0.0906 0.0311 0.0296 0.1532
# #> typic1 : blurfac1 0.1621 0.0634 0.0379 0.2901
# #> typic1 : blurfac2 0.3612 0.0692 0.2138 0.4951
# #> typic1 : blurfac3 -0.0260 0.0642 -0.1543 0.0996
# #> typic1 : blurfac4 -0.1653 0.0625 -0.2830 -0.0409
# #> typic1 : color1:blurfac1 -0.1443 0.0645 -0.2727 -0.0231
# #> typic1 : color1:blurfac2 0.0344 0.0671 -0.1041 0.1637
# #> typic1 : color1:blurfac3 -0.0238 0.0597 -0.1456 0.0915
# #> typic1 : color1:blurfac4 0.0956 0.0619 -0.0272 0.2211
# #> p.value Signif.codes
# #> (Intercept) : (Intercept) <0.0001 ***
# #> (Intercept) : color1 0.0100 **
# #> (Intercept) : blurfac1 <0.0001 ***
# #> (Intercept) : blurfac2 0.6400
# #> (Intercept) : blurfac3 0.8430
# #> (Intercept) : blurfac4 0.5910
# #> (Intercept) : color1:blurfac1 0.1590
# #> (Intercept) : color1:blurfac2 0.3360
# #> (Intercept) : color1:blurfac3 0.4850
# #> (Intercept) : color1:blurfac4 0.8890
# #> typic1 : (Intercept) <0.0001 ***
# #> typic1 : color1 0.0010 ***
# #> typic1 : blurfac1 0.0080 **
# #> typic1 : blurfac2 <0.0001 ***
# #> typic1 : blurfac3 0.6920
# #> typic1 : blurfac4 0.0060 **
# #> typic1 : color1:blurfac1 0.0200 *
# #> typic1 : color1:blurfac2 0.5940
# #> typic1 : color1:blurfac3 0.6940
# #> typic1 : color1:blurfac4 0.1150
# #> ---
# #> Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
# #>
# #> Multiple R-squared: 0.0856
# #>
# #> Table of predictions:
# #>
# #> Grand mean:
# #> 9.9522
# #> 2.5% 97.5%
# #> 9.5174 10.3726
# #>
# #>
# #> typic mean 2.5% 97.5%
# #> 0 11.0645 10.5896 11.4879
# #> 1 8.7534 8.2242 9.2339
# #>
# #>
# #> color mean 2.5% 97.5%
# #> 0 10.5167 9.9177 11.0551
# #> 1 9.3662 8.7386 9.9471
# #>
# #> blurfac mean 2.5% 97.5%
# #> 1 11.8745 11.0664 12.6146
# #> 2 10.1591 9.1897 11.1158
# #> 3 10.0247 9.1808 10.8356
# #> 4 9.7383 8.8491 10.6451
# #> 5 7.6834 6.6721 8.65
# #>
# #>
# #> typic color mean 2.5% 97.5%
# #> 0 0 11.8558 11.2628 12.3795
# #> 0 1 10.1961 9.521 10.8499
# #> 1 0 9.0004 8.262 9.6717
# #> 1 1 8.5049 7.8023 9.2008
# #>
# #> typic blurfac mean 2.5% 97.5%
# #> 0 1 13.1487 12.3854 13.7718
# #> 0 2 12.3638 11.4074 13.14
# #> 0 3 11.0416 10.0703 11.8974
# #> 0 4 10.2774 9.2503 11.2558
# #> 0 5 7.5923 6.4556 8.7182
# #> 1 1 10.2786 9.1893 11.2832
# #> 1 2 7.533 6.3988 8.7
# #> 1 3 8.9327 7.9134 9.9488
# #> 1 4 9.1821 8.1045 10.2629
# #> 1 5 7.7745 6.6116 8.9589
# #>
# #>
# #> color blurfac mean 2.5% 97.5%
# #> 0 1 11.8576 10.7518 12.8309
# #> 1 1 11.8912 10.7507 12.8908
# #> 0 2 11.1088 9.6862 12.2988
# #> 1 2 9.1388 7.7334 10.5106
# #> 0 3 10.3056 9.0203 11.4538
# #> 1 3 9.7384 8.5515 10.9235
# #> 0 4 10.3571 8.9993 11.6076
# #> 1 4 9.0969 7.7976 10.4325
# #> 0 5 8.7333 7.3643 10.1124
# #> 1 5 6.6442 5.314 8.0042
# #>
# #>
# #> typic color blurfac mean 2.5% 97.5%
# #> 0 0 1 13.0075 11.8829 13.8698
# #> 0 1 1 13.2845 12.2295 14.1165
# #> 0 0 2 13.3472 12.179 14.2525
# #> 0 1 2 11.1483 9.6802 12.4133
# #> 0 0 3 11.5161 10.1419 12.6794
# #> 0 1 3 10.5408 9.1534 11.8042
# #> 0 0 4 11.4974 10.0861 12.6792
# #> 0 1 4 8.9302 7.4175 10.3435
# #> 0 0 5 9.1508 7.5622 10.651
# #> 0 1 5 6.0642 4.63 7.6654
# #> 1 0 1 10.4543 8.9691 11.7715
# #> 1 1 1 10.1005 8.5915 11.5018
# #> 1 0 2 8.0995 6.3761 9.7681
# #> 1 1 2 6.9711 5.4889 8.5847
# #> 1 0 3 8.9678 7.3996 10.3327
# #> 1 1 3 8.8976 7.5123 10.3464
# #> 1 0 4 9.1014 7.5952 10.681
# #> 1 1 4 9.2626 7.7261 10.8305
# #> 1 0 5 8.3118 6.8199 9.9193
# #> 1 1 5 7.2393 5.6957 8.8424
| /scratch/gouwar.j/cran-all/cranData/BANOVA/inst/doc/banova_examples.R |
---
title: "BANOVA examples"
author: "Chen Dong"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{BANOVA examples}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
We illustrate the application of the **BANOVA** package in a study into the influence
of color on gist perception of advertising, which is the very rapid identification of ads during
brief exposures. Specifically, we analyze the effect of color on the perception of the gist of ads
when the advertising exposure is brief and blurred (Wedel and Pieters 2015). In the study,
116 subjects were randomly assigned to one condition of a 5 (**blur**: normal, low, medium,
high, very high) x 2 (**color**: full color, grayscale) between-subjects, x 2 (**image**: typical ads, atypical ads) within-subjects, mixed design. Participants were exposed to 40 images, 32 fullpage
ads and 8 editorial pages. There were 8 ads per product category, with 4 typical and 4
atypical ones. Blur was manipulated by processing the advertising images with a Gaussian
blur filter of different radius. Subjects were flashed an image for 100msec. and then asked to
identify whether the image was an ad or not.
## Data
```{r, message=FALSE}
library(BANOVA)
data(colorad)
head(colorad)
```
The structure of colorad (data frame) is shown above using the `head()` function. It is in long format
including both within- subjects and between- subjects variables. Here, the within-subjects variable **typic** is a factor with 2 levels '0' (typical ads) and '1'(atypical ads); between-subjects variables are: **blur**, a numerical variable representing the blur of the image (the log-radius of a Gaussian blur filter used to produce the images); **blurfac**, a
factor variable with the five levels of blur; and **color**, a factor representing the color of the ads with 2 levels '0'(full color) and '1'(grayscale). id is the subject identification number. The dependent variable is the number of times ads were correctly identified as an ad, out of the 16 ads, for each subject for each level of typic.
## Models & results
We are interested in the effects of within- and between- subjects factors typic and color, and
the variable blur, as well as their interactions. The factor typic varies within individuals; the
factors blur, color and blur x color interaction vary between subjects.
The analysis of this experiment is executed with the function `BANOVA.run()` in the
**BANOVA** package (the continuous covariate blur is mean centered by default). The R code
to implement the analysis is shown below. For this model, the `BANOVA` function call needs
to include the binomial total (16) as an additional argument.
```{r, message=FALSE, eval=FALSE}
library(rstan)
set.seed(700)
model <- BANOVA.model(model_name = 'Binomial')
banova_fit <- BANOVA.build(model)
res <- BANOVA.run(y~typic, ~color*blur, data = colorad, fit = banova_fit,
id = 'id', num_trials = as.integer(16), iter = 1000, thin = 1, chains = 2)
```
The commands above load and build (compile) a Binomial Stan model included in the package. Then, the function `BANOVA.run` is called to run the simulation using two chains (1000 iterations each with thin = 1). Alternatively, users can set up the `model_name` argument to run the simulation directly using a precompiled model (note that it might report errors if compiler settings are not correct).
```{r, message=FALSE, eval=FALSE}
res_alt <- BANOVA.run(y~typic, ~color*blur, data = colorad, model_name = 'Binomial',
id = 'id', num_trials = as.integer(16), iter = 1000, thin = 1, chains = 2)
```
**ANOVA**-like table of sums of squares, effect sizes and p values, as well as the posterior means, standard
deviations, 95% credible intervals and p values of the parameters are produced with the
function `summary()`, the results are presented below. Note
that each of these tables now have two rows, one for each between-subject model (intercept
and typic).
```{r, message=FALSE, eval=FALSE}
summary(res)
#> Call:
#> BANOVA.run(l1_formula = y ~ typic, l2_formula = ~color * blur,
#> fit = banova_fit, data = colorad, id = 'id', iter = 1000,
#> num_trials = as.integer(16), thin = 1, chains = 2)
#>
#> Convergence diagnostics:
#> Geweke Diag. & Heidelberger and Welch's Diag.
#> Geweke stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blur passed
#> (Intercept) : color1:blur passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blur passed
#> typic1 : color1:blur passed
#> Geweke convergence p value
#> (Intercept) : (Intercept) 0.1409
#> (Intercept) : color1 0.9288
#> (Intercept) : blur 0.4537
#> (Intercept) : color1:blur 0.9024
#> typic1 : (Intercept) 0.9642
#> typic1 : color1 0.9105
#> typic1 : blur 0.1451
#> typic1 : color1:blur 0.4603
#> H. & W. stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blur passed
#> (Intercept) : color1:blur passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blur passed
#> typic1 : color1:blur passed
#> H. & W. convergence p value
#> (Intercept) : (Intercept) 0.4819
#> (Intercept) : color1 0.6041
#> (Intercept) : blur 0.7871
#> (Intercept) : color1:blur 0.4488
#> typic1 : (Intercept) 0.8005
#> typic1 : color1 0.8028
#> typic1 : blur 0.1004
#> typic1 : color1:blur 0.6634
#>
#> The Chain has converged.
#>
#> Table of sum of squares & effect sizes:
#>
#> Table of sum of squares:
#> (Intercept) color blur color:blur Residuals Total
#> (Intercept) 59.5532 2.3591 26.1587 9.0749 138.4249 229.8047
#> typic1 21.9510 1.9610 5.4139 7.0553 20.1769 50.6221
#>
#> Table of effect sizes (95% credible interval):
#> (Intercept) color
#> (Intercept) 0.3014 (0.249,0.358) 0.0159 (-0.015,0.104)
#> typic1 0.5215 (0.402,0.638) 0.0781 (-0.015,0.34)
#> blur color:blur
#> (Intercept) 0.1590 (0.108,0.21) 0.0581 (-0.006,0.199)
#> typic1 0.2114 (0.088,0.362) 0.2352 (0.006,0.521)
#>
#> Table of p-values (Multidimensional):
#> (Intercept) color blur color:blur
#> (Intercept) <0.0001 0.9560 <0.0001 0.1400
#> typic <0.0001 0.4180 <0.0001 0.0280
#>
#> Table of coefficients:
#> mean SD Quantile0.025 Quantile0.975
#> (Intercept) : (Intercept) 0.4975 0.0572 0.3881 0.6101
#> (Intercept) : color1 -0.0069 0.1245 -0.2605 0.2413
#> (Intercept) : blur -0.1716 0.0307 -0.2333 -0.1133
#> (Intercept) : color1:blur 0.0410 0.0291 -0.0171 0.1001
#> typic1 : (Intercept) 0.3011 0.0313 0.2374 0.3580
#> typic1 : color1 -0.0596 0.0736 -0.2062 0.0781
#> typic1 : blur -0.0767 0.0170 -0.1087 -0.0439
#> typic1 : color1:blur 0.0384 0.0178 0.0052 0.0733
#> p.value Signif.codes
#> (Intercept) : (Intercept) <0.0001 ***
#> (Intercept) : color1 0.9560
#> (Intercept) : blur <0.0001 ***
#> (Intercept) : color1:blur 0.1400
#> typic1 : (Intercept) <0.0001 ***
#> typic1 : color1 0.4180
#> typic1 : blur <0.0001 ***
#> typic1 : color1:blur 0.0280 *
#> ---
#> Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
#>
#> Multiple R-squared: 0.0664
#>
#> Table of predictions:
#>
#> Grand mean:
#> 9.95
#> 2.5% 97.5%
#> 9.5332 10.3673
#>
#>
#> typic mean 2.5% 97.5%
#> 0 11.035 10.5818 11.4579
#> 1 8.7829 8.2705 9.2933
#>
#>
#> color mean 2.5% 97.5%
#> 0 9.924 8.7817 10.9414
#> 1 9.9759 9.0196 10.8926
#>
#>
#> typic color mean 2.5% 97.5%
#> 0 0 10.8042 9.4812 11.9297
#> 0 1 11.26 10.202 12.271
#> 1 0 8.9913 7.7188 10.2174
#> 1 1 8.5735 7.4431 9.6343
```
Based on the above estimates, ad identification is significantly influenced by ad typicality
(typic): typical ads are identified more accurately as ads, compared to atypical ads. The
accuracy of ad identification is also affected by the degree of blur and its interaction with
typic. The three-factor interaction (blur x color x typic) is significant, which reveals that
color protects the identification of typical ads against blur, which is in line with the findings
of Wedel and Pieters (2015).
These results are based on the **BANOVA** model with blur as a continuous covariate. To
further understand the effects of blur, we can use the discrete variable blur (blurfac) in a
two-way **BANOVA** at the between-subjects level (and the factor typic again within-subjects),
using the following command:
```{r, message=FALSE, eval=FALSE}
library(rstan)
set.seed(900)
res_fac <- BANOVA.run(y~typic, ~color*blurfac, data = colorad, fit = banova_fit,
id = 'id', num_trials = as.integer(16), iter = 2000, thin = 1, chains = 2)
```
Since the above model involves more parameters, a larger number of iterations is used to ensure the chains for all parameters converge (iter = 2000).
```{r, message=FALSE, eval=FALSE}
summary(res_fac)
#> Call:
#> BANOVA.run(l1_formula = y ~ typic, l2_formula = ~color * blurfac,
#> fit = banova_fit, data = colorad, id = 'id', iter = 2000,
#> num_trials = as.integer(16), thin = 1, chains = 2)
#>
#> Convergence diagnostics:
#> Geweke Diag. & Heidelberger and Welch's Diag.
#> Geweke stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blurfac1 passed
#> (Intercept) : blurfac2 passed
#> (Intercept) : blurfac3 passed
#> (Intercept) : blurfac4 passed
#> (Intercept) : color1:blurfac1 passed
#> (Intercept) : color1:blurfac2 passed
#> (Intercept) : color1:blurfac3 passed
#> (Intercept) : color1:blurfac4 passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blurfac1 passed
#> typic1 : blurfac2 passed
#> typic1 : blurfac3 passed
#> typic1 : blurfac4 passed
#> typic1 : color1:blurfac1 passed
#> typic1 : color1:blurfac2 passed
#> typic1 : color1:blurfac3 passed
#> typic1 : color1:blurfac4 passed
#> Geweke convergence p value
#> (Intercept) : (Intercept) 0.0217
#> (Intercept) : color1 0.4861
#> (Intercept) : blurfac1 0.7050
#> (Intercept) : blurfac2 0.5498
#> (Intercept) : blurfac3 0.4843
#> (Intercept) : blurfac4 0.6209
#> (Intercept) : color1:blurfac1 0.9840
#> (Intercept) : color1:blurfac2 0.6900
#> (Intercept) : color1:blurfac3 0.2931
#> (Intercept) : color1:blurfac4 0.7919
#> typic1 : (Intercept) 0.0159
#> typic1 : color1 0.5622
#> typic1 : blurfac1 0.0594
#> typic1 : blurfac2 0.1408
#> typic1 : blurfac3 0.0534
#> typic1 : blurfac4 0.3087
#> typic1 : color1:blurfac1 0.3151
#> typic1 : color1:blurfac2 0.4267
#> typic1 : color1:blurfac3 0.1776
#> typic1 : color1:blurfac4 0.8341
#> H. & W. stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blurfac1 passed
#> (Intercept) : blurfac2 passed
#> (Intercept) : blurfac3 passed
#> (Intercept) : blurfac4 passed
#> (Intercept) : color1:blurfac1 passed
#> (Intercept) : color1:blurfac2 passed
#> (Intercept) : color1:blurfac3 passed
#> (Intercept) : color1:blurfac4 passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blurfac1 passed
#> typic1 : blurfac2 passed
#> typic1 : blurfac3 passed
#> typic1 : blurfac4 passed
#> typic1 : color1:blurfac1 passed
#> typic1 : color1:blurfac2 passed
#> typic1 : color1:blurfac3 passed
#> typic1 : color1:blurfac4 passed
#> H. & W. convergence p value
#> (Intercept) : (Intercept) 0.2829
#> (Intercept) : color1 0.8963
#> (Intercept) : blurfac1 0.5252
#> (Intercept) : blurfac2 0.8212
#> (Intercept) : blurfac3 0.5227
#> (Intercept) : blurfac4 0.9169
#> (Intercept) : color1:blurfac1 0.5844
#> (Intercept) : color1:blurfac2 0.4926
#> (Intercept) : color1:blurfac3 0.7559
#> (Intercept) : color1:blurfac4 0.8684
#> typic1 : (Intercept) 0.0515
#> typic1 : color1 0.0775
#> typic1 : blurfac1 0.2471
#> typic1 : blurfac2 0.1948
#> typic1 : blurfac3 0.0845
#> typic1 : blurfac4 0.0610
#> typic1 : color1:blurfac1 0.1983
#> typic1 : color1:blurfac2 0.2473
#> typic1 : color1:blurfac3 0.2181
#> typic1 : color1:blurfac4 0.8831
#>
#> The Chain has converged.
#>
#> Table of sum of squares & effect sizes:
#>
#> Table of sum of squares:
#> (Intercept) color blurfac color:blurfac Residuals Total
#> (Intercept) 59.3470 5.1145 29.5136 1.0276 136.9923 231.8971
#> typic1 21.3932 2.0202 13.6640 1.9275 16.7336 55.6143
#>
#> Table of effect sizes (95% credible interval):
#> (Intercept) color blurfac
#> (Intercept) 0.3028 (0.25,0.36) 0.0361 (0.01,0.066) 0.1774 (0.123,0.232)
#> typic1 0.5602 (0.444,0.67) 0.1075 (0.017,0.231) 0.4476 (0.315,0.585)
#> color:blurfac
#> (Intercept) 0.0075 (-0.028,0.038)
#> typic1 0.1023 (0.009,0.231)
#>
#> Table of p-values (Multidimensional):
#> (Intercept) color blurfac color:blurfac
#> (Intercept) <0.0001 0.0100 <0.0001 0.1590
#> typic <0.0001 0.0010 <0.0001 0.0200
#>
#> Table of coefficients:
#> mean SD Quantile0.025 Quantile0.975
#> (Intercept) : (Intercept) 0.4981 0.0574 0.3840 0.6115
#> (Intercept) : color1 0.1532 0.0567 0.0404 0.2683
#> (Intercept) : blurfac1 0.5591 0.1139 0.3470 0.7807
#> (Intercept) : blurfac2 0.0554 0.1168 -0.1731 0.2883
#> (Intercept) : blurfac3 0.0193 0.1036 -0.1775 0.2226
#> (Intercept) : blurfac4 -0.0565 0.1094 -0.2689 0.1672
#> (Intercept) : color1:blurfac1 -0.1586 0.1146 -0.3897 0.0724
#> (Intercept) : color1:blurfac2 0.1137 0.1162 -0.1094 0.3347
#> (Intercept) : color1:blurfac3 -0.0774 0.1096 -0.2961 0.1376
#> (Intercept) : color1:blurfac4 0.0125 0.1114 -0.2098 0.2329
#> typic1 : (Intercept) 0.3092 0.0318 0.2481 0.3742
#> typic1 : color1 0.0906 0.0311 0.0296 0.1532
#> typic1 : blurfac1 0.1621 0.0634 0.0379 0.2901
#> typic1 : blurfac2 0.3612 0.0692 0.2138 0.4951
#> typic1 : blurfac3 -0.0260 0.0642 -0.1543 0.0996
#> typic1 : blurfac4 -0.1653 0.0625 -0.2830 -0.0409
#> typic1 : color1:blurfac1 -0.1443 0.0645 -0.2727 -0.0231
#> typic1 : color1:blurfac2 0.0344 0.0671 -0.1041 0.1637
#> typic1 : color1:blurfac3 -0.0238 0.0597 -0.1456 0.0915
#> typic1 : color1:blurfac4 0.0956 0.0619 -0.0272 0.2211
#> p.value Signif.codes
#> (Intercept) : (Intercept) <0.0001 ***
#> (Intercept) : color1 0.0100 **
#> (Intercept) : blurfac1 <0.0001 ***
#> (Intercept) : blurfac2 0.6400
#> (Intercept) : blurfac3 0.8430
#> (Intercept) : blurfac4 0.5910
#> (Intercept) : color1:blurfac1 0.1590
#> (Intercept) : color1:blurfac2 0.3360
#> (Intercept) : color1:blurfac3 0.4850
#> (Intercept) : color1:blurfac4 0.8890
#> typic1 : (Intercept) <0.0001 ***
#> typic1 : color1 0.0010 ***
#> typic1 : blurfac1 0.0080 **
#> typic1 : blurfac2 <0.0001 ***
#> typic1 : blurfac3 0.6920
#> typic1 : blurfac4 0.0060 **
#> typic1 : color1:blurfac1 0.0200 *
#> typic1 : color1:blurfac2 0.5940
#> typic1 : color1:blurfac3 0.6940
#> typic1 : color1:blurfac4 0.1150
#> ---
#> Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
#>
#> Multiple R-squared: 0.0856
#>
#> Table of predictions:
#>
#> Grand mean:
#> 9.9522
#> 2.5% 97.5%
#> 9.5174 10.3726
#>
#>
#> typic mean 2.5% 97.5%
#> 0 11.0645 10.5896 11.4879
#> 1 8.7534 8.2242 9.2339
#>
#>
#> color mean 2.5% 97.5%
#> 0 10.5167 9.9177 11.0551
#> 1 9.3662 8.7386 9.9471
#>
#> blurfac mean 2.5% 97.5%
#> 1 11.8745 11.0664 12.6146
#> 2 10.1591 9.1897 11.1158
#> 3 10.0247 9.1808 10.8356
#> 4 9.7383 8.8491 10.6451
#> 5 7.6834 6.6721 8.65
#>
#>
#> typic color mean 2.5% 97.5%
#> 0 0 11.8558 11.2628 12.3795
#> 0 1 10.1961 9.521 10.8499
#> 1 0 9.0004 8.262 9.6717
#> 1 1 8.5049 7.8023 9.2008
#>
#> typic blurfac mean 2.5% 97.5%
#> 0 1 13.1487 12.3854 13.7718
#> 0 2 12.3638 11.4074 13.14
#> 0 3 11.0416 10.0703 11.8974
#> 0 4 10.2774 9.2503 11.2558
#> 0 5 7.5923 6.4556 8.7182
#> 1 1 10.2786 9.1893 11.2832
#> 1 2 7.533 6.3988 8.7
#> 1 3 8.9327 7.9134 9.9488
#> 1 4 9.1821 8.1045 10.2629
#> 1 5 7.7745 6.6116 8.9589
#>
#>
#> color blurfac mean 2.5% 97.5%
#> 0 1 11.8576 10.7518 12.8309
#> 1 1 11.8912 10.7507 12.8908
#> 0 2 11.1088 9.6862 12.2988
#> 1 2 9.1388 7.7334 10.5106
#> 0 3 10.3056 9.0203 11.4538
#> 1 3 9.7384 8.5515 10.9235
#> 0 4 10.3571 8.9993 11.6076
#> 1 4 9.0969 7.7976 10.4325
#> 0 5 8.7333 7.3643 10.1124
#> 1 5 6.6442 5.314 8.0042
#>
#>
#> typic color blurfac mean 2.5% 97.5%
#> 0 0 1 13.0075 11.8829 13.8698
#> 0 1 1 13.2845 12.2295 14.1165
#> 0 0 2 13.3472 12.179 14.2525
#> 0 1 2 11.1483 9.6802 12.4133
#> 0 0 3 11.5161 10.1419 12.6794
#> 0 1 3 10.5408 9.1534 11.8042
#> 0 0 4 11.4974 10.0861 12.6792
#> 0 1 4 8.9302 7.4175 10.3435
#> 0 0 5 9.1508 7.5622 10.651
#> 0 1 5 6.0642 4.63 7.6654
#> 1 0 1 10.4543 8.9691 11.7715
#> 1 1 1 10.1005 8.5915 11.5018
#> 1 0 2 8.0995 6.3761 9.7681
#> 1 1 2 6.9711 5.4889 8.5847
#> 1 0 3 8.9678 7.3996 10.3327
#> 1 1 3 8.8976 7.5123 10.3464
#> 1 0 4 9.1014 7.5952 10.681
#> 1 1 4 9.2626 7.7261 10.8305
#> 1 0 5 8.3118 6.8199 9.9193
#> 1 1 5 7.2393 5.6957 8.8424
```
We first inspect the tables of sums of squares and effect sizes. In these tables, the columns
denote between-subjects factors and the rows denote the within-subjects factors. The values
in the table present the sum-of-squares and effect sizes of the effects of these factors. Again,
the accuracy of ad identification is affected by blur, and to a lesser extent by color. From
the tables of p values, ad typicality (the value corresponding to the row name 'typic' and
column name '(Intercept)') and the degree of blur (the value corresponding to the row name
'(Intercept)' and column name 'blurfac') are again highly significant. There is also support
for the main effect of color. The three-factor interaction (blurfac x color x typic) is also
significant, which again shows that color protects the identification of typical ads against blur
(Wedel and Pieters 2015). The conclusions from the table of estimates are similar to those
from the results of the previous model, but this table for nonlinear effects of blur allows us
to inspect the effects of each level of bur, and the interactive effects with color and typicality.
Through the tables of predictions for all factors and their interactions, we can inspect these
effects in more detail. We can see that typical color ads (typic = 0, color = 0) are always
more accurately identified than atypical color ads (typic = 1, color = 0). Typical grayscale
ads (typic = 0, color = 1, blur = 1,...,5), however, are only more accurately identified than
atypical grayscale ads (typic = 1, color = 1, blur = 1,...,5) when there is no blur, or a low
level of blur (Wedel and Pieters 2015).
## References
- Wedel M and Pieters R (2015). "The Buffer Effect: The Role of Color When Advertising Exposures
Are Brief and Blurred." Marketing Science, 34(1), 134-143.
- Dong C and Wedel M (2017). "BANOVA: An R Package for Hierarchical Bayesian ANOVA."Journal of Statistical Software, 81(9), pp. 1-46.
| /scratch/gouwar.j/cran-all/cranData/BANOVA/inst/doc/banova_examples.Rmd |
# packageStartupMessage('Compiling models which will take a while...')
# lib_dir <- file.path(R_PACKAGE_DIR, paste('libs', R_ARCH, sep = ""))
# dir.create(lib_dir, recursive = TRUE, showWarnings = FALSE)
# packageStartupMessage(paste('Writing models to:', lib_dir))
# #packageStartupMessage('No models compiled currently!')
# BANOVA.model <- function (model_name,
# single_level = F){
# if(model_name %in% c('Normal', 'Poisson', 'T', 'Bernoulli',
# 'Binomial', 'ordMultinomial', 'Multinomial')){
# if(single_level){
# name <- paste("single_",model_name, ".stan", sep = "")
# }else{
# name <- paste(model_name, "Normal.stan", sep = "_")
# }
# file_src <- file.path(R_PACKAGE_SOURCE, 'inst', 'stan', name)
# #file_src <- system.file(name, package = 'BANOVA', mustWork = TRUE)
# #file_src <- paste("BANOVA_v9/BANOVA_R/inst/stan/",name,sep = "")
# model_code = readChar(file_src, nchars=1000000)
#
# }else{
# stop(paste(model_name, " model is not supported currently!"))
# }
# sol <- list(model_code = model_code, model_name = model_name, single_level = single_level)
# class(sol) <- 'BANOVA.model'
# return(sol)
# }
#
# BANOVA.build <- function(BANOVA_model){
# if(!is(BANOVA_model, 'BANOVA.model')) stop('BANOVA_model must be a BANOVA.model object, use the BANOVA.model function to create a model first!')
# cat('Compiling the', BANOVA_model$model_name, 'model...\n')
# stan_c <- rstan::stanc(model_code = BANOVA_model$model_code, model_name = BANOVA_model$model_name)
# utils::capture.output(stanmodel <- rstan::stan_model(stanc_ret = stan_c,save_dso = T), type = "output")
# cat('Compiled successfully\n')
# sol <- list(stanmodel = stanmodel, model_name = BANOVA_model$model_name, single_level = BANOVA_model$single_level)
# class(sol) <- 'BANOVA.build'
# return(sol)
# }
#
# model_Normal_2 <- BANOVA.model('Normal')
# Normal_Normal_stanmodel <- BANOVA.build(BANOVA_model = model_Normal_2)
#
# model_T_2 <- BANOVA.model('T', single_level = F)
# T_Normal_stanmodel <- BANOVA.build(BANOVA_model = model_T_2)
#
# model_P_2 <- BANOVA.model('Poisson', single_level = F)
# Poisson_Normal_stanmodel <- BANOVA.build(BANOVA_model = model_P_2)
#
# model_Bern_2 <- BANOVA.model('Bernoulli', single_level = F)
# Bernoulli_Normal_stanmodel <- BANOVA.build(BANOVA_model = model_Bern_2)
#
# model_Bin_2 <- BANOVA.model('Binomial', single_level = F)
# Binomial_Normal_stanmodel <- BANOVA.build(BANOVA_model = model_Bin_2)
#
# model_ordMulti_2 <- BANOVA.model('ordMultinomial', single_level = F)
# ordMultinomial_Normal_stanmodel <- BANOVA.build(BANOVA_model = model_ordMulti_2 )
#
# model_Multi_2 <- BANOVA.model('Multinomial', single_level = F)
# Multinomial_Normal_stanmodel <- BANOVA.build(BANOVA_model = model_Multi_2)
#
# model_l2 <- file.path(lib_dir, 'BANOVA.RData')
# save(Normal_Normal_stanmodel, Binomial_Normal_stanmodel, Bernoulli_Normal_stanmodel,
# T_Normal_stanmodel, Poisson_Normal_stanmodel, ordMultinomial_Normal_stanmodel,
# Multinomial_Normal_stanmodel, file = model_l2)
#
# model_Normal_1 <- BANOVA.model('Normal', single_level = T)
# Normal_Normal_stanmodel_1 <- BANOVA.build(BANOVA_model = model_Normal_1)
#
# model_T_1 <- BANOVA.model('T', single_level = T)
# T_Normal_stanmodel_1 <- BANOVA.build(BANOVA_model = model_T_1)
#
# model_P_1 <- BANOVA.model('Poisson', single_level = T)
# Poisson_Normal_stanmodel_1 <- BANOVA.build(BANOVA_model = model_P_1)
#
# model_Bern_1 <- BANOVA.model('Bernoulli', single_level = T)
# Bernoulli_Normal_stanmodel_1 <- BANOVA.build(BANOVA_model = model_Bern_1)
#
# model_Bin_1 <- BANOVA.model('Binomial', single_level = T)
# Binomial_Normal_stanmodel_1 <- BANOVA.build(BANOVA_model = model_Bin_1)
#
# model_ordMulti_1 <- BANOVA.model('ordMultinomial', single_level = T)
# ordMultinomial_Normal_stanmodel_1 <- BANOVA.build(BANOVA_model = model_ordMulti_1 )
#
# model_Multi_1 <- BANOVA.model('Multinomial', single_level = T)
# Multinomial_Normal_stanmodel_1 <- BANOVA.build(BANOVA_model = model_Multi_1)
#
# model_l1 <- file.path(lib_dir, 'single_BANOVA.RData')
# save(Normal_Normal_stanmodel_1, Binomial_Normal_stanmodel_1, Bernoulli_Normal_stanmodel_1,
# T_Normal_stanmodel_1, Poisson_Normal_stanmodel_1, ordMultinomial_Normal_stanmodel_1,
# Multinomial_Normal_stanmodel_1, file = model_l1)
#
# packageStartupMessage('Models compiled successfully!')
| /scratch/gouwar.j/cran-all/cranData/BANOVA/src/install.libs.R |
---
title: "BANOVA examples"
author: "Chen Dong"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{BANOVA examples}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
We illustrate the application of the **BANOVA** package in a study into the influence
of color on gist perception of advertising, which is the very rapid identification of ads during
brief exposures. Specifically, we analyze the effect of color on the perception of the gist of ads
when the advertising exposure is brief and blurred (Wedel and Pieters 2015). In the study,
116 subjects were randomly assigned to one condition of a 5 (**blur**: normal, low, medium,
high, very high) x 2 (**color**: full color, grayscale) between-subjects, x 2 (**image**: typical ads, atypical ads) within-subjects, mixed design. Participants were exposed to 40 images, 32 fullpage
ads and 8 editorial pages. There were 8 ads per product category, with 4 typical and 4
atypical ones. Blur was manipulated by processing the advertising images with a Gaussian
blur filter of different radius. Subjects were flashed an image for 100msec. and then asked to
identify whether the image was an ad or not.
## Data
```{r, message=FALSE}
library(BANOVA)
data(colorad)
head(colorad)
```
The structure of colorad (data frame) is shown above using the `head()` function. It is in long format
including both within- subjects and between- subjects variables. Here, the within-subjects variable **typic** is a factor with 2 levels '0' (typical ads) and '1'(atypical ads); between-subjects variables are: **blur**, a numerical variable representing the blur of the image (the log-radius of a Gaussian blur filter used to produce the images); **blurfac**, a
factor variable with the five levels of blur; and **color**, a factor representing the color of the ads with 2 levels '0'(full color) and '1'(grayscale). id is the subject identification number. The dependent variable is the number of times ads were correctly identified as an ad, out of the 16 ads, for each subject for each level of typic.
## Models & results
We are interested in the effects of within- and between- subjects factors typic and color, and
the variable blur, as well as their interactions. The factor typic varies within individuals; the
factors blur, color and blur x color interaction vary between subjects.
The analysis of this experiment is executed with the function `BANOVA.run()` in the
**BANOVA** package (the continuous covariate blur is mean centered by default). The R code
to implement the analysis is shown below. For this model, the `BANOVA` function call needs
to include the binomial total (16) as an additional argument.
```{r, message=FALSE, eval=FALSE}
library(rstan)
set.seed(700)
model <- BANOVA.model(model_name = 'Binomial')
banova_fit <- BANOVA.build(model)
res <- BANOVA.run(y~typic, ~color*blur, data = colorad, fit = banova_fit,
id = 'id', num_trials = as.integer(16), iter = 1000, thin = 1, chains = 2)
```
The commands above load and build (compile) a Binomial Stan model included in the package. Then, the function `BANOVA.run` is called to run the simulation using two chains (1000 iterations each with thin = 1). Alternatively, users can set up the `model_name` argument to run the simulation directly using a precompiled model (note that it might report errors if compiler settings are not correct).
```{r, message=FALSE, eval=FALSE}
res_alt <- BANOVA.run(y~typic, ~color*blur, data = colorad, model_name = 'Binomial',
id = 'id', num_trials = as.integer(16), iter = 1000, thin = 1, chains = 2)
```
**ANOVA**-like table of sums of squares, effect sizes and p values, as well as the posterior means, standard
deviations, 95% credible intervals and p values of the parameters are produced with the
function `summary()`, the results are presented below. Note
that each of these tables now have two rows, one for each between-subject model (intercept
and typic).
```{r, message=FALSE, eval=FALSE}
summary(res)
#> Call:
#> BANOVA.run(l1_formula = y ~ typic, l2_formula = ~color * blur,
#> fit = banova_fit, data = colorad, id = 'id', iter = 1000,
#> num_trials = as.integer(16), thin = 1, chains = 2)
#>
#> Convergence diagnostics:
#> Geweke Diag. & Heidelberger and Welch's Diag.
#> Geweke stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blur passed
#> (Intercept) : color1:blur passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blur passed
#> typic1 : color1:blur passed
#> Geweke convergence p value
#> (Intercept) : (Intercept) 0.1409
#> (Intercept) : color1 0.9288
#> (Intercept) : blur 0.4537
#> (Intercept) : color1:blur 0.9024
#> typic1 : (Intercept) 0.9642
#> typic1 : color1 0.9105
#> typic1 : blur 0.1451
#> typic1 : color1:blur 0.4603
#> H. & W. stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blur passed
#> (Intercept) : color1:blur passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blur passed
#> typic1 : color1:blur passed
#> H. & W. convergence p value
#> (Intercept) : (Intercept) 0.4819
#> (Intercept) : color1 0.6041
#> (Intercept) : blur 0.7871
#> (Intercept) : color1:blur 0.4488
#> typic1 : (Intercept) 0.8005
#> typic1 : color1 0.8028
#> typic1 : blur 0.1004
#> typic1 : color1:blur 0.6634
#>
#> The Chain has converged.
#>
#> Table of sum of squares & effect sizes:
#>
#> Table of sum of squares:
#> (Intercept) color blur color:blur Residuals Total
#> (Intercept) 59.5532 2.3591 26.1587 9.0749 138.4249 229.8047
#> typic1 21.9510 1.9610 5.4139 7.0553 20.1769 50.6221
#>
#> Table of effect sizes (95% credible interval):
#> (Intercept) color
#> (Intercept) 0.3014 (0.249,0.358) 0.0159 (-0.015,0.104)
#> typic1 0.5215 (0.402,0.638) 0.0781 (-0.015,0.34)
#> blur color:blur
#> (Intercept) 0.1590 (0.108,0.21) 0.0581 (-0.006,0.199)
#> typic1 0.2114 (0.088,0.362) 0.2352 (0.006,0.521)
#>
#> Table of p-values (Multidimensional):
#> (Intercept) color blur color:blur
#> (Intercept) <0.0001 0.9560 <0.0001 0.1400
#> typic <0.0001 0.4180 <0.0001 0.0280
#>
#> Table of coefficients:
#> mean SD Quantile0.025 Quantile0.975
#> (Intercept) : (Intercept) 0.4975 0.0572 0.3881 0.6101
#> (Intercept) : color1 -0.0069 0.1245 -0.2605 0.2413
#> (Intercept) : blur -0.1716 0.0307 -0.2333 -0.1133
#> (Intercept) : color1:blur 0.0410 0.0291 -0.0171 0.1001
#> typic1 : (Intercept) 0.3011 0.0313 0.2374 0.3580
#> typic1 : color1 -0.0596 0.0736 -0.2062 0.0781
#> typic1 : blur -0.0767 0.0170 -0.1087 -0.0439
#> typic1 : color1:blur 0.0384 0.0178 0.0052 0.0733
#> p.value Signif.codes
#> (Intercept) : (Intercept) <0.0001 ***
#> (Intercept) : color1 0.9560
#> (Intercept) : blur <0.0001 ***
#> (Intercept) : color1:blur 0.1400
#> typic1 : (Intercept) <0.0001 ***
#> typic1 : color1 0.4180
#> typic1 : blur <0.0001 ***
#> typic1 : color1:blur 0.0280 *
#> ---
#> Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
#>
#> Multiple R-squared: 0.0664
#>
#> Table of predictions:
#>
#> Grand mean:
#> 9.95
#> 2.5% 97.5%
#> 9.5332 10.3673
#>
#>
#> typic mean 2.5% 97.5%
#> 0 11.035 10.5818 11.4579
#> 1 8.7829 8.2705 9.2933
#>
#>
#> color mean 2.5% 97.5%
#> 0 9.924 8.7817 10.9414
#> 1 9.9759 9.0196 10.8926
#>
#>
#> typic color mean 2.5% 97.5%
#> 0 0 10.8042 9.4812 11.9297
#> 0 1 11.26 10.202 12.271
#> 1 0 8.9913 7.7188 10.2174
#> 1 1 8.5735 7.4431 9.6343
```
Based on the above estimates, ad identification is significantly influenced by ad typicality
(typic): typical ads are identified more accurately as ads, compared to atypical ads. The
accuracy of ad identification is also affected by the degree of blur and its interaction with
typic. The three-factor interaction (blur x color x typic) is significant, which reveals that
color protects the identification of typical ads against blur, which is in line with the findings
of Wedel and Pieters (2015).
These results are based on the **BANOVA** model with blur as a continuous covariate. To
further understand the effects of blur, we can use the discrete variable blur (blurfac) in a
two-way **BANOVA** at the between-subjects level (and the factor typic again within-subjects),
using the following command:
```{r, message=FALSE, eval=FALSE}
library(rstan)
set.seed(900)
res_fac <- BANOVA.run(y~typic, ~color*blurfac, data = colorad, fit = banova_fit,
id = 'id', num_trials = as.integer(16), iter = 2000, thin = 1, chains = 2)
```
Since the above model involves more parameters, a larger number of iterations is used to ensure the chains for all parameters converge (iter = 2000).
```{r, message=FALSE, eval=FALSE}
summary(res_fac)
#> Call:
#> BANOVA.run(l1_formula = y ~ typic, l2_formula = ~color * blurfac,
#> fit = banova_fit, data = colorad, id = 'id', iter = 2000,
#> num_trials = as.integer(16), thin = 1, chains = 2)
#>
#> Convergence diagnostics:
#> Geweke Diag. & Heidelberger and Welch's Diag.
#> Geweke stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blurfac1 passed
#> (Intercept) : blurfac2 passed
#> (Intercept) : blurfac3 passed
#> (Intercept) : blurfac4 passed
#> (Intercept) : color1:blurfac1 passed
#> (Intercept) : color1:blurfac2 passed
#> (Intercept) : color1:blurfac3 passed
#> (Intercept) : color1:blurfac4 passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blurfac1 passed
#> typic1 : blurfac2 passed
#> typic1 : blurfac3 passed
#> typic1 : blurfac4 passed
#> typic1 : color1:blurfac1 passed
#> typic1 : color1:blurfac2 passed
#> typic1 : color1:blurfac3 passed
#> typic1 : color1:blurfac4 passed
#> Geweke convergence p value
#> (Intercept) : (Intercept) 0.0217
#> (Intercept) : color1 0.4861
#> (Intercept) : blurfac1 0.7050
#> (Intercept) : blurfac2 0.5498
#> (Intercept) : blurfac3 0.4843
#> (Intercept) : blurfac4 0.6209
#> (Intercept) : color1:blurfac1 0.9840
#> (Intercept) : color1:blurfac2 0.6900
#> (Intercept) : color1:blurfac3 0.2931
#> (Intercept) : color1:blurfac4 0.7919
#> typic1 : (Intercept) 0.0159
#> typic1 : color1 0.5622
#> typic1 : blurfac1 0.0594
#> typic1 : blurfac2 0.1408
#> typic1 : blurfac3 0.0534
#> typic1 : blurfac4 0.3087
#> typic1 : color1:blurfac1 0.3151
#> typic1 : color1:blurfac2 0.4267
#> typic1 : color1:blurfac3 0.1776
#> typic1 : color1:blurfac4 0.8341
#> H. & W. stationarity test
#> (Intercept) : (Intercept) passed
#> (Intercept) : color1 passed
#> (Intercept) : blurfac1 passed
#> (Intercept) : blurfac2 passed
#> (Intercept) : blurfac3 passed
#> (Intercept) : blurfac4 passed
#> (Intercept) : color1:blurfac1 passed
#> (Intercept) : color1:blurfac2 passed
#> (Intercept) : color1:blurfac3 passed
#> (Intercept) : color1:blurfac4 passed
#> typic1 : (Intercept) passed
#> typic1 : color1 passed
#> typic1 : blurfac1 passed
#> typic1 : blurfac2 passed
#> typic1 : blurfac3 passed
#> typic1 : blurfac4 passed
#> typic1 : color1:blurfac1 passed
#> typic1 : color1:blurfac2 passed
#> typic1 : color1:blurfac3 passed
#> typic1 : color1:blurfac4 passed
#> H. & W. convergence p value
#> (Intercept) : (Intercept) 0.2829
#> (Intercept) : color1 0.8963
#> (Intercept) : blurfac1 0.5252
#> (Intercept) : blurfac2 0.8212
#> (Intercept) : blurfac3 0.5227
#> (Intercept) : blurfac4 0.9169
#> (Intercept) : color1:blurfac1 0.5844
#> (Intercept) : color1:blurfac2 0.4926
#> (Intercept) : color1:blurfac3 0.7559
#> (Intercept) : color1:blurfac4 0.8684
#> typic1 : (Intercept) 0.0515
#> typic1 : color1 0.0775
#> typic1 : blurfac1 0.2471
#> typic1 : blurfac2 0.1948
#> typic1 : blurfac3 0.0845
#> typic1 : blurfac4 0.0610
#> typic1 : color1:blurfac1 0.1983
#> typic1 : color1:blurfac2 0.2473
#> typic1 : color1:blurfac3 0.2181
#> typic1 : color1:blurfac4 0.8831
#>
#> The Chain has converged.
#>
#> Table of sum of squares & effect sizes:
#>
#> Table of sum of squares:
#> (Intercept) color blurfac color:blurfac Residuals Total
#> (Intercept) 59.3470 5.1145 29.5136 1.0276 136.9923 231.8971
#> typic1 21.3932 2.0202 13.6640 1.9275 16.7336 55.6143
#>
#> Table of effect sizes (95% credible interval):
#> (Intercept) color blurfac
#> (Intercept) 0.3028 (0.25,0.36) 0.0361 (0.01,0.066) 0.1774 (0.123,0.232)
#> typic1 0.5602 (0.444,0.67) 0.1075 (0.017,0.231) 0.4476 (0.315,0.585)
#> color:blurfac
#> (Intercept) 0.0075 (-0.028,0.038)
#> typic1 0.1023 (0.009,0.231)
#>
#> Table of p-values (Multidimensional):
#> (Intercept) color blurfac color:blurfac
#> (Intercept) <0.0001 0.0100 <0.0001 0.1590
#> typic <0.0001 0.0010 <0.0001 0.0200
#>
#> Table of coefficients:
#> mean SD Quantile0.025 Quantile0.975
#> (Intercept) : (Intercept) 0.4981 0.0574 0.3840 0.6115
#> (Intercept) : color1 0.1532 0.0567 0.0404 0.2683
#> (Intercept) : blurfac1 0.5591 0.1139 0.3470 0.7807
#> (Intercept) : blurfac2 0.0554 0.1168 -0.1731 0.2883
#> (Intercept) : blurfac3 0.0193 0.1036 -0.1775 0.2226
#> (Intercept) : blurfac4 -0.0565 0.1094 -0.2689 0.1672
#> (Intercept) : color1:blurfac1 -0.1586 0.1146 -0.3897 0.0724
#> (Intercept) : color1:blurfac2 0.1137 0.1162 -0.1094 0.3347
#> (Intercept) : color1:blurfac3 -0.0774 0.1096 -0.2961 0.1376
#> (Intercept) : color1:blurfac4 0.0125 0.1114 -0.2098 0.2329
#> typic1 : (Intercept) 0.3092 0.0318 0.2481 0.3742
#> typic1 : color1 0.0906 0.0311 0.0296 0.1532
#> typic1 : blurfac1 0.1621 0.0634 0.0379 0.2901
#> typic1 : blurfac2 0.3612 0.0692 0.2138 0.4951
#> typic1 : blurfac3 -0.0260 0.0642 -0.1543 0.0996
#> typic1 : blurfac4 -0.1653 0.0625 -0.2830 -0.0409
#> typic1 : color1:blurfac1 -0.1443 0.0645 -0.2727 -0.0231
#> typic1 : color1:blurfac2 0.0344 0.0671 -0.1041 0.1637
#> typic1 : color1:blurfac3 -0.0238 0.0597 -0.1456 0.0915
#> typic1 : color1:blurfac4 0.0956 0.0619 -0.0272 0.2211
#> p.value Signif.codes
#> (Intercept) : (Intercept) <0.0001 ***
#> (Intercept) : color1 0.0100 **
#> (Intercept) : blurfac1 <0.0001 ***
#> (Intercept) : blurfac2 0.6400
#> (Intercept) : blurfac3 0.8430
#> (Intercept) : blurfac4 0.5910
#> (Intercept) : color1:blurfac1 0.1590
#> (Intercept) : color1:blurfac2 0.3360
#> (Intercept) : color1:blurfac3 0.4850
#> (Intercept) : color1:blurfac4 0.8890
#> typic1 : (Intercept) <0.0001 ***
#> typic1 : color1 0.0010 ***
#> typic1 : blurfac1 0.0080 **
#> typic1 : blurfac2 <0.0001 ***
#> typic1 : blurfac3 0.6920
#> typic1 : blurfac4 0.0060 **
#> typic1 : color1:blurfac1 0.0200 *
#> typic1 : color1:blurfac2 0.5940
#> typic1 : color1:blurfac3 0.6940
#> typic1 : color1:blurfac4 0.1150
#> ---
#> Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
#>
#> Multiple R-squared: 0.0856
#>
#> Table of predictions:
#>
#> Grand mean:
#> 9.9522
#> 2.5% 97.5%
#> 9.5174 10.3726
#>
#>
#> typic mean 2.5% 97.5%
#> 0 11.0645 10.5896 11.4879
#> 1 8.7534 8.2242 9.2339
#>
#>
#> color mean 2.5% 97.5%
#> 0 10.5167 9.9177 11.0551
#> 1 9.3662 8.7386 9.9471
#>
#> blurfac mean 2.5% 97.5%
#> 1 11.8745 11.0664 12.6146
#> 2 10.1591 9.1897 11.1158
#> 3 10.0247 9.1808 10.8356
#> 4 9.7383 8.8491 10.6451
#> 5 7.6834 6.6721 8.65
#>
#>
#> typic color mean 2.5% 97.5%
#> 0 0 11.8558 11.2628 12.3795
#> 0 1 10.1961 9.521 10.8499
#> 1 0 9.0004 8.262 9.6717
#> 1 1 8.5049 7.8023 9.2008
#>
#> typic blurfac mean 2.5% 97.5%
#> 0 1 13.1487 12.3854 13.7718
#> 0 2 12.3638 11.4074 13.14
#> 0 3 11.0416 10.0703 11.8974
#> 0 4 10.2774 9.2503 11.2558
#> 0 5 7.5923 6.4556 8.7182
#> 1 1 10.2786 9.1893 11.2832
#> 1 2 7.533 6.3988 8.7
#> 1 3 8.9327 7.9134 9.9488
#> 1 4 9.1821 8.1045 10.2629
#> 1 5 7.7745 6.6116 8.9589
#>
#>
#> color blurfac mean 2.5% 97.5%
#> 0 1 11.8576 10.7518 12.8309
#> 1 1 11.8912 10.7507 12.8908
#> 0 2 11.1088 9.6862 12.2988
#> 1 2 9.1388 7.7334 10.5106
#> 0 3 10.3056 9.0203 11.4538
#> 1 3 9.7384 8.5515 10.9235
#> 0 4 10.3571 8.9993 11.6076
#> 1 4 9.0969 7.7976 10.4325
#> 0 5 8.7333 7.3643 10.1124
#> 1 5 6.6442 5.314 8.0042
#>
#>
#> typic color blurfac mean 2.5% 97.5%
#> 0 0 1 13.0075 11.8829 13.8698
#> 0 1 1 13.2845 12.2295 14.1165
#> 0 0 2 13.3472 12.179 14.2525
#> 0 1 2 11.1483 9.6802 12.4133
#> 0 0 3 11.5161 10.1419 12.6794
#> 0 1 3 10.5408 9.1534 11.8042
#> 0 0 4 11.4974 10.0861 12.6792
#> 0 1 4 8.9302 7.4175 10.3435
#> 0 0 5 9.1508 7.5622 10.651
#> 0 1 5 6.0642 4.63 7.6654
#> 1 0 1 10.4543 8.9691 11.7715
#> 1 1 1 10.1005 8.5915 11.5018
#> 1 0 2 8.0995 6.3761 9.7681
#> 1 1 2 6.9711 5.4889 8.5847
#> 1 0 3 8.9678 7.3996 10.3327
#> 1 1 3 8.8976 7.5123 10.3464
#> 1 0 4 9.1014 7.5952 10.681
#> 1 1 4 9.2626 7.7261 10.8305
#> 1 0 5 8.3118 6.8199 9.9193
#> 1 1 5 7.2393 5.6957 8.8424
```
We first inspect the tables of sums of squares and effect sizes. In these tables, the columns
denote between-subjects factors and the rows denote the within-subjects factors. The values
in the table present the sum-of-squares and effect sizes of the effects of these factors. Again,
the accuracy of ad identification is affected by blur, and to a lesser extent by color. From
the tables of p values, ad typicality (the value corresponding to the row name 'typic' and
column name '(Intercept)') and the degree of blur (the value corresponding to the row name
'(Intercept)' and column name 'blurfac') are again highly significant. There is also support
for the main effect of color. The three-factor interaction (blurfac x color x typic) is also
significant, which again shows that color protects the identification of typical ads against blur
(Wedel and Pieters 2015). The conclusions from the table of estimates are similar to those
from the results of the previous model, but this table for nonlinear effects of blur allows us
to inspect the effects of each level of bur, and the interactive effects with color and typicality.
Through the tables of predictions for all factors and their interactions, we can inspect these
effects in more detail. We can see that typical color ads (typic = 0, color = 0) are always
more accurately identified than atypical color ads (typic = 1, color = 0). Typical grayscale
ads (typic = 0, color = 1, blur = 1,...,5), however, are only more accurately identified than
atypical grayscale ads (typic = 1, color = 1, blur = 1,...,5) when there is no blur, or a low
level of blur (Wedel and Pieters 2015).
## References
- Wedel M and Pieters R (2015). "The Buffer Effect: The Role of Color When Advertising Exposures
Are Brief and Blurred." Marketing Science, 34(1), 134-143.
- Dong C and Wedel M (2017). "BANOVA: An R Package for Hierarchical Bayesian ANOVA."Journal of Statistical Software, 81(9), pp. 1-46.
| /scratch/gouwar.j/cran-all/cranData/BANOVA/vignettes/banova_examples.Rmd |
get_oc_BAR <- function(success_prob, n_burn_in, tot_num, block_size,
power_c = "n/2N", lower_bound = .05, reptime,
control_arm = "", output = "", seed = 100){
set.seed(seed)
if (!control_arm %in% c("", "fixed")){
stop("Please make sure the argument of control_arm is specified as default or fixed")
}
if(n_burn_in * length(success_prob) > tot_num){
stop("Burn-in sample size greater than total sample size")
}
if((tot_num - n_burn_in * length(success_prob)) %% block_size != 0){
stop("Please make sure the sample size after burn-in period can be divided by block size")
}
assigning_prob_list <- list()
alloc_prob_matrix <- matrix(NA, reptime, length(success_prob))
pat_num_matrix <- matrix(NA, reptime, length(success_prob))
for(m in 1:reptime){
shapeBetas<-matrix(rep(0.5,2*length(success_prob)),nrow=length(success_prob),byrow=T)
for(ii in 1:length(success_prob)){
assign(paste("xx", ii, sep = ""), NULL)
}
for(ii in 1:length(success_prob)){
assign(paste("xx", ii, sep = ""), c(eval(parse(text = paste("xx", ii, sep = ""))), rbinom(n_burn_in,1,success_prob[ii])))
}
N<-rep(n_burn_in,length(success_prob))
for(ii in 1:length(success_prob)){
shapeBetas[ii,1] <- shapeBetas[ii,1]+sum(eval(parse(text = paste("xx", ii, sep = ""))))
shapeBetas[ii,2] <- shapeBetas[ii,2]+N[ii]-sum(eval(parse(text = paste("xx", ii, sep = ""))))
}
for(ii in 1:length(success_prob)){
assign(paste("a", ii, sep = ""), rbeta(1000,shapeBetas[ii,1],shapeBetas[ii,2]))
}
#pmaxfunction <- paste0("pmax(",paste(paste0("a", 1:length(group.level)), collapse =","),")")
pmaxfunction <- paste0("pmax(",paste(paste0("a", 1:length(success_prob)), collapse =","),")")
for(ii in 1:length(success_prob)){
#assign(paste("c", ii, sep = ""), eval(parse(text=paste0("length(which(a",ii,"==", paste0("pmax(a1,", "a", ii, ")"),"))/1000"))))
#assign(paste("c", ii, sep = ""), eval(parse(text=paste0("length(which(a",ii,"==", success_prob))))
assign(paste("c", ii, sep = ""), eval(parse(text=paste0("length(which(a",ii,"==", pmaxfunction,"))/1000"))))
}
if (control_arm == "fixed"){
previous_rem_sum <- 1-c1
c1 <- 1/length(success_prob)
after_rem_sum <- 1-c1
for(xx in 2:length(success_prob)){
assign(paste("c", xx, sep = ""), eval(parse(text = paste0("c", xx, "/previous_rem_sum*after_rem_sum"))))
}
}
prob_matrix <- matrix(NA, (tot_num-n_burn_in*length(success_prob))/block_size, length(success_prob))
for (j in 1:((tot_num-n_burn_in*length(success_prob))/block_size)){
if(power_c == "n/2N"){
lambda <- (sum(N)+j-1)/(2*tot_num)
}
else{
lambda <- power_c
}
lambdafunction1 <- paste(paste0("c", 1:length(success_prob),"^lambda"), collapse = "+")
lambdafunction2 <- paste(paste0("c", 2:length(success_prob),"^lambda"), collapse = "+")
if(control_arm == "fixed"){
rem_sum <- 1-c1
r1 <- c1
for(z in 2:length(success_prob)){
assign(paste("r", z, sep = ""), eval(parse(text=paste0("(c",z,"^lambda)/(",lambdafunction2,")*rem_sum"))))
}
}
else{
for(z in 1:length(success_prob)){
assign(paste("r", z, sep = ""), eval(parse(text=paste0("(c",z,"^lambda)/(",lambdafunction1,")"))))
}
}
assign("r", eval(parse(text=paste("c(",paste(paste0("r", 1:length(success_prob)), collapse = ","),")"))))
#r1<-c1^lambda/(c1^lambda+c2^lambda+c3^lambda)
#r2<-c2^lambda/(c1^lambda+c2^lambda+c3^lambda)
#r3<-c3^lambda/(c1^lambda+c2^lambda+c3^lambda)
all_i <- c(1:length(r))
max_i <- which.max(r)
min_i <- which.min(r)
else_i <- all_i[! all_i %in% c(max_i, min_i)]
min_threshold <- lower_bound
max_threshold <- 1-(length(r)-1)*lower_bound
#control arm 1/length(r) CANNOT less than min_threshold OR more than max_threshold
# if it less than min_threshold: 1/length(r)<0.05 ====> length(r)>20
# if it more than max_threshold: 1/length(r)>1-(length(r)-1)*0.05
# ====> length(r)**2 -21length(r)+20>0
# ====> (length(r)-20)(length(r)-1)>0
# ====> length(r)>20 & length(r)>1
#control arm 1/length(r) CANNOT be the maximum of the vector:
# for example: if it is the maximum of the vector
# sum( arm1 arm2 arm3 arm4 arm5 ...)
# sum( 1/length(r) <1/length(r) <1/length(r) <1/length(r) <1/length(r) ...)
# <1
if (max(r)>max_threshold & min(r)<min_threshold) {
assign(paste0("r", max_i), eval(parse(text=paste0("min(",max_threshold, ",r",max_i,")"))))
assign(paste0("r", min_i), eval(parse(text=paste0("max(",min_threshold, ",r",min_i,")"))))
#assign(paste0("r", else_i), eval(parse(text=paste0("1-r",max_i,"-r",min_i))))
for(i in else_i){
assign(paste0("r", i), eval(parse(text=paste0("max(",min_threshold, ",r",i,")"))))
if (eval(paste0("r", i))>min_threshold){
assign(paste0("r", i), min_threshold)
}
}
}
if (max(r)<=max_threshold & min(r)<min_threshold) {
assign(paste0("r", min_i), eval(parse(text=paste0("max(",min_threshold, ",r",min_i,")"))))
for(i in else_i){
assign(paste0("r", i), eval(parse(text=paste0("max(",min_threshold, ",r",i,")"))))
}
assign(paste0("r", max_i), eval(parse(text=paste0("1-r",min_i,"-",paste(paste0("r", else_i, collapse = "-"))))))
}
assign("tempprob", eval(parse(text=paste("c(",paste(paste0("r", 1:length(success_prob)), collapse = ","),")"))))
#tempprob=threshold(r1,r2,r3)
Rho=tempprob
#gamma=2
#allocation probability function
if(control_arm == "fixed"){
phi.jk<-Rho*((Rho/(N/(sum(N))))^2)
phi <- phi.jk
ratio <- phi.jk/sum(phi.jk)
previous_rem_sum <- 1-ratio[1]
phi[1] <- 1/length(success_prob)
after_rem_sum <- 1-phi[1]
for(zzz in 2:length(success_prob)){
phi[zzz] <- after_rem_sum*ratio[zzz]/previous_rem_sum
}
}
else{
phi.jk<-Rho*((Rho/(N/(sum(N))))^2)
phi<-phi.jk/sum(phi.jk)
}
all_i <- c(1:length(phi))
max_i <- which.max(phi)
min_i <- which.min(phi)
else_i <- all_i[! all_i %in% c(max_i, min_i)]
min_threshold <- lower_bound
max_threshold <- 1-(length(phi)-1)*lower_bound
for (i in all_i){
assign(paste0("phi",i),eval(parse(text=paste0("phi[",i,"]"))))
}
if (max(phi)>max_threshold & min(phi)<min_threshold) {
assign(paste0("phi", max_i), eval(parse(text=paste0("min(",max_threshold, ",phi",max_i,")"))))
assign(paste0("phi", min_i), eval(parse(text=paste0("max(",min_threshold, ",phi",min_i,")"))))
#assign(paste0("phi", else_i), eval(parse(text=paste0("1-phi",max_i,"-phi",min_i,""))))
for(i in else_i){
assign(paste0("phi", i), eval(parse(text=paste0("max(",min_threshold, ",phi",i,")"))))
if (eval(paste0("phi", i))>min_threshold){
assign(paste0("phi", i), min_threshold)
}
}
}
if (max(phi)<=max_threshold & min(phi)<min_threshold) {
assign(paste0("phi", min_i), eval(parse(text=paste0("max(",min_threshold, ",phi",min_i,")"))))
for(i in else_i){
assign(paste0("phi", i), eval(parse(text=paste0("max(",min_threshold, ",phi",i,")"))))
}
assign(paste0("phi", max_i), eval(parse(text=paste0("1-phi",min_i,"-",paste(paste0("phi", else_i,collapse = "-"))))))
}
assign("phi", eval(parse(text=paste("c(",paste(paste0("phi", 1:length(phi)), collapse = ","),")"))))
#phi<-threshold(phi[1],phi[2],phi[3])
prob_matrix[j, ] <- phi
x<-rep(runif(1,0,1), block_size)
ind <- findInterval(x, cumsum(phi), all.inside = FALSE, left.open = TRUE)+1
for (i in all_i){
assign(paste0("N",i),eval(parse(text=paste0("N[",i,"]"))))
}
for (i in all_i){
assign(paste0("N",i), eval(parse(text = paste0("N", i, "+", "sum(ind==", i, ")"))))
}
assign("N", eval(parse(text=paste("c(",paste(paste0("N", all_i), collapse = ","),")"))))
for (i in ind){
assign(paste0("xx", i), eval(parse(text=paste0("c(xx",i, ",rbinom(1, 1, success_prob[",i,"]))"))))
}
ind_table <- table(factor(ind, levels = 1:length(success_prob)))
which_ind_table <- which(ind_table != 0)
for(ii in which_ind_table){
for(i in 1:ind_table[ii]){
if(eval(parse(text = paste0("xx", ii, "[length(xx", ii, ")+", -i+1, "]"))) == 1){
shapeBetas[ii,1]<-shapeBetas[ii,1]+1
}
if(eval(parse(text = paste0("xx", ii, "[length(xx", ii, ")+", -i+1, "]"))) == 0){
shapeBetas[ii,2]<-shapeBetas[ii,2]+1
}
}
}
#if (x>=0 & x<phi[1]) {
# N[1]<-N[1]+1
# xx1<-c(xx1,rbinom(1,1,success_prob[1]))
# if(xx1[length(xx1)] == 1){
# shapeBetas[1,1]<-shapeBetas[1,1]+1
# }
# if(xx1[length(xx1)] == 0){
# shapeBetas[1,2]<-shapeBetas[1,2]+1
# }
#}
#else if (x<=phi[1]+phi[2]){
# N[2]<-N[2]+1
# xx2<-c(xx2,rbinom(1,1,success_prob[2]))
# if(xx2[length(xx2)] == 1){
# shapeBetas[2,1]<-shapeBetas[2,1]+1
# }
# if(xx2[length(xx2)] == 0){
# shapeBetas[2,2]<-shapeBetas[2,2]+1
# }
#}
#else{
# N[3]<-N[3]+1
# xx3<-c(xx3,rbinom(1,1,success_prob[3]))
# if(xx3[length(xx3)] == 1){
# shapeBetas[3,1]<-shapeBetas[3,1]+1
# }
# if(xx3[length(xx3)] == 0){
# shapeBetas[3,2]<-shapeBetas[3,2]+1
# }
#}
for(ii in 1:length(success_prob)){
assign(paste("a", ii, sep = ""), rbeta(1000,shapeBetas[ii,1],shapeBetas[ii,2]))
}
#pmaxfunction <- paste0("pmax(",paste(paste0("a", 1:length(group.level)), collapse =","),")")
pmaxfunction <- paste0("pmax(",paste(paste0("a", 1:length(success_prob)), collapse =","),")")
for(ii in 1:length(success_prob)){
#assign(paste("c", ii, sep = ""), eval(parse(text=paste0("length(which(a",ii,"==", paste0("pmax(a1,", "a", ii, ")"),"))/1000"))))
#assign(paste("c", ii, sep = ""), eval(parse(text=paste0("length(which(a",ii,"==", success_prob))))
assign(paste("c", ii, sep = ""), eval(parse(text=paste0("length(which(a",ii,"==", pmaxfunction,"))/1000"))))
}
if (control_arm == "fixed"){
previous_rem_sum <- 1-c1
c1 <- 1/length(success_prob)
after_rem_sum <- 1-c1
for(xx in 2:length(success_prob)){
assign(paste("c", xx, sep = ""), eval(parse(text = paste0("c", xx, "/previous_rem_sum*after_rem_sum"))))
}
}
for(d in 1:length(success_prob)){
Rho[d] <- eval(parse(text = paste0("c", d)))
}
}
assigning_prob_list[[m]] <- prob_matrix
alloc_prob_matrix[m, ] <- N/sum(N)
pat_num_matrix[m, ] <- N
}
mean_alloc_prob <- apply(alloc_prob_matrix, 2, mean)
mean_pat_num <- apply(pat_num_matrix, 2, mean)
if(output == "raw"){
return(assigning_prob_list)
}
return(list(avg_alloc_prob = mean_alloc_prob, avg_pat_num = mean_pat_num))
}
| /scratch/gouwar.j/cran-all/cranData/BAR/R/get_oc_BAR.R |
next_allocation_rate_BAR <- function(n, success_count, tot_num, power_c = "n/2N",
lower_bound = .05, control_arm = "", seed = 100){
set.seed(seed)
if (!control_arm %in% c("", "fixed")){
stop("Please make sure the argument of control_arm is specified as default or fixed")
}
prior_a <- .5
prior_b <- .5
shapeBetas <- matrix(rep(c(prior_a, prior_b), length(success_count)), nrow = length(success_count), byrow = TRUE)
for(i in 1:length(success_count)){
shapeBetas[i, 1] <- shapeBetas[i, 1] + success_count[i]
shapeBetas[i, 2] <- shapeBetas[i, 2] + n[i] - success_count[i]
}
for(i in 1:length(success_count)){
assign(paste("a", i, sep = ""), rbeta(1000,shapeBetas[i,1],shapeBetas[i,2]))
}
pmaxfunction <- paste0("pmax(",paste(paste0("a", 1:length(success_count)), collapse =","),")")
for(i in 1:length(success_count)){
assign(paste("c", i, sep = ""), eval(parse(text=paste0("length(which(a",i,"==", pmaxfunction,"))/1000"))))
}
if (control_arm == "fixed"){
previous_rem_sum <- 1-c1
c1 <- 1/length(success_count)
after_rem_sum <- 1-c1
for(xx in 2:length(success_count)){
assign(paste("c", xx, sep = ""), eval(parse(text = paste0("c", xx, "/previous_rem_sum*after_rem_sum"))))
}
}
if(power_c == "n/2N"){
lambda <- sum(n)/(2*tot_num)
}
else{
lambda <- power_c
}
lambdafunction1 <- paste(paste0("c", 1:length(success_count),"^lambda"), collapse = "+")
lambdafunction2 <- paste(paste0("c", 2:length(success_count),"^lambda"), collapse = "+")
if(control_arm == "fixed"){
rem_sum <- 1-c1
r1 <- c1
for(z in 2:length(success_count)){
assign(paste("r", z, sep = ""), eval(parse(text=paste0("(c",z,"^lambda)/(",lambdafunction2,")*rem_sum"))))
}
}
else{
for(z in 1:length(success_count)){
assign(paste("r", z, sep = ""), eval(parse(text=paste0("(c",z,"^lambda)/(",lambdafunction1,")"))))
}
}
assign("r", eval(parse(text=paste("c(",paste(paste0("r", 1:length(success_count)), collapse = ","),")"))))
all_i <- c(1:length(r))
max_i <- which.max(r)
min_i <- which.min(r)
else_i <- all_i[! all_i %in% c(max_i, min_i)]
min_threshold <- lower_bound
max_threshold <- 1-(length(r)-1)*lower_bound
if (max(r)>max_threshold & min(r)<min_threshold) {
assign(paste0("r", max_i), eval(parse(text=paste0("min(",max_threshold, ",r",max_i,")"))))
assign(paste0("r", min_i), eval(parse(text=paste0("max(",min_threshold, ",r",min_i,")"))))
for(i in else_i){
assign(paste0("r", i), eval(parse(text=paste0("max(",min_threshold, ",r",i,")"))))
if (eval(paste0("r", i))>min_threshold){
assign(paste0("r", i), min_threshold)
}
}
}
if (max(r)<=max_threshold & min(r)<min_threshold) {
assign(paste0("r", min_i), eval(parse(text=paste0("max(",min_threshold, ",r",min_i,")"))))
for(i in else_i){
assign(paste0("r", i), eval(parse(text=paste0("max(",min_threshold, ",r",i,")"))))
}
assign(paste0("r", max_i), eval(parse(text=paste0("1-r",min_i,"-",paste(paste0("r", else_i, collapse = "-"))))))
}
assign("tempprob", eval(parse(text=paste("c(",paste(paste0("r", 1:length(success_count)), collapse = ","),")"))))
Rho <- tempprob
if(control_arm == "fixed"){
phi.jk<-Rho*((Rho/(n/(sum(n))))^2)
phi <- phi.jk
ratio <- phi.jk/sum(phi.jk)
previous_rem_sum <- 1-ratio[1]
phi[1] <- 1/length(success_count)
after_rem_sum <- 1-phi[1]
for(zzz in 2:length(success_count)){
phi[zzz] <- after_rem_sum*ratio[zzz]/previous_rem_sum
}
}
else{
phi.jk<-Rho*((Rho/(n/(sum(n))))^2)
phi<-phi.jk/sum(phi.jk)
}
all_i <- c(1:length(phi))
max_i <- which.max(phi)
min_i <- which.min(phi)
else_i <- all_i[! all_i %in% c(max_i, min_i)]
min_threshold <- lower_bound
max_threshold <- 1-(length(phi)-1)*lower_bound
for (i in all_i){
assign(paste0("phi",i),eval(parse(text=paste0("phi[",i,"]"))))
}
if (max(phi)>max_threshold & min(phi)<min_threshold) {
assign(paste0("phi", max_i), eval(parse(text=paste0("min(",max_threshold, ",phi",max_i,")"))))
assign(paste0("phi", min_i), eval(parse(text=paste0("max(",min_threshold, ",phi",min_i,")"))))
#assign(paste0("phi", else_i), eval(parse(text=paste0("1-phi",max_i,"-phi",min_i,""))))
for(i in else_i){
assign(paste0("phi", i), eval(parse(text=paste0("max(",min_threshold, ",phi",i,")"))))
if (eval(paste0("phi", i))>min_threshold){
assign(paste0("phi", i), min_threshold)
}
}
}
if (max(phi)<=max_threshold & min(phi)<min_threshold) {
assign(paste0("phi", min_i), eval(parse(text=paste0("max(",min_threshold, ",phi",min_i,")"))))
for(i in else_i){
assign(paste0("phi", i), eval(parse(text=paste0("max(",min_threshold, ",phi",i,")"))))
}
assign(paste0("phi", max_i), eval(parse(text=paste0("1-phi",min_i,"-",paste(paste0("phi", else_i,collapse = "-"))))))
}
assign("phi", eval(parse(text=paste("c(",paste(paste0("phi", 1:length(phi)), collapse = ","),")"))))
x <- runif(1, 0, 1)
ind <- findInterval(x, cumsum(phi), all.inside = FALSE, left.open = TRUE) + 1
return(phi)
}
| /scratch/gouwar.j/cran-all/cranData/BAR/R/next_allocation_rate_BAR.R |
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----setup, warning = FALSE---------------------------------------------------
library(BAR)
## -----------------------------------------------------------------------------
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 100, seed = 100)
## -----------------------------------------------------------------------------
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 1, output = "raw", seed = 100)
## -----------------------------------------------------------------------------
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 3, reptime = 100, seed = 100)
## -----------------------------------------------------------------------------
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 100, control_arm = "fixed", seed = 100)
## -----------------------------------------------------------------------------
next_allocation_rate_BAR(n = c(20, 25, 30), success_count = c(2, 9, 15), tot_num = 150, power_c = "n/2N")
## -----------------------------------------------------------------------------
next_allocation_rate_BAR(n = c(20, 25, 30), success_count = c(2, 10, 15), tot_num = 150, power_c = .5)
| /scratch/gouwar.j/cran-all/cranData/BAR/inst/doc/BAR.R |
---
title: "BAR"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Bayesian adaptive randomization}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```{r setup, warning = FALSE}
library(BAR)
```
This vignette provides a step-by-step guidance for applying Bayesian adaptive randomization with binary outcomes using the package `BAR`.
### Function setting
We first specify the unknown true successful probability (e.g., response rate) for each arm. For example, we have three arms with 0.1 for the control arm, 0.5 and 0.8 for two experimental arms, denoted as `success_prob = c(.1, .5, .8)`. We set up a number of burn-ins for each arm before initiating the adaptive randomization procedure. During the burn-in period, an equal randomization for each arm will be employed. Here the number of burn-in is set up to be 10, denoted as `n_burn_in = 10`, that is, 10 * 3 = 30 patients will be equally randomized to each of three arms. We plan to recruit a total of 150 patients (including number of burn-ins, that is, the BAR procedure for each arm will be applied from the $31^{st}$ patient) into our study and simulate the trial 100 times, that is, we have `tot_num = 150` and `reptime = 100`. The argument `block_size = 1` means that the allocation probability will be updated for the next one incoming patient. An example with `block_size` $\neq 1$ is shown later.
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 100, seed = 100)
```
The above results consist of two parts. The first part `$avg_alloc_prob` is the average allocation probability for each arm in 100 simulations. The second part `$avg_pat_num` is the average number of patients assigned to each arm.
Sometimes we may want to see the updated allocation probability path after burn-in for each arm for each simulated trial. We can have these results by setting argument `output = "raw"` in the `get_oc_BAR()` function. To save the space of the document, we only show one trial result here. For example, by setting up `reptime = 1`, we can have the following outputs.
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 1, output = "raw", seed = 100)
```
From the result above, since 10 * 3 = 30 sample size has been used in the burn-in period, we therefore have 120 (= 150 - 30) patients in the adaptive randomization period. We can see the updated allocation probabilities for each arm in each step after the burn-in period.
In this package, we also provide users flexibility to allow update the allocation probability block-wisely by using the `block_size` argument. For example, if `block_size = 1`, it indicates that the assignment of a new patient depends on the previous patients' responses to treatment in the ongoing trial while `block_size = 3`, the assignment of next 3 new patients depend on the previous patients' responses to treatment. An example is shown as below.
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 3, reptime = 100, seed = 100)
```
### Bayesian adaptive randomization with fixed allocation ratio for the control arm
In this case, the allocation probability will hold constant for the control arm, which is a usual practice since we want to maintain a good number for the control such that if we want to conduct hypothesis tests between experimental and control arms, we can have a desirable power and results can be interpreted. For this, we can have this argument setting `control_arm = "fixed"` in the function, which will make the allocation probability of control arm (the first slot) to be fixed to $\frac{1}{K}$, where K indicates total number of arms (including control arm).
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 100, control_arm = "fixed", seed = 100)
```
From the result above, we can see the average allocation probability for control arm is close to 0.33 = $\frac{1}{K},$ where K = 3 here.
### Calculate the allocation probability for the next block of new patients using Bayesian adaptive randomization
Here, we provide two examples. The first example uses the `power_c` to be $\frac{n}{2N}$ (this is a default option), here, N is the pre-planned total sample size and n is the accumulative sample size when updating the allocation probabilities. In this case, we need to have N, an example is shown below.
```{r}
next_allocation_rate_BAR(n = c(20, 25, 30), success_count = c(2, 9, 15), tot_num = 150, power_c = "n/2N")
```
In this example (outputs shown above), we can see that we have 3 arms (the $1^{st}$ is control and $2^{rd}$ and $3^{nd}$ are experimental arms). The study plans to enroll 150 patients and at the time of updating the allocation probabilities for the next patient, the accrual number of patients for the three arms are 20, 25 and 30 with number of responders of 2, 9, and 15, respectively. By using the BAR algorithm, we can compute the allocation probabilities for these three arms are 0.05, 0.266 and 0.684, respectively.
Another example is that we use the `power_c` to be a numeric, e.g., 0.5. In this case, the N is not required. Even you can see that there is still a N in the below code, this N is no use and plays no role in updating the allocation probabilities. Outputs are shown below and can be interpreted similarly.
```{r}
next_allocation_rate_BAR(n = c(20, 25, 30), success_count = c(2, 10, 15), tot_num = 150, power_c = .5)
```
| /scratch/gouwar.j/cran-all/cranData/BAR/inst/doc/BAR.Rmd |
---
title: "BAR"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Bayesian adaptive randomization}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```{r setup, warning = FALSE}
library(BAR)
```
This vignette provides a step-by-step guidance for applying Bayesian adaptive randomization with binary outcomes using the package `BAR`.
### Function setting
We first specify the unknown true successful probability (e.g., response rate) for each arm. For example, we have three arms with 0.1 for the control arm, 0.5 and 0.8 for two experimental arms, denoted as `success_prob = c(.1, .5, .8)`. We set up a number of burn-ins for each arm before initiating the adaptive randomization procedure. During the burn-in period, an equal randomization for each arm will be employed. Here the number of burn-in is set up to be 10, denoted as `n_burn_in = 10`, that is, 10 * 3 = 30 patients will be equally randomized to each of three arms. We plan to recruit a total of 150 patients (including number of burn-ins, that is, the BAR procedure for each arm will be applied from the $31^{st}$ patient) into our study and simulate the trial 100 times, that is, we have `tot_num = 150` and `reptime = 100`. The argument `block_size = 1` means that the allocation probability will be updated for the next one incoming patient. An example with `block_size` $\neq 1$ is shown later.
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 100, seed = 100)
```
The above results consist of two parts. The first part `$avg_alloc_prob` is the average allocation probability for each arm in 100 simulations. The second part `$avg_pat_num` is the average number of patients assigned to each arm.
Sometimes we may want to see the updated allocation probability path after burn-in for each arm for each simulated trial. We can have these results by setting argument `output = "raw"` in the `get_oc_BAR()` function. To save the space of the document, we only show one trial result here. For example, by setting up `reptime = 1`, we can have the following outputs.
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 1, output = "raw", seed = 100)
```
From the result above, since 10 * 3 = 30 sample size has been used in the burn-in period, we therefore have 120 (= 150 - 30) patients in the adaptive randomization period. We can see the updated allocation probabilities for each arm in each step after the burn-in period.
In this package, we also provide users flexibility to allow update the allocation probability block-wisely by using the `block_size` argument. For example, if `block_size = 1`, it indicates that the assignment of a new patient depends on the previous patients' responses to treatment in the ongoing trial while `block_size = 3`, the assignment of next 3 new patients depend on the previous patients' responses to treatment. An example is shown as below.
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 3, reptime = 100, seed = 100)
```
### Bayesian adaptive randomization with fixed allocation ratio for the control arm
In this case, the allocation probability will hold constant for the control arm, which is a usual practice since we want to maintain a good number for the control such that if we want to conduct hypothesis tests between experimental and control arms, we can have a desirable power and results can be interpreted. For this, we can have this argument setting `control_arm = "fixed"` in the function, which will make the allocation probability of control arm (the first slot) to be fixed to $\frac{1}{K}$, where K indicates total number of arms (including control arm).
```{r}
get_oc_BAR(success_prob = c(.1, .5, .8), n_burn_in = 10, tot_num = 150, block_size = 1, reptime = 100, control_arm = "fixed", seed = 100)
```
From the result above, we can see the average allocation probability for control arm is close to 0.33 = $\frac{1}{K},$ where K = 3 here.
### Calculate the allocation probability for the next block of new patients using Bayesian adaptive randomization
Here, we provide two examples. The first example uses the `power_c` to be $\frac{n}{2N}$ (this is a default option), here, N is the pre-planned total sample size and n is the accumulative sample size when updating the allocation probabilities. In this case, we need to have N, an example is shown below.
```{r}
next_allocation_rate_BAR(n = c(20, 25, 30), success_count = c(2, 9, 15), tot_num = 150, power_c = "n/2N")
```
In this example (outputs shown above), we can see that we have 3 arms (the $1^{st}$ is control and $2^{rd}$ and $3^{nd}$ are experimental arms). The study plans to enroll 150 patients and at the time of updating the allocation probabilities for the next patient, the accrual number of patients for the three arms are 20, 25 and 30 with number of responders of 2, 9, and 15, respectively. By using the BAR algorithm, we can compute the allocation probabilities for these three arms are 0.05, 0.266 and 0.684, respectively.
Another example is that we use the `power_c` to be a numeric, e.g., 0.5. In this case, the N is not required. Even you can see that there is still a N in the below code, this N is no use and plays no role in updating the allocation probabilities. Outputs are shown below and can be interpreted similarly.
```{r}
next_allocation_rate_BAR(n = c(20, 25, 30), success_count = c(2, 10, 15), tot_num = 150, power_c = .5)
```
| /scratch/gouwar.j/cran-all/cranData/BAR/vignettes/BAR.Rmd |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
abart=function(
x.train, times, delta,
x.test=matrix(0,0,0), K=100,
type='abart', ntype=1,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
sigest=NA, sigdf=3, sigquant=0.90,
k=2, power=2, base=0.95,
##sigmaf=NA,
lambda=NA, tau.num=c(NA, 3, 6)[ntype],
##tau.interval=0.9973,
offset=NULL, w=rep(1, length(times)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
mc.cores = 1L, nice = 19L, seed = 99L
)
{
if(type!='abart') stop('type must be "abart"')
if(ntype!=1) stop('ntype must be 1')
y.train=log(times)
n = length(y.train)
if(n!=length(delta))
stop("length of times and delta must be equal")
delta=as.integer(delta)
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
grp <- temp$grp
rm(temp)
}
else {
rm.const <- NULL
grp <- NULL
}
if(n!=ncol(x.train))
stop('The length of times and the number of rows in x.train must be identical')
p = nrow(x.train)
np = ncol(x.test)
if(length(rho)==0) rho=p
if(length(rm.const)==0) rm.const <- 1:p
if(length(grp)==0) grp <- 1:p
if(length(offset)==0) {
offset=mean(y.train)
}
if(type=='abart') {
y.train = y.train-offset
if(is.na(lambda)) {
if(is.na(sigest)) {
if(p < n)
sigest = summary(lm(y.train~.,
data.frame(t(x.train),y.train)))$sigma
else sigest = sd(y.train)
}
qchi = qchisq(1-sigquant, sigdf)
lambda = (sigest^2)*qchi/sigdf #lambda parameter for sigma prior
} else {
sigest=sqrt(lambda)
}
if(is.na(tau.num)) {
tau=(max(y.train)-min(y.train))/(2*k*sqrt(ntree))
} else {
tau=tau.num/(k*sqrt(ntree))
}
} else {
lambda=1
sigest=1
tau=tau.num/(k*sqrt(ntree))
## tau=1-tau.interval
## if(type=='pbart')
## tau=qnorm(1-0.5*tau)/(k*sqrt(ntree))
## else if(type=='lbart')
## tau=qlogis(1-0.5*tau)/(k*sqrt(ntree))
}
ptm <- proc.time()
res = .Call("cabart",
ntype, ##as.integer(factor(type, levels=check))-1,
n, #number of observations in training data
p, #dimension of x
np, #number of observations in test data
x.train, #pxn training data x
y.train, #pxn training data x
delta, ## censoring indicator
x.test, #p*np test data x
ntree,
numcut,
ndpost*keepevery,
nskip,
keepevery,
power,
base,
offset,
tau,
sigdf,
lambda,
sigest,
w,
sparse,
theta,
omega,
grp,
a,
b,
rho,
augment,
printevery,
xinfo
)
res$proc.time <- proc.time()-ptm
K <- min(n, K)
events=unique(sort(times))
if(length(events)>K) {
events <- unique(quantile(times, probs=(1:K)/K))
attr(events, 'names') <- NULL
}
K <- length(events)
if(type=='abart') {
res$surv.train <- matrix(nrow=ndpost, ncol=n*K)
for(i in 1:n)
for(j in 1:K) {
h <- (i-1)*K+j
res$surv.train[ , h] <-
pnorm(log(events[j]),
mean=res$yhat.train[ , i],
sd=res$sigma[-(1:nskip)],
lower.tail=FALSE)
}
res$yhat.train.mean <- apply(res$yhat.train, 2, mean)
res$surv.train.mean <- apply(res$surv.train, 2, mean)
}
else {
if(type=='pbart') res$prob.train = pnorm(res$yhat.train)
else if(type=='lbart') res$prob.train = plogis(res$yhat.train)
res$prob.train.mean <- apply(res$prob.train, 2, mean)
}
if(np>0) {
if(type=='abart') {
res$surv.test <- matrix(nrow=ndpost, ncol=np*K)
for(i in 1:np)
for(j in 1:K) {
h <- (i-1)*K+j
res$surv.test[ , h] <-
pnorm(log(events[j]),
mean=res$yhat.test[ , i],
sd=res$sigma[-(1:nskip)],
lower.tail=FALSE)
}
res$yhat.test.mean <- apply(res$yhat.test, 2, mean)
res$surv.test.mean <- apply(res$surv.test, 2, mean)
}
else {
if(type=='pbart') res$prob.test = pnorm(res$yhat.test)
else if(type=='lbart') res$prob.test = plogis(res$yhat.test)
res$prob.test.mean <- apply(res$prob.test, 2, mean)
}
}
res$times = events
res$K = K
res$offset = offset
names(res$treedraws$cutpoints) = dimnames(x.train)[[1]]
dimnames(res$varcount)[[2]] = as.list(dimnames(x.train)[[1]])
dimnames(res$varprob)[[2]] = as.list(dimnames(x.train)[[1]])
res$varcount.mean <- apply(res$varcount, 2, mean)
res$varprob.mean <- apply(res$varprob, 2, mean)
res$rm.const <- rm.const
attr(res, 'class') <- type
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/abart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
bartModelMatrix=function(X, numcut=0L, usequants=FALSE, type=7,
rm.const=FALSE, cont=FALSE, xinfo=NULL) {
X.class = class(X)[1]
if(X.class=='factor') {
X.class='data.frame'
X=data.frame(X=X)
}
grp=NULL
if(X.class=='data.frame') {
p=dim(X)[2]
xnm = names(X)
for(i in 1:p) {
if(is.factor(X[[i]])) {
Xtemp = class.ind(X[[i]])
colnames(Xtemp) = paste(xnm[i],1:ncol(Xtemp),sep='')
X[[i]]=Xtemp
grp=c(grp, rep(i, ncol(Xtemp)))
} else {
X[[i]]=cbind(X[[i]])
colnames(X[[i]])=xnm[i]
grp=c(grp, i)
}
}
Xtemp=cbind(X[[1]])
if(p>1) for(i in 2:p) Xtemp=cbind(Xtemp, X[[i]])
X=Xtemp
}
else if(X.class=='numeric' | X.class=='integer') {
X=cbind(as.numeric(X))
grp=1
}
else if(X.class=='NULL') return(X)
else if(X.class!='matrix')
stop('Expecting either a factor, a vector, a matrix or a data.frame')
N <- nrow(X)
p <- ncol(X)
xinfo. <- matrix(nrow=p, ncol=numcut)
nc <- numcut
rm.vars <- c()
if(N>0 & p>0 & (rm.const | numcut[1]>0)) {
for(j in 1:p) {
X.class <- class(X[1, j])[1]
if(X.class=='numeric' | X.class=='integer') {
xs <- unique(sort(X[ , j]))
k <- length(xs)
nc[j] <- numcut
if(k %in% 0:1) {
rm.vars <- c(rm.vars, -j)
nc[j] <- 1
if(k==0) xs <- NA
}
else if(cont)
xs <- seq(xs[1], xs[k], length.out=numcut+2)[-c(1, numcut+2)]
## if(cont) {
## if(k==1) xs <-
## seq(xs[1], xs[1]+1, length.out=numcut+2)[-c(1, numcut+2)]
## else xs <-
## seq(xs[1], xs[k], length.out=numcut+2)[-c(1, numcut+2)]
## }
## else if(k==1) {
## rm.vars <- c(rm.vars, -j)
## nc[j] <- 1
## }
else if(k<numcut) {
xs <- 0.5*(xs[1:(k-1)]+xs[2:k])
nc[j] <- k-1
}
else if(usequants) {
xs <- quantile(X[ , j], type=type,
probs=(0:(numcut+1))/(numcut+1))[-c(1, numcut+2)]
##xs <- quantile(X[ , j], type=type, probs=(1:numcut)/(numcut+1))
names(xs) <- NULL
}
else xs <-
seq(xs[1], xs[k], length.out=numcut+2)[-c(1, numcut+2)]
}
else
stop(paste0('Variables of type ', X.class, ' are not supported'))
##nc[j] <- length(xs)
xinfo.[j, 1:nc[j] ] <- xs
}
}
X <- data.matrix(X)
if(length(xinfo)>0) {
if(is.list(xinfo)) for(j in 1:p) xinfo.[j, 1:length(xinfo[[j]])] <- xinfo[[j]]
else if(is.matrix(xinfo)) xinfo. <- xinfo
else stop('Only a list or a matrix can be provided for xinfo')
for(j in 1:p) nc[j] <- sum(!is.na(xinfo.[j, ]))
}
xinfo <- xinfo.
if(rm.const & length(rm.vars)>0) {
X <- X[ , rm.vars]
nc <- nc[rm.vars]
xinfo <- xinfo[rm.vars, ]
}
else if(length(rm.vars)==0) rm.vars <- 1:p
dimnames(xinfo) <- list(dimnames(X)[[2]], NULL)
##dimnames(xinfo)[[1]] <- dimnames(X)[[2]]
if(numcut==0) return(X)
else return(list(X=X, numcut=as.integer(nc), rm.const=rm.vars,
xinfo=xinfo, grp=grp))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/bartModelMatrix.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
crisk.bart <- function(
x.train=matrix(0,0,0), y.train=NULL,
x.train2=x.train, y.train2=NULL,
times=NULL, delta=NULL, K=NULL,
x.test=matrix(0,0,0), x.test2=x.test, cond=NULL,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL, rho2=NULL,
xinfo=matrix(0,0,0), xinfo2=matrix(0,0,0), usequants=FALSE,
##cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2, ## BEWARE: do NOT use k for other purposes below
power = 2, base = 0.95,
offset = NULL, offset2 = NULL,
tau.num=c(NA, 3, 6)[ntype], ##tau.num2=c(NA, 3, 6)[ntype],
##binaryOffset = NULL, binaryOffset2 = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L,
keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptestmean=ndpost,
##nkeeptreedraws=ndpost,
printevery=100L,
##treesaslists=FALSE,
##keeptrainfits=TRUE,
id = NULL,
seed=99, ## mc.crisk.bart only
mc.cores=2, ## mc.crisk.bart only
nice=19L ## mc.crisk.bart only
)
{
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train2 <- bartModelMatrix(x.train2)
x.test2 <- bartModelMatrix(x.test2)
x.train <- bartModelMatrix(x.train)
x.test <- bartModelMatrix(x.test)
if(length(rho)==0) rho=ncol(x.train)
if(length(rho2)==0) rho2=ncol(x.train2)
if(length(y.train)==0) {
pre <- crisk.pre.bart(times, delta, x.train, x.test,
x.train2, x.test2, K=K)
y.train <- pre$y.train
x.train <- pre$tx.train
x.test <- pre$tx.test
y.train2 <- pre$y.train2
x.train2 <- pre$tx.train2
x.test2 <- pre$tx.test2
times <- pre$times
K <- pre$K
if(length(cond)==0) cond <- pre$cond
##if(length(binaryOffset)==0) binaryOffset <- pre$binaryOffset
##if(length(binaryOffset2)==0) binaryOffset2 <- pre$binaryOffset2
}
else {
if(length(x.train)>0 & length(x.train2)>0 & nrow(x.train)!=nrow(x.train2))
stop('number of rows in x.train and x.train2 must be equal')
if(length(x.test)>0 & length(x.test2)>0 & nrow(x.test)!=nrow(x.test2))
stop('number of rows in x.test and x.test2 must be equal')
##if(length(binaryOffset)==0) binaryOffset <- 0
##if(length(binaryOffset2)==0) binaryOffset2 <- 0
times <- unique(sort(x.train[ , 1]))
K <- length(times)
}
if(length(xinfo)==0) {
temp = bartModelMatrix(x.train2[cond, ], numcut, usequants=usequants,
##cont=cont,
xinfo=xinfo, rm.const=rm.const)
x.train2 = t(temp$X)
numcut2 = temp$numcut
xinfo2 = temp$xinfo
## if(length(x.test2)>0)
## x.test2 = t(bartModelMatrix(x.test2[ , temp$rm.const]))
if(length(x.test2)>0) {
x.test2 = bartModelMatrix(x.test2)
x.test2 = t(x.test2[ , temp$rm.const])
}
rm.const2 <- temp$rm.const
rm(temp)
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
##cont=cont,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
xinfo2[1, ] <- xinfo[1, ] ## same time grid
transposed <- TRUE
}
else {
x.train2=as.matrix(x.train2[cond, ])
rm.const <- 1:ncol(x.train)
rm.const2 <- 1:ncol(x.train2)
transposed <- FALSE
}
## if(length(binaryOffset)==0)
## binaryOffset <- qnorm(mean(y.train))
## if(length(binaryOffset2)==0)
## binaryOffset2 <- qnorm(mean(y.train2[cond]))
## if(type=='pbart') call <- pbart
## else if(type=='lbart') {
## ##binaryOffset <- 0
## ##binaryOffset2 <- 0
## call <- lbart
## }
post <- gbart(x.train=x.train, y.train=y.train,
x.test=x.test, type=type,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
##cont=cont,
rm.const=rm.const,
k=k, power=power, base=base,
offset=offset, tau.num=tau.num,
##binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=ndpost, nskip=nskip,
keepevery=keepevery, ##nkeeptrain=0,
##nkeeptest=nkeeptest, #nkeeptestmean=nkeeptestmean,
##nkeeptreedraws=nkeeptreedraws,
printevery=printevery,
transposed=transposed) #, treesaslists=treesaslists)
if(type!=attr(post, 'class')) return(post)
##post2 <- call(x.train=as.matrix(x.train2[cond, ]),
post2 <- gbart(x.train=x.train2, y.train=y.train2[cond],
x.test=x.test2, type=type,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho2,
xinfo=xinfo2, usequants=usequants,
##cont=cont,
rm.const=rm.const,
k=k, power=power, base=base,
offset=offset2, tau.num=tau.num,
##binaryOffset=binaryOffset2,
ntree=ntree, numcut=numcut2,
ndpost=ndpost, nskip=nskip,
keepevery=keepevery, ##nkeeptrain=0,
##nkeeptest=nkeeptest, #nkeeptestmean=nkeeptestmean,
##nkeeptreedraws=nkeeptreedraws,
printevery=printevery,
transposed=transposed) #, treesaslists=treesaslists)
if(type!=attr(post2, 'class')) return(post2)
##post$binaryOffset <- binaryOffset
post$offset2 <- post2$offset
##post$binaryOffset2 <- post2$binaryOffset
post$id <- id
post$times <- times
post$K <- K
if(!transposed) {
post$tx.train <- x.train
post$tx.train2 <- x.train2
} else {
post$tx.train <- t(x.train)
post$tx.train2 <- t(x.train2)
}
post$type <- type
post$cond <- cond
post$treedraws2 <- post2$treedraws
post$varcount2 <- post2$varcount
post$varcount2.mean <- post2$varcount.mean
post$varprob2 <- post2$varprob
post$varprob2.mean <- post2$varprob.mean
post$rm.const <- rm.const
post$rm.const2 <- rm.const2
post$yhat.train <- NULL
post$yhat.train.mean <- NULL
if(length(x.test)>0) {
if(!transposed) {
post$tx.test <- x.test
post$tx.test2 <- x.test2
} else {
post$tx.test <- t(x.test)
post$tx.test2 <- t(x.test2)
}
H <- nrow(post$tx.test)/K ## the number of different settings
post$yhat.test2 <- post2$yhat.test
post$prob.test2 <- post2$prob.test
## if(type=='pbart') {
## post$prob.test <- pnorm(post$yhat.test)
## post$prob.test2 <- pnorm(post$yhat.test2)
## }
## else if(type=='lbart') {
## post$prob.test <- plogis(post$yhat.test)
## post$prob.test2 <- plogis(post$yhat.test2)
## }
post$surv.test <- (1-post$prob.test)*(1-post$prob.test2)
post$prob.test2 <- (1-post$prob.test)*post$prob.test2
post$cif.test <- post$prob.test
post$cif.test2 <- post$prob.test2
for(h in 1:H)
for(j in 2:K) {
l <- K*(h-1)+j
post$cif.test[ , l] <- post$cif.test[ , l-1]+post$surv.test[ , l-1]*post$cif.test[ , l]
post$cif.test2[ , l] <- post$cif.test2[ , l-1]+post$surv.test[ , l-1]*post$cif.test2[ , l]
post$surv.test[ , l] <- post$surv.test[ , l-1]*post$surv.test[ , l]
}
post$cif.test.mean <- apply(post$cif.test, 2, mean)
post$cif.test2.mean <- apply(post$cif.test2, 2, mean)
post$surv.test.mean <- apply(post$surv.test, 2, mean)
}
attr(post, 'class') <- 'criskbart'
return(post)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/crisk.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
## you call this function before crisk.bart()
## this function takes traditional time/delta
## competing risk variables and regressors (if any)
## and it constructs the corresponding
## tx.train, y.train, y.train2, and tx.test appropriate
## for use with pbart()
crisk.pre.bart <- function(
times,
## vector of survival times
delta,
## vector of event indicators
## 0=censoring, 1=cause 1, 2=cause 2
x.train=NULL,
## matrix of covariate regressors for cause 1
## can be NULL, i.e. KM analog
x.test=NULL,
## matrix of covariate regressors for cause 1
x.train2=x.train,
## matrix of covariate regressors for cause 2
## can be NULL, i.e. KM analog
x.test2=x.test,
## matrix of covariate regressors for cause 2
K=NULL
## if specified, then use K quantiles for time grid
) {
## currently does not handle time dependent Xs
## can be extended later
## most likely via the alternative counting process notation
check <- unique(sort(delta))
C <- length(check)
## with gap times, there is no censoring per se, only 1s and 2s
if(!(C %in% 2:3) || (C==3 && !all(check==0:2)) || (C==2 && !all(check==1:2)))
stop('delta must be coded as: 0(censored), 1(cause 1) or 2(cause 2)')
if(length(x.train)>0 && length(x.train2)>0 && nrow(x.train)!=nrow(x.train2))
stop('number of rows in x.train and x.train2 must be equal')
if(length(x.test)>0 && length(x.test2)>0 && nrow(x.test)!=nrow(x.test2))
stop('number of rows in x.test and x.test2 must be equal')
pre <- surv.pre.bart(times=times, 1*(delta==1), K=K,
x.train=x.train, x.test=x.test)
pre$cond <- which(pre$y.train==0)
pre2 <- surv.pre.bart(times=times, 1*(delta==2), K=K,
x.train=x.train2, x.test=x.test2)
pre$tx.train2 <- pre2$tx.train
pre$tx.test2 <- pre2$tx.test
pre$y.train2 <- pre2$y.train
##pre$binaryOffset2 <- pre2$binaryOffset
return(pre)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/crisk.pre.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
crisk2.bart <- function(
x.train=matrix(0,0,0), y.train=NULL, x.train2=x.train,
y.train2=NULL, times=NULL, delta=NULL, K=NULL,
x.test=matrix(0,0,0), x.test2=x.test,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL, rho2=NULL,
xinfo=matrix(0,0,0), xinfo2=matrix(0,0,0), usequants=FALSE,
##cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2, ## BEWARE: do NOT use k for other purposes below
power = 2, base = 0.95,
offset = NULL, offset2 = NULL,
tau.num=c(NA, 3, 6)[ntype],
##binaryOffset = NULL, binaryOffset2 = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L,
keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost, nkeeptreedraws=ndpost,
printevery=100L,
##keeptrainfits=TRUE,
id = NULL,
seed=99, ## mc.crisk2.bart only
mc.cores=2, ## mc.crisk2.bart only
nice=19L ## mc.crisk2.bart only
)
{
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train2 <- bartModelMatrix(x.train2)
x.test2 <- bartModelMatrix(x.test2)
x.train <- bartModelMatrix(x.train)
x.test <- bartModelMatrix(x.test)
if(length(rho)==0) rho=ncol(x.train)
if(length(rho2)==0) rho2=ncol(x.train2)
if(length(y.train)==0) {
pre <- surv.pre.bart(times, delta, x.train, x.test, K=K)
pre2 <- surv.pre.bart(times, delta, x.train2, x.test2, K=K)
y.train <- pre$y.train
x.train <- pre$tx.train
x.test <- pre$tx.test
y.train2 <- 1*(y.train[y.train>0]==1)
x.train2 <- cbind(pre2$tx.train[y.train>0, ])
x.test2 <- pre2$tx.test
y.train <- 1*(y.train>0)
times <- pre$times
K <- pre$K
}
else {
## if(length(x.train)>0 & length(x.train2)>0 &
## nrow(x.train)!=nrow(x.train2))
## stop('number of rows in x.train and x.train2 must be equal')
if(length(x.test)>0 & length(x.test2)>0 & nrow(x.test)!=nrow(x.test2))
stop('number of rows in x.test and x.test2 must be equal')
times <- unique(sort(x.train[ , 1]))
K <- length(times)
}
if(length(xinfo)==0) {
temp = bartModelMatrix(x.train2, numcut, usequants=usequants,
##cont=cont,
xinfo=xinfo, rm.const=rm.const)
x.train2 = t(temp$X)
numcut2 = temp$numcut
xinfo2 = temp$xinfo
## if(length(x.test2)>0)
## x.test2 = t(bartModelMatrix(x.test2[ , temp$rm.const]))
if(length(x.test2)>0) {
x.test2 = bartModelMatrix(x.test2)
x.test2 = t(x.test2[ , temp$rm.const])
}
rm.const2 <- temp$rm.const
rm(temp)
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
##cont=cont,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
xinfo2[1, ] <- xinfo[1, ] ## same time grid
transposed <- TRUE
}
else {
rm.const <- 1:ncol(x.train)
rm.const2 <- 1:ncol(x.train2)
transposed <- FALSE
}
## if(type=='pbart') call <- pbart
## else if(type=='lbart') {
## ##binaryOffset <- 0
## ##binaryOffset2 <- 0
## call <- lbart
## }
post <- gbart(x.train=x.train, y.train=y.train,
x.test=x.test, type=type,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
##cont=cont,
rm.const=rm.const,
k=k, power=power, base=base,
offset=offset, tau.num=tau.num,
##binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=ndpost, nskip=nskip,
keepevery=keepevery, ##nkeeptrain=0,
##nkeeptest=nkeeptest, nkeeptreedraws=nkeeptreedraws,
printevery=printevery, transposed=transposed)
if(type!=attr(post, 'class')) return(post)
post2 <- gbart(x.train=x.train2, y.train=y.train2,
x.test=x.test2, type=type,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho2,
xinfo=xinfo2, usequants=usequants,
##cont=cont,
rm.const=rm.const,
k=k, power=power, base=base,
offset=offset2, tau.num=tau.num,
##binaryOffset=binaryOffset2,
ntree=ntree, numcut=numcut2,
ndpost=ndpost, nskip=nskip,
keepevery=keepevery, ##nkeeptrain=0,
##nkeeptest=nkeeptest,
##nkeeptreedraws=nkeeptreedraws,
printevery=printevery, transposed=transposed)
if(type!=attr(post2, 'class')) return(post2)
##post$binaryOffset <- binaryOffset
post$offset2 <- post2$offset
##post$binaryOffset2 <- post2$binaryOffset
post$id <- id
post$times <- times
post$K <- K
if(!transposed) {
post$tx.train <- x.train
post$tx.train2 <- x.train2
} else {
post$tx.train <- t(x.train)
post$tx.train2 <- t(x.train2)
}
post$type <- type
post$treedraws2 <- post2$treedraws
post$varcount2 <- post2$varcount
post$varcount2.mean <- post2$varcount.mean
post$varprob2 <- post2$varprob
post$varprob2.mean <- post2$varprob.mean
post$rm.const <- rm.const
post$rm.const2 <- rm.const2
post$yhat.train <- NULL
post$yhat.train.mean <- NULL
if(length(x.test)>0) {
if(!transposed) {
post$tx.test <- x.test
post$tx.test2 <- x.test2
} else {
post$tx.test <- t(x.test)
post$tx.test2 <- t(x.test2)
}
H <- nrow(post$tx.test)/K ## the number of different settings
post$yhat.test2 <- post2$yhat.test
post$prob.test2 <- post2$prob.test
post$surv.test <- 1-post$prob.test
post$cif.test <- post$prob.test*post$prob.test2
post$cif.test2 <- post$prob.test*(1-post$prob.test2)
for(h in 1:H)
for(j in 2:K) {
l <- K*(h-1)+j
post$cif.test[ , l] <- post$cif.test[ , l-1]+
post$surv.test[ , l-1]*post$cif.test[ , l]
post$cif.test2[ , l] <- post$cif.test2[ , l-1]+
post$surv.test[ , l-1]*post$cif.test2[ , l]
post$surv.test[ , l] <- post$surv.test[ , l-1]*
post$surv.test[ , l]
}
post$cif.test.mean <- apply(post$cif.test, 2, mean)
post$cif.test2.mean <- apply(post$cif.test2, 2, mean)
post$surv.test.mean <- apply(post$surv.test, 2, mean)
}
attr(post, 'class') <- 'crisk2bart'
return(post)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/crisk2.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch, Rodney Sparapani
## and Robert Gramacy
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
draw_lambda=function(lambda, mean, kmax=1000, thin=1)
.Call("cdraw_lambda", lambda, mean, kmax, thin)
| /scratch/gouwar.j/cran-all/cranData/BART/R/draw_lambda.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch, Rodney Sparapani
## and Robert Gramacy
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
draw_lambda_i=function(lambda, mean, kmax=1000, thin=1)
.Call("cdraw_lambda_i", lambda, mean, kmax, thin)
| /scratch/gouwar.j/cran-all/cranData/BART/R/draw_lambda_i.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
draw_z=function(mean, tau, lambda)
.Call("cdraw_z", mean, tau, lambda)
| /scratch/gouwar.j/cran-all/cranData/BART/R/draw_z.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
gbart=function(
x.train, y.train,
x.test=matrix(0,0,0), type='wbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
sigest=NA, sigdf=3, sigquant=0.90,
k=2, power=2, base=0.95,
##sigmaf=NA,
lambda=NA, tau.num=c(NA, 3, 6)[ntype],
##tau.interval=0.9973,
offset=NULL, w=rep(1, length(y.train)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
hostname=FALSE,
mc.cores = 1L, nice = 19L, seed = 99L
)
{
if(is.na(ntype))
stop("type argument must be set to either 'wbart', 'pbart' or 'lbart'")
n = length(y.train)
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
grp <- temp$grp
rm(temp)
}
else {
rm.const <- NULL
grp <- NULL
}
if(n!=ncol(x.train))
stop('The length of y.train and the number of rows in x.train must be identical')
p = nrow(x.train)
np = ncol(x.test)
if(length(rho)==0) rho=p
if(length(rm.const)==0) rm.const <- 1:p
if(length(grp)==0) grp <- 1:p
check <- unique(sort(y.train))
if(length(check)==2) {
if(!all(check==0:1))
stop('Binary y.train must be coded as 0 and 1')
if(type=='wbart')
stop("The outcome is binary so set type to 'pbart' or 'lbart'")
}
## check <- c('wbart', 'pbart', 'lbart')
## if(!(type %in% check))
## stop("type argument must be set to either 'wbart', 'pbart' or 'lbart'")
if(length(offset)==0) {
offset=mean(y.train)
if(type=='pbart') offset=qnorm(offset)
else if(type=='lbart') offset=qlogis(offset)
}
if(type=='wbart') {
y.train = y.train-offset
if(!is.na(sigest) && !is.na(lambda) && lambda==0) {
##no op: sigma is fixed and known at given sigest value
}
else if(is.na(lambda)) {
if(is.na(sigest)) {
if(p < n)
sigest = summary(lm(y.train~.,
data.frame(t(x.train),y.train)))$sigma
else sigest = sd(y.train)
}
qchi = qchisq(1-sigquant, sigdf)
lambda = (sigest^2)*qchi/sigdf #lambda parameter for sigma prior
} else {
sigest=sqrt(lambda)
}
if(is.na(tau.num)) {
tau=(max(y.train)-min(y.train))/(2*k*sqrt(ntree))
} else {
tau=tau.num/(k*sqrt(ntree))
}
} else {
lambda=1
sigest=1
tau=tau.num/(k*sqrt(ntree))
## tau=1-tau.interval
## if(type=='pbart')
## tau=qnorm(1-0.5*tau)/(k*sqrt(ntree))
## else if(type=='lbart')
## tau=qlogis(1-0.5*tau)/(k*sqrt(ntree))
}
## hot deck missing imputation
## must be conducted here since it would
## cause trouble with multi-threading on the C++ side
check=(np>0 && np==n)
for(i in 1:n)
for(j in 1:p) {
if(check) check=((is.na(x.train[j, i]) && is.na(x.test[j, i])) ||
(!is.na(x.train[j, i]) && !is.na(x.test[j, i]) &&
x.train[j, i]==x.test[j, i]))
while(is.na(x.train[j, i])) {
h=sample.int(n, 1)
x.train[j, i]=x.train[j, h]
}
}
if(check) x.test=x.train
else if(np>0) {
for(i in 1:np)
for(j in 1:p)
while(is.na(x.test[j, i])) {
h=sample.int(np, 1)
x.test[j, i]=x.test[j, h]
}
}
## if(hotdeck) ## warnings are suppressed with mc.gbart anyways
## warning('missing elements of x imputed with hot decking')
if(.Platform$OS.type!='unix') hostname <- FALSE
else if(hostname)
hostname <- system('hostname', intern=TRUE)
ptm <- proc.time()
res = .Call("cgbart",
ntype, ##as.integer(factor(type, levels=check))-1,
n, #number of observations in training data
p, #dimension of x
np, #number of observations in test data
x.train, #pxn training data x
y.train, #pxn training data x
x.test, #p*np test data x
ntree,
numcut,
ndpost*keepevery,
nskip,
keepevery,
power,
base,
offset,
tau,
sigdf,
lambda,
sigest,
w,
sparse,
theta,
omega,
grp,
a,
b,
rho,
augment,
printevery,
xinfo
)
res$proc.time <- proc.time()-ptm
res$hostname <- hostname
Y=t(matrix(y.train, nrow=n, ncol=ndpost))
if(type=='wbart') {
res$yhat.train.mean <- apply(res$yhat.train, 2, mean)
SD=matrix(res$sigma[-(1:nskip)], nrow=ndpost, ncol=n)
##CPO=1/apply(1/dnorm(Y, res$yhat.train, SD), 2, mean)
log.pdf=dnorm(Y, res$yhat.train, SD, TRUE)
res$sigma.mean=mean(SD[ , 1])
}
else {
if(type=='pbart') res$prob.train = pnorm(res$yhat.train)
else if(type=='lbart') res$prob.train = plogis(res$yhat.train)
##CPO=1/apply(1/dbinom(Y, 1, res$prob.train), 2, mean)
log.pdf=dbinom(Y, 1, res$prob.train, TRUE)
res$prob.train.mean <- apply(res$prob.train, 2, mean)
}
min.log.pdf=t(matrix(apply(log.pdf, 2, min), nrow=n, ncol=ndpost))
log.CPO=log(ndpost)+min.log.pdf[1, ]-
log(apply(exp(min.log.pdf-log.pdf), 2, sum))
res$LPML=sum(log.CPO)
##res$CPO=exp(log.CPO)
##res$LPML=sum(log(CPO))
if(np>0) {
if(type=='wbart')
res$yhat.test.mean <- apply(res$yhat.test, 2, mean)
else {
if(type=='pbart') res$prob.test = pnorm(res$yhat.test)
else if(type=='lbart') res$prob.test = plogis(res$yhat.test)
res$prob.test.mean <- apply(res$prob.test, 2, mean)
}
}
res$ndpost = ndpost
res$offset = offset
names(res$treedraws$cutpoints) = dimnames(x.train)[[1]]
dimnames(res$varcount)[[2]] = as.list(dimnames(x.train)[[1]])
dimnames(res$varprob)[[2]] = as.list(dimnames(x.train)[[1]])
res$varcount.mean <- apply(res$varcount, 2, mean)
res$varprob.mean <- apply(res$varprob, 2, mean)
res$rm.const <- rm.const
attr(res, 'class') <- type
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/gbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
gewekediag <- function (x, frac1 = 0.1, frac2 = 0.5)
{
if (frac1 < 0 || frac1 > 1) stop("frac1 invalid")
if (frac2 < 0 || frac2 > 1) stop("frac2 invalid")
if (frac1 + frac2 > 1) stop("start and end sequences are overlapping")
end. <- nrow(x)
xstart <- c(1, floor(end. - frac2 * (end. - 1)))
xend <- c(ceiling(1 + frac1 * (end. - 1)), end.)
y.variance <- y.mean <- vector("list", 2)
for (i in 1:2) {
y <- x[xstart[i]:xend[i], ]
y.mean[[i]] <- apply(y, 2, mean)
y.variance[[i]] <- spectrum0ar(y)$spec/(xend[i]-xstart[i]+1)
}
z <- (y.mean[[1]] - y.mean[[2]])/sqrt(y.variance[[1]] + y.variance[[2]])
out <- list(z = z, frac = c(frac1, frac2))
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/gewekediag.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
lbart=function(
x.train, y.train, x.test=matrix(0.0,0,0),
sparse=FALSE, a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0.0,0,0), usequants=FALSE,
cont=FALSE, rm.const=TRUE, tau.interval=0.95,
k=2.0, power=2.0, base=.95,
binaryOffset=NULL,
ntree=200L, numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=1L,
nkeeptrain=ndpost, nkeeptest=ndpost,
#nkeeptestmean=ndpost,
nkeeptreedraws=ndpost,
printevery=100, transposed=FALSE
##treesaslists=FALSE
)
{
#--------------------------------------------------
#data
n = length(y.train)
## if(binaryOffset!=0)
## stop('binaryOffset not supported by lbart')
if(length(binaryOffset)==0) binaryOffset=qlogis(mean(y.train))
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
cont=cont, xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
if(n!=ncol(x.train))
stop('The length of y.train and the number of rows in x.train must be identical')
p = nrow(x.train)
np = ncol(x.test)
if(length(rho)==0) rho <- p
if(length(rm.const)==0) rm.const <- 1:p
if(tau.interval>0.5) tau.interval=1-tau.interval
tau=qlogis(1-0.5*tau.interval)/(k*sqrt(ntree))
#--------------------------------------------------
#set nkeeps for thinning
if((nkeeptrain!=0) & ((ndpost %% nkeeptrain) != 0)) {
nkeeptrain=ndpost
cat('*****nkeeptrain set to ndpost\n')
}
if((nkeeptest!=0) & ((ndpost %% nkeeptest) != 0)) {
nkeeptest=ndpost
cat('*****nkeeptest set to ndpost\n')
}
## if((nkeeptestmean!=0) & ((ndpost %% nkeeptestmean) != 0)) {
## nkeeptestmean=ndpost
## cat('*****nkeeptestmean set to ndpost\n')
## }
if((nkeeptreedraws!=0) & ((ndpost %% nkeeptreedraws) != 0)) {
nkeeptreedraws=ndpost
cat('*****nkeeptreedraws set to ndpost\n')
}
#--------------------------------------------------
#prior
## nu=sigdf
## if(is.na(lambda)) {
## if(is.na(sigest)) {
## if(p < n) {
## df = data.frame(t(x.train),y.train)
## lmf = lm(y.train~.,df)
## rm(df)
## sigest = summary(lmf)$sigma
## } else {
## sigest = sd(y.train)
## }
## }
## qchi = qchisq(1.0-sigquant,nu)
## lambda = (sigest*sigest*qchi)/nu #lambda parameter for sigma prior
## }
## if(is.na(sigmaf)) {
## tau=(max(y.train)-min(y.train))/(2*k*sqrt(ntree));
## } else {
## tau = sigmaf/sqrt(ntree)
## }
#--------------------------------------------------
#call
res = .Call("clbart",
n, #number of observations in training data
p, #dimension of x
np, #number of observations in test data
x.train, #p*n training data x
as.integer(2*y.train-1), #n*1 training data y
x.test, #p*np test data x
ntree,
numcut,
ndpost*keepevery,
nskip,
power,
base,
binaryOffset,
tau,
sparse,
a,
b,
rho,
augment,
nkeeptrain,
nkeeptest,
#nkeeptestmean,
nkeeptreedraws,
printevery,
##treesaslists,
xinfo
)
if(nkeeptrain>0) {
##res$yhat.train.mean <- NULL
##res$yhat.train.mean = res$yhat.train.mean+binaryOffset
res$yhat.train = res$yhat.train+binaryOffset
res$prob.train = plogis(res$yhat.train)
res$prob.train.mean <- apply(res$prob.train, 2, mean)
} else {
res$yhat.train <- NULL
##res$yhat.train.mean <- NULL
}
if(np>0) {
##res$yhat.test.mean <- NULL
##res$yhat.test.mean = res$yhat.test.mean+binaryOffset
res$yhat.test = res$yhat.test+binaryOffset
res$prob.test = plogis(res$yhat.test)
res$prob.test.mean <- apply(res$prob.test, 2, mean)
} else {
res$yhat.test <- NULL
##res$yhat.test.mean <- NULL
}
if(nkeeptreedraws>0)
names(res$treedraws$cutpoints) = dimnames(x.train)[[1]]
dimnames(res$varcount)[[2]] = as.list(dimnames(x.train)[[1]])
dimnames(res$varprob)[[2]] = as.list(dimnames(x.train)[[1]])
res$varcount.mean <- apply(res$varcount, 2, mean)
res$varprob.mean <- apply(res$varprob, 2, mean)
res$binaryOffset=binaryOffset
res$rm.const <- rm.const
attr(res, 'class') <- 'lbart'
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/lbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mbart <- function(
x.train, y.train,
x.test=matrix(0,0,0), type='pbart',
ntype=as.integer(
factor(type,
levels=c('wbart', 'pbart', 'lbart'))),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
k=2, power=2, base=0.95,
##sigest=NA, sigdf=3, sigquant=0.90, lambda=NA,
tau.num=c(NA, 3, 6)[ntype],
offset=NULL, ##w=rep(1, length(y.train)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
hostname=FALSE,
mc.cores = 2L, nice = 19L, seed = 99L
)
{
if(type=='wbart' || is.na(ntype))
stop("type argument must be set to either 'pbart' or 'lbart'")
cats <- unique(sort(y.train))
K <- length(cats)
if(K<2)
stop("there must be at least 2 categories")
L=length(offset)
if(!(L %in% c(0, K)))
stop(paste0("length of offset argument must be 0 or ", K))
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
post <- list()
post$K <- K
post$cats <- cats
N <- length(y.train)
P <- nrow(x.train) ## transposed
## post$yhat.train <- matrix(nrow=ndpost, ncol=N*K)
## post$prob.train <- matrix(nrow=ndpost, ncol=N*K)
## post$comp.train <- matrix(nrow=ndpost, ncol=N*K)
if(length(x.test)) {
Q <- ncol(x.test) ## transposed
post$yhat.test <- matrix(nrow=ndpost, ncol=Q*K)
post$prob.test <- matrix(nrow=ndpost, ncol=Q*K)
post$comp.test <- matrix(nrow=ndpost, ncol=Q*K)
}
else Q <- 0
L <- K-1
post$varcount <- as.list(1:L)
post$varprob <- as.list(1:L)
##post$varcount <- array(dim=c(ndpost, P, L))
post$varcount.mean <- matrix(nrow=L, ncol=P)
##post$varprob <- array(dim=c(ndpost, P, L))
post$varprob.mean <- matrix(nrow=L, ncol=P)
post$offset <- 0
post$treedraws <- list()
post$treedraws$trees <- as.list(1:L)
##post$rm.const <- as.list(1:L)
post.list <- as.list(1:L)
for(h in 1:K) {
cond <- which(y.train>=cats[h])
if(h<K) {
post.list[[h]] <-
gbart(x.train=x.train[ , cond],
y.train=(y.train[cond]==h)*1,
x.test=x.test,
type=type, ntype=ntype,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
rm.const=rm.const,
k=k, power=power, base=base,
tau.num=tau.num,
offset=offset[h],
ntree=ntree, numcut=numcut,
ndpost=ndpost, nskip=nskip,
keepevery=keepevery,
printevery=printevery, transposed=TRUE,
hostname=hostname)
if(attr(post.list[[h]], 'class')!=type)
return(post.list[[h]])
}
## for(i in 1:N) {
## j <- (i-1)*K+h
## if(i %in% cond) {
## l <- which(i==cond)
## post$yhat.train[ , j] <- post.list[[h]]$yhat.train[ , l]
## if(h==1) {
## post$comp.train[ , j] <-
## 1-post.list[[h]]$prob.train[ , l]
## post$prob.train[ , j] <- post.list[[h]]$prob.train[ , l]
## } else {
## post$comp.train[ , j] <- post$comp.train[ , j-1]*
## (1-post.list[[h]]$prob.train[ , l])
## post$prob.train[ , j] <- post$comp.train[ , j-1]*
## post.list[[h]]$prob.train[ , l]
## }
## }
## else {
## post$yhat.train[ , j] <- -Inf
## post$prob.train[ , j] <- 0
## post$comp.train[ , j] <- 1
## }
## }
if(Q>0)
for(i in 1:Q) {
j <- (i-1)*K+h
if(h==K)
post$prob.test[ , j] <- post$comp.test[ , j-1]
else {
post$yhat.test[ , j] <- post.list[[h]]$yhat.test[ , i]
if(h==1) {
post$comp.test[ , j] <-
1-post.list[[h]]$prob.test[ , i]
post$prob.test[ , j] <- post.list[[h]]$prob.test[ , i]
}
else {
post$comp.test[ , j] <- post$comp.test[ , j-1]*
(1-post.list[[h]]$prob.test[ , i])
post$prob.test[ , j] <- post$comp.test[ , j-1]*
post.list[[h]]$prob.test[ , i]
}
}
}
if(h<K) {
post$varcount[[h]] <- post.list[[h]]$varcount
post$varprob[[h]] <- post.list[[h]]$varprob
for(j in 1:P) {
##post$varcount[ , j, h] <- post.list[[h]]$varcount[ , j]
post$varcount.mean[h, j] <- post.list[[h]]$varcount.mean[j]
##post$varprob[ , j, h] <- post.list[[h]]$varprob[ , j]
post$varprob.mean[h, j] <- post.list[[h]]$varprob.mean[j]
}
post$offset[h] <- post.list[[h]]$offset
##post$rm.const[[h]] <- post.list[[h]]$rm.const
post$treedraws$trees[[h]] <- post.list[[h]]$treedraws$trees
}
}
post$treedraws$cutpoints <- post.list[[1]]$treedraws$cutpoints
dimnames(post$varcount.mean)[[2]] <- dimnames(post$varcount[[1]])[[2]]
dimnames(post$varprob.mean)[[2]] <- dimnames(post$varprob[[1]])[[2]]
post$rm.const <- post.list[[1]]$rm.const
post$type <- type
post$comp.test <- NULL
## post$prob.train.mean <- apply(post$prob.train, 2, mean)
## post$comp.train.mean <- apply(post$comp.train, 2, mean)
if(Q>0) {
post$prob.test.mean <- apply(post$prob.test, 2, mean)
##post$comp.test.mean <- apply(post$comp.test, 2, mean)
}
attr(post, 'class') <- 'mbart'
return(post)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mbart2 <- function(
x.train, y.train,
x.test=matrix(0,0,0), type='lbart',
ntype=as.integer(
factor(type,
levels=c('wbart', 'pbart', 'lbart'))),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
k=2, power=2, base=0.95,
##sigest=NA, sigdf=3, sigquant=0.90, lambda=NA,
tau.num=c(NA, 3, 6)[ntype],
offset=NULL, ##w=rep(1, length(y.train)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
hostname=FALSE,
mc.cores = 2L, nice = 19L, seed = 99L
)
{
if(type=='wbart' || is.na(ntype))
stop("type argument must be set to either 'pbart' or 'lbart'")
cats <- unique(sort(y.train))
K <- length(cats)
if(K<2)
stop("there must be at least 2 categories")
L=length(offset)
if(!(L %in% c(0, K)))
stop(paste0("length of offset argument must be 0 or ", K))
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
post <- list()
post$K <- K
post$cats <- cats
N <- length(y.train)
P <- nrow(x.train) ## transposed
post$yhat.train <- matrix(nrow=ndpost, ncol=N*K)
post$prob.train <- matrix(nrow=ndpost, ncol=N*K)
post$tot.train <- matrix(0, nrow=ndpost, ncol=N)
if(length(x.test)) {
Q <- ncol(x.test) ## transposed
post$yhat.test <- matrix(nrow=ndpost, ncol=Q*K)
post$prob.test <- matrix(nrow=ndpost, ncol=Q*K)
post$tot.test <- matrix(0, nrow=ndpost, ncol=Q)
}
else Q <- 0
post$varcount <- as.list(1:K)
post$varprob <- as.list(1:K)
post$varcount.mean <- matrix(nrow=K, ncol=P)
post$varprob.mean <- matrix(nrow=K, ncol=P)
post$offset <- 0
post$treedraws <- list()
post$treedraws$trees <- as.list(1:K)
post.list <- as.list(1:K)
for(h in 1:K) {
post.list[[h]] <-
gbart(x.train=x.train,
y.train=(y.train==h)*1,
x.test=x.test,
type=type, ntype=ntype,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
rm.const=rm.const,
k=k, power=power, base=base,
tau.num=tau.num,
offset=offset[h],
ntree=ntree, numcut=numcut,
ndpost=ndpost, nskip=nskip,
keepevery=keepevery,
printevery=printevery, transposed=TRUE,
hostname=hostname)
if(attr(post.list[[h]], 'class')!=type) return(post.list[[h]])
for(i in 1:N) {
j <- (i-1)*K+h
post$yhat.train[ , j] <- post.list[[h]]$yhat.train[ , i]
post$tot.train[ , i] <-
post$tot.train[ , i]+exp(post$yhat.train[ , j])
if(h==K)
for(j in (i-1)*K+1:K)
post$prob.train[ , j] <-
exp(post$yhat.train[ , j])/post$tot.train[ , i]
}
if(Q>0) {
for(i in 1:Q) {
j <- (i-1)*K+h
post$yhat.test[ , j] <- post.list[[h]]$yhat.test[ , i]
post$tot.test[ , i] <-
post$tot.test[ , i]+exp(post$yhat.test[ , j])
if(h==K)
for(j in (i-1)*K+1:K)
post$prob.test[ , j] <-
exp(post$yhat.test[ , j])/post$tot.test[ , i]
}
}
post$varcount[[h]] <- post.list[[h]]$varcount
post$varprob[[h]] <- post.list[[h]]$varprob
for(j in 1:P) {
##post$varcount[ , j, h] <- post.list[[h]]$varcount[ , j]
post$varcount.mean[h, j] <- post.list[[h]]$varcount.mean[j]
##post$varprob[ , j, h] <- post.list[[h]]$varprob[ , j]
post$varprob.mean[h, j] <- post.list[[h]]$varprob.mean[j]
}
post$offset[h] <- post.list[[h]]$offset
##post$rm.const[[h]] <- post.list[[h]]$rm.const
post$treedraws$trees[[h]] <- post.list[[h]]$treedraws$trees
}
post$treedraws$cutpoints <- post.list[[1]]$treedraws$cutpoints
dimnames(post$varcount.mean)[[2]] <- dimnames(post$varcount[[1]])[[2]]
dimnames(post$varprob.mean)[[2]] <- dimnames(post$varprob[[1]])[[2]]
post$rm.const <- post.list[[1]]$rm.const
post$type <- type
post$prob.train.mean <- apply(post$prob.train, 2, mean)
if(Q>0) {
post$prob.test.mean <- apply(post$prob.test, 2, mean)
##post$comp.test.mean <- apply(post$comp.test, 2, mean)
}
post$tot.train <- NULL
post$tot.test <- NULL
attr(post, 'class') <- 'mbart2'
return(post)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mbart2.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.abart <- function(
x.train, times, delta,
x.test=matrix(0,0,0), K=100,
type='abart', ntype=1,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
sigest=NA, sigdf=3, sigquant=0.90,
k=2, power=2, base=0.95,
##sigmaf=NA,
lambda=NA, tau.num=c(NA, 3, 6)[ntype],
##tau.interval=0.9973,
offset=NULL, w=rep(1, length(times)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
mc.cores = 2L, nice = 19L, seed = 99L
)
{
if(type!='abart') stop('type must be "abart"')
if(ntype!=1) stop('ntype must be 1')
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
mc.ndpost <- ceiling(ndpost/mc.cores)
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
abart(x.train=x.train, times=times, delta=delta,
x.test=x.test, K=K, type=type, ntype=ntype,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
rm.const=rm.const,
sigest=sigest, sigdf=sigdf, sigquant=sigquant,
k=k, power=power, base=base,
##sigmaf=sigmaf,
lambda=lambda, tau.num=tau.num,
##tau.interval=tau.interval,
offset=offset,
w=w, ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip,
keepevery=keepevery, printevery=printevery,
transposed=TRUE)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list <- parallel::mccollect()
post <- post.list[[1]]
if(mc.cores==1 | attr(post, 'class')!=type) return(post)
else {
if(class(rm.const)[1]!='logical') post$rm.const <- rm.const
post$ndpost <- mc.cores*mc.ndpost
p <- nrow(x.train[post$rm.const, ])
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree),
' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost), ' ',
as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees)
keeptest <- length(x.test)>0
for(i in 2:mc.cores) {
post$sigma <- cbind(post$sigma, post.list[[i]]$sigma)
post$yhat.train <- rbind(post$yhat.train,
post.list[[i]]$yhat.train)
post$surv.train <- rbind(post$surv.train,
post.list[[i]]$surv.train)
if(keeptest) {
post$yhat.test <- rbind(post$yhat.test,
post.list[[i]]$yhat.test)
post$surv.test <- rbind(post$surv.test,
post.list[[i]]$surv.test)
}
post$varcount <- rbind(post$varcount, post.list[[i]]$varcount)
post$varprob <- rbind(post$varprob, post.list[[i]]$varprob)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[i]]$treedraws$trees)))
post$proc.time['elapsed'] <- max(post$proc.time['elapsed'],
post.list[[i]]$proc.time['elapsed'])
for(j in 1:5)
if(j!=3)
post$proc.time[j] <- post$proc.time[j]+post.list[[i]]$proc.time[j]
}
if(type=='abart') {
post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
post$surv.train.mean <- apply(post$surv.train, 2, mean)
if(keeptest) {
post$yhat.test.mean <- apply(post$yhat.test, 2, mean)
post$surv.test.mean <- apply(post$surv.test, 2, mean)
}
} else {
post$prob.train.mean <- apply(post$prob.train, 2, mean)
if(keeptest)
post$prob.test.mean <- apply(post$prob.test, 2, mean)
}
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
attr(post, 'class') <- type
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.abart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.cores.openmp=function() .Call("mc_cores_openmp")
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.cores.openmp.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.crisk.bart <- function(
x.train = matrix(0,0,0), y.train=NULL,
x.train2 = x.train, y.train2=NULL,
times=NULL, delta=NULL, K=NULL,
x.test = matrix(0,0,0), x.test2 = x.test, cond=NULL,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL, rho2=NULL,
xinfo=matrix(0,0,0), xinfo2=matrix(0,0,0), usequants=FALSE,
##cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2, ## BEWARE: do NOT use k for other purposes below
power = 2, base = 0.95,
offset = NULL, offset2 = NULL,
tau.num=c(NA, 3, 6)[ntype], ##tau.num2=c(NA, 3, 6)[ntype],
##binaryOffset = NULL, binaryOffset2 = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L,
keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptestmean=ndpost,
##nkeeptreedraws=ndpost,
printevery=100L,
##treesaslists=FALSE,
##keeptrainfits=TRUE,
id=NULL, ## crisk.bart only
seed = 99L, mc.cores = 2L, nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train2 <- bartModelMatrix(x.train2)
x.test2 <- bartModelMatrix(x.test2)
x.train <- bartModelMatrix(x.train)
x.test <- bartModelMatrix(x.test)
if(length(y.train)==0) {
pre <- crisk.pre.bart(times, delta, x.train, x.test,
x.train2, x.test2, K=K)
y.train <- pre$y.train
x.train <- pre$tx.train
x.test <- pre$tx.test
y.train2 <- pre$y.train2
x.train2 <- pre$tx.train2
x.test2 <- pre$tx.test2
times <- pre$times
K <- pre$K
if(length(cond)==0) cond <- pre$cond
##if(length(binaryOffset)==0) binaryOffset <- pre$binaryOffset
##if(length(binaryOffset2)==0) binaryOffset2 <- pre$binaryOffset2
}
else {
if(length(x.train)==0 | length(x.train2)==0)
stop('both x.train and x.train2 must be provided')
if(nrow(x.train)!=nrow(x.train2))
stop('number of rows in x.train and x.train2 must be equal')
##if(length(binaryOffset)==0) binaryOffset <- 0
##if(length(binaryOffset2)==0) binaryOffset2 <- 0
times <- unique(sort(x.train[ , 1]))
K <- length(times)
}
H <- 1
Mx <- 2^31-1
Nx <- 2*max(nrow(x.train), nrow(x.test))
if(Nx>Mx%/%ndpost) {
H <- ceiling(ndpost / (Mx %/% Nx))
ndpost <- ndpost %/% H
##nrow*ndpost>2Gi: due to the 2Gi limit in sendMaster
##(unless this limit was increased): reducing ndpost
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) {
message('The number of cores requested, ', mc.cores,
',\n exceeds the number of cores detected via detectCores() ',
'reducing to ', mc.cores.detected)
mc.cores <- mc.cores.detected
}
mc.ndpost <- ceiling(ndpost/mc.cores)
## mc.ndpost <- ((ndpost %/% mc.cores) %/% keepevery)*keepevery
## while(mc.ndpost*mc.cores<ndpost) mc.ndpost <- mc.ndpost+keepevery
## mc.nkeep <- mc.ndpost %/% keepevery
post.list <- list()
for(h in 1:H) {
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
crisk.bart(x.train=x.train, y.train=y.train,
x.train2=x.train2, y.train2=y.train2,
x.test=x.test, x.test2=x.test2, cond=cond,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho, rho2=rho2,
xinfo=xinfo, xinfo2=xinfo2, usequants=usequants,
##cont=cont,
rm.const=rm.const, type=type,
k=k, power=power, base=base,
##binaryOffset=binaryOffset,
##binaryOffset2=binaryOffset2,
offset=offset, offset2=offset2,
tau.num=tau.num, ##tau.num2=tau.num2,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip,
keepevery = keepevery,
##nkeeptrain=mc.ndpost, nkeeptest=mc.ndpost,
##nkeeptestmean=mc.ndpost,
##nkeeptreedraws=mc.ndpost,
printevery=printevery)},
##treesaslists=FALSE,
##keeptrainfits=TRUE)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list[[h]] <- parallel::mccollect()
}
if((H==1 & mc.cores==1) | attr(post.list[[1]][[1]], 'class')!='criskbart')
return(post.list[[1]][[1]])
else {
for(h in 1:H) for(i in mc.cores:1) {
if(h==1 & i==mc.cores) {
post <- post.list[[1]][[mc.cores]]
post$ndpost <- H*mc.cores*mc.ndpost
p <- ncol(x.train[ , post$rm.const])
old.text <- paste0(as.character(mc.ndpost), ' ',
as.character(ntree), ' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost),
' ', as.character(ntree),
' ', as.character(p)),
post$treedraws$trees)
p <- ncol(x.train2[ , post$rm.const2])
old.text <- paste0(as.character(mc.ndpost), ' ',
as.character(ntree), ' ', as.character(p))
old.stop2 <- nchar(old.text)
post$treedraws2$trees <- sub(old.text,
paste0(as.character(post$ndpost),
' ', as.character(ntree),
' ', as.character(p)),
post$treedraws2$trees)
}
else {
if(length(x.test)>0) {
post$yhat.test <- rbind(post$yhat.test,
post.list[[h]][[i]]$yhat.test)
post$yhat.test2 <- rbind(post$yhat.test2,
post.list[[h]][[i]]$yhat.test2)
post$prob.test <- rbind(post$prob.test,
post.list[[h]][[i]]$prob.test)
post$prob.test2 <- rbind(post$prob.test2,
post.list[[h]][[i]]$prob.test2)
post$cif.test <- rbind(post$cif.test,
post.list[[h]][[i]]$cif.test)
post$cif.test2 <- rbind(post$cif.test2,
post.list[[h]][[i]]$cif.test2)
post$surv.test <- rbind(post$surv.test,
post.list[[h]][[i]]$surv.test)
}
post$varcount <- rbind(post$varcount,
post.list[[h]][[i]]$varcount)
post$varcount2 <- rbind(post$varcount2,
post.list[[h]][[i]]$varcount2)
post$varprob <- rbind(post$varprob,
post.list[[h]][[i]]$varprob)
post$varprob2 <- rbind(post$varprob2,
post.list[[h]][[i]]$varprob2)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[h]][[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[h]][[i]]$treedraws$trees)))
post$treedraws2$trees <- paste0(post$treedraws2$trees,
substr(post.list[[h]][[i]]$treedraws2$trees, old.stop2+2,
nchar(post.list[[h]][[i]]$treedraws2$trees)))
## if(treesaslists) {
## post$treedraws$lists <-
## c(post$treedraws$lists, post.list[[h]][[i]]$treedraws$lists)
## post$treedraws2$lists <-
## c(post$treedraws2$lists, post.list[[h]][[i]]$treedraws2$lists)
## }
}
post.list[[h]][[i]] <- NULL
}
if(length(x.test)>0) {
post$prob.test.mean <- apply(post$prob.test, 2, mean)
post$prob.test2.mean <- apply(post$prob.test2, 2, mean)
post$cif.test.mean <- apply(post$cif.test, 2, mean)
post$cif.test2.mean <- apply(post$cif.test2, 2, mean)
post$surv.test.mean <- apply(post$surv.test, 2, mean)
}
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varcount2.mean <- apply(post$varcount2, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
post$varprob2.mean <- apply(post$varprob2, 2, mean)
attr(post, 'class') <- 'criskbart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.crisk.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.crisk.pwbart <- function(
x.test, #x.test for cause 1
x.test2, #x.test for cause 2
treedraws, #$treedraws for cause 1 from crisk.bart/mc.crisk.bart
treedraws2, #$treedraws for cause 2
binaryOffset=0, #mean to add on for cause 1
binaryOffset2=0, #mean to add on for cause 2
mc.cores=2L,
type='pbart',
transposed=FALSE,
nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
if(length(x.test)==0 | length(x.test2)==0)
stop('both x.test and x.test2 must be provided')
if(nrow(x.test)!=nrow(x.test2))
stop('number of rows in x.test and x.test2 must be equal')
if(!transposed) {
x.test <- t(bartModelMatrix(x.test))
x.test2 <- t(bartModelMatrix(x.test2))
}
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
p <- length(treedraws2$cutpoints)
if(p!=nrow(x.test2))
stop(paste0('The number of columns in x.test2 must be equal to ', p))
K <- ncol(x.test)
k <- K%/%mc.cores
j <- K
for(i in 1:mc.cores) {
if(i==mc.cores) h <- 1
else h <- j-k
parallel::mcparallel({psnice(value=nice);
pwbart(x.test[ , h:j], treedraws, binaryOffset, 1, TRUE)},
silent=(i!=1))
j <- h-1
}
yhat.test.list <- parallel::mccollect()
j <- K
for(i in 1:mc.cores) {
if(i==mc.cores) h <- 1
else h <- j-k
parallel::mcparallel({psnice(value=nice);
pwbart(x.test2[ , h:j], treedraws2, binaryOffset2, 1, TRUE)},
silent=(i!=1))
j <- h-1
}
yhat.test2.list <- parallel::mccollect()
pred <- list()
pred$binaryOffset <- binaryOffset
pred$binaryOffset2 <- binaryOffset2
x.test <- t(x.test)
pred$tx.test <- x.test
pred$tx.test2 <- t(x.test2)
times <- unique(sort(x.test[ , 1]))
pred$times <- times
K <- length(times)
pred$K <- K
pred$yhat.test <- yhat.test.list[[1]]
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
pred$yhat.test2 <- yhat.test2.list[[1]]
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
if(mc.cores>1)
for(i in 2:mc.cores) {
pred$yhat.test <- cbind(pred$yhat.test, yhat.test.list[[i]])
pred$yhat.test2 <- cbind(pred$yhat.test2, yhat.test2.list[[i]])
}
H <- nrow(x.test)/K ## the number of different settings
if(type=='pbart') {
pred$prob.test <- pnorm(pred$yhat.test)
pred$prob.test2 <- pnorm(pred$yhat.test2)
}
else if(type=='lbart') {
pred$prob.test <- plogis(pred$yhat.test)
pred$prob.test2 <- plogis(pred$yhat.test2)
}
pred$surv.test <- (1-pred$prob.test)*(1-pred$prob.test2)
pred$prob.test2 <- (1-pred$prob.test)*pred$prob.test2
pred$cif.test <- pred$prob.test
pred$cif.test2 <- pred$prob.test2
for(h in 1:H)
for(j in 2:K) {
l <- K*(h-1)+j
pred$cif.test[ , l] <- pred$cif.test[ , l-1]+
pred$surv.test[ , l-1]*pred$cif.test[ , l]
pred$cif.test2[ , l] <- pred$cif.test2[ , l-1]+
pred$surv.test[ , l-1]*pred$cif.test2[ , l]
pred$surv.test[ , l] <- pred$surv.test[ , l-1]*
pred$surv.test[ , l]
}
pred$cif.test.mean <- apply(pred$cif.test, 2, mean)
pred$cif.test2.mean <- apply(pred$cif.test2, 2, mean)
pred$surv.test.mean <- apply(pred$surv.test, 2, mean)
attr(pred, 'class') <- 'criskbart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.crisk.pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.crisk2.bart <- function(
x.train = matrix(0,0,0), y.train=NULL,
x.train2 = x.train, y.train2=NULL,
times=NULL, delta=NULL, K=NULL,
x.test = matrix(0,0,0), x.test2 = x.test,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL, rho2=NULL,
xinfo=matrix(0,0,0), xinfo2=matrix(0,0,0), usequants=FALSE,
##cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2, ## BEWARE: do NOT use k for other purposes below
power = 2, base = 0.95,
offset = NULL, offset2 = NULL,
tau.num=c(NA, 3, 6)[ntype],
##binaryOffset = NULL, binaryOffset2 = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L,
keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptestmean=ndpost,
##nkeeptreedraws=ndpost,
printevery=100L,
##treesaslists=FALSE,
##keeptrainfits=TRUE,
id=NULL, ## crisk2.bart only
seed = 99L, mc.cores = 2L, nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train2 <- bartModelMatrix(x.train2)
x.test2 <- bartModelMatrix(x.test2)
x.train <- bartModelMatrix(x.train)
x.test <- bartModelMatrix(x.test)
if(length(y.train)==0) {
pre <- surv.pre.bart(times, delta, x.train, x.test, K=K)
pre2 <- surv.pre.bart(times, delta, x.train2, x.test2, K=K)
y.train <- pre$y.train
x.train <- pre$tx.train
x.test <- pre$tx.test
y.train2 <- 1*(y.train[y.train>0]==1)
x.train2 <- cbind(pre2$tx.train[y.train>0, ])
x.test2 <- pre2$tx.test
y.train <- 1*(y.train>0)
times <- pre$times
K <- pre$K
}
else {
if(length(x.train)==0 | length(x.train2)==0)
stop('both x.train and x.train2 must be provided')
## if(nrow(x.train)!=nrow(x.train2))
## stop('number of rows in x.train and x.train2 must be equal')
times <- unique(sort(x.train[ , 1]))
K <- length(times)
}
H <- 1
Mx <- 2^31-1
Nx <- 2*max(nrow(x.train), nrow(x.test))
if(Nx>Mx%/%ndpost) {
H <- ceiling(ndpost / (Mx %/% Nx))
ndpost <- ndpost %/% H
##nrow*ndpost>2Gi: due to the 2Gi limit in sendMaster
##(unless this limit was increased): reducing ndpost
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) {
message('The number of cores requested, ', mc.cores,
',\n exceeds the number of cores detected via detectCores() ',
'reducing to ', mc.cores.detected)
mc.cores <- mc.cores.detected
}
mc.ndpost <- ceiling(ndpost/mc.cores)
post.list <- list()
for(h in 1:H) {
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
crisk2.bart(x.train=x.train, y.train=y.train,
x.train2=x.train2, y.train2=y.train2,
x.test=x.test, x.test2=x.test2,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment,
rho=rho, rho2=rho2,
xinfo=xinfo, xinfo2=xinfo2, usequants=usequants,
##cont=cont,
rm.const=rm.const, type=type,
k=k, power=power, base=base,
offset=offset, offset2=offset2, tau.num=tau.num,
##binaryOffset=binaryOffset,
##binaryOffset2=binaryOffset2,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip,
keepevery = keepevery,
##nkeeptrain=mc.ndpost, nkeeptest=mc.ndpost,
##nkeeptreedraws=mc.ndpost,
printevery=printevery)},
##keeptrainfits=TRUE)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list[[h]] <- parallel::mccollect()
}
if((H==1 & mc.cores==1) |
attr(post.list[[1]][[1]], 'class')!='crisk2bart')
return(post.list[[1]][[1]])
else {
for(h in 1:H) for(i in mc.cores:1) {
if(h==1 & i==mc.cores) {
post <- post.list[[1]][[mc.cores]]
post$ndpost <- H*mc.cores*mc.ndpost
p <- ncol(x.train[ , post$rm.const])
old.text <- paste0(as.character(mc.ndpost), ' ',
as.character(ntree), ' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost),
' ', as.character(ntree),
' ', as.character(p)),
post$treedraws$trees)
p <- ncol(x.train2[ , post$rm.const2])
old.text <- paste0(as.character(mc.ndpost), ' ',
as.character(ntree), ' ', as.character(p))
old.stop2 <- nchar(old.text)
post$treedraws2$trees <- sub(old.text,
paste0(as.character(post$ndpost),
' ', as.character(ntree),
' ', as.character(p)),
post$treedraws2$trees)
}
else {
if(length(x.test)>0) {
post$yhat.test <- rbind(post$yhat.test,
post.list[[h]][[i]]$yhat.test)
post$yhat.test2 <- rbind(post$yhat.test2,
post.list[[h]][[i]]$yhat.test2)
post$prob.test <- rbind(post$prob.test,
post.list[[h]][[i]]$prob.test)
post$prob.test2 <- rbind(post$prob.test2,
post.list[[h]][[i]]$prob.test2)
post$cif.test <- rbind(post$cif.test,
post.list[[h]][[i]]$cif.test)
post$cif.test2 <- rbind(post$cif.test2,
post.list[[h]][[i]]$cif.test2)
post$surv.test <- rbind(post$surv.test,
post.list[[h]][[i]]$surv.test)
}
post$varcount <- rbind(post$varcount,
post.list[[h]][[i]]$varcount)
post$varcount2 <- rbind(post$varcount2,
post.list[[h]][[i]]$varcount2)
post$varprob <- rbind(post$varprob,
post.list[[h]][[i]]$varprob)
post$varprob2 <- rbind(post$varprob2,
post.list[[h]][[i]]$varprob2)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[h]][[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[h]][[i]]$treedraws$trees)))
post$treedraws2$trees <- paste0(post$treedraws2$trees,
substr(post.list[[h]][[i]]$treedraws2$trees, old.stop2+2,
nchar(post.list[[h]][[i]]$treedraws2$trees)))
}
post.list[[h]][[i]] <- NULL
}
if(length(x.test)>0) {
post$prob.test.mean <- apply(post$prob.test, 2, mean)
post$prob.test2.mean <- apply(post$prob.test2, 2, mean)
post$cif.test.mean <- apply(post$cif.test, 2, mean)
post$cif.test2.mean <- apply(post$cif.test2, 2, mean)
post$surv.test.mean <- apply(post$surv.test, 2, mean)
}
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varcount2.mean <- apply(post$varcount2, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
post$varprob2.mean <- apply(post$varprob2, 2, mean)
attr(post, 'class') <- 'crisk2bart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.crisk2.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.crisk2.pwbart <- function(
x.test, #x.test for an event from either cause
x.test2, #x.test to discriminate between cause 1 and
treedraws, #$treedraws for an event from crisk2.bart/mc.crisk2.bart
treedraws2, #$treedraws for to discriminate
binaryOffset=0, #mean offset to add for an event
binaryOffset2=0, #mean offset to add to discriminate
mc.cores=2L,
type='pbart',
transposed=FALSE,
nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
if(length(x.test)==0 | length(x.test2)==0)
stop('both x.test and x.test2 must be provided')
if(nrow(x.test)!=nrow(x.test2))
stop('number of rows in x.test and x.test2 must be equal')
if(!transposed) {
x.test <- t(bartModelMatrix(x.test))
x.test2 <- t(bartModelMatrix(x.test2))
}
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
p <- length(treedraws2$cutpoints)
if(p!=nrow(x.test2))
stop(paste0('The number of columns in x.test2 must be equal to ', p))
K <- ncol(x.test)
k <- K%/%mc.cores
j <- K
for(i in 1:mc.cores) {
if(i==mc.cores) h <- 1
else h <- j-k
parallel::mcparallel({psnice(value=nice);
pwbart(x.test[ , h:j], treedraws, binaryOffset, 1, TRUE)},
silent=(i!=1))
j <- h-1
}
yhat.test.list <- parallel::mccollect()
j <- K
for(i in 1:mc.cores) {
if(i==mc.cores) h <- 1
else h <- j-k
parallel::mcparallel({psnice(value=nice);
pwbart(x.test2[ , h:j], treedraws2, binaryOffset2, 1, TRUE)},
silent=(i!=1))
j <- h-1
}
yhat.test2.list <- parallel::mccollect()
pred <- list()
pred$binaryOffset <- binaryOffset
pred$binaryOffset2 <- binaryOffset2
x.test <- t(x.test)
pred$tx.test <- x.test
pred$tx.test2 <- t(x.test2)
times <- unique(sort(x.test[ , 1]))
pred$times <- times
K <- length(times)
pred$K <- K
pred$yhat.test <- yhat.test.list[[1]]
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
pred$yhat.test2 <- yhat.test2.list[[1]]
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
if(mc.cores>1)
for(i in 2:mc.cores) {
pred$yhat.test <- cbind(pred$yhat.test, yhat.test.list[[i]])
pred$yhat.test2 <- cbind(pred$yhat.test2, yhat.test2.list[[i]])
}
H <- nrow(x.test)/K ## the number of different settings
if(type=='pbart') {
pred$prob.test <- pnorm(pred$yhat.test)
pred$prob.test2 <- pnorm(pred$yhat.test2)
}
else if(type=='lbart') {
pred$prob.test <- plogis(pred$yhat.test)
pred$prob.test2 <- plogis(pred$yhat.test2)
}
pred$surv.test <- 1-pred$prob.test
#pred$prob.test2 <- (1-pred$prob.test)*pred$prob.test2
pred$cif.test <- pred$prob.test*pred$prob.test2
pred$cif.test2 <- pred$prob.test*(1-pred$prob.test2)
for(h in 1:H)
for(j in 2:K) {
l <- K*(h-1)+j
pred$cif.test[ , l] <- pred$cif.test[ , l-1]+
pred$surv.test[ , l-1]*pred$cif.test[ , l]
pred$cif.test2[ , l] <- pred$cif.test2[ , l-1]+
pred$surv.test[ , l-1]*pred$cif.test2[ , l]
pred$surv.test[ , l] <- pred$surv.test[ , l-1]*
pred$surv.test[ , l]
}
pred$cif.test.mean <- apply(pred$cif.test, 2, mean)
pred$cif.test2.mean <- apply(pred$cif.test2, 2, mean)
pred$surv.test.mean <- apply(pred$surv.test, 2, mean)
attr(pred, 'class') <- 'crisk2bart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.crisk2.pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.gbart <- function(
x.train, y.train,
x.test=matrix(0,0,0), type='wbart',
ntype=as.integer(
factor(type,
levels=c('wbart', 'pbart', 'lbart'))),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
sigest=NA, sigdf=3, sigquant=0.90,
k=2, power=2, base=0.95,
##sigmaf=NA,
lambda=NA, tau.num=c(NA, 3, 6)[ntype],
##tau.interval=0.9973,
offset=NULL, w=rep(1, length(y.train)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
hostname=FALSE,
mc.cores = 2L, nice = 19L, seed = 99L
)
{
if(is.na(ntype))
stop("type argument must be set to either 'wbart', 'pbart' or 'lbart'")
check <- unique(sort(y.train))
if(length(check)==2) {
if(!all(check==0:1))
stop('Binary y.train must be coded as 0 and 1')
if(type=='wbart')
stop("The outcome is binary so set type to 'pbart' or 'lbart'")
}
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
mc.ndpost <- ceiling(ndpost/mc.cores)
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
gbart(x.train=x.train, y.train=y.train,
x.test=x.test, type=type, ntype=ntype,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
rm.const=rm.const,
sigest=sigest, sigdf=sigdf, sigquant=sigquant,
k=k, power=power, base=base,
##sigmaf=sigmaf,
lambda=lambda, tau.num=tau.num,
##tau.interval=tau.interval,
offset=offset,
w=w, ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip,
keepevery=keepevery, printevery=printevery,
transposed=TRUE, hostname=hostname)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list <- parallel::mccollect()
post <- post.list[[1]]
if(mc.cores==1 | attr(post, 'class')!=type) return(post)
else {
if(class(rm.const)[1]!='logical') post$rm.const <- rm.const
post$ndpost <- mc.cores*mc.ndpost
p <- nrow(x.train[post$rm.const, ])
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree),
' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost), ' ',
as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees)
keeptest <- length(x.test)>0
if(type=='wbart') sigma <- post$sigma[-(1:nskip)]
for(i in 2:mc.cores) {
post$hostname[i] <- post.list[[i]]$hostname
post$yhat.train <- rbind(post$yhat.train,
post.list[[i]]$yhat.train)
if(keeptest) post$yhat.test <- rbind(post$yhat.test,
post.list[[i]]$yhat.test)
if(type=='wbart') {
post$sigma <- cbind(post$sigma, post.list[[i]]$sigma)
sigma <- c(sigma, post.list[[i]]$sigma[-(1:nskip)])
}
post$varcount <- rbind(post$varcount, post.list[[i]]$varcount)
post$varprob <- rbind(post$varprob, post.list[[i]]$varprob)
post$treedraws$trees <-
paste0(post$treedraws$trees,
substr(post.list[[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[i]]$treedraws$trees)))
post$proc.time['elapsed'] <-
max(post$proc.time['elapsed'],
post.list[[i]]$proc.time['elapsed'])
for(j in 1:5)
if(j!=3)
post$proc.time[j] <-
post$proc.time[j]+post.list[[i]]$proc.time[j]
}
n=length(y.train)
Y=t(matrix(y.train, nrow=n, ncol=post$ndpost))
if(type=='wbart') {
post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
SD=matrix(sigma, nrow=post$ndpost, ncol=n)
##CPO=1/apply(1/dnorm(Y, post$yhat.train, SD), 2, mean)
log.pdf=dnorm(Y, post$yhat.train, SD, TRUE)
post$sigma.mean=mean(SD[ , 1])
if(keeptest)
post$yhat.test.mean <- apply(post$yhat.test, 2, mean)
} else {
post$prob.train.mean <- apply(post$prob.train, 2, mean)
##CPO=1/apply(1/dbinom(Y, 1, post$prob.train), 2, mean)
log.pdf=dbinom(Y, 1, post$prob.train, TRUE)
if(keeptest)
post$prob.test.mean <- apply(post$prob.test, 2, mean)
}
min.log.pdf=t(matrix(apply(log.pdf, 2, min),
nrow=n, ncol=post$ndpost))
log.CPO=log(post$ndpost)+min.log.pdf[1, ]-
log(apply(exp(min.log.pdf-log.pdf), 2, sum))
post$LPML=sum(log.CPO)
##post$LPML=sum(log(CPO))
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
attr(post, 'class') <- type
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.gbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.lbart <- function(
x.train, y.train, x.test = matrix(0.0, 0L, 0L),
sparse=FALSE, a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0.0,0,0), usequants=FALSE,
cont=FALSE, rm.const=TRUE, tau.interval=0.95,
k = 2.0, ## BEWARE: do NOT use k for other purposes below
power = 2.0, base = 0.95,
binaryOffset = NULL,
ntree=50L, numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=1L, printevery=100L,
keeptrainfits=TRUE, transposed=FALSE,
##treesaslists=FALSE,
mc.cores = 2L, nice = 19L,
seed = 99L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
cont=cont, xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
## warning(paste0('The number of cores requested, mc.cores=', mc.cores,
## ',\n exceeds the number of cores detected via detectCores() ',
## 'which yields ', mc.cores.detected, ' .'))
mc.ndpost <- ceiling(ndpost/mc.cores)
## mc.ndpost <- ((ndpost %/% mc.cores) %/% keepevery)*keepevery
## while(mc.ndpost*mc.cores<ndpost) mc.ndpost <- mc.ndpost+keepevery
## mc.nkeep <- mc.ndpost %/% keepevery
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
lbart(x.train=x.train, y.train=y.train, x.test=x.test,
sparse=sparse, a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, tau.interval=tau.interval,
k=k, power=power, base=base,
binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip, keepevery=keepevery,
## nkeeptrain=mc.nkeep, nkeeptest=mc.nkeep,
## nkeeptestmean=mc.nkeep, nkeeptreedraws=mc.nkeep,
printevery=printevery, transposed=TRUE)},
##treesaslists=treesaslists)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list <- parallel::mccollect()
post <- post.list[[1]]
if(mc.cores==1 | attr(post, 'class')!='lbart') return(post)
else {
if(class(rm.const)[1]!='logical') post$rm.const <- rm.const
post$ndpost <- mc.cores*mc.ndpost
p <- nrow(x.train[post$rm.const, ])
##if(length(rm.const)==0) rm.const <- 1:p
##post$rm.const <- rm.const
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree),
' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost), ' ',
as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees)
keeptestfits <- length(x.test)>0
for(i in 2:mc.cores) {
if(keeptrainfits)
post$yhat.train <- rbind(post$yhat.train,
post.list[[i]]$yhat.train)
if(keeptestfits) post$yhat.test <- rbind(post$yhat.test,
post.list[[i]]$yhat.test)
post$varcount <- rbind(post$varcount, post.list[[i]]$varcount)
post$varprob <- rbind(post$varprob, post.list[[i]]$varprob)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[i]]$treedraws$trees)))
## if(treesaslists) post$treedraws$lists <-
## c(post$treedraws$lists, post.list[[i]]$treedraws$lists)
}
if(length(post$yhat.train.mean)>0)
post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
if(length(post$yhat.test.mean)>0)
post$yhat.test.mean <- apply(post$yhat.test, 2, mean)
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
attr(post, 'class') <- 'lbart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.lbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.mbart <- function(
x.train, y.train,
x.test=matrix(0,0,0), type='pbart',
ntype=as.integer(
factor(type,
levels=c('wbart', 'pbart', 'lbart'))),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
k=2, power=2, base=0.95,
##sigest=NA, sigdf=3, sigquant=0.90, lambda=NA,
tau.num=c(NA, 3, 6)[ntype],
offset=NULL, ##w=rep(1, length(y.train)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
hostname=FALSE,
mc.cores = 2L, nice = 19L, seed = 99L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(type=='wbart' || is.na(ntype))
stop("type argument must be set to either 'pbart' or 'lbart'")
cats <- unique(sort(y.train))
K <- length(cats)
if(K<2)
stop("there must be at least 2 categories")
L <- length(offset)
if(!(L %in% c(0, K)))
stop(paste0("length of offset argument must be 0 or ", K))
L <- K-1
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
mc.ndpost <- ceiling(ndpost/mc.cores)
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
mbart(x.train=x.train, y.train=y.train,
x.test=x.test,
type=type, ntype=ntype,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
rm.const=rm.const,
k=k, power=power, base=base,
tau.num=tau.num,
offset=offset,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip,
keepevery=keepevery,
printevery=printevery, transposed=TRUE,
hostname=hostname)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list <- parallel::mccollect()
post <- post.list[[1]]
if(mc.cores==1 | attr(post, 'class')!='mbart') return(post)
else {
if(class(rm.const)[1]!='logical') post$rm.const <- rm.const
post$ndpost <- mc.cores*mc.ndpost
p <- nrow(x.train[ , post$rm.const])
if(length(rm.const)==0) rm.const <- 1:p
post$rm.const <- rm.const
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree),
' ', as.character(p))
old.stop <- nchar(old.text)
for(j in 1:L)
post$treedraws$trees[[j]] <- sub(old.text,
paste0(as.character(post$ndpost), ' ',
as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees[[j]])
keeptestfits <- length(x.test)>0
for(i in 2:mc.cores) {
if(keeptestfits) {
post$yhat.test <- rbind(post$yhat.test,
post.list[[i]]$yhat.test)
post$prob.test <- rbind(post$prob.test,
post.list[[i]]$prob.test)
}
for(j in 1:L) {
post$varcount[[j]] <- rbind(post$varcount[[j]],
post.list[[i]]$varcount[[j]])
post$varprob[[j]] <- rbind(post$varprob[[j]],
post.list[[i]]$varprob[[j]])
post$treedraws$trees[[j]] <- paste0(post$treedraws$trees[[j]],
substr(post.list[[i]]$treedraws$trees[[j]], old.stop+2,
nchar(post.list[[i]]$treedraws$trees[[j]])))
}
}
##post$prob.train.mean <- apply(post$prob.train, 2, mean)
if(keeptestfits) post$prob.test.mean <- apply(post$prob.test, 2, mean)
for(j in 1:L) {
post$varcount.mean[j, ] <- apply(post$varcount[[j]], 2, mean)
post$varprob.mean[j, ] <- apply(post$varprob[[j]], 2, mean)
}
attr(post, 'class') <- 'mbart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.mbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.mbart2 <- function(
x.train, y.train,
x.test=matrix(0,0,0), type='lbart',
ntype=as.integer(
factor(type,
levels=c('wbart', 'pbart', 'lbart'))),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
rm.const=TRUE,
k=2, power=2, base=0.95,
##sigest=NA, sigdf=3, sigquant=0.90, lambda=NA,
tau.num=c(NA, 3, 6)[ntype],
offset=NULL, ##w=rep(1, length(y.train)),
ntree=c(200L, 50L, 50L)[ntype], numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=c(1L, 10L, 10L)[ntype],
printevery=100L, transposed=FALSE,
hostname=FALSE,
mc.cores = 2L, nice = 19L, seed = 99L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(type=='wbart' || is.na(ntype))
stop("type argument must be set to either 'pbart' or 'lbart'")
cats <- unique(sort(y.train))
K <- length(cats)
if(K<2)
stop("there must be at least 2 categories")
L <- length(offset)
if(!(L %in% c(0, K)))
stop(paste0("length of offset argument must be 0 or ", K))
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
mc.ndpost <- ceiling(ndpost/mc.cores)
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
mbart2(x.train=x.train, y.train=y.train,
x.test=x.test,
type=type, ntype=ntype,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
rm.const=rm.const,
k=k, power=power, base=base,
tau.num=tau.num,
offset=offset,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip,
keepevery=keepevery,
printevery=printevery, transposed=TRUE,
hostname=hostname)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list <- parallel::mccollect()
post <- post.list[[1]]
if(mc.cores==1 | attr(post, 'class')!='mbart2') return(post)
else {
if(class(rm.const)[1]!='logical') post$rm.const <- rm.const
post$ndpost <- mc.cores*mc.ndpost
p <- nrow(x.train[ , post$rm.const])
if(length(rm.const)==0) rm.const <- 1:p
post$rm.const <- rm.const
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree),
' ', as.character(p))
old.stop <- nchar(old.text)
for(j in 1:K)
post$treedraws$trees[[j]] <- sub(old.text,
paste0(as.character(post$ndpost), ' ',
as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees[[j]])
keeptestfits <- length(x.test)>0
for(i in 2:mc.cores) {
post$yhat.train <- rbind(post$yhat.train,
post.list[[i]]$yhat.train)
post$prob.train <- rbind(post$prob.train,
post.list[[i]]$prob.train)
if(keeptestfits) {
post$yhat.test <- rbind(post$yhat.test,
post.list[[i]]$yhat.test)
post$prob.test <- rbind(post$prob.test,
post.list[[i]]$prob.test)
}
for(j in 1:K) {
post$varcount[[j]] <- rbind(post$varcount[[j]],
post.list[[i]]$varcount[[j]])
post$varprob[[j]] <- rbind(post$varprob[[j]],
post.list[[i]]$varprob[[j]])
post$treedraws$trees[[j]] <- paste0(post$treedraws$trees[[j]],
substr(post.list[[i]]$treedraws$trees[[j]], old.stop+2,
nchar(post.list[[i]]$treedraws$trees[[j]])))
}
}
post$prob.train.mean <- apply(post$prob.train, 2, mean)
if(keeptestfits) post$prob.test.mean <- apply(post$prob.test, 2, mean)
for(j in 1:K) {
post$varcount.mean[j, ] <- apply(post$varcount[[j]], 2, mean)
post$varprob.mean[j, ] <- apply(post$varprob[[j]], 2, mean)
}
attr(post, 'class') <- 'mbart2'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.mbart2.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.pbart <- function(
x.train, y.train, x.test = matrix(0.0, 0L, 0L),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0.0,0,0), usequants=FALSE,
cont=FALSE, rm.const=TRUE,
k = 2.0, ## BEWARE: do NOT use k for other purposes below
power = 2.0, base = 0.95,
binaryOffset = NULL,
ntree=50L, numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=1L, printevery=100L,
keeptrainfits=TRUE, transposed=FALSE,
## treesaslists=FALSE,
mc.cores = 2L, nice = 19L,
seed = 99L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
cont=cont, xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
## warning(paste0('The number of cores requested, mc.cores=', mc.cores,
## ',\n exceeds the number of cores detected via detectCores() ',
## 'which yields ', mc.cores.detected, ' .'))
mc.ndpost <- ceiling(ndpost/mc.cores)
## mc.ndpost <- ((ndpost %/% mc.cores) %/% keepevery)*keepevery
## while(mc.ndpost*mc.cores<ndpost) mc.ndpost <- mc.ndpost+keepevery
## mc.nkeep <- mc.ndpost %/% keepevery
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
pbart(x.train=x.train, y.train=y.train, x.test=x.test,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo,
k=k, power=power, base=base,
binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip, keepevery=keepevery,
## nkeeptrain=mc.nkeep, nkeeptest=mc.nkeep,
## nkeeptestmean=mc.nkeep, nkeeptreedraws=mc.nkeep,
printevery=printevery, transposed=TRUE)},
##treesaslists=treesaslists)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list <- parallel::mccollect()
post <- post.list[[1]]
if(mc.cores==1 | attr(post, 'class')!='pbart') return(post)
else {
if(class(rm.const)[1]!='logical') post$rm.const <- rm.const
post$ndpost <- mc.cores*mc.ndpost
p <- nrow(x.train[post$rm.const, ])
##p <- nrow(x.train[ , post$rm.const])
## if(length(rm.const)==0) rm.const <- 1:p
## post$rm.const <- rm.const
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree),
' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost), ' ',
as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees)
keeptestfits <- length(x.test)>0
for(i in 2:mc.cores) {
if(keeptrainfits) {
post$yhat.train <- rbind(post$yhat.train,
post.list[[i]]$yhat.train)
post$prob.train <- rbind(post$prob.train,
post.list[[i]]$prob.train)
}
if(keeptestfits) {
post$yhat.test <- rbind(post$yhat.test,
post.list[[i]]$yhat.test)
post$prob.test <- rbind(post$prob.test,
post.list[[i]]$prob.test)
}
post$varcount <- rbind(post$varcount, post.list[[i]]$varcount)
post$varprob <- rbind(post$varprob, post.list[[i]]$varprob)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[i]]$treedraws$trees)))
## if(treesaslists) post$treedraws$lists <-
## c(post$treedraws$lists, post.list[[i]]$treedraws$lists)
}
## if(length(post$yhat.train.mean)>0)
## post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
## if(length(post$yhat.test.mean)>0)
## post$yhat.test.mean <- apply(post$yhat.test, 2, mean)
if(length(post$prob.train.mean)>0)
post$prob.train.mean <- apply(post$prob.train, 2, mean)
if(length(post$prob.test.mean)>0)
post$prob.test.mean <- apply(post$prob.test, 2, mean)
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
attr(post, 'class') <- 'pbart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.pbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## mc.pwbart
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.pwbart = function(
x.test, #x matrix to predict at
treedraws, #$treedraws from wbart
mu=0, #mean to add on
mc.cores=2L,
transposed=FALSE,
dodraws=TRUE,
nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
if(!transposed) x.test <- t(bartModelMatrix(x.test))
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
mc.cores.detected <- detectCores()
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
K <- ncol(x.test)
if(K<mc.cores) mc.cores=K
k <- K%/%mc.cores-1
j <- K
for(i in 1:mc.cores) {
if(i==mc.cores) h <- 1
else h <- j-k
##print(c(i=i, h=h, j=j))
parallel::mcparallel({psnice(value=nice);
pwbart(matrix(x.test[ , h:j], nrow=p, ncol=j-h+1), treedraws, mu, 1, TRUE)},
silent=(i!=1))
j <- h-1
}
## K <- ncol(x.test)
## k <- ceiling(K/mc.cores)
## h <- K-k
## parallel::mcparallel({psnice(value=nice);
## pwbart(trees, x.test[ , max(1, h):K], mu, 1, TRUE)})
## if(mc.cores>1) for(i in 1:(mc.cores-1)) {
## parallel::mcparallel({psnice(value=nice);
## pwbart(trees, x.test[ , max(1, (h-k)):(h-1)], mu, 1, TRUE)},
## silent=TRUE)
## h <- h-k
## }
pred.list <- parallel::mccollect()
pred <- pred.list[[1]]
type=class(pred)[1]
if(type=='list') pred <- pred[[1]]
else if(type!='matrix') return(pred.list) ## likely error messages
if(mc.cores>1) for(i in 2:mc.cores) {
if(type=='list') pred <- cbind(pred, pred.list[[i]][[1]])
else pred <- cbind(pred, pred.list[[i]])
}
##if(mc.cores>1) for(i in 2:mc.cores) pred <- cbind(pred, pred.list[[i]])
if(dodraws) return(pred)
else return(apply(pred, 2, mean))
## if(dodraws) return(pred+mu)
## else return(apply(pred, 2, mean)+mu)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.recur.bart <- function(
x.train = matrix(0,0,0),
y.train=NULL, times=NULL, delta=NULL,
x.test = matrix(0,0,0),
x.test.nogrid = FALSE, ## you may not need the whole grid
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
##cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2, ## BEWARE: do NOT use k for other purposes below
power = 2, base = 0.95,
offset = NULL, tau.num=c(NA, 3, 6)[ntype],
##binaryOffset = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L,
keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptestmean=ndpost,
##nkeeptreedraws=ndpost,
printevery=100L,
##treesaslists=FALSE,
keeptrainfits=TRUE,
seed = 99L, ## only used by mc.recur.bart
mc.cores = 2L, ## ditto
nice=19L ## ditto
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train <- bartModelMatrix(x.train)
##x.test <- bartModelMatrix(x.test)
if(length(y.train)==0) {
recur <- recur.pre.bart(times, delta, x.train)
##recur <- recur.pre.bart(times, delta, x.train, x.test)
y.train <- recur$y.train
x.train <- recur$tx.train
x.test <- recur$tx.test
}
## if(length(binaryOffset)==0) {
## lambda <- sum(delta, na.rm=TRUE)/
## sum(apply(times, 1, max, na.rm=TRUE))
## ##lambda <- sum(delta)/sum(times[ , ncol(times)])
## binaryOffset <- qnorm(1-exp(-lambda))
## }
## }
## else if(length(binaryOffset)==0) binaryOffset <- 0
H <- 1
Mx <- 2^31-1
Nx <- max(nrow(x.train), nrow(x.test))
if(Nx>Mx%/%ndpost) {
H <- ceiling(ndpost / (Mx %/% Nx))
ndpost <- ndpost %/% H
##nrow*ndpost>2Gi!
##due to the 2Gi limit in sendMaster, breaking run into H parts
##this bug/feature might be addressed in R-devel post 3.3.2
##i.e., the fix is NOT in R version 3.3.2
##will revisit once there is a fix in an official R release
##New Features entry for R-devel post 3.3.2
## The unexported low-level functions in package parallel for passing
## serialized R objects to and from forked children now support long
## vectors on 64-bit platforms. This removes some limits on
## higher-level functions such as mclapply()
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores->mc.cores.detected
## warning(paste0('The number of cores requested, mc.cores=', mc.cores,
## ',\n exceeds the number of cores detected via detectCores() ',
## 'which yields ', mc.cores.detected, ' .'))
mc.ndpost <- ceiling(ndpost/mc.cores)
## mc.ndpost <- ((ndpost %/% mc.cores) %/% keepevery)*keepevery
## while(mc.ndpost*mc.cores<ndpost) mc.ndpost <- mc.ndpost+keepevery
## mc.nkeep <- mc.ndpost %/% keepevery
post.list <- list()
for(h in 1:H) {
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
recur.bart(x.train=x.train, y.train=y.train,
x.test=x.test, x.test.nogrid=x.test.nogrid,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
##cont=cont,
rm.const=rm.const, type=type,
k=k, power=power, base=base,
offset=offset, tau.num=tau.num,
##binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip, keepevery=keepevery,
##nkeeptrain=mc.ndpost, nkeeptest=mc.ndpost,
##nkeeptestmean=mc.ndpost,
##nkeeptreedraws=mc.ndpost,
printevery=printevery, ##treesaslists=treesaslists,
keeptrainfits=keeptrainfits)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list[[h]] <- parallel::mccollect()
}
if((H==1 & mc.cores==1) | attr(post.list[[1]][[1]], 'class')!='recurbart') return(post.list[[1]][[1]])
else {
for(h in 1:H) for(i in mc.cores:1) {
if(h==1 & i==mc.cores) {
post <- post.list[[1]][[mc.cores]]
post$ndpost <- H*mc.cores*mc.ndpost
p <- ncol(x.train[ , post$rm.const])
old.text <- paste0(as.character(mc.ndpost), ' ',
as.character(ntree), ' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost),
' ', as.character(ntree),
' ', as.character(p)),
post$treedraws$trees)
}
else {
if(keeptrainfits) {
post$yhat.train <- rbind(post$yhat.train,
post.list[[h]][[i]]$yhat.train)
post$prob.train <- rbind(post$prob.train,
post.list[[h]][[i]]$prob.train)
post$haz.train <- rbind(post$haz.train,
post.list[[h]][[i]]$haz.train)
post$cum.train <- rbind(post$cum.train,
post.list[[h]][[i]]$cum.train)
}
if(length(x.test)>0) {
post$yhat.test <- rbind(post$yhat.test, post.list[[h]][[i]]$yhat.test)
post$prob.test <- rbind(post$prob.test, post.list[[h]][[i]]$prob.test)
post$haz.test <- rbind(post$haz.test, post.list[[h]][[i]]$haz.test)
if(!x.test.nogrid) post$cum.test <- rbind(post$cum.test, post.list[[h]][[i]]$cum.test)
}
## if(length(post$sigma)>0)
## post$sigma <- c(post$sigma, post.list[[h]][[i]]$sigma)
post$varcount <- rbind(post$varcount, post.list[[h]][[i]]$varcount)
post$varprob <- rbind(post$varprob, post.list[[h]][[i]]$varprob)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[h]][[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[h]][[i]]$treedraws$trees)))
## if(treesaslists) post$treedraws$lists <-
## c(post$treedraws$lists, post.list[[h]][[i]]$treedraws$lists)
}
post.list[[h]][[i]] <- NULL
}
##post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
if(keeptrainfits) {
post$prob.train.mean <- apply(post$prob.train, 2, mean)
post$haz.train.mean <- apply(post$haz.train, 2, mean)
post$cum.train.mean <- apply(post$cum.train, 2, mean)
}
if(length(x.test)>0) {
post$prob.test.mean <- apply(post$prob.test, 2, mean)
post$haz.test.mean <- apply(post$haz.test, 2, mean)
if(!x.test.nogrid) post$cum.test.mean <- apply(post$cum.test, 2, mean)
}
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
attr(post, 'class') <- 'recurbart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.recur.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.recur.pwbart <- function(
x.test, #x matrix to predict at with time points expanded
treedraws, #$treedraws for from recur.bart/mc.recur.bart
binaryOffset=0, #mean to add on
mc.cores=2L,
type='pbart',
transposed=FALSE,
nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
if(!transposed) x.test <- t(bartModelMatrix(x.test))
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
K <- ncol(x.test)
k <- K%/%mc.cores
j <- K
for(i in 1:mc.cores) {
if(i==mc.cores) h <- 1
else h <- j-k
parallel::mcparallel({psnice(value=nice);
pwbart(x.test[ , h:j], treedraws, binaryOffset, 1, TRUE)},
silent=(i!=1))
j <- h-1
}
yhat.test.list <- parallel::mccollect()
pred <- list()
pred$binaryOffset <- binaryOffset
x.test <- t(x.test)
pred$tx.test <- x.test
times <- unique(sort(x.test[ , 1]))
pred$times <- times
K <- length(times)
pred$K <- K
pred$yhat.test <- yhat.test.list[[1]]
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
if(mc.cores>1)
for(i in 2:mc.cores)
pred$yhat.test <- cbind(pred$yhat.test, yhat.test.list[[i]])
H <- nrow(x.test)/K ## the number of different settings
if(type=='pbart') pred$prob.test <- pnorm(pred$yhat.test)
else if(type=='lbart') pred$prob.test <- plogis(pred$yhat.test)
pred$haz.test <- pred$prob.test
pred$cum.test <- pred$haz.test
H <- nrow(x.test)
for(h in 1:H) {
j <- which(x.test[h, 1]==times) ## for grid points only
if(j==1) pred$haz.test[ , h] <- pred$haz.test[ , h]/times[1]
else {
pred$haz.test[ , h] <- pred$haz.test[ , h]/(times[j]-times[j-1])
pred$cum.test[ , h] <- pred$cum.test[ , h-1]+pred$cum.test[ , h]
}
}
pred$prob.test.mean <- apply(pred$prob.test, 2, mean)
pred$haz.test.mean <- apply(pred$haz.test, 2, mean)
pred$cum.test.mean <- apply(pred$cum.test, 2, mean)
attr(pred, 'class') <- 'recurbart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.recur.pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
## run BART and generate survival in parallel
mc.surv.bart <- function(
x.train = matrix(0,0,0),
y.train=NULL, times=NULL, delta=NULL,
x.test = matrix(0,0,0),
K=NULL, events=NULL, ztimes=NULL, zdelta=NULL,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
##cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2.0, ## BEWARE: do NOT use k for other purposes below
power = 2.0, base = 0.95,
offset = NULL, tau.num=c(NA, 3, 6)[ntype],
##binaryOffset = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L, keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptreedraws=ndpost,
printevery=100L,
##treesaslists=FALSE,
##keeptrainfits=TRUE,
id = NULL, ## only used by surv.bart
seed = 99L, ## only used by mc.surv.bart
mc.cores = 2L, ## ditto
nice=19L ## ditto
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train <- bartModelMatrix(x.train)
x.test <- bartModelMatrix(x.test)
if(length(y.train)==0) {
pre <- surv.pre.bart(times, delta, x.train, x.test, K=K,
events=events, ztimes=ztimes, zdelta=zdelta)
y.train <- pre$y.train
x.train <- pre$tx.train
x.test <- pre$tx.test
##if(length(binaryOffset)==0) binaryOffset <- pre$binaryOffset
}
else {
if(length(unique(sort(y.train)))>2)
stop('y.train has >2 values; make sure you specify times=times & delta=delta')
##if(length(binaryOffset)==0) binaryOffset <- 0
}
H <- 1
Mx <- 2^31-1
Nx <- max(nrow(x.train), nrow(x.test))
if(Nx>Mx%/%ndpost) {
H <- ceiling(ndpost / (Mx %/% Nx))
ndpost <- ndpost %/% H
##nrow*ndpost>2Gi: due to the 2Gi limit in sendMaster
##(unless this limit was increased): reducing ndpost
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) {
message('The number of cores requested, ', mc.cores,
',\n exceeds the number of cores detected via detectCores() ',
'reducing to ', mc.cores.detected)
mc.cores <- mc.cores.detected
}
mc.ndpost <- ceiling(ndpost/mc.cores)
## mc.ndpost <- ((ndpost %/% mc.cores) %/% keepevery)*keepevery
## while(mc.ndpost*mc.cores<ndpost) mc.ndpost <- mc.ndpost+keepevery
## mc.nkeep <- mc.ndpost %/% keepevery
post.list <- list()
for(h in 1:H) {
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
surv.bart(x.train=x.train, y.train=y.train, x.test=x.test,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
##cont=cont,
rm.const=rm.const, type=type,
k=k, power=power, base=base,
offset=offset, tau.num=tau.num,
##binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip, keepevery=keepevery,
##nkeeptrain=mc.ndpost, nkeeptest=mc.ndpost,
##nkeeptestmean=mc.ndpost,
##nkeeptreedraws=mc.ndpost,
printevery=printevery)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list[[h]] <- parallel::mccollect()
}
if((H==1 & mc.cores==1) | attr(post.list[[1]][[1]], 'class')!='survbart') return(post.list[[1]][[1]])
else {
for(h in 1:H) for(i in mc.cores:1) {
if(h==1 & i==mc.cores) {
post <- post.list[[1]][[mc.cores]]
post$ndpost <- H*mc.cores*mc.ndpost
p <- ncol(x.train[ , post$rm.const])
old.text <- paste0(as.character(mc.ndpost), ' ',
as.character(ntree), ' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost),
' ', as.character(ntree),
' ', as.character(p)),
post$treedraws$trees)
}
else {
## if(length(x.test)==0) {
## post$yhat.train <- rbind(post$yhat.train, post.list[[h]][[i]]$yhat.train)
## post$prob.train <- rbind(post$prob.train, post.list[[h]][[i]]$prob.train)
## ##post$surv.train <- rbind(post$surv.train, post.list[[h]][[i]]$surv.train)
## } else {
if(length(x.test)>0) {
post$yhat.test <- rbind(post$yhat.test,
post.list[[h]][[i]]$yhat.test)
post$prob.test <- rbind(post$prob.test,
post.list[[h]][[i]]$prob.test)
post$surv.test <- rbind(post$surv.test,
post.list[[h]][[i]]$surv.test)
}
post$varcount <- rbind(post$varcount,
post.list[[h]][[i]]$varcount)
post$varprob <- rbind(post$varprob,
post.list[[h]][[i]]$varprob)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[h]][[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[h]][[i]]$treedraws$trees)))
## if(treesaslists) post$treedraws$lists <-
## c(post$treedraws$lists, post.list[[h]][[i]]$treedraws$lists)
post$proc.time['elapsed'] <- max(post$proc.time['elapsed'],
post.list[[h]][[i]]$proc.time['elapsed'])
for(j in 1:5)
if(j!=3)
post$proc.time[j] <- post$proc.time[j]+post.list[[h]][[i]]$proc.time[j]
}
post.list[[h]][[i]] <- NULL
}
## if(length(post$yhat.train.mean)>0)
## post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
## if(keeptrainfits)
## post$surv.train.mean <- apply(post$surv.train, 2, mean)
## if(length(post$yhat.test.mean)>0)
## post$yhat.test.mean <- apply(post$yhat.test, 2, mean)
if(length(x.test)>0)
post$surv.test.mean <- apply(post$surv.test, 2, mean)
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
attr(post, 'class') <- 'survbart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.surv.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.surv.pwbart <- function(
x.test, #x matrix to predict at with time points expanded
treedraws, #$treedraws for from surv.bart/mc.surv.bart
binaryOffset=0, #mean to add on
mc.cores=2L,
type='pbart',
transposed=FALSE,
nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
if(!transposed) x.test <- t(bartModelMatrix(x.test))
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
K <- ncol(x.test)
k <- K%/%mc.cores
j <- K
for(i in 1:mc.cores) {
if(i==mc.cores) h <- 1
else h <- j-k
parallel::mcparallel({psnice(value=nice);
pwbart(x.test[ , h:j], treedraws, binaryOffset, 1, TRUE)},
silent=(i!=1))
j <- h-1
}
yhat.test.list <- parallel::mccollect()
pred <- list()
x.test <- t(x.test)
pred$tx.test <- x.test
times <- unique(sort(x.test[ , 1]))
pred$times <- times
K <- length(times)
pred$K <- K
pred$yhat.test <- yhat.test.list[[1]]
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
if(mc.cores>1) for(i in 2:mc.cores)
pred$yhat.test <- cbind(pred$yhat.test, yhat.test.list[[i]])
H <- nrow(x.test)/K ## the number of different settings
if(type=='pbart') pred$prob.test <- pnorm(pred$yhat.test)
else if(type=='lbart') pred$prob.test <- plogis(pred$yhat.test)
pred$surv.test <- 1-pred$prob.test
for(h in 1:H)
for(j in 2:K) {
l <- K*(h-1)+j
pred$surv.test[ , l] <- pred$surv.test[ , l-1]*pred$surv.test[ , l]
}
pred$surv.test.mean <- apply(pred$surv.test, 2, mean)
pred$binaryOffset <- binaryOffset
attr(pred, 'class') <- 'survbart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.surv.pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.wbart <- function(
x.train, y.train, x.test=matrix(0.0,0,0),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0.0,0,0), usequants=FALSE,
cont=FALSE, rm.const=TRUE,
sigest=NA, sigdf=3, sigquant=0.90,
k=2.0, power=2.0, base=.95,
sigmaf=NA, lambda=NA,
fmean=mean(y.train),
w=rep(1,length(y.train)),
ntree=200L, numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=1L, printevery=100L,
keeptrainfits=TRUE, transposed=FALSE,
##treesaslists=FALSE,
mc.cores = 2L, nice = 19L,
seed = 99L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
cont=cont, xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
rm(temp)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
## warning(paste0('The number of cores requested, mc.cores=', mc.cores,
## ',\n exceeds the number of cores detected via detectCores() ',
## 'which yields ', mc.cores.detected, ' .'))
mc.ndpost <- ceiling(ndpost/mc.cores)
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
wbart(x.train=x.train, y.train=y.train, x.test=x.test,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo,
sigest=sigest, sigdf=sigdf, sigquant=sigquant,
k=k, power=power, base=base,
sigmaf=sigmaf, lambda=lambda, fmean=fmean, w=w,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip, keepevery=keepevery,
printevery=printevery, transposed=TRUE)},
##treesaslists=treesaslists)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list <- parallel::mccollect()
post <- post.list[[1]]
## sigma.len <- length(post$sigma)
## if(sigma.len>mc.ndpost) {
## sigma.beg <- 1+sigma.len-mc.ndpost
## post$sigma <- post$sigma[sigma.beg:sigma.len]
## }
if(mc.cores==1 | attr(post, 'class')!='wbart') return(post)
else {
if(class(rm.const)[1]!='logical') post$rm.const <- rm.const
post$ndpost <- mc.cores*mc.ndpost
p <- nrow(x.train[post$rm.const, ])
##p <- nrow(x.train[ , post$rm.const])
## if(length(rm.const)==0) rm.const <- 1:p
## post$rm.const <- rm.const
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree),
' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(post$ndpost), ' ',
as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees)
for(i in 2:mc.cores) {
post$yhat.train <- rbind(post$yhat.train,
post.list[[i]]$yhat.train)
if(length(post$yhat.test)>0)
post$yhat.test <- rbind(post$yhat.test,
post.list[[i]]$yhat.test)
## if(sigma.len>0)
## post$sigma <- c(post$sigma, post.list[[i]]$sigma[sigma.beg:sigma.len])
post$sigma <- cbind(post$sigma, post.list[[i]]$sigma)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[i]]$treedraws$trees)))
## if(treesaslists) post$treedraws$lists <-
## c(post$treedraws$lists, post.list[[i]]$treedraws$lists)
if(length(post$varcount)>0) {
post$varcount <- rbind(post$varcount, post.list[[i]]$varcount)
post$varprob <- rbind(post$varprob, post.list[[i]]$varprob)
}
post$proc.time['elapsed'] <- max(post$proc.time['elapsed'],
post.list[[i]]$proc.time['elapsed'])
for(j in 1:5)
if(j!=3)
post$proc.time[j] <- post$proc.time[j]+post.list[[i]]$proc.time[j]
}
if(length(post$yhat.train.mean)>0)
post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
if(length(post$yhat.test.mean)>0)
post$yhat.test.mean <- apply(post$yhat.test, 2, mean)
if(length(post$varcount)>0) {
post$varcount.mean <- apply(post$varcount, 2, mean)
post$varprob.mean <- apply(post$varprob, 2, mean)
}
attr(post, 'class') <- 'wbart'
return(post)
}
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.wbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
mc.wbart.gse <- function(
x.train, y.train,
P=50L, ## number of permutations
R=5L, ## number of replicates
ntree=20L, numcut=100L,
C=1, alpha=0.05,
k=2.0, power=2.0, base=0.95,
ndpost=2000L, nskip=100L,
printevery=100L, keepevery=1L, keeptrainfits=FALSE,
seed = 99L,
mc.cores = 2L,
nice=19L
)
{
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
set.seed(seed)
N <- length(y.train)
K <- ncol(x.train)
perm <- matrix(runif(N*P), nrow=N, ncol=P)
prob <- matrix(nrow=P, ncol=K)
h <- 1
for(i in 0:P) {
if(i==0) y. <- y.train
else y. <- y.train
tmp2 <- matrix(nrow=R, ncol=K)
for(j in 1:R) {
tmp1 <- mc.wbart(x.train=x.train, y.train=y.,
k=k, power=power, base=base,
ntree=ntree, numcut=numcut,
ndpost=ndpost, nskip=nskip,
printevery=printevery,
keepevery=keepevery,
keeptrainfits=keeptrainfits,
seed=h, mc.cores=mc.cores, nice=nice)$varcount
tmp2[j, ] <- apply(tmp1, 2, mean)
h <- h+1
}
tmp1 <- apply(tmp2, 2, mean)
tmp1 <- tmp1/sum(tmp1)
if(i==0) varcount <- tmp1
else prob[i, ] <- tmp1
}
mu.k <- apply(prob, 2, mean)
sd.k <- apply(prob, 2, sd)
cov.prob <- double(K)
iter <- 0
while(min(cov.prob)<(1-alpha)) {
if(iter>0) {
C <- C*1.01
cov.prob <- cov.prob*0
}
for(i in 1:P) for(j in 1:K) {
cov.prob[j] <- cov.prob[j]+(prob[i, j]<=(mu.k[j]+C*sd.k[j]))/P
}
iter <- iter+1
}
if(iter==1)
warning('Algorithm stopped at iteration 1. Try again with a smaller C.')
return(list(which=which(varcount>(mu.k+C*sd.k)), prob=varcount,
C=C, mu.k=mu.k, sd.k=sd.k, iter=iter, perm.prob=prob))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/mc.wbart.gse.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
pbart=function(
x.train, y.train, x.test=matrix(0.0,0,0),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0.0,0,0), usequants=FALSE,
cont=FALSE, rm.const=TRUE,
k=2.0, power=2.0, base=.95,
binaryOffset=NULL,
ntree=50L, numcut=100L,
ndpost=1000L, nskip=100L, keepevery=1L,
nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptestmean=ndpost,
nkeeptreedraws=ndpost,
printevery=100L, transposed=FALSE
##treesaslists=FALSE
)
{
#--------------------------------------------------
#data
n = length(y.train)
if(length(binaryOffset)==0) binaryOffset=qnorm(mean(y.train))
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
cont=cont, xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
## if(length(x.test)>0)
## x.test = t(bartModelMatrix(x.test[ , temp$rm.const]))
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
grp <- temp$grp
rm(temp)
}
else {
rm.const <- NULL
grp <- NULL
}
if(n!=ncol(x.train))
stop('The length of y.train and the number of rows in x.train must be identical')
p = nrow(x.train)
np = ncol(x.test)
if(length(rho)==0) rho <- p
if(length(rm.const)==0) rm.const <- 1:p
if(length(grp)==0) grp <- 1:p
#--------------------------------------------------
#set nkeeps for thinning
if((nkeeptrain!=0) & ((ndpost %% nkeeptrain) != 0)) {
nkeeptrain=ndpost
cat('*****nkeeptrain set to ndpost\n')
}
if((nkeeptest!=0) & ((ndpost %% nkeeptest) != 0)) {
nkeeptest=ndpost
cat('*****nkeeptest set to ndpost\n')
}
## if((nkeeptestmean!=0) & ((ndpost %% nkeeptestmean) != 0)) {
## nkeeptestmean=ndpost
## cat('*****nkeeptestmean set to ndpost\n')
## }
if((nkeeptreedraws!=0) & ((ndpost %% nkeeptreedraws) != 0)) {
nkeeptreedraws=ndpost
cat('*****nkeeptreedraws set to ndpost\n')
}
#--------------------------------------------------
#prior
## nu=sigdf
## if(is.na(lambda)) {
## if(is.na(sigest)) {
## if(p < n) {
## df = data.frame(t(x.train),y.train)
## lmf = lm(y.train~.,df)
## rm(df)
## sigest = summary(lmf)$sigma
## } else {
## sigest = sd(y.train)
## }
## }
## qchi = qchisq(1.0-sigquant,nu)
## lambda = (sigest*sigest*qchi)/nu #lambda parameter for sigma prior
## }
## if(is.na(sigmaf)) {
## tau=(max(y.train)-min(y.train))/(2*k*sqrt(ntree));
## } else {
## tau = sigmaf/sqrt(ntree)
## }
#--------------------------------------------------
ptm <- proc.time()
#call
res = .Call("cpbart",
n, #number of observations in training data
p, #dimension of x
np, #number of observations in test data
x.train, #p*n training data x
y.train, #n*1 training data y
x.test, #p*np test data x
ntree,
numcut,
ndpost*keepevery,
nskip,
power,
base,
binaryOffset,
3/(k*sqrt(ntree)),
sparse,
theta,
omega,
grp,
a,
b,
rho,
augment,
nkeeptrain,
nkeeptest,
##nkeeptestmean,
nkeeptreedraws,
printevery,
##treesaslists,
xinfo
)
res$proc.time <- proc.time()-ptm
if(nkeeptrain>0) {
##res$yhat.train.mean <- NULL
##res$yhat.train.mean = res$yhat.train.mean+binaryOffset
res$yhat.train = res$yhat.train+binaryOffset
res$prob.train = pnorm(res$yhat.train)
res$prob.train.mean <- apply(res$prob.train, 2, mean)
} else {
res$yhat.train <- NULL
##res$yhat.train.mean <- NULL
}
if(np>0) {
##res$yhat.test.mean <- NULL
##res$yhat.test.mean = res$yhat.test.mean+binaryOffset
res$yhat.test = res$yhat.test+binaryOffset
res$prob.test = pnorm(res$yhat.test)
res$prob.test.mean <- apply(res$prob.test, 2, mean)
} else {
res$yhat.test <- NULL
##res$yhat.test.mean <- NULL
}
if(nkeeptreedraws>0) ## & !treesaslists)
names(res$treedraws$cutpoints) = dimnames(x.train)[[1]]
dimnames(res$varcount)[[2]] = as.list(dimnames(x.train)[[1]])
dimnames(res$varprob)[[2]] = as.list(dimnames(x.train)[[1]])
res$varcount.mean <- apply(res$varcount, 2, mean)
res$varprob.mean <- apply(res$varprob, 2, mean)
res$rm.const <- rm.const
res$binaryOffset=binaryOffset
attr(res, 'class') <- 'pbart'
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/pbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.crisk2bart <- function(object, newdata, newdata2, mc.cores=1,
openmp=(mc.cores.openmp()>0), ...) {
## if(class(newdata) != "matrix") stop("newdata must be a matrix")
## if(class(newdata2) != "matrix") stop("newdata2 must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
p <- length(object$treedraws2$cutpoints)
if(p!=ncol(newdata2))
stop(paste0('The number of columns in newdata2 must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected)
mc.cores <- mc.cores.detected
if(length(object$binaryOffset)==0) object$binaryOffset=object$offset
if(length(object$binaryOffset2)==0) object$binaryOffset2=object$offset2
return(mc.crisk2.pwbart(newdata, newdata2,
object$treedraws, object$treedraws2,
object$binaryOffset, object$binaryOffset2,
mc.cores=mc.cores, type=object$type, ...))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.crisk2bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.criskbart <- function(object, newdata, newdata2, mc.cores=1,
openmp=(mc.cores.openmp()>0), ...) {
## if(class(newdata) != "matrix") stop("newdata must be a matrix")
## if(class(newdata2) != "matrix") stop("newdata2 must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
p <- length(object$treedraws2$cutpoints)
if(p!=ncol(newdata2))
stop(paste0('The number of columns in newdata2 must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected)
mc.cores <- mc.cores.detected
if(length(object$binaryOffset)==0) object$binaryOffset=object$offset
if(length(object$binaryOffset2)==0) object$binaryOffset2=object$offset2
return(mc.crisk.pwbart(newdata, newdata2,
object$treedraws, object$treedraws2,
object$binaryOffset, object$binaryOffset2,
mc.cores=mc.cores, type=object$type, ...))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.criskbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.lbart <- function(object, newdata, mc.cores=1, openmp=(mc.cores.openmp()>0), ...) {
##if(class(newdata) != "matrix") stop("newdata must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
if(.Platform$OS.type != "unix" || openmp || mc.cores==1) call <- pwbart
else call <- mc.pwbart
##return(call(newdata, object$treedraws, mc.cores=mc.cores, mu=object$binaryOffset, ...))
if(length(object$binaryOffset)==0) object$binaryOffset=object$offset
pred <- list(yhat.test=call(newdata, object$treedraws, mc.cores=mc.cores,
mu=object$binaryOffset, ...))
pred$prob.test <- plogis(pred$yhat.test)
pred$prob.test.mean <- apply(pred$prob.test, 2, mean)
pred$binaryOffset <- object$binaryOffset
attr(pred, 'class') <- 'lbart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.lbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.mbart <- function(object, newdata, mc.cores=1,
openmp=(mc.cores.openmp()>0), ...) {
##if(class(newdata) != "matrix") stop("newdata must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected)
mc.cores <- mc.cores.detected
if(.Platform$OS.type != "unix" || openmp || mc.cores==1) call <- pwbart
else call <- mc.pwbart
##call <- predict.gbart
##return(call(newdata, object$treedraws, mc.cores=mc.cores, mu=object$binaryOffset, ...))
K <- object$K
L <- K-1
pred <- as.list(1:L)
trees <- object$treedraws$trees
for(h in 1:L) {
## eval(parse(text=paste0('object$treedraws$trees=',
## 'object$treedraws$tree', h)))
object$treedraws$trees <- trees[[h]]
pred[[h]] <- list(yhat.test=call(newdata, object$treedraws,
mc.cores=mc.cores,
mu=object$offset[h], ...))
## predict.gbart testing
## pred[[h]] <- call(object, newdata, mc.cores=mc.cores,
## openmp=openmp, type=object$type)
}
H <- dim(pred[[1]]$yhat.test)
ndpost <- H[1]
np <- H[2]
res <- list()
res$yhat.test <- matrix(nrow=ndpost, ncol=K*np)
res$prob.test <- matrix(nrow=ndpost, ncol=K*np)
res$comp.test <- matrix(nrow=ndpost, ncol=K*np)
for(i in 1:np) {
for(j in 1:K) {
h <- (i-1)*K+j
if(j<K) {
res$yhat.test[ , h] <- pred[[j]]$yhat.test[ , i]
if(object$type=='pbart')
res$prob.test[ , h] <- pnorm(res$yhat.test[ , h])
else if(object$type=='lbart')
res$prob.test[ , h] <- plogis(res$yhat.test[ , h])
if(j==1) res$comp.test[ , h] <- 1-res$prob.test[ , h]
else {
res$comp.test[ , h] <- res$comp.test[ , h-1]*
(1-res$prob.test[ , h])
res$prob.test[ , h] <- res$comp.test[ , h-1]*
res$prob.test[ , h]
}
} else res$prob.test[ , h] <- res$comp.test[ , h-1]
}
}
res$prob.test.mean <- apply(res$prob.test, 2, mean)
res$yhat.test.mean <- NULL
res$comp.test <- NULL
res$K <- K
res$offset <- object$offset
attr(res, 'class') <- 'mbart'
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.mbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.mbart2 <- function(object, newdata, mc.cores=1,
openmp=(mc.cores.openmp()>0), ...) {
##if(class(newdata) != "matrix") stop("newdata must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected)
mc.cores <- mc.cores.detected
if(.Platform$OS.type != "unix" || openmp || mc.cores==1) call <- pwbart
else call <- mc.pwbart
##call <- predict.gbart
##return(call(newdata, object$treedraws, mc.cores=mc.cores, mu=object$binaryOffset, ...))
K <- object$K
pred <- as.list(1:K)
trees <- object$treedraws$trees
for(j in 1:K) {
object$treedraws$trees <- trees[[j]]
pred[[j]] <- list(yhat.test=call(newdata, object$treedraws,
mc.cores=mc.cores,
mu=object$offset[j], ...))
}
H <- dim(pred[[1]]$yhat.test)
ndpost <- H[1]
np <- H[2]
res <- list()
res$yhat.test <- matrix(nrow=ndpost, ncol=K*np)
res$prob.test <- matrix(nrow=ndpost, ncol=K*np)
res$tot.test <- matrix(0, nrow=ndpost, ncol=np)
for(i in 1:np) {
for(j in 1:K) {
h <- (i-1)*K+j
res$yhat.test[ , h] <- pred[[j]]$yhat.test[ , i]
res$tot.test[ , i] <- res$tot.test[ , i]+exp(res$yhat.test[ , h])
if(j==K)
for(h in (i-1)*K+1:K)
res$prob.test[ , h] <- exp(res$yhat.test[ , h])/
res$tot.test[ , i]
}
}
res$prob.test.mean <- apply(res$prob.test, 2, mean)
res$yhat.test.mean <- NULL
res$tot.test <- NULL
res$K <- K
res$offset <- object$offset
attr(res, 'class') <- 'mbart2'
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.mbart2.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.pbart <- function(object, newdata, mc.cores=1, openmp=(mc.cores.openmp()>0), ...) {
##if(class(newdata) != "matrix") stop("newdata must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
if(.Platform$OS.type != "unix" || openmp || mc.cores==1) call <- pwbart
else call <- mc.pwbart
##return(call(newdata, object$treedraws, mc.cores=mc.cores, mu=object$binaryOffset, ...))
if(length(object$binaryOffset)==0) object$binaryOffset=object$offset
pred <- list(yhat.test=call(newdata, object$treedraws, mc.cores=mc.cores,
mu=object$binaryOffset, ...))
pred$prob.test <- pnorm(pred$yhat.test)
pred$prob.test.mean <- apply(pred$prob.test, 2, mean)
pred$binaryOffset <- object$binaryOffset
attr(pred, 'class') <- 'pbart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.pbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.recurbart <- function(object, newdata, mc.cores=1, openmp=(mc.cores.openmp()>0), ...) {
##if(class(newdata) != "matrix") stop("newdata must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
if(.Platform$OS.type != "unix" || openmp || mc.cores==1) call <- recur.pwbart
else call <- mc.recur.pwbart
if(length(object$binaryOffset)==0) object$binaryOffset=object$offset
return(call(newdata, object$treedraws, mc.cores=mc.cores,
binaryOffset=object$binaryOffset,
type=object$type, ...))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.recurbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.survbart <- function(object, newdata, mc.cores=1,
openmp=(mc.cores.openmp()>0), ...) {
##if(class(newdata) != "matrix") stop("newdata must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
if(.Platform$OS.type != "unix" || openmp || mc.cores==1) call <- surv.pwbart
else call <- mc.surv.pwbart
if(length(object$binaryOffset)==0) object$binaryOffset=object$offset
return(call(newdata, object$treedraws, mc.cores=mc.cores,
binaryOffset=object$binaryOffset, type=object$type, ...))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.survbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
predict.wbart <- function(object, newdata, mc.cores=1, openmp=(mc.cores.openmp()>0), ...) {
##if(class(newdata) != "matrix") stop("newdata must be a matrix")
p <- length(object$treedraws$cutpoints)
if(p!=ncol(newdata))
stop(paste0('The number of columns in newdata must be equal to ', p))
if(.Platform$OS.type == "unix") mc.cores.detected <- detectCores()
else mc.cores.detected <- NA
if(!is.na(mc.cores.detected) && mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
if(.Platform$OS.type != "unix" || openmp || mc.cores==1) call <- pwbart
else call <- mc.pwbart
if(length(object$mu)==0) object$mu=object$offset
return(call(newdata, object$treedraws, mc.cores=mc.cores, mu=object$mu, ...))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/predict.wbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
pwbart = function(
x.test, #x matrix to predict at
treedraws, #$treedraws from wbart
mu=0, #mean to add on
mc.cores=1L, #thread count
transposed=FALSE,
dodraws=TRUE,
nice=19L #mc.pwbart only
)
{
if(!transposed) x.test <- t(bartModelMatrix(x.test))
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
res = .Call("cpwbart",
treedraws, #trees list
x.test, #the test x
mc.cores #thread count
)
if(dodraws) return(res$yhat.test+mu)
else return(apply(res$yhat.test, 2, mean)+mu)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
recur.bart <- function(
x.train = matrix(0,0,0),
y.train=NULL, times=NULL, delta=NULL,
x.test = matrix(0,0,0),
x.test.nogrid = FALSE, ## you may not need the whole grid
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
##cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2, ## BEWARE: do NOT use k for other purposes below
power = 2, base = 0.95,
offset = NULL, tau.num=c(NA, 3, 6)[ntype],
##binaryOffset = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L,
keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptestmean=ndpost,
##nkeeptreedraws=ndpost,
printevery=100L,
##treesaslists=FALSE,
keeptrainfits=TRUE,
seed = 99L, ## only used by mc.recur.bart
mc.cores = 2L, ## ditto
nice=19L ## ditto
)
{
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train <- bartModelMatrix(x.train)
x.test <- bartModelMatrix(x.test)
if(length(rho)==0) rho <- ncol(x.train)
if(length(y.train)==0) {
## if(length(binaryOffset)==0) {
## lambda <- sum(delta, na.rm=TRUE)/
## sum(apply(times, 1, max, na.rm=TRUE))
## binaryOffset <- qnorm(1-exp(-lambda))
## }
recur <- recur.pre.bart(times, delta, x.train)
##recur <- recur.pre.bart(times, delta, x.train, x.test)
y.train <- recur$y.train
x.train <- recur$tx.train
x.test <- recur$tx.test
times <- recur$times
K <- recur$K
}
else {
times <- unique(sort(x.train[ , 1]))
K <- length(times)
}
##if(length(binaryOffset)==0) binaryOffset <- qnorm(mean(y.train))
## if(type=='pbart') call <- pbart
## else if(type=='lbart') {
## ##binaryOffset <- 0
## call <- lbart
## }
post <- gbart(x.train=x.train, y.train=y.train,
x.test=x.test, type=type,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
k=k, power=power, base=base,
xinfo=xinfo, usequants=usequants,
##cont=cont,
rm.const=rm.const,
offset=offset, tau.num=tau.num,
##binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=ndpost, nskip=nskip,
keepevery=keepevery,
##nkeeptrain=nkeeptrain, nkeeptest=nkeeptest,
##nkeeptestmean=nkeeptestmean,
##nkeeptreedraws=nkeeptreedraws,
printevery=printevery)
if(type!=attr(post, 'class')) return(post)
##post$binaryOffset <- binaryOffset
post$times <- times
post$K <- K
post$tx.train <- x.train
post$type <- type
if(keeptrainfits) {
## if(type=='pbart') post$haz.train <- pnorm(post$yhat.train)
## else if(type=='lbart') post$haz.train <- plogis(post$yhat.train)
post$haz.train <- post$prob.train
post$cum.train <- post$haz.train
H <- nrow(x.train)
for(h in 1:H) {
j <- which(x.train[h, 1]==times) ## for grid points only
if(j==1) post$haz.train[ , h] <- post$haz.train[ , h]/times[1]
else {
post$haz.train[ , h] <- post$haz.train[ , h]/(times[j]-times[j-1])
post$cum.train[ , h] <- post$cum.train[ , h-1]+post$cum.train[ , h]
}
}
post$haz.train.mean <- apply(post$haz.train, 2, mean)
post$cum.train.mean <- apply(post$cum.train, 2, mean)
}
if(length(x.test)>0) { ## this should always be the case
post$tx.test <- x.test
## if(type=='pbart') post$haz.test <- pnorm(post$yhat.test)
## else if(type=='lbart') post$haz.test <- plogis(post$yhat.test)
if(!x.test.nogrid) {
post$haz.test <- post$prob.test
post$cum.test <- post$haz.test
H <- nrow(x.test)
for(h in 1:H) {
j <- which(x.test[h, 1]==times) ## for grid points only
if(j==1) post$haz.test[ , h] <- post$haz.test[ , h]/times[1]
else {
post$haz.test[ , h] <- post$haz.test[ , h]/(times[j]-times[j-1])
post$cum.test[ , h] <- post$cum.test[ , h-1]+post$cum.test[ , h]
}
}
post$haz.test.mean <- apply(post$haz.test, 2, mean)
post$cum.test.mean <- apply(post$cum.test, 2, mean)
}
## H <- nrow(x.test)
## time <- 0
## for(h in 1:H) {
## prev <- time
## time <- x.test[h, 1]
## if(time==post$times[1]) post$haz.test[ , h] <- post$haz.test[ , h]/time
## else {
## post$haz.test[ , h] <- post$haz.test[ , h]/(time-prev)
## post$cum.test[ , h] <- post$cum.test[ , h-1]+post$cum.test[ , h]
## }
## }
}
attr(post, 'class') <- 'recurbart'
return(post)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/recur.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
recur.pre.bart <- function(
times,
## matrix of recur times (start times)
delta,
## matrix of indicators: 0=no event, 1=event
x.train=NULL,
## matrix of covariate regressors
## can be NULL, i.e. KM analog
tstop=NULL,
## for non-instantaneous events, this the
## matrix of event stop times, i.e., between
## times[i, j] and tstop[i, j] subject i is
## not in the risk set for a recurrent event
## N.B. NOT for counting process notation
last.value=TRUE
) {
## currently does not handle time dependent Xs
## can be extended later
## most likely via the alternative counting process notation
N <- nrow(times)
if(N!=nrow(delta))
stop('The number of rows in times and delta must be identical')
if(length(x.train)>0 && N!=nrow(x.train))
stop('The number of rows in times and x.train, if any, must be identical')
J <- ncol(times)
times <- cbind(times, apply(times, 1, max, na.rm=TRUE))
dimnames(times)[[2]][J+1] <- 'stop'
events <- unique(sort(c(times, tstop)))
## time grid of events including stop times
if(events[1]==0) events <- events[-1]
K <- length(events)
y.train <- integer(N) ## y.train is at least N long
k <- 1
id <- 0
for(i in 1:N)
for(j in 1:K)
if(events[j] <= times[i, J+1]) {
y.train[k] <- 0
id[k] <- i
for(h in 1:J) if(!is.na(times[i, h]) && !is.na(delta[i, h]) &&
y.train[k]==0 && events[j]==times[i, h] && delta[i, h]==1)
y.train[k] <- 1
k <- k+1
}
m <- length(y.train)
##binaryOffset <- qnorm(mean(y.train))
if(length(x.train)==0) {
p <- 0
n <- 1
X.train <- matrix(nrow=m, ncol=3)
dimnames(X.train)[[2]] <- c('t', 'v', 'N')
} else {
p <- ncol(x.train)
##if(length(x.test)>0) n <- nrow(x.test)
X.train <- matrix(nrow=m, ncol=p+3)
if(length(dimnames(x.train)[[2]])>0)
dimnames(X.train)[[2]] <- c('t', 'v', 'N', dimnames(x.train)[[2]])
else dimnames(X.train)[[2]] <- c('t', 'v', 'N', paste0('x', 1:p))
}
X.test <- matrix(nrow=N*K, ncol=ncol(X.train))
dimnames(X.test)[[2]] <- dimnames(X.train)[[2]]
k <- 1
for(i in 1:N) {
n.t <- 0
t.0 <- 0
for(j in 1:K) if(events[j] <= times[i, J+1]) {
X.train[k, 1:3] <- c(events[j], events[j]-t.0, n.t)
for(h in 1:J) if(!is.na(times[i, h]) && !is.na(delta[i, h]) &&
events[j]==times[i, h] && delta[i, h]==1) {
n.t <- n.t+1
t.0 <- events[j]
}
if(p>0) X.train[k, 4:(3+p)] <- x.train[i, ]
k <- k+1
}
}
## generate X.test from X.train with v(t) & N(t-) as NA beyond follow-up
k <- 1
for(i in 1:N) {
n.t <- 0
t.0 <- 0
for(j in 1:K) {
X.test[k, 1:3] <- c(events[j], events[j]-t.0, n.t)
for(h in 1:J) {
if(!is.na(times[i, h]) && !is.na(delta[i, h]) &&
events[j]==times[i, h] && delta[i, h]==1) {
n.t <- n.t+1
t.0 <- events[j]
}
else if(!last.value & events[j] == times[i, J+1]) {
n.t <- NA
t.0 <- NA
}
}
if(p>0) X.test[k, 4:(3+p)] <- x.train[i, ]
k <- k+1
}
}
## remove training entries not in the risk-set
h <- TRUE
if(length(tstop)>0) {
for(k in 1:m) {
i <- id[k]
t <- X.train[k, 1]
j <- 1
h[k] <- TRUE
while(h[k] & j<=J) {
h[k] <- (tstop[i, j]==0 | !(times[i, j]<t & t<=tstop[i, j]))
j <- j+1
}
}
y.train <- y.train[h]
X.train <- X.train[h, ]
}
return(list(y.train=y.train, tx.train=X.train, tx.test=X.test,
times=events, K=K)) ##, binaryOffset=binaryOffset))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/recur.pre.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
recur.pwbart <- function(
x.test, #x matrix to predict at with time points expanded
treedraws, #$treedraws for from surv.bart/mc.surv.bart
binaryOffset=0, #mean to add on
mc.cores=1L,
type='pbart',
transposed=FALSE,
nice=19L # mc.surv.pwbart only
)
{
if(!transposed) x.test <- t(bartModelMatrix(x.test))
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
pred <- list()
pred$yhat.test <- pwbart(x.test, treedraws, binaryOffset, mc.cores, TRUE)
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
x.test <- t(x.test)
pred$tx.test <- x.test
times <- unique(sort(x.test[ , 1]))
pred$times <- times
K <- length(times)
pred$K <- K
if(type=='pbart') pred$prob.test <- pnorm(pred$yhat.test)
else if(type=='lbart') pred$prob.test <- plogis(pred$yhat.test)
pred$haz.test <- pred$prob.test
pred$cum.test <- pred$haz.test
H <- nrow(x.test)
for(h in 1:H) {
j <- which(x.test[h, 1]==times) ## for grid points only
if(j==1) pred$haz.test[ , h] <- pred$haz.test[ , h]/times[1]
else {
pred$haz.test[ , h] <- pred$haz.test[ , h]/(times[j]-times[j-1])
pred$cum.test[ , h] <- pred$cum.test[ , h-1]+pred$cum.test[ , h]
}
}
pred$prob.test.mean <- apply(pred$prob.test, 2, mean)
pred$haz.test.mean <- apply(pred$haz.test, 2, mean)
pred$cum.test.mean <- apply(pred$cum.test, 2, mean)
pred$binaryOffset <- binaryOffset
attr(pred, 'class') <- 'recurbart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/recur.pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
rs.pbart <- function(
x.train, y.train, x.test = matrix(0.0, 0L, 0L),
C = floor(length(y.train)/2000),
k = 2.0, ## BEWARE: do NOT use k for other purposes below
power = 2.0, base = 0.95,
binaryOffset = 0,
ntree=50L, numcut=100L,
ndpost=1000L, nskip=100L,
keepevery=1L, printevery=100L,
keeptrainfits=FALSE,
transposed=FALSE,
#treesaslists=FALSE,
mc.cores = 2L, nice = 19L,
seed = 99L
)
{
if(C<=1) stop('The number of shards must be >1')
if(.Platform$OS.type!='unix')
stop('parallel::mcparallel/mccollect do not exist on windows')
RNGkind("L'Ecuyer-CMRG")
set.seed(seed)
parallel::mc.reset.stream()
if(!transposed) {
temp = bartModelMatrix(x.train, numcut)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
rm(temp)
##x.test <- t(x.test)
}
mc.cores.detected <- detectCores()
if(mc.cores>mc.cores.detected) mc.cores <- mc.cores.detected
## warning(paste0('The number of cores requested, mc.cores=', mc.cores,
## ',\n exceeds the number of cores detected via detectCores() ',
## 'which yields ', mc.cores.detected, ' .'))
mc.ndpost <- ceiling(ndpost/mc.cores)
## mc.ndpost <- ((ndpost %/% mc.cores) %/% keepevery)*keepevery
## while(mc.ndpost*mc.cores<ndpost) mc.ndpost <- mc.ndpost+keepevery
## mc.nkeep <- mc.ndpost %/% keepevery
p <- nrow(x.train)
##xinfo <- makexinfo(x.train, numcut=numcut, transposed=TRUE)
## xinfo <- matrix(nrow=p, ncol=numcut)
## for(i in 1:p)
## xinfo[i, ] <- seq(min(x.train[i, ]), max(x.train[i, ]),
## length.out=numcut+2)[2:(numcut+1)]
rs <- stratrs(y.train, C)
post.list <- as.list(1:C)
shard <- as.list(1:C)
for(h in 1:C) {
shard[[h]] <- rs==h
for(i in 1:mc.cores) {
parallel::mcparallel({psnice(value=nice);
pbart(x.train=x.train[ , shard[[h]] ], y.train=y.train[shard[[h]] ],
xinfo=xinfo,
k=k, power=power, base=base,
binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=mc.ndpost, nskip=nskip, keepevery=keepevery,
## nkeeptrain=mc.nkeep, nkeeptest=mc.nkeep,
## nkeeptestmean=mc.nkeep, nkeeptreedraws=mc.nkeep,
printevery=printevery, transposed=TRUE)},
silent=(i!=1))
## to avoid duplication of output
## capture stdout from first posterior only
}
post.list[[h]] <- parallel::mccollect()
if(h==1) {
post <- post.list[[1]][[1]]
if(attr(post, 'class')!='pbart') return(post)
## for(i in 1:p)
## if(!all(xinfo[i, ]==post$treedraws$cutpoints[[i]])) {
## stop('Cutpoints must be identical for all samples')
## ##print(c(xinfo=xinfo[[i]]))
## ##print(c(cutpoints=post$treedraws$cutpoints[[i]]))
## }
post$yhat.shard <- matrix(nrow=mc.ndpost*mc.cores, ncol=length(y.train))
post$yhat.shard[1:mc.ndpost, shard[[1]] ] <- post$yhat.train
post$yhat.train <- NULL
post$yhat.train.mean <- NULL
}
}
old.text <- paste0(as.character(mc.ndpost), ' ', as.character(ntree), ' ', as.character(p))
##old.text <- paste0(as.character(mc.nkeep), ' ', as.character(ntree), ' ', as.character(p))
old.stop <- nchar(old.text)
post$treedraws$trees <- sub(old.text,
paste0(as.character(C*mc.cores*mc.ndpost), ' ',
as.character(ntree), ' ',
##paste0(as.character(mc.cores*mc.nkeep), ' ', as.character(ntree), ' ',
as.character(p)),
post$treedraws$trees)
##keeptestfits <- length(x.test)>0
for(h in 1:C)
for(i in 1:mc.cores)
if(!(h==1 && i==1)) {
##if(keeptrainfits) post$yhat.train <- rbind(post$yhat.train, post.list[[h]][[i]]$yhat.train)
##if(keeptestfits) post$yhat.test <- rbind(post$yhat.test, post.list[[h]][[i]]$yhat.test)
post$yhat.shard[(i-1)*mc.ndpost+1:mc.ndpost, shard[[h]] ] <- post.list[[h]][[i]]$yhat.train
post$varcount <- rbind(post$varcount, post.list[[h]][[i]]$varcount)
post$treedraws$trees <- paste0(post$treedraws$trees,
substr(post.list[[h]][[i]]$treedraws$trees, old.stop+2,
nchar(post.list[[h]][[i]]$treedraws$trees)))
## if(treesaslists) post$treedraws$lists <-
## c(post$treedraws$lists, post.list[[h]][[i]]$treedraws$lists)
}
## if(length(post$yhat.train.mean)>0)
## post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
## if(length(post$yhat.test.mean)>0)
## post$yhat.test.mean <- apply(post$yhat.test, 2, mean)
attr(post, 'class') <- 'pbart'
if(keeptrainfits) {
post$x.train <- t(x.train)
post$yhat.train <- predict(post, newdata=post$x.train, mc.cores=mc.cores)
}
if(length(x.test)>0) {
post$x.test <- bartModelMatrix(x.test)
post$yhat.test <- predict(post, newdata=post$x.test, mc.cores=mc.cores)
}
return(post)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/rs.pbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2019 Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
rtgamma=function(n, shape, rate, a) .Call("crtgamma", n, shape, rate, a)
| /scratch/gouwar.j/cran-all/cranData/BART/R/rtgamma.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch, Rodney Sparapani
## and Robert Gramacy
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
rtnorm=function(n, mean, sd, tau) .Call("crtnorm", n, mean, tau, sd)
| /scratch/gouwar.j/cran-all/cranData/BART/R/rtnorm.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
rtnorm_reject=function(mean, tau, sd)
.Call("crtnorm_reject", mean, tau, sd)
| /scratch/gouwar.j/cran-all/cranData/BART/R/rtnorm_reject.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
spectrum0ar <- function(x)
{
v0 <- order <- numeric(ncol(x))
names(v0) <- names(order) <- colnames(x)
z <- 1:nrow(x)
for (i in 1:ncol(x)) {
lm.out <- lm(x[,i] ~ z)
if (identical(all.equal(sd(residuals(lm.out)), 0), TRUE)) {
v0[i] <- 0
order[i] <- 0
}
else {
ar.out <- ar(x[,i], aic=TRUE)
v0[i] <- ar.out$var.pred/(1 - sum(ar.out$ar))^2
order[i] <- ar.out$order
}
}
return(list(spec=v0, order=order))
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/spectrum0ar.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
srstepwise=function(x, times, delta, sle=0.15, sls=0.15, dist='lognormal') {
x=cbind(x)
P=ncol(x)
in.=c()
out.=1:P
step=TRUE
H=0
L=P
y=Surv(time=times, event=delta)
while(step) {
fits=as.list(1:L)
A=matrix(nrow=L, ncol=H+1)
for(i in 1:L) {
if(H==0)
fits[[i]]=survreg(y~x[ , out.[i]], dist=dist)
else
fits[[i]]=survreg(y~x[ , out.[i]]+x[ , in.], dist=dist)
A[i, ]=pnorm(-abs(coef(fits[[i]])[2:(H+2)]/
sqrt(diag(vcov(fits[[i]]))[2:(H+2)])))
}
##return(A)
##forward step
j=which(order(A[ , 1])==1)[1]
if(A[j, 1]<sle) {
in.=c(out.[j], in.)
H=H+1
out.=out.[-j]
L=L-1
if(L==0) step=FALSE
}
else if(H==0) step=FALSE
else {
fits[[1]]=survreg(y~x[ , in.], dist=dist)
A=A[ , -(H+1)]
A[1, ]=pnorm(-abs(coef(fits[[i]])[2:(H+1)]/
sqrt(diag(vcov(fits[[i]]))[2:(H+1)])))
j=1
step=FALSE
}
##backward step
if(H>0) {
k=which(order(-A[j, ])==1)[1]
if(A[j, k]>=sls) {
out.=c(out., in.[k])
L=L+1
in.=in.[-k]
H=H-1
if(step && k==1) step=FALSE
else step=TRUE
}
}
}
return(in.)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/srstepwise.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
stratrs <- function(y, C=5, P=0)
{
N <- length(y)
rs <- integer(N)
if(P>0) {
## for continuous variables
Q=quantile(y, probs=(1:(P-1))/P)
for(i in 1:P) {
if(i<P) {
M <- sum(y<=Q[i])
rs[y<=Q[i]] <- sample(1:M, M)%%C
} else {
M <- sum(y>Q[P-1])
rs[y>Q[P-1] ] <- sample(1:M, M)%%C
}
}
} else {
## for categorical variables
strat <- unique(sort(y))
for(i in strat) {
M <- sum(y==i)
rs[y==i] <- sample(1:M, M)%%C
}
}
return(rs+1)
}
## set.seed(12)
## x <- rbinom(25000, 1, 0.1)
## a <- stratrs(x)
## table(a, x)
## z <- pmin(rpois(25000, 0.8), 5)
## b <- stratrs(z)
## table(b, z)
| /scratch/gouwar.j/cran-all/cranData/BART/R/stratrs.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2018 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
surv.bart <- function(
x.train = matrix(0,0,0),
y.train=NULL, times=NULL, delta=NULL,
x.test = matrix(0,0,0),
K=NULL, events=NULL, ztimes=NULL, zdelta=NULL,
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0,0,0), usequants=FALSE,
## cont=FALSE,
rm.const=TRUE, type='pbart',
ntype=as.integer(
factor(type, levels=c('wbart', 'pbart', 'lbart'))),
k = 2, ## BEWARE: do NOT use k for other purposes below
power = 2, base = 0.95,
offset = NULL, tau.num=c(NA, 3, 6)[ntype],
##binaryOffset = NULL,
ntree = 50L, numcut = 100L,
ndpost = 1000L, nskip = 250L, keepevery = 10L,
##nkeeptrain=ndpost, nkeeptest=ndpost,
##nkeeptreedraws=ndpost,
printevery=100L,
##keeptrainfits=TRUE,
id = NULL, ## only used by surv.bart
seed = 99L, ## only used by mc.surv.bart
mc.cores = 2L, ## ditto
nice=19L ## ditto
)
{
if(is.na(ntype) || ntype==1)
stop("type argument must be set to either 'pbart' or 'lbart'")
x.train <- bartModelMatrix(x.train)
x.test <- bartModelMatrix(x.test)
if(length(rho)==0) rho=ncol(x.train)
if(length(y.train)==0) {
pre <- surv.pre.bart(times, delta, x.train, x.test, K=K,
events=events, ztimes=ztimes, zdelta=zdelta)
y.train <- pre$y.train
x.train <- pre$tx.train
x.test <- pre$tx.test
times <- pre$times
K <- pre$K
##if(length(binaryOffset)==0) binaryOffset <- pre$binaryOffset
}
else {
if(length(unique(sort(y.train)))>2)
stop('y.train has >2 values; make sure you specify times=times & delta=delta')
##if(length(binaryOffset)==0) binaryOffset <- 0
times <- unique(sort(x.train[ , 1]))
K <- length(times)
}
##if(length(binaryOffset)==0) binaryOffset <- qnorm(mean(y.train))
## if(type=='pbart') call <- pbart
## else if(type=='lbart') {
## ##binaryOffset <- 0
## call <- lbart
## }
post <- gbart(x.train=x.train, y.train=y.train,
x.test=x.test, type=type,
sparse=sparse, theta=theta, omega=omega,
a=a, b=b, augment=augment, rho=rho,
xinfo=xinfo, usequants=usequants,
##cont=cont,
rm.const=rm.const,
k=k, power=power, base=base,
offset=offset, tau.num=tau.num,
##binaryOffset=binaryOffset,
ntree=ntree, numcut=numcut,
ndpost=ndpost, nskip=nskip, keepevery=keepevery,
##nkeeptrain=nkeeptrain, nkeeptest=nkeeptest,
##nkeeptestmean=nkeeptestmean,
##nkeeptreedraws=nkeeptreedraws,
printevery=printevery)
if(type!=attr(post, 'class')) return(post)
##post$binaryOffset <- binaryOffset
post$id <- id
post$times <- times
post$K <- K
post$tx.train <- x.train
post$type <- type
## if(keeptrainfits) {
## post$surv.train <- 1-post$prob.train
## H <- nrow(x.train)/K ## the number of different settings
## for(h in 1:H)
## for(j in 2:K) {
## l <- K*(h-1)+j
## post$surv.train[ , l] <-
## post$surv.train[ , l-1]*post$surv.train[ , l]
## }
## post$surv.train.mean <- apply(post$surv.train, 2, mean)
## }
if(length(x.test)>0) {
post$tx.test <- x.test
H <- nrow(x.test)/K ## the number of different settings
post$surv.test <- 1-post$prob.test
## if(type=='pbart') post$surv.test <- 1-pnorm(post$yhat.test)
## else if(type=='lbart') post$surv.test <- 1-plogis(post$yhat.test)
for(h in 1:H)
for(j in 2:K) {
l <- K*(h-1)+j
post$surv.test[ , l] <-
post$surv.test[ , l-1]*post$surv.test[ , l]
}
post$surv.test.mean <- apply(post$surv.test, 2, mean)
}
attr(post, 'class') <- 'survbart'
return(post)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/surv.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017-2022 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
## you call this function before surv.bart()
## this function takes traditional time/delta
## survival variables and regressors (if any)
## and it constructs the corresponding
## tx.train, y.train and tx.test appropriate
## for use with pbart()
surv.pre.bart <- function(
times,
## vector of survival times
delta,
## vector of event indicators: 1 event, 0 censoring
x.train=NULL,
## matrix of covariate regressors
## can be NULL, i.e. KM analog
x.test=NULL,
## matrix of covariate regressors at tx.test settings
K=NULL,
## if specified, then use K quantiles for time grid
events=NULL,
## if specified, then use events for time grid
ztimes=NULL,
zdelta=NULL
## column numbers of (ztimes, zdelta) time-dependent pairs
##u.train=NULL
## shared cluster identifiers
) {
## currently does not handle time dependent Xs
## can be extended later
## most likely via the alternative counting process notation
##binaryOffset <- qnorm(1-exp(-sum(delta)/sum(times)))
N <- length(times)
if(N!=length(delta))
stop('The length of times and delta must be identical')
if(length(x.train)>0 && N!=nrow(x.train))
stop('The length of times and the number of rows in x.train, if any, must be identical')
L <- length(ztimes)
if(L!=length(zdelta))
stop('The length of ztimes and zdelta, if any, must be identical')
if(length(K)>0 || length(events)>0) {
if(length(events)==0)
events <- unique(quantile(times, probs=(1:K)/K))
else if(!all(events==unique(events)))
stop(paste0('events must be unique: ', events))
attr(events, 'names') <- NULL
events=sort(events)
K <- length(events)
for(i in 1:N) {
if(times[i]>events[K]) {
delta[i]=0
times[i]=events[K]
} else {
k <- min(which(times[i]<=events))
times[i] <- events[k]
}
}
}
else {
events <- unique(sort(times))
## time grid of events including censoring times
K <- length(events)
}
##K <- length(events)
if(events[1]<=0)
stop('Time points exist less than or equal to time zero.')
## if(events[1]<0)
## stop('Time points exist less than time zero.')
## else if(events[1]==0) {
## warning('Time points exist equal to time zero.')
## events=events[-1]
## K=K-1
## }
y.train <- integer(N) ## y.train is at least N long
k <- 1
for(i in 1:N) for(j in 1:K) if(events[j] <= times[i]) {
y.train[k] <- delta[i]*(times[i] == events[j])
k <- k+1
}
m <- length(y.train)
##binaryOffset <- qnorm(mean(y.train))
## if(length(u.train)>0) {
## makeU = TRUE
## U.train <- integer(m)
## }
## else {
## makeU = FALSE
## U.train = NULL
## }
if(length(x.train)==0) {
p <- 0
n <- 1
X.train <- matrix(nrow=m, ncol=1, dimnames=list(NULL, 't'))
} else {
if(class(x.train)[1]=='data.frame') x.train=bartModelMatrix(x.train)
p <- ncol(x.train)
if(length(x.test)>0) {
if(class(x.test)[1]=='data.frame') x.test=bartModelMatrix(x.test)
n <- nrow(x.test)
}
X.train <- matrix(nrow=m, ncol=p+1)
if(length(dimnames(x.train)[[2]])>0)
dimnames(X.train)[[2]] <- c('t', dimnames(x.train)[[2]])
else dimnames(X.train)[[2]] <- c('t', paste0('x', 1:p))
}
k <- 1
for(i in 1:N) for(j in 1:K) if(events[j] <= times[i]) {
##if(makeU) U.train[k] <- u.train[i]
if(p==0) X.train[k, ] <- c(events[j])
else X.train[k, ] <- c(events[j], x.train[i, ])
k <- k+1
}
if(p==0 | length(x.test)>0) {
X.test <- matrix(nrow=K*n, ncol=p+1, dimnames=dimnames(X.train))
for(i in 1:n) for(j in 1:K) {
if(p==0) X.test[j, ] <- c(events[j])
else X.test[(i-1)*K+j, ] <- c(events[j], x.test[i, ])
}
}
else X.test <- matrix(nrow=0, ncol=0)*0
if(L>0) {
ztimes=ztimes+1
zdelta=zdelta+1
for(l in 1:L) {
i=ztimes[l]
j=zdelta[l]
X.train[ , j]=X.train[ , j]*(X.train[ , 1]>=X.train[ , i])
X.train[ , i]=X.train[ , 1]-X.train[ , j]*X.train[ , i]
if(length(x.test)>0) {
X.test[ , j]=X.test[ , j]*(X.test[ , 1]>=X.test[ , i])
X.test[ , i]=X.test[ , 1]-X.test[ , j]*X.test[ , i]
}
}
}
return(list(y.train=y.train, tx.train=X.train, tx.test=X.test,
times=events, K=K))
##, u.train=U.train ##binaryOffset=binaryOffset
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/surv.pre.bart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
surv.pwbart <- function(
x.test, #x matrix to predict at with time points expanded
treedraws, #$treedraws for from surv.bart/mc.surv.bart
binaryOffset=0, #mean to add on
mc.cores=1L,
type='pbart',
transposed=FALSE,
nice=19L # mc.surv.pwbart only
)
{
if(!transposed) x.test <- t(bartModelMatrix(x.test))
p <- length(treedraws$cutpoints)
if(p!=nrow(x.test))
stop(paste0('The number of columns in x.test must be equal to ', p))
pred <- list()
pred$yhat.test <- pwbart(x.test, treedraws, binaryOffset, mc.cores, TRUE)
if(class(pred$yhat.test)[1]!='matrix') return(pred$yhat.test)
x.test <- t(x.test)
pred$tx.test <- x.test
times <- unique(sort(x.test[ , 1]))
pred$times <- times
K <- length(times)
pred$K <- K
H <- nrow(x.test)/K ## the number of different settings
if(type=='pbart') pred$prob.test <- pnorm(pred$yhat.test)
else if(type=='lbart') pred$prob.test <- plogis(pred$yhat.test)
pred$surv.test <- 1-pred$prob.test
for(h in 1:H)
for(j in 2:K) {
l <- K*(h-1)+j
pred$surv.test[ , l] <- pred$surv.test[ , l-1]*pred$surv.test[ , l]
}
pred$surv.test.mean <- apply(pred$surv.test, 2, mean)
pred$binaryOffset <- binaryOffset
attr(pred, 'class') <- 'survbart'
return(pred)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/surv.pwbart.R |
## BART: Bayesian Additive Regression Trees
## Copyright (C) 2017 Robert McCulloch and Rodney Sparapani
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, a copy is available at
## https://www.R-project.org/Licenses/GPL-2
wbart=function(
x.train, y.train, x.test=matrix(0.0,0,0),
sparse=FALSE, theta=0, omega=1,
a=0.5, b=1, augment=FALSE, rho=NULL,
xinfo=matrix(0.0,0,0), usequants=FALSE,
cont=FALSE, rm.const=TRUE,
sigest=NA, sigdf=3, sigquant=.90,
k=2.0, power=2.0, base=.95,
sigmaf=NA, lambda=NA,
fmean=mean(y.train),
w=rep(1,length(y.train)),
ntree=200L, numcut=100L,
ndpost=1000L, nskip=100L, keepevery=1L,
nkeeptrain=ndpost, nkeeptest=ndpost,
nkeeptestmean=ndpost, nkeeptreedraws=ndpost,
printevery=100L, transposed=FALSE
)
{
#--------------------------------------------------
#data
n = length(y.train)
if(!transposed) {
temp = bartModelMatrix(x.train, numcut, usequants=usequants,
cont=cont, xinfo=xinfo, rm.const=rm.const)
x.train = t(temp$X)
numcut = temp$numcut
xinfo = temp$xinfo
if(length(x.test)>0) {
x.test = bartModelMatrix(x.test)
x.test = t(x.test[ , temp$rm.const])
}
rm.const <- temp$rm.const
grp <- temp$grp
rm(temp)
}
else {
rm.const <- NULL
grp <- NULL
}
if(n!=ncol(x.train))
stop('The length of y.train and the number of rows in x.train must be identical')
p = nrow(x.train)
np = ncol(x.test)
if(length(rho)==0) rho=p
if(length(rm.const)==0) rm.const <- 1:p
if(length(grp)==0) grp <- 1:p
##if(p>1 & length(numcut)==1) numcut=rep(numcut, p)
y.train = y.train-fmean
#--------------------------------------------------
#set nkeeps for thinning
if((nkeeptrain!=0) & ((ndpost %% nkeeptrain) != 0)) {
nkeeptrain=ndpost
cat('*****nkeeptrain set to ndpost\n')
}
if((nkeeptest!=0) & ((ndpost %% nkeeptest) != 0)) {
nkeeptest=ndpost
cat('*****nkeeptest set to ndpost\n')
}
if((nkeeptestmean!=0) & ((ndpost %% nkeeptestmean) != 0)) {
nkeeptestmean=ndpost
cat('*****nkeeptestmean set to ndpost\n')
}
if((nkeeptreedraws!=0) & ((ndpost %% nkeeptreedraws) != 0)) {
nkeeptreedraws=ndpost
cat('*****nkeeptreedraws set to ndpost\n')
}
#--------------------------------------------------
#prior
nu=sigdf
if(is.na(lambda)) {
if(is.na(sigest)) {
if(p < n) {
df = data.frame(t(x.train),y.train)
lmf = lm(y.train~.,df)
sigest = summary(lmf)$sigma
} else {
sigest = sd(y.train)
}
}
qchi = qchisq(1.0-sigquant,nu)
lambda = (sigest*sigest*qchi)/nu #lambda parameter for sigma prior
} else {
sigest=sqrt(lambda)
}
if(is.na(sigmaf)) {
tau=(max(y.train)-min(y.train))/(2*k*sqrt(ntree))
} else {
tau = sigmaf/sqrt(ntree)
}
#--------------------------------------------------
ptm <- proc.time()
#call
res = .Call("cwbart",
n, #number of observations in training data
p, #dimension of x
np, #number of observations in test data
x.train, #pxn training data x
y.train, #pxn training data x
x.test, #p*np test data x
ntree,
numcut,
ndpost*keepevery,
nskip,
power,
base,
tau,
nu,
lambda,
sigest,
w,
sparse,
theta,
omega,
grp,
a,
b,
rho,
augment,
nkeeptrain,
nkeeptest,
nkeeptestmean,
nkeeptreedraws,
printevery,
xinfo
)
res$proc.time <- proc.time()-ptm
res$mu = fmean
res$yhat.train.mean = res$yhat.train.mean+fmean
res$yhat.train = res$yhat.train+fmean
res$yhat.test.mean = res$yhat.test.mean+fmean
res$yhat.test = res$yhat.test+fmean
if(nkeeptreedraws>0)
names(res$treedraws$cutpoints) = dimnames(x.train)[[1]]
dimnames(res$varcount)[[2]] = as.list(dimnames(x.train)[[1]])
dimnames(res$varprob)[[2]] = as.list(dimnames(x.train)[[1]])
##res$nkeeptreedraws=nkeeptreedraws
res$varcount.mean <- apply(res$varcount, 2, mean)
res$varprob.mean <- apply(res$varprob, 2, mean)
res$rm.const <- rm.const
attr(res, 'class') <- 'wbart'
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BART/R/wbart.R |
library(BART)
data(ACTG175)
## exclude those who do not have CD4 count at 96 weeks
## or their baseline CD4 is ineligible
## (inclusion criteria: CD4 counts between 200 and 500)
ex <- is.na(ACTG175$cd496) | ACTG175$cd40<200 | ACTG175$cd40>500
table(ex)
## calculate relative CD4 decline
y <- ((ACTG175$cd496-ACTG175$cd40)/ACTG175$cd40)[!ex]
summary(y)
## 0=failure, 1=success
y <- 1*(y > -0.5)
## summarize CD4 outcomes
a <- table(y, ACTG175$arms[!ex])
b <- apply(a, 2, sum)
a/rbind(b, b)
## drop unneeded and unwanted variables
## 1: 'pidnum' patient ID number
##10: 'zprior' zidovudine use prior to treatment initiation
##14: 'str2' which will be handled by strat1 below
##15: 'strat' which will be handled by strat1-strat3 below
##17: 'treat' handled by arm0-arm3 below
##18: 'offtrt' indicator of off-treatment before 96 weeks
##20: 'cd420' CD4 T cell count at 20 weeks
##21: 'cd496' CD4 T cell count at 96 weeks
##22: 'r' missing CD4 T cell count at 96 weeks
##23: 'cd80' CD8 T cell count at baseline
##24: 'cd820' CD8 T cell count at 20 weeks
##25: 'cens' indicator of observing the event in days
##26: 'days' number of days until the primary endpoint
##27: 'arms' handled by arm0-arm3 below
train <- as.matrix(ACTG175)[!ex, -c(1, 10, 14:15, 17, 18, 20:27)]
train <- cbind(1*(ACTG175$strat[!ex]==1), 1*(ACTG175$strat[!ex]==2),
1*(ACTG175$strat[!ex]==3), train)
dimnames(train)[[2]][1:3] <- paste0('strat', 1:3)
train <- cbind(1*(ACTG175$arms[!ex]==0), 1*(ACTG175$arms[!ex]==1),
1*(ACTG175$arms[!ex]==2), 1*(ACTG175$arms[!ex]==3), train)
dimnames(train)[[2]][1:4] <- paste0('arm', 0:3)
N <- nrow(train)
test0 <- train; test0[ , 1:4] <- 0; test0[ , 1] <- 1
test1 <- train; test1[ , 1:4] <- 0; test1[ , 2] <- 1
test2 <- train; test2[ , 1:4] <- 0; test2[ , 3] <- 1
test3 <- train; test3[ , 1:4] <- 0; test3[ , 4] <- 1
test <- rbind(test0, test1, test2, test3)
set.seed(21)
post <- mc.lbart(train, y, test, mc.cores=8)
## place estimates for arms 0-3 next to each other for convenience
itr <- cbind(post$prob.test.mean[(1:N)],
post$prob.test.mean[N+(1:N)],
post$prob.test.mean[2*N+(1:N)],
post$prob.test.mean[3*N+(1:N)])
## find the BART ITR for each patient
itr.pick <- integer(N)
for(i in 1:N) itr.pick[i] <- which(itr[i, ]==max(itr[i, ]))-1
## arms 0 and 3 (monotherapy) are never chosen
table(itr.pick)
## do arms 1 and 2 show treatment heterogeneity?
diff. <- apply(post$prob.test[ , 2*N+(1:N)]-
post$prob.test[ , N+(1:N)], 2, mean)
plot(sort(diff.), type='h',
main='ACTG175 trial: 50% CD4 decline from baseline at 96 weeks',
xlab='Arm 2 (1) Preferable to the Right (Left)',
ylab='Prob.Diff.: Arms 2 - 1')
library(rpart)
library(rpart.plot)
## make data frame for nicer names in the plot
var <- as.data.frame(train[ , -(1:4)])
##check <- complete.cases(var)
##table(check)
dss <- rpart(diff. ~ var$age+var$gender+var$race+var$wtkg+##var$cd80+
var$karnof+var$symptom+var$hemo+var$homo+var$drugs+var$z30+
var$oprior+var$strat1+var$strat2+var$strat3,
method='anova', control=rpart.control(cp=0.05))
rpart.plot(dss, type=3, extra=101)
## if drugs==1, then arm 1
## otherwise, arm 2
print(dss)
all0 <- apply(post$prob.test[ , (1:N)], 1, mean)
all1 <- apply(post$prob.test[ , N+(1:N)], 1, mean)
all2 <- apply(post$prob.test[ , 2*N+(1:N)], 1, mean)
all3 <- apply(post$prob.test[ , 3*N+(1:N)], 1, mean)
## BART ITR
BART.itr <- apply(post$prob.test[ , c(N+which(itr.pick==1), 2*N+which(itr.pick==2))], 1, mean)
test <- train
test[ , 1:4] <- 0
test[var$drugs==1, 2] <- 1
test[ , 3] <- 1-test[ , 2]
table(test[ , 2], test[ , 3])
## BART ITR simple
BART.itr.simp <- predict(post, newdata=test, mc.cores=8)
BART.itr.simp$prob <- apply(BART.itr.simp$prob.test, 1, mean)
plot(density(BART.itr), xlab='Value', lwd=2, xlim=c(0.7, 0.95),
main='ACTG175 trial: 50% CD4 decline from baseline at 96 weeks')
lines(density(BART.itr.simp$prob), col='brown', lwd=2)
lines(density(all0), col='green', lwd=2)
lines(density(all1), col='red', lwd=2)
lines(density(all2), col='blue', lwd=2)
lines(density(all3), col='yellow', lwd=2)
legend('topleft', legend=c('All Arm 0 (ZDV only)',
'All Arm 1 (ZDV+DDI)',
'All Arm 2 (ZDV+DDC)',
'All Arm 3 (DDI only)',
'BART ITR simple',
'BART ITR'),
col=c('green', 'red', 'blue', 'yellow', 'brown', 'black'),
lty=1, lwd=2)
##dev.copy2pdf(file='aids.itr.lbart.pdf')
| /scratch/gouwar.j/cran-all/cranData/BART/demo/aids.itr.lbart.R |
library(BART)
data(ACTG175)
## exclude those who do not have CD4 count at 96 weeks
## or their baseline CD4 is ineligible
## (inclusion criteria: CD4 counts between 200 and 500)
ex <- is.na(ACTG175$cd496) | ACTG175$cd40<200 | ACTG175$cd40>500
table(ex)
## calculate relative CD4 decline
y <- ((ACTG175$cd496-ACTG175$cd40)/ACTG175$cd40)[!ex]
summary(y)
## 0=failure, 1=success
y <- 1*(y > -0.5)
## summarize CD4 outcomes
a <- table(y, ACTG175$arms[!ex])
b <- apply(a, 2, sum)
a/rbind(b, b)
## drop unneeded and unwanted variables
## 1: 'pidnum' patient ID number
##10: 'zprior' zidovudine use prior to treatment initiation
##14: 'str2' which will be handled by strat1 below
##15: 'strat' which will be handled by strat1-strat3 below
##17: 'treat' handled by arm0-arm3 below
##18: 'offtrt' indicator of off-treatment before 96 weeks
##20: 'cd420' CD4 T cell count at 20 weeks
##21: 'cd496' CD4 T cell count at 96 weeks
##22: 'r' missing CD4 T cell count at 96 weeks
##23: 'cd80' CD8 T cell count at baseline
##24: 'cd820' CD8 T cell count at 20 weeks
##25: 'cens' indicator of observing the event in days
##26: 'days' number of days until the primary endpoint
##27: 'arms' handled by arm0-arm3 below
train <- as.matrix(ACTG175)[!ex, -c(1, 10, 14:15, 17, 18, 20:27)]
train <- cbind(1*(ACTG175$strat[!ex]==1), 1*(ACTG175$strat[!ex]==2),
1*(ACTG175$strat[!ex]==3), train)
dimnames(train)[[2]][1:3] <- paste0('strat', 1:3)
train <- cbind(1*(ACTG175$arms[!ex]==0), 1*(ACTG175$arms[!ex]==1),
1*(ACTG175$arms[!ex]==2), 1*(ACTG175$arms[!ex]==3), train)
dimnames(train)[[2]][1:4] <- paste0('arm', 0:3)
N <- nrow(train)
test0 <- train; test0[ , 1:4] <- 0; test0[ , 1] <- 1
test1 <- train; test1[ , 1:4] <- 0; test1[ , 2] <- 1
test2 <- train; test2[ , 1:4] <- 0; test2[ , 3] <- 1
test3 <- train; test3[ , 1:4] <- 0; test3[ , 4] <- 1
test <- rbind(test0, test1, test2, test3)
set.seed(21)
post <- pbart(train, y, test)
## place estimates for arms 0-3 next to each other for convenience
itr <- cbind(post$prob.test.mean[(1:N)],
post$prob.test.mean[N+(1:N)],
post$prob.test.mean[2*N+(1:N)],
post$prob.test.mean[3*N+(1:N)])
## find the BART ITR for each patient
itr.pick <- integer(N)
for(i in 1:N) itr.pick[i] <- which(itr[i, ]==max(itr[i, ]))-1
## arms 0 and 3 (monotherapy) are never chosen
table(itr.pick)
## do arms 1 and 2 show treatment heterogeneity?
diff. <- apply(post$prob.test[ , 2*N+(1:N)]-
post$prob.test[ , N+(1:N)], 2, mean)
plot(sort(diff.), type='h',
main='ACTG175 trial: 50% CD4 decline from baseline at 96 weeks',
xlab='Arm 2 (1) Preferable to the Right (Left)',
ylab='Prob.Diff.: Arms 2 - 1')
library(rpart)
library(rpart.plot)
## make data frame for nicer names in the plot
var <- as.data.frame(train[ , -(1:4)])
##check <- complete.cases(var)
##table(check)
dss <- rpart(diff. ~ var$age+var$gender+var$race+var$wtkg+##var$cd80+
var$karnof+var$symptom+var$hemo+var$homo+var$drugs+var$z30+
var$oprior+var$strat1+var$strat2+var$strat3,
method='anova', control=rpart.control(cp=0.05))
rpart.plot(dss, type=3, extra=101)
## if race==0 & (age<30.5 | drugs==0), then arm 2
## otherwise, arm 1
print(dss)
all0 <- apply(post$prob.test[ , (1:N)], 1, mean)
all1 <- apply(post$prob.test[ , N+(1:N)], 1, mean)
all2 <- apply(post$prob.test[ , 2*N+(1:N)], 1, mean)
all3 <- apply(post$prob.test[ , 3*N+(1:N)], 1, mean)
## BART ITR
BART.itr <- apply(post$prob.test[ , c(N+which(itr.pick==1), 2*N+which(itr.pick==2))], 1, mean)
test <- train
test[ , 1:4] <- 0
test[var$race==0 & (var$age<30.5 | var$drugs==0), 3] <- 1
test[ , 2] <- 1-test[ , 3]
table(test[ , 2], test[ , 3])
## BART ITR simple
BART.itr.simp <- predict(post, newdata=test, mc.cores=8)
BART.itr.simp$prob <- apply(BART.itr.simp$prob.test, 1, mean)
plot(density(BART.itr), xlab='Value', lwd=2, xlim=c(0.7, 0.95),
main='ACTG175 trial: 50% CD4 decline from baseline at 96 weeks')
lines(density(BART.itr.simp$prob), col='brown', lwd=2)
lines(density(all0), col='green', lwd=2)
lines(density(all1), col='red', lwd=2)
lines(density(all2), col='blue', lwd=2)
lines(density(all3), col='yellow', lwd=2)
legend('topleft', legend=c('All Arm 0 (ZDV only)',
'All Arm 1 (ZDV+DDI)',
'All Arm 2 (ZDV+DDC)',
'All Arm 3 (DDI only)',
'BART ITR simple',
'BART ITR'),
col=c('green', 'red', 'blue', 'yellow', 'brown', 'black'),
lty=1, lwd=2)
| /scratch/gouwar.j/cran-all/cranData/BART/demo/aids.itr.pbart.R |
library(BART)
B <- getOption('mc.cores', 1)
figures = getOption('figures', default='NONE')
data(alligator)
## nnet::multinom Multinomial logit model fit with neural nets
fit <- multinom(food ~ lake+size+sex, data=alligator, weights=count)
summary(fit$fitted.values)
## 1=bird, 2=fish, 3=invert, 4=other, 5=reptile
(L=length(alligator$count))
(N=sum(alligator$count))
y.train=integer(N)
x.train=matrix(nrow=N, ncol=3)
x.test=matrix(nrow=L, ncol=3)
k=1
for(i in 1:L) {
x.test[i, ]=as.integer(
c(alligator$lake[i], alligator$size[i], alligator$sex[i]))
if(alligator$count[i]>0)
for(j in 1:alligator$count[i]) {
y.train[k]=as.integer(alligator$food[i])
x.train[k, ]=as.integer(
c(alligator$lake[i], alligator$size[i], alligator$sex[i]))
k=k+1
}
}
table(y.train)
post=mc.mbart(x.train, y.train, x.test, mc.cores=B, seed=99)
##check=predict(post, x.test, mc.cores=B)
##print(cor(post$prob.test.mean, check$prob.test.mean)^2)
par(mfrow=c(3, 2))
K=5
for(j in 1:5) {
h=seq(j, L*K, K)
print(cor(fit$fitted.values[ , j], post$prob.test.mean[h])^2)
plot(fit$fitted.values[ , j], post$prob.test.mean[h],
xlim=0:1, ylim=0:1,
xlab=paste0('NN: Est. Prob. j=', j),
ylab=paste0('BART: Est. Prob. j=', j))
abline(a=0, b=1)
}
par(mfrow=c(1, 1))
L=16
x.test=matrix(nrow=L, ncol=3)
k=1
for(size in 1:2)
for(sex in 1:2)
for(lake in 1:4) {
x.test[k, ]=c(lake, size, sex)
k=k+1
}
x.test
## two sizes: 1=large: >2.3m, 2=small: <=2.3m
pred=predict(post, x.test, mc.cores=B)
ndpost=nrow(pred$prob.test)
size.test=matrix(nrow=ndpost, ncol=K*2)
for(i in 1:K) {
j=seq(i, L*K/2, K) ## large
size.test[ , i]=apply(pred$prob.test[ , j], 1, mean)
j=j+L*K/2 ## small
size.test[ , i+K]=apply(pred$prob.test[ , j], 1, mean)
}
size.test.mean=apply(size.test, 2, mean)
size.test.025=apply(size.test, 2, quantile, probs=0.025)
size.test.975=apply(size.test, 2, quantile, probs=0.975)
k=1:K
size.test.LH1=double(2*K)
size.test.LH1[2*k-1]=size.test.025[k]
size.test.LH1[2*k]=size.test.975[k]
size.test.LH2=double(2*K)
size.test.LH2[2*k-1]=size.test.025[k+K]
size.test.LH2[2*k]=size.test.975[k+K]
plot(factor(k, labels=c('bird', 'fish', 'invert', 'other', 'reptile')),
rep(1, K), col=k, type='n', lwd=2, lty=0,
xlim=c(1, K), ylim=c(0, 0.6), ylab='Probability',
sub="Multinomial BART\nFriedman's partial dependence function")
points(k-0.05, size.test.mean[k+K], lwd=2, col=1)
points(k+0.05, size.test.mean[k], lwd=2, col=2)
for(k in 1:K) {
lines(rep(k+0.05, 2), size.test.LH1[c(2*k-1, 2*k)], lwd=2, col=2)
lines(rep(k-0.05, 2), size.test.LH2[c(2*k-1, 2*k)], lwd=2, lty=2)
}
legend('topright', legend=c('Small', 'Large'),
pch=1, col=1:2, lty=2:1, lwd=2)
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'alligator.pdf', sep='/'))
## plot(factor(1:K, labels=c('bird', 'fish', 'invert', 'other', 'reptile')),
## rep(1, K), col=1:K, type='n', lwd=2, lty=0,
## xlim=c(1, K), ylim=c(0, 0.5), ylab='Prob.',
## sub="Multinomial BART\nFriedman's partial dependence function")
## points(1:K, size.test.mean[1:K+K], lwd=2, col=1)
## lines(1:K, size.test.025[1:K+K], lwd=2, col=1, lty=2)
## lines(1:K, size.test.975[1:K+K], lwd=2, col=1, lty=2)
## points(1:K, size.test.mean[1:K], lwd=2, col=2)
## lines(1:K, size.test.025[1:K], lwd=2, col=2, lty=2)
## lines(1:K, size.test.975[1:K], lwd=2, col=2, lty=2)
## legend('topright', legend=c('Small', 'Large'),
## pch=1, col=1:2)
| /scratch/gouwar.j/cran-all/cranData/BART/demo/alligator.R |
library(BART)
B <- getOption('mc.cores', 1)
figures = getOption('figures', default='NONE')
data(bladder)
subset <- -which(bladder1$stop==0)
bladder0 <- bladder1[subset, ]
id <- unique(sort(bladder0$id))
N <- length(id)
L <- max(bladder0$enum)
times <- matrix(0, nrow=N, ncol=L)
dimnames(times)[[1]] <- paste0(id)
delta <- matrix(0, nrow=N, ncol=L)
dimnames(delta)[[1]] <- paste0(id)
x.train <- matrix(NA, nrow=N, ncol=3+2*L) ## add time-dependent cols too
dimnames(x.train)[[1]] <- paste0(id)
dimnames(x.train)[[2]] <- c('Pl', 'B6', 'Th', rep(c('number', 'size'), L))
for(i in 1:N) {
h <- id[i]
for(j in 1:L) {
k <- which(bladder0$id==h & bladder0$enum==j)
if(length(k)==1) {
times[i, j] <- bladder0$stop[k]
delta[i, j] <- (bladder0$status[k]==1)*1
if(j==1) {
x.train[i, 1] <- as.numeric(bladder0$treatment[k])==1
x.train[i, 2] <- as.numeric(bladder0$treatment[k])==2
x.train[i, 3] <- as.numeric(bladder0$treatment[k])==3
x.train[i, 4] <- bladder0$number[k]
x.train[i, 5] <- bladder0$size[k]
}
else if(delta[i, j]==1) {
if(bladder0$rtumor[k]!='.')
x.train[i, 2*j+2] <- as.numeric(bladder0$rtumor[k])
if(bladder0$rsize[k]!='.')
x.train[i, 2*j+3] <- as.numeric(bladder0$rsize[k])
}
}
}
}
pre <- recur.pre.bart(times=times, delta=delta, x.train=x.train)
J <- nrow(pre$tx.train)
for(j in 1:J) {
if(pre$tx.train[j, 3]>0) {
pre$tx.train[j, 7] <- pre$tx.train[j, 7+pre$tx.train[j, 3]*2]
pre$tx.train[j, 8] <- pre$tx.train[j, 8+pre$tx.train[j, 3]*2]
}
}
pre$tx.train <- pre$tx.train[ , 1:8]
K <- pre$K
NK <- N*K
for(j in 1:NK) {
if(pre$tx.test[j, 3]>0) {
pre$tx.test[j, 7] <- pre$tx.test[j, 7+pre$tx.test[j, 3]*2]
pre$tx.test[j, 8] <- pre$tx.test[j, 8+pre$tx.test[j, 3]*2]
}
}
pre$tx.test <- pre$tx.test[ , 1:8]
## in bladder1 both number and size are recorded as integers
## from 1 to 8 however they are often missing for recurrences
## at baseline there are no missing and 1 is the mode of both
pre$tx.train[which(is.na(pre$tx.train[ , 7])), 7] <- 1
pre$tx.train[which(is.na(pre$tx.train[ , 8])), 8] <- 1
pre$tx.test[which(is.na(pre$tx.test[ , 7])), 7] <- 1
pre$tx.test[which(is.na(pre$tx.test[ , 8])), 8] <- 1
## it is a good idea to explore more sophisticated methods
## such as imputing the missing data with Sequential BART
## Xu, Daniels and Winterstein. Sequential BART for imputation of missing
## covariates. Biostatistics 2016 doi: 10.1093/biostatistics/kxw009
## http://biostatistics.oxfordjournals.org/content/early/2016/03/15/biostatistics.kxw009/suppl/DC1
## https://cran.r-project.org/package=sbart
## library(sbart)
## set.seed(21)
## train <- seqBART(xx=pre$tx.train, yy=NULL, datatype=rep(0, 6),
## type=0, numskip=20, burn=1000)
## coarsen the imputed data same way as observed example data
## train$imputed5[which(train$imputed5[ , 7]<1), 7] <- 1
## train$imputed5[which(train$imputed5[ , 7]>8), 7] <- 8
## train$imputed5[ , 7] <- round(train$imputed5[ , 7])
## train$imputed5[which(train$imputed5[ , 8]<1), 8] <- 1
## train$imputed5[which(train$imputed5[ , 8]>8), 8] <- 8
## train$imputed5[ , 8] <- round(train$imputed5[ , 8])
## for Friedman's partial dependence, we need to estimate the whole cohort
## at each treatment assignment (and, average over those)
pre$tx.test <- rbind(pre$tx.test, pre$tx.test, pre$tx.test)
pre$tx.test[ , 4] <- c(rep(1, NK), rep(0, 2*NK)) ## Pl
pre$tx.test[ , 5] <- c(rep(0, NK), rep(1, NK), rep(0, NK))## B6
pre$tx.test[ , 6] <- c(rep(0, 2*NK), rep(1, NK)) ## Th
## set.seed(99)
## post <- recur.bart(y.train=pre$y.train, x.train=pre$tx.train, x.test=pre$tx.test)
## depending on your performance, you may want to run in parallel if available
post <- mc.recur.bart(y.train=pre$y.train, x.train=pre$tx.train,
x.test=pre$tx.test, mc.cores=B, seed=99)
M <- nrow(post$yhat.test)
RI.B6.Pl <- matrix(0, nrow=M, ncol=K)
RI.Th.Pl <- matrix(0, nrow=M, ncol=K)
RI.Th.B6 <- matrix(0, nrow=M, ncol=K)
for(j in 1:K) {
h <- seq(j, NK, K)
RI.B6.Pl[ , j] <- apply(post$prob.test[ , h+NK]/
post$prob.test[ , h], 1, mean)
RI.Th.Pl[ , j] <- apply(post$prob.test[ , h+2*NK]/
post$prob.test[ , h], 1, mean)
RI.Th.B6[ , j] <- apply(post$prob.test[ , h+2*NK]/
post$prob.test[ , h+NK], 1, mean)
}
RI.B6.Pl.mu <- apply(RI.B6.Pl, 2, mean)
RI.B6.Pl.025 <- apply(RI.B6.Pl, 2, quantile, probs=0.025)
RI.B6.Pl.975 <- apply(RI.B6.Pl, 2, quantile, probs=0.975)
RI.Th.Pl.mu <- apply(RI.Th.Pl, 2, mean)
RI.Th.Pl.025 <- apply(RI.Th.Pl, 2, quantile, probs=0.025)
RI.Th.Pl.975 <- apply(RI.Th.Pl, 2, quantile, probs=0.975)
RI.Th.B6.mu <- apply(RI.Th.B6, 2, mean)
RI.Th.B6.025 <- apply(RI.Th.B6, 2, quantile, probs=0.025)
RI.Th.B6.975 <- apply(RI.Th.B6, 2, quantile, probs=0.975)
plot(post$times, RI.Th.Pl.mu, col='blue',
log='y', main='Bladder cancer: Thiotepa vs. Placebo',
type='l', ylim=c(0.1, 10), ylab='RI(t)', xlab='t (months)')
lines(post$times, RI.Th.Pl.025, col='red')
lines(post$times, RI.Th.Pl.975, col='red')
abline(h=1)
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'RI-Th-Pl.pdf', sep='/'))
plot(post$times, RI.B6.Pl.mu, col='blue',
log='y', main='Bladder cancer: Vitamin B6 vs. Placebo',
type='l', ylim=c(0.1, 10), ylab='RI(t)', xlab='t (months)')
lines(post$times, RI.B6.Pl.025, col='red')
lines(post$times, RI.B6.Pl.975, col='red')
abline(h=1)
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'RI-B6-Pl.pdf', sep='/'))
plot(post$times, RI.Th.B6.mu, col='blue',
log='y', main='Bladder cancer: Thiotepa vs. Vitamin B6',
type='l', ylim=c(0.1, 10), ylab='RI(t)', xlab='t (months)')
lines(post$times, RI.Th.B6.025, col='red')
lines(post$times, RI.Th.B6.975, col='red')
abline(h=1)
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'RI-Th-B6.pdf', sep='/'))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/bladder.recur.bart.R |
library(MASS)
B <- getOption('mc.cores', 1)
figures = getOption('figures', default='NONE')
x = Boston[,c(6,13)] #rm=number of rooms and lstat= percent lower status
y = Boston$medv # median value
head(cbind(x, y))
par(mfrow=c(2,2))
par(mai=c(.8,.8,.2,.2))
plot(x[,1],y,xlab="x1=rm",ylab="y=mdev",cex.axis=1.3,cex.lab=1.2)
plot(x[,2],y,xlab="x2=lstat",ylab="y=mdev",cex.axis=1.3,cex.lab=1.2)
plot(x[,1],x[,2],xlab="x1=rm",ylab="x2=lstat",cex.axis=1.3,cex.lab=1.2) > par(mfrow=c(1,1))
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'boston1.pdf', sep='/'))
library(BART) ## load library
set.seed(99) ## MCMC posterior sampling: set seed for reproducibility
nd=200 ## number of draws to keep
burn=50 ## number of draws to discard
bf = wbart(x,y,nskip=burn,ndpost=nd)
plot(bf$sigma, ylab='post$sigma', type="l")
abline(v=burn,lwd=2,col="red")
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'boston2.pdf', sep='/'))
lmf = lm(y~.,data.frame(x,y))
fitmat = cbind(y,bf$yhat.train.mean,lmf$fitted.values)
colnames(fitmat)=c("y","BART","Linear")
cor(fitmat)
pairs(fitmat)
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'boston3.pdf', sep='/'))
ii = order(bf$yhat.train.mean) ## order observations by predicted value
boxplot(bf$yhat.train[,ii], ylab='post$yhat.train') ## boxplots of f(x) draws
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'boston4.pdf', sep='/'))
n=length(y) ## total sample size
set.seed(14) ## Dave Keon, greatest Leaf of all time!
## ii = sample(1:n,floor(.75*n)) ## indices for train data, 75% of data
## xtrain=x[ii,]; ytrain=y[ii] ## training data
## xtest=x[-ii,]; ytest=y[-ii] ## test data
## cat("train sample size is ",length(ytrain),"\n")
## cat("test sample size is ",length(ytest),"\n")
i <- sample(1:n, floor(0.75 * n))
xtrain <- x[i, ]; ytrain = y[i]
xtest <- x[-i, ]; ytest = y[-i]
cat("training sample size = ", length(ytrain), "\n")
cat("testing sample size = ", length(ytest), "\n")
set.seed(99)
bfp1 = wbart(xtrain,ytrain,xtest)
set.seed(99)
bfp2 = wbart(xtrain,ytrain)
yhat = predict(bfp2, as.matrix(xtest), mc.cores=B)
set.seed(4) #Bobby Orr's jersey number is the seed
bfthin = wbart(xtrain,ytrain,nskip=1000,ndpost=10000,
nkeeptrain=0,nkeeptest=0,nkeeptestmean=0,nkeeptreedraws=200)
yhatthin = predict(bfthin, as.matrix(xtest), mc.cores=B)
fmat=cbind(ytest,bfp1$yhat.test.mean,apply(yhatthin,2,mean))
colnames(fmat) = c("y","yhat","yhatThin")
##colnames(fmat) = c("y","BARTpred","BARTpredThin")
pairs(fmat)
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'boston5.pdf', sep='/'))
y.train = ytrain
x.train = as.matrix(Boston[i, -14])
set.seed(12) ## Aaron Rodgers
post4 = wbart(x.train, y.train)
N=379
L=41
x=seq(min(x.train[ , 13]), max(x.train[ , 13]), length.out=L)
x.test = cbind(x.train[ , -13], x[1])
names(x.test)[13]='lstat'
for(j in 2:L)
x.test = rbind(x.test, cbind(x.train[ , -13], x[j]))
pred1 = predict(post4, x.test, mc.cores=B)
partial = matrix(nrow=1000, ncol=L)
for(j in 1:L) {
h=(j-1)*N+1:N
partial[ , j] = apply(pred1[ , h], 1, mean)
}
plot(x, apply(partial, 2, mean), type='l',
xlab='lstat', ylab='mdev',
##xlab='lstat: percent lower status', ylab='mdev: median home value',
ylim=c(10, 50))
lines(x, apply(partial, 2, quantile, probs=0.025), lty=2)
lines(x, apply(partial, 2, quantile, probs=0.975), lty=2)
if(figures!='NONE')
dev.copy2pdf(file=paste(figures, 'boston6.pdf', sep='/'))
H = 6
x.train.mean = apply(x.train, 2, mean)
x.test = matrix(x.train.mean, nrow=H, ncol=13, byrow=TRUE)
dimnames(x.test)[[2]]=names(x.train.mean)
##lstat = range(x.train[ , 'lstat'])
lstat = quantile(x.train[ , 'lstat'], probs=c(0.05, 0.95))
lstat = seq(lstat[1], lstat[2], length.out=H)
lstat.diff = lstat[2]-lstat[1]
x.test[ , 'lstat'] = lstat
pred2 = predict(post4, x.test, mc.cores=B)
diff = (pred2[ , 2:H]-pred2[ , 1:(H-1)])/lstat.diff
diff.mean = apply(diff, 2, mean)
diff.025 = apply(diff, 2, quantile, probs=0.025)
diff.975 = apply(diff, 2, quantile, probs=0.975)
plot(lstat[-H], diff.mean, type='l',
xlab='lstat', ylab='conditional effect',
ylim=c(min(min(diff.025), -max(diff.975)),
max(-min(diff.025), max(diff.975))))
lines(lstat[-H], diff.025, type='l', lty=2)
lines(lstat[-H], diff.975, type='l', lty=2)
abline(h=0, col='gray')
| /scratch/gouwar.j/cran-all/cranData/BART/demo/boston.R |
library(BART)
## estimate concordance probability: P(t1<t2)
N <- 2000
r1 <- 0.1
r2 <- 0.3
## true concordance
true.p <- r1/(r1+r2)
set.seed(12)
x <- rbinom(N, 1, 0.5)
t <- ceiling(rexp(N, r1*x+r2*(1-x)))
c <- ceiling(rexp(N, 0.035))
delta <- (t<c)
table(delta)/N
t <- delta*t+(1-delta)*c
post <- mc.surv.bart(x.train=cbind(x), x.test=rbind(0, 1),
times=t, delta=delta, mc.cores=8, seed=99)
K <- post$K
q <- 1-pnorm(post$yhat.test)
for(j in 1:K) {
if(j==1) P <- q[ , K+1]-q[ , 1]
else P <- P+(q[ , K+j]-q[ , j])*post$surv.test[ , K+j-1]*post$surv.test[ , j-1]
}
C <- 0.5*(1-P)
## estimate concordance
summary(C)
| /scratch/gouwar.j/cran-all/cranData/BART/demo/c.surv.bart.R |
library(BART)
## simulate recurrent events data set with Exponential proportional intensity
N <- 250
K <- 60
NK <- N*K
C <- 8
set.seed(-1)
x <- matrix(nrow=NK, ncol=23)
dimnames(x)[[2]] <- c('t', 'v', 'N', paste0('x', 1:20))
b <- c(1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1.5, 0, 0, 0, 0, 0, 0, 0, 0, 0)
N. <- double(NK)
y <- integer(NK)
cum <- double(NK)
k <- 1
for(i in 1:N) {
v <- 0
x[k, 4:13] <- runif(10)
x[k, 14:23] <- rbinom(10, 1, 0.5)
for(j in 1:K) {
x[k, 1:3] <- c(j, j-v, N.[k])
if(j>1) x[k, 4:23] <- x[k-1, 4:23]
alpha <- 0.0001*exp(sum(b*x[k, 4:23])+sqrt(N.[k]))
cum[k] <- pexp(30, alpha)
y[k] <- rbinom(1, 1, cum[k])
if(y[k]==1) v <- j
if(j>1) cum[k] <- cum[k-1]+cum[k]
if(j<K) N.[k+1] <- N.[k]+y[k]
k <- k+1
}
}
table(x[K*(1:N), 3])
table(x[K*(1:N), 3])/N
for(i in 1:N) {
j <- (i-1)*K+1:K
if(i==1) plot(1:K, cum[j], type='l',
xlab='t', ylab=expression(Lambda(t, x)),
sub='Proportional Setting', ylim=c(0, 20))
else lines(1:K, cum[j], col=i)
}
M <- 5
H <- NK/5
fits <- as.list(1:M)
x.test <- as.list(1:M)
x.train <- as.list(1:M)
y.train <- as.list(1:M)
xinfo <- bartModelMatrix(x, numcut=100)$xinfo
for(m in 1:M) {
h <- (m-1)*H+1:H
x.test[[m]] <- x[h, ]
x.train[[m]] <- x[-h, ]
y.train[[m]] <- y[-h]
fits[[m]] <- mc.recur.bart(x.train=x.train[[m]], y.train=y.train[[m]],
x.test=x.test[[m]], nskip=1000, keepevery=100,
sparse=TRUE, augment=TRUE,
keeptrainfits=TRUE, xinfo=xinfo, mc.cores=8,
seed=m)
}
for(m in 1:M) {
h <- (m-1)*H+1:H
if(m==1) {
cum.test.mean <- fits[[1]]$cum.test.mean
cum.test <- fits[[1]]$cum.test
cum.train <- cbind(fits[[M]]$cum.train[ , h], fits[[1]]$cum.train)
}
else {
k <- 1:(m*H)
cum.test.mean <- c(cum.test.mean, fits[[m]]$cum.test.mean)
cum.test <- cbind(cum.test, fits[[m]]$cum.test)
if(m<M) cum.train <- rbind(cum.train, cbind(fits[[m]]$cum.train[ , k],
fits[[M]]$cum.train[ , h],
fits[[m]]$cum.train[ , -k]))
}
}
## equal tailed
lower <- 0
upper <- 1
tol <- 0.001
cover <- 1
value <- 0.95
while(!((value-tol)<=cover & cover<=(value+tol))) {
print(c(cover=cover, lower=lower, upper=upper))
cum.train.lower <- apply(cum.train, 2, quantile, probs=lower)
cum.train.upper <- apply(cum.train, 2, quantile, probs=upper)
cover <- mean(cum.train.lower<=cum.test.mean & cum.test.mean<=cum.train.upper)
if(cover<value) {
upper <- upper+0.01
if(upper>1) break
}
else upper <- upper/1.01
lower <- 1-upper
}
print(c(cover=cover, lower=lower, upper=upper))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/cal.recur.bart.R |
library(BART)
N <- 1000
K <- 25
set.seed(12)
x <- rbinom(N, 1, 0.5)
l1 <- 0.5
l2 <- 2
T <- rexp(N, l1*(1-x)+x*l2)
C <- rexp(N, 0.25)
delta <- (T < C)
times <- delta*T+(1-delta)*C
table(delta)/N
post <- mc.surv.bart(x.train=x, times=times, delta=delta,
x.test=matrix(0:1, nrow=2, ncol=1),
K=25, mc.cores=8, seed=99)
c.true <- l1/(l1+l2)
c.true
c.est <- (1-post$prob.test[ , 1])-(1-post$prob.test[ , 26])
for(j in 2:K)
c.est <- c.est+((1-post$prob.test[ , j])-(1-post$prob.test[ , j+K]))*
post$surv.test[ , j-1]*post$surv.test[ , j-1+K]
c.est <- 0.5*(1-c.est)
mean(c.est)
quantile(c.est, probs=c(0.025, 0.975))
mean(c.est-c.true)
quantile(c.est-c.true, probs=c(0.025, 0.975))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/concord.surv.bart.R |
library(BART)
N = 1000
NP = 200
P = 5 #number of covariates
M = 8
ndpost = 1000
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
mu = x.train[ , 1]^3
print(quantile(mu, probs=c(0.1, 0.3, 0.5, 0.7, 0.9)))
x.test=matrix(runif(NP*P, -2, 2), NP, P)
x1=c(-1, 0, 1)
x.test=cbind(c(rep(x1[1], NP), rep(x1[2], NP), rep(x1[3], NP)),
rbind(x.test, x.test, x.test)[ , -1])
y=rnorm(N, mu)
offset=mean(y)
T=exp(y)
C=rexp(N, 0.05)
delta=(T<C)*1
table(delta)/N
times=(T*delta+C*(1-delta))
post = mc.abart(x.train, times, delta, x.test,
mc.cores=M, seed=99, ndpost=ndpost)
## post2 = mc.abart(x.train, times, delta, x.test, offset=offset,
## mc.cores=M, seed=99, ndpost=ndpost)
Z=8
plot(mu, post$yhat.train.mean, asp=1,
xlim=c(-Z, Z), ylim=c(-Z, Z))
abline(a=0, b=1)
## plot(mu, post2$yhat.train.mean, asp=1,
## xlim=c(-Z, Z), ylim=c(-Z, Z))
## abline(a=0, b=1)
## plot(post$yhat.train.mean, post2$yhat.train.mean, asp=1,
## xlim=c(-Z, Z), ylim=c(-Z, Z))
## abline(a=0, b=1)
K <- post$K
par(mfrow=c(3, 1))
for(i in 1:length(x1)) {
plot(c(0, post$times),
c(1, pnorm(log(post$times), mean=x1[i]^3,
lower.tail=FALSE)),
type='l', ylim=0:1, xlab='t', ylab='S(t, x)')
lines(c(0, post$times),
c(1, post$surv.test.mean[(i-1)*K+1:K]),
col=2, type='s')
post$surv.test.025 <- matrix(nrow=ndpost, ncol=K)
post$surv.test.975 <- matrix(nrow=ndpost, ncol=K)
for(j in 1:K) {
post$surv.test.025[ , j] <-
apply(post$surv.test[ , (i-1)*K*NP+seq(j, K*NP, K)],
1, mean)
post$surv.test.975[ , j] <-
apply(post$surv.test[ , (i-1)*K*NP+seq(j, K*NP, K)],
1, mean)
}
post$surv.test.025 <- apply(post$surv.test.025, 2,
quantile, probs=0.025)
post$surv.test.975 <- apply(post$surv.test.975, 2,
quantile, probs=0.975)
lines(c(0, post$times), c(1, post$surv.test.025),
col=2, type='s', lty=2)
lines(c(0, post$times), c(1, post$surv.test.975),
col=2, type='s', lty=2)
}
par(mfrow=c(1, 1))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/cube.abart.R |
library(BART)
N = 1000
P = 5 #number of covariates
ndpost = 1000
nskip = 100
C = 8
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
Ey.train = x.train[ , 1]^3
y.train=rnorm(N, Ey.train)
##run BART with C cores in parallel
post = mc.wbart(x.train, y.train, mc.cores=C,
seed=99, ndpost=ndpost, nskip=nskip)
gost = mc.gbart(x.train, y.train, mc.cores=C,
seed=99, ndpost=ndpost, nskip=nskip)
plot(post$yhat.train.mean, gost$yhat.train.mean)
print(cor(post$yhat.train.mean, gost$yhat.train.mean))
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
Ey.train = x.train[ , 1]^3
y.train=rbinom(N, 1, pnorm(Ey.train))
table(y.train)
##run BART with C cores in parallel
post = mc.pbart(x.train, y.train, mc.cores=C, keepevery=10,
seed=99, ndpost=ndpost, nskip=nskip)
gost = mc.gbart(x.train, y.train, mc.cores=C, type='pbart',
seed=99, ndpost=ndpost, nskip=nskip)
plot(post$prob.train.mean, gost$prob.train.mean,
xlim=0:1, ylim=0:1)
print(cor(post$prob.train.mean, gost$prob.train.mean))
post = mc.lbart(x.train, y.train, mc.cores=C, keepevery=10,
seed=99, ndpost=ndpost, nskip=nskip)
gost = mc.gbart(x.train, y.train, mc.cores=C, type='lbart',
tau.num=3.663562, seed=99, ndpost=ndpost, nskip=nskip)
plot(post$prob.train.mean, gost$prob.train.mean,
xlim=0:1, ylim=0:1)
print(cor(post$prob.train.mean, gost$prob.train.mean))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/cube.gbart.R |
library(BART)
N = 1000
P = 5 #number of covariates
ndpost = 1000
nskip = 100
C = 8
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
Ey.train = x.train[ , 1]^3
y.train=rnorm(N, Ey.train)
##run BART with C cores in parallel
post = mc.wbart(x.train, y.train, mc.cores=C,
seed=99, ndpost=ndpost, nskip=nskip)
gost = gbmm(x.train, y.train, u.train=1:N, mc.cores=C,
seed=99, ndpost=ndpost, nskip=nskip)
gost = mc.gbmm(x.train, y.train, u.train=1:N, mc.cores=C,
seed=99, ndpost=ndpost, nskip=nskip)
plot(post$yhat.train.mean, gost$yhat.train.mean)
print(cor(post$yhat.train.mean, gost$yhat.train.mean))
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
Ey.train = x.train[ , 1]^3
y.train=rbinom(N, 1, pnorm(Ey.train))
table(y.train)
##run BART with C cores in parallel
post = mc.pbart(x.train, y.train, mc.cores=C, keepevery=10,
seed=99, ndpost=ndpost, nskip=nskip)
gost = mc.gbmm(x.train, y.train, u.train=1:N, mc.cores=C, type='pbart',
seed=99, ndpost=ndpost, nskip=nskip)
plot(post$prob.train.mean, gost$prob.train.mean,
xlim=0:1, ylim=0:1)
print(cor(post$prob.train.mean, gost$prob.train.mean))
post = mc.lbart(x.train, y.train, mc.cores=C, keepevery=10,
seed=99, ndpost=ndpost, nskip=nskip)
gost = mc.gbart(x.train, y.train, mc.cores=C, type='lbart',
tau.num=3.663562, seed=99, ndpost=ndpost, nskip=nskip)
plot(post$prob.train.mean, gost$prob.train.mean,
xlim=0:1, ylim=0:1)
print(cor(post$prob.train.mean, gost$prob.train.mean))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/cube.gbmm.R |
library(BART)
N = 1000
P = 5 #number of covariates
ndpost = 1000
nskip = 100
C = 8
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
Ey.train = x.train[ , 1]^3
y.train=rbinom(N, 1, pnorm(Ey.train))
table(y.train)
##run BART with C cores in parallel
post = mc.lbart(x.train, y.train, mc.cores=C, keepevery=10,
seed=99, ndpost=ndpost, nskip=nskip)
M <- 11
x <- seq(-2, 2, length.out=M)
x.test <- as.matrix(expand.grid(list(x5=x, x4=x, x3=x, x2=x, x1=x)))[ , 5:1]
pred <- predict(post, x.test, mc.cores=C)
K <- M^4
prob.mean <- 0
prob.025 <- 0
prob.975 <- 0
for(i in 1:M) {
j <- (i-1)*K+1:K
prob <- apply(pred$prob.test[ , j], 1, mean)
prob.mean[i] <- mean(prob)
prob.025[i] <- quantile(prob, probs=0.025)
prob.975[i] <- quantile(prob, probs=0.975)
}
X <- seq(-2, 2, length.out=50)
plot(X, pnorm(X^3), type='l',
xlab='x', ylab=expression(Phi(f(x))))
lines(x, prob.mean, col='blue')
lines(x, prob.025, col='red')
lines(x, prob.975, col='red')
##dev.copy2pdf(file='cube-lbart.pdf')
| /scratch/gouwar.j/cran-all/cranData/BART/demo/cube.lbart.R |
library(BART)
N = 1000
P = 5 #number of covariates
ndpost = 1000
nskip = 100
C = 8
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
Ey.train = x.train[ , 1]^3
y.train=rbinom(N, 1, pnorm(Ey.train))
table(y.train)
## set.seed(99)
## post = mbart(x.train, y.train, keepevery=10,
## ndpost=10, nskip=nskip)
##run BART with C cores in parallel
post = mc.mbart(x.train, y.train, mc.cores=C,
seed=99, ndpost=ndpost, nskip=nskip)
M <- 11
x <- seq(-2, 2, length.out=M)
x.test <- as.matrix(expand.grid(list(x5=x, x4=x, x3=x, x2=x, x1=x)))[ , 5:1]
pred <- predict(post, x.test, mc.cores=C)
K <- M^4
prob.mean <- 0
prob.025 <- 0
prob.975 <- 0
for(i in 1:M) {
j <- (i-1)*K+1:K
prob <- 1-apply(pred$prob.test[ , 2*j], 1, mean)
##prob <- apply(pred[[2]]$prob.test[ , j], 1, mean)
prob.mean[i] <- mean(prob)
prob.025[i] <- quantile(prob, probs=0.025)
prob.975[i] <- quantile(prob, probs=0.975)
}
X <- seq(-2, 2, length.out=50)
plot(X, pnorm(X^3), type='l',
xlab='x', ylab=expression(Phi(f(x))))
lines(x, prob.mean, col='blue')
lines(x, prob.025, col='red')
lines(x, prob.975, col='red')
##dev.copy2pdf(file='cube-mbart.pdf')
| /scratch/gouwar.j/cran-all/cranData/BART/demo/cube.mbart.R |
library(BART)
N = 1000
P = 5 #number of covariates
ndpost = 1000
nskip = 100
C = 8
set.seed(12)
x.train=matrix(runif(N*P, -2, 2), N, P)
Ey.train = x.train[ , 1]^3
y.train=rbinom(N, 1, pnorm(Ey.train))
table(y.train)
##run BART with C cores in parallel
post = mc.pbart(x.train, y.train, mc.cores=C, keepevery=10,
seed=99, ndpost=ndpost, nskip=nskip)
M <- 11
x <- seq(-2, 2, length.out=M)
x.test <- as.matrix(expand.grid(list(x5=x, x4=x, x3=x, x2=x, x1=x)))[ , 5:1]
pred <- predict(post, x.test, mc.cores=C)
K <- M^4
prob.mean <- 0
prob.025 <- 0
prob.975 <- 0
for(i in 1:M) {
j <- (i-1)*K+1:K
prob <- apply(pred$prob.test[ , j], 1, mean)
prob.mean[i] <- mean(prob)
prob.025[i] <- quantile(prob, probs=0.025)
prob.975[i] <- quantile(prob, probs=0.975)
}
X <- seq(-2, 2, length.out=50)
plot(X, pnorm(X^3), type='l',
xlab='x', ylab=expression(Phi(f(x))))
lines(x, prob.mean, col='blue')
lines(x, prob.025, col='red')
lines(x, prob.975, col='red')
dev.copy2pdf(file='cube-pbart.pdf')
| /scratch/gouwar.j/cran-all/cranData/BART/demo/cube.pbart.R |
library(BART)
times <- matrix(c(3, 8, 9,
4, 12, 12),
nrow=2, ncol=3, byrow=TRUE)
tstop <- matrix(c(7, 8, 0,
7, 0, 0),
nrow=2, ncol=3, byrow=TRUE)
delta <- matrix(c(1, 1, 0,
1, 0, 0),
nrow=2, ncol=3, byrow=TRUE)
data. <- recur.pre.bart(times=times, delta=delta,
tstop=tstop)
print(data.)
data. <- recur.pre.bart(times=times, delta=delta,
tstop=tstop, last.value=FALSE)
print(data.$tx.test)
| /scratch/gouwar.j/cran-all/cranData/BART/demo/data.recur.pre.bart.R |
library(BART)
## load 20 percent random sample
data(xdm20.train)
data(xdm20.test)
data(ydm20.train)
## set.seed(99)
## post <- recur.bart(x.train=xdm20.train, y.train=ydm20.train,
## keeptrainfits=TRUE)
## larger data sets can take some time so, if parallel processing
## is available, submit this statement instead
post <- mc.recur.bart(x.train=xdm20.train, y.train=ydm20.train,
keeptrainfits=TRUE, mc.cores=8, seed=99)
require(rpart)
require(rpart.plot)
post$yhat.train.mean <- apply(post$yhat.train, 2, mean)
dss <- rpart(post$yhat.train.mean~xdm20.train)
rpart.plot(dss)
## for the 20 percent sample, notice that the top splits
## involve cci_pvd and n
## for the full data set, notice that all splits
## involve ca, cci_pud, cci_pvd, ins270 and n
## (except one at the bottom involving a small group)
## compare patients treated with insulin (ins270=1) vs
## not treated with insulin (ins270=0)
N <- 50 ## 50 training patients and 50 validation patients
K <- post$K ## 798 unique time points
NK <- 50*K
## only testing set, i.e., remove training set
xdm20.test. <- xdm20.test[NK+1:NK, post$rm.const]
xdm20.test. <- rbind(xdm20.test., xdm20.test.)
xdm20.test.[ , 'ins270'] <- rep(0:1, each=NK)
## multiple threads will be utilized if available
pred <- predict(post, xdm20.test., mc.cores=8)
## create Friedman's partial dependence function for the
## relative intensity for ins270 by time
M <- nrow(pred$haz.test) ## number of MCMC samples
RI <- matrix(0, M, K)
for(j in 1:K) {
h <- seq(j, NK, by=K)
RI[ , j] <- apply(pred$haz.test[ , h+NK]/
pred$haz.test[ , h], 1, mean)
}
RI.lo <- apply(RI, 2, quantile, probs=0.025)
RI.mu <- apply(RI, 2, mean)
RI.hi <- apply(RI, 2, quantile, probs=0.975)
plot(post$times, RI.hi, type='l', lty=2, log='y',
ylim=c(min(RI.lo, 1/RI.hi), max(1/RI.lo, RI.hi)),
xlab='t', ylab='RI(t, x)',
sub='insulin(ins270=1) vs. no insulin(ins270=0)',
main='Relative intensity of hospital admissions for diabetics')
lines(post$times, RI.mu)
lines(post$times, RI.lo, lty=2)
lines(post$times, rep(1, K), col='darkgray')
## RI for insulin therapy seems fairly constant with time
mean(RI.mu)
| /scratch/gouwar.j/cran-all/cranData/BART/demo/dm.recur.bart.R |
library(BART)
##simulate from Friedman's five-dimensional test function
##Friedman JH. Multivariate adaptive regression splines
##(with discussion and a rejoinder by the author).
##Annals of Statistics 1991; 19:1-67.
f = function(x) #only the first 5 matter
sin(pi*x[ , 1]*x[ , 2]) + 2*(x[ , 3]-.5)^2+x[ , 4]+0.5*x[ , 5]-1.5
sigma = 1.0 # y~Logistic(f(x), sigma)
P = 5 # number of covariates
N = 2500
K = 3 # number of categories
set.seed(12)
x.train=matrix(runif(N*P), N, P)
dimnames(x.train)[[2]] <- paste0('x', 1:5)
Ey.train = f(x.train)
y.train=rnorm(N, Ey.train, sigma)
i <- y.train > -1
j <- y.train > 1
y.train[!i] <- 1
y.train[i] <- 2
y.train[j] <- 3
table(y.train)
## set.seed(99)
## post = mbart(x.train, y.train, x.train)
post = mc.mbart(x.train, y.train, x.train, mc.cores=8, seed=99)
h <- seq(1, K*N, by=K)
print(cor(post$prob.test.mean[h], pnorm(-1, Ey.train, sigma))^2)
print(cor(post$prob.test.mean[h+1], pnorm(1, Ey.train, sigma)-pnorm(-1, Ey.train, sigma))^2)
print(cor(post$prob.test.mean[h+2], pnorm(1, Ey.train, sigma, 0))^2)
par(mfrow=c(2, 2))
plot(pnorm(-1, Ey.train, sigma), post$prob.test.mean[h], pch='.',
xlim=0:1, ylim=0:1, xlab='Known P(y=1)', ylab='Est. P(y=1)')
abline(0, 1)
plot(pnorm(1, Ey.train, sigma)-pnorm(-1, Ey.train, sigma), post$prob.test.mean[h+1], pch='.',
xlim=0:1, ylim=0:1, xlab='Known P(y=2)', ylab='Est. P(y=2)')
abline(0, 1)
plot(pnorm(1, Ey.train, sigma, 0), post$prob.test.mean[h+2], pch='.',
xlim=0:1, ylim=0:1, xlab='Known P(y=3)', ylab='Est. P(y=3)')
abline(0, 1)
par(mfrow=c(1, 1))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/ex.mbart.R |
library(BART)
## simulate recurrent events data set with Exponential proportional intensity
N <- 250
K <- 60
NK <- N*K
C <- 8
set.seed(-1)
x <- matrix(nrow=NK, ncol=23)
dimnames(x)[[2]] <- c('t', 'v', 'N', paste0('x', 1:20))
b <- c(1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1.5, 0, 0, 0, 0, 0, 0, 0, 0, 0)
N. <- double(NK)
y <- integer(NK)
cum <- double(NK)
k <- 1
for(i in 1:N) {
v <- 0
x[k, 4:13] <- runif(10)
x[k, 14:23] <- rbinom(10, 1, 0.5)
for(j in 1:K) {
x[k, 1:3] <- c(j, j-v, N.[k])
if(j>1) x[k, 4:23] <- x[k-1, 4:23]
alpha <- 0.0001*exp(sum(b*x[k, 4:23])+sqrt(N.[k]))
cum[k] <- pexp(30, alpha)
y[k] <- rbinom(1, 1, cum[k])
if(y[k]==1) v <- j
if(j>1) cum[k] <- cum[k-1]+cum[k]
if(j<K) N.[k+1] <- N.[k]+y[k]
k <- k+1
}
}
table(x[K*(1:N), 3])
table(x[K*(1:N), 3])/N
post <- mc.recur.bart(x.train=x, y.train=y, x.test=x,
nskip=1000, keepevery=100,
sparse=TRUE, mc.cores=C, seed=99)
print(cor(cum, post$cum.test.mean)^2)
par(mfrow=c(1, 2))
for(i in 1:N) {
j <- (i-1)*K+1:K
if(i==1) plot(1:K, cum[j], type='l',
xlab='t', ylab=expression(Lambda(t, x)),
sub='Known Values', ylim=c(0, 20))
else lines(1:K, cum[j], col=i)
}
for(i in 1:N) {
j <- (i-1)*K+1:K
if(i==1) plot(1:K, post$cum.test.mean[j], type='l',
xlab='t', ylab=expression(Lambda(t, x)),
sub='Estimates', ylim=c(0, 20))
else lines(1:K, post$cum.test.mean[j], col=i)
}
par(mfrow=c(1, 1))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/exp.recur.bart.R |
library(BART)
##simulate from Friedman's five-dimensional test function
##Friedman JH. Multivariate adaptive regression splines
##(with discussion and a rejoinder by the author).
##Annals of Statistics 1991; 19:1-67.
f = function(x) #only the first 5 matter
10*sin(pi*x[ , 1]*x[ , 2]) + 20*(x[ , 3]-.5)^2+10*x[ , 4]+5*x[ , 5]
sigma = 1.0 #y = f(x) + sigma*z where z~N(0, 1)
n = 10000 #number of observations
k = 500 #number of covariates
set.seed(12)
x.train=matrix(runif(n*k), n, k)
Ey.train = f(x.train)
y.train=Ey.train+sigma*rnorm(n)
set.seed(21)
m = 10000
x.test=matrix(runif(m*k), m, k)
Ey.test = f(x.test)
y.test=Ey.test+sigma*rnorm(m)
ndpost = 1000
nskip = 100
C = 8
##run BART with 1 core
num <- proc.time()
set.seed(99)
train = wbart(x.train, y.train, ndpost=ndpost, nskip=nskip)
num <- proc.time()-num
print(num[3])
##run BART with C cores in parallel
den <- proc.time()
mc.train = mc.wbart(x.train, y.train, mc.cores=C,
seed=99, ndpost=ndpost, nskip=nskip)
den <- proc.time()-den
print(den[3])
print(c("realized gain:"=num[3]/den[3]))
##Amdahl's Law: theoretical maximum gain
b <- nskip/(ndpost+nskip)
print(c("Amdahl's Law:"=1/((1-b)/C+b)))
par(mfrow=c(2, 2))
y.min <- min(y.train)
y.max <- max(y.train)
plot(y.train, train$yhat.train.mean, asp=1, pch='.',
xlim=c(y.min, y.max), ylab='wbart train', xlab='true train')
lines(c(y.min, y.max), c(y.min, y.max), type='l')
plot(y.train, mc.train$yhat.train.mean, asp=1, pch='.',
xlim=c(y.min, y.max), ylab='mc.wbart train', xlab='true train')
lines(c(y.min, y.max), c(y.min, y.max), type='l')
##run predict with 1 core
num <- proc.time()
test = predict(train, x.test)
num <- proc.time()-num
print(num[3])
##run predict with C cores in parallel
den <- proc.time()
mc.test = predict(train, x.test, mc.cores=C)
den <- proc.time()-den
print(den[3])
print(c("realized gain:"=num[3]/den[3]))
y.min <- min(y.test)
y.max <- max(y.test)
yhat.test.mean <- apply(test, 2, mean)
plot(y.test, yhat.test.mean, asp=1, pch='.',
xlim=c(y.min, y.max), ylab='wbart test', xlab='true test')
lines(c(y.min, y.max), c(y.min, y.max), type='l')
mc.yhat.test.mean <- apply(mc.test, 2, mean)
plot(y.test, mc.yhat.test.mean, asp=1, pch='.',
xlim=c(y.min, y.max), ylab='mc.wbart test', xlab='true test')
lines(c(y.min, y.max), c(y.min, y.max), type='l')
par(mfrow=c(1, 1))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/friedman.wbart.R |
library(BART)
data(alligator)
## nnet::multinom Multinomial logit model fit with neural nets
fit <- multinom(food ~ lake+size+sex, data=alligator, weights=count)
summary(fit$fitted.values)
## 1=bird, 2=fish, 3=invert, 4=other, 5=reptile
(L=length(alligator$count))
(N=sum(alligator$count))
y.train=integer(N)
x.train=matrix(nrow=N, ncol=3)
x.test=matrix(nrow=L, ncol=3)
k=1
for(i in 1:L) {
x.test[i, ]=as.integer(
c(alligator$lake[i], alligator$size[i], alligator$sex[i]))
if(alligator$count[i]>0)
for(j in 1:alligator$count[i]) {
y.train[k]=as.integer(alligator$food[i])
x.train[k, ]=as.integer(
c(alligator$lake[i], alligator$size[i], alligator$sex[i]))
k=k+1
}
}
table(y.train)
##set.seed(99)
##post=mbart2(x.train, y.train, x.test, type='pbart')
post=mc.mbart2(x.train, y.train, x.test, type='pbart', mc.cores=8, seed=99)
## check=predict(post, x.test, mc.cores=8)
## print(cor(post$prob.test.mean, check$prob.test.mean)^2)
par(mfrow=c(3, 2))
K=5
for(j in 1:5) {
h=seq(j, L*K, K)
print(cor(fit$fitted.values[ , j], post$prob.test.mean[h])^2)
plot(fit$fitted.values[ , j], post$prob.test.mean[h],
xlim=0:1, ylim=0:1,
xlab=paste0('NN: Est. Prob. j=', j),
ylab=paste0('BART: Est. Prob. j=', j))
abline(a=0, b=1)
}
par(mfrow=c(1, 1))
L=16
x.test=matrix(nrow=L, ncol=3)
k=1
for(size in 1:2)
for(sex in 1:2)
for(lake in 1:4) {
x.test[k, ]=c(lake, size, sex)
k=k+1
}
x.test
## two sizes: 1=large: >2.3m, 2=small: <=2.3m
pred=predict(post, x.test, mc.cores=8)
ndpost=nrow(pred$prob.test)
size.test=matrix(nrow=ndpost, ncol=K*2)
for(i in 1:K) {
j=seq(i, L*K/2, K) ## large
size.test[ , i]=apply(pred$prob.test[ , j], 1, mean)
j=j+L*K/2 ## small
size.test[ , i+K]=apply(pred$prob.test[ , j], 1, mean)
}
size.test.mean=apply(size.test, 2, mean)
size.test.025=apply(size.test, 2, quantile, probs=0.025)
size.test.975=apply(size.test, 2, quantile, probs=0.975)
k=1:K
size.test.LH1=double(2*K)
size.test.LH1[2*k-1]=size.test.025[k]
size.test.LH1[2*k]=size.test.975[k]
size.test.LH2=double(2*K)
size.test.LH2[2*k-1]=size.test.025[k+K]
size.test.LH2[2*k]=size.test.975[k+K]
plot(factor(k, labels=c('bird', 'fish', 'invert', 'other', 'reptile')),
rep(1, K), col=k, type='n', lwd=2, lty=0,
xlim=c(1, K), ylim=c(0, 0.6), ylab='Probability',
sub="Multinomial BART\nFriedman's partial dependence function")
points(k-0.05, size.test.mean[k+K], lwd=2, col=1)
points(k+0.05, size.test.mean[k], lwd=2, col=2)
for(k in 1:K) {
lines(rep(k+0.05, 2), size.test.LH1[c(2*k-1, 2*k)], lwd=2, col=2)
lines(rep(k-0.05, 2), size.test.LH2[c(2*k-1, 2*k)], lwd=2, lty=2)
}
legend('topright', legend=c('Small', 'Large'),
pch=1, col=1:2, lty=2:1, lwd=2)
dev.copy2pdf(file='../vignettes/figures/alligator.pdf')
## plot(factor(1:K, labels=c('bird', 'fish', 'invert', 'other', 'reptile')),
## rep(1, K), col=1:K, type='n', lwd=2, lty=0,
## xlim=c(1, K), ylim=c(0, 0.5), ylab='Prob.',
## sub="Multinomial BART\nFriedman's partial dependence function")
## points(1:K, size.test.mean[1:K+K], lwd=2, col=1)
## lines(1:K, size.test.025[1:K+K], lwd=2, col=1, lty=2)
## lines(1:K, size.test.975[1:K+K], lwd=2, col=1, lty=2)
## points(1:K, size.test.mean[1:K], lwd=2, col=2)
## lines(1:K, size.test.025[1:K], lwd=2, col=2, lty=2)
## lines(1:K, size.test.975[1:K], lwd=2, col=2, lty=2)
## legend('topright', legend=c('Small', 'Large'),
## pch=1, col=1:2)
##dev.copy2pdf(file='../vignettes/figures/alligator.pdf')
| /scratch/gouwar.j/cran-all/cranData/BART/demo/gator.mbart2.R |
library(survival)
library(BART)
## load survival package for the advanced lung cancer example
data(lung)
N <- length(lung$status)
table(lung$ph.karno, lung$pat.karno)
h <- which(is.na(lung$ph.karno))
lung$ph.karno[h] <- lung$pat.karno[h]
times <- lung$time
delta <- lung$status-1 ##lung$status: 1=censored, 2=dead
##delta: 0=censored, 1=dead
## this study reports time in days rather than weeks or months
## coarsening from days to weeks or months will reduce the computational burden
times <- ceiling(times/30) ## months
##times <- ceiling(times/7) ## weeks
table(times)
table(delta)
## matrix of observed covariates
x.train <- cbind(lung$age, lung$sex, lung$ph.karno)
## lung$age: Age in years
## lung$sex: Male=1 Female=2
## lung$ph.karno: Karnofsky performance score (dead=0:normal=100:by=10)
## rated by physician
dimnames(x.train)[[2]] <- c('age(yr)', 'M(1):F(2)', 'ph.karno(0:100:10)')
## run one long MCMC chain in one process
## set.seed(99)
## post <- surv.bart(x.train=x.train, times=times, delta=delta, x.test=x.test)
## in the interest of time, consider speeding it up by parallel processing
## run "mc.cores" number of shorter MCMC chains in parallel processes
post <- mc.surv.bart(x.train=x.train, times=times, delta=delta, x.test=x.train,
mc.cores=8, seed=99)
K <- post$K
## select 10 lung cancer patients uniformly spread out over the data set
h <- seq(1, N*K, floor(N/10)*K)
for(i in h) {
post.mcmc <- post$yhat.test[ , (i-1)+1:K]
z <- gewekediag(post.mcmc)$z
y <- max(c(4, abs(z)))
## plot the z scores vs. time for each patient
if(i==1) plot(post$times, z, ylim=c(-y, y), type='l',
xlab='t', ylab='z')
else lines(post$times, z, type='l')
}
## add two-sided alpha=0.05 critical value lines
lines(post$times, rep(-1.96, K), type='l', lty=2)
lines(post$times, rep( 1.96, K), type='l', lty=2)
| /scratch/gouwar.j/cran-all/cranData/BART/demo/geweke.lung.surv.bart.R |
library(BART)
k = 50 #number of covariates
C = 8
thin = 10
ndpost = 1000
nskip = 100
##pdf(file='geweke-pbart1.pdf')
par(mfrow=c(2, 2))
for(n in c(100, 1000, 10000)) {
set.seed(12)
x.train=matrix(runif(n*k, min=-1, max=1), n, k)
Ey.train = pnorm(x.train[ , 1]^3)
y.train=rbinom(n, 1, Ey.train)
table(y.train)
##run BART with C cores in parallel
mc.train = mc.pbart(x.train, y.train, mc.cores=C, keepevery=thin,
seed=99, ndpost=ndpost, nskip=nskip)
x <- seq(-1, 1, length.out=200)
plot(x, x^3, ylab='f(x)', type='l',
sub=paste0('N:', n, ', k:', k, ', thin:', thin))
points(x.train[ , 1], mc.train$yhat.train.mean, pch='.', cex=2)
i <- floor(seq(1, n, length.out=10))
auto.corr <- acf(mc.train$yhat.train[ , i], plot=FALSE)
max.lag <- max(auto.corr$lag[ , 1, 1])
j <- seq(-0.5, 0.4, length.out=10)
for(h in 1:10) {
if(h==1)
plot(1:max.lag+j[h], auto.corr$acf[1+(1:max.lag), h, h],
type='h', xlim=c(0, max.lag+1), ylim=c(-1, 1),
ylab='acf', xlab='lag')
else
lines(1:max.lag+j[h], auto.corr$acf[1+(1:max.lag), h, h],
type='h', col=h)
}
for(j in 1:10) {
if(j==1)
plot(pnorm(mc.train$yhat.train[ , i[j]]),
type='l', ylim=c(0, 1),
sub=paste0('N:', n, ', k:', k, ', thin:', thin),
ylab=expression(Phi(f(x))), xlab='m')
else
lines(pnorm(mc.train$yhat.train[ , i[j]]),
type='l', col=j)
}
geweke <- gewekediag(mc.train$yhat.train)
j <- -10^(log10(n)-1)
plot(geweke$z, pch='.', cex=2, ylab='z', xlab='i',
sub=paste0('N:', n, ', k:', k, ', thin:', thin),
xlim=c(j, n), ylim=c(-5, 5))
lines(1:n, rep(-1.96, n), type='l', col=6)
lines(1:n, rep(+1.96, n), type='l', col=6)
lines(1:n, rep(-2.576, n), type='l', col=5)
lines(1:n, rep(+2.576, n), type='l', col=5)
lines(1:n, rep(-3.291, n), type='l', col=4)
lines(1:n, rep(+3.291, n), type='l', col=4)
lines(1:n, rep(-3.891, n), type='l', col=3)
lines(1:n, rep(+3.891, n), type='l', col=3)
lines(1:n, rep(-4.417, n), type='l', col=2)
lines(1:n, rep(+4.417, n), type='l', col=2)
text(c(1, 1), c(-1.96, 1.96), pos=2, cex=0.6, labels='0.95')
text(c(1, 1), c(-2.576, 2.576), pos=2, cex=0.6, labels='0.99')
text(c(1, 1), c(-3.291, 3.291), pos=2, cex=0.6, labels='0.999')
text(c(1, 1), c(-3.891, 3.891), pos=2, cex=0.6, labels='0.9999')
text(c(1, 1), c(-4.417, 4.417), pos=2, cex=0.6, labels='0.99999')
}
##dev.off()
par(mfrow=c(1, 1))
| /scratch/gouwar.j/cran-all/cranData/BART/demo/geweke.pbart1.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.