content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' make predictions from a Bayenet object #' #' make predictions from a Bayenet object #' #' @param object Bayenet object. #' @param X.new a matrix of new values for X at which predictions are to be made. #' @param clin.new a vector or matrix of new values for clin at which predictions are to be made. #' @param Y.new a vector of the response of new observations. If provided, the prediction error will be computed based on Y.new. #' @param ... other predict arguments #' @details X.new must have the same number of columns as X used for fitting the model. If clin was provided when fit the model, clin.new #' must not be NULL, and vice versa. The predictions are made based on the posterior estimates of coefficients in the Bayenet object. #' Note that the effects of clinical factors are not subject to selection. #' #' If Y.new is provided, the prediction error will be computed. For robust methods, the prediction mean absolute deviations (PMAD) will be computed. #' For non-robust methods, the prediction mean squared error (PMSE) will be computed. #' #' @return an object of class `Bayenet.pred' is returned, which is a list with components: #' \item{error}{prediction error. error is NULL is Y.new=NULL.} #' \item{y.pred}{predicted values of the new observations.} #' #' @rdname predict.Bayenet #' @seealso \code{\link{Bayenet}} #' #' @examples #' data(dat) #' test=sample((1:nrow(X)), floor(nrow(X)/5)) #' fit=Bayenet(X[-test,], Y[-test], clin[-test,], max.steps=500,penalty="lasso") #' predict(fit, X[test,], clin[test,], Y[test,]) #' #' @export predict.Bayenet=function(object, X.new, clin.new, Y.new,...){ intercept = TRUE dat = DataMatrix(X.new, Y.new, clin.new, intercept) c=dat$c; g=dat$g; y=dat$y; beta_true=dat$coef n = dat$n; p= dat$p; q=ncol(c) coeff = object$coefficient$G coeff.clc = object$coefficient$clin y.pred = g %*% coeff + c %*% coeff.clc error = NULL if(inherits(object, "RBVS")){ error = sum(abs(Y.new - y.pred))/length(Y.new) # error.type = "PMAD" names(error) = "PMAD" }else{ error = sum((Y.new - y.pred)^2)/length(Y.new) # error.type = "PMSE" names(error) = "PMSE" } pred = list(error=error, y.pred=y.pred) class(pred) = "Bayenet.pred" pred }
/scratch/gouwar.j/cran-all/cranData/Bayenet/R/predict.Bayenet.R
#' print a Bayenet object #' #' Print a summary of a Bayenet object #' #' @param x Bayenet object. #' @param digits significant digits in printout. #' @param ... other print arguments. #' @return No return value, called for side effects. #' @usage \method{print}{Bayenet}(x, digits = max(3, getOption("digits") - 3), \dots) #' @seealso \code{\link{Bayenet}} #' @export print.Bayenet=function(x, digits = max(3, getOption("digits") - 3),...){ cat("\nCoefficients:\n") print(x$coefficient, digits) } #' print a Selection object #' #' Print a summary of a Selection object #' #' @param x Selection object. #' @param digits significant digits in printout. #' @param ... other print arguments #' @return No return value, called for side effects. #' @usage \method{print}{Selection}(x, digits = max(3, getOption("digits") - 3), \dots) #' @seealso \code{\link{Selection}} #' @export print.Selection=function(x, digits = max(3, getOption("digits") - 3),...){ cat("\nMethod:\n") print(x$method) cat("\n") print(x$summary) } #' print a predict.Bayenet object #' #' Print a summary of a predict.Bayenet object #' #' @param x predict.Bayenet object. #' @param digits significant digits in printout. #' @param ... other print arguments. #' @return No return value, called for side effects. #' @usage \method{print}{Bayenet.pred}(x, digits = max(3, getOption("digits") - 3), \dots) #' @seealso \code{\link{predict.Bayenet}} #' @export print.Bayenet.pred=function(x, digits = max(3, getOption("digits") - 3),...){ cat("\nPMSE:\n") print(x$error, digits) cat("\npredicted ", length(x$y.pred), " y (list component y.pred)", sep = "") }
/scratch/gouwar.j/cran-all/cranData/Bayenet/R/print.Bayenet.R
#' @importFrom stats quantile quanfun <- function(x,prob) { q_beta = as.matrix(quantile(x,c(prob,(1-prob)))) pp = prod(q_beta) if(sign(pp)==1) {1} else {0} }
/scratch/gouwar.j/cran-all/cranData/Bayenet/R/quanfun.R
robust <- function(X, Y, clin, max.steps, sparse, penalty,debugging=FALSE) { dat = DataMatrix(X, Y, clin, intercept=TRUE, debugging=FALSE) c=dat$c; g=dat$g; y=dat$y; beta_true=dat$coef n = dat$n; p= dat$p; q=ncol(c) G.names = dat$G.names clin.names = dat$clin.names theta=0.5 hatb = rep(1,q); hatEta= rep(1,p); hatTau=1; hatV = rep(1,n) invSigb0 = diag(rep(1,q)) hatSg2 = rep(1,p); hatEtaSq2=1; r=1; a=1; b=1; ss2 = rep(1,p) hatPiBeta=1/2; hatPiEta=1/2 sh0=1; sh1=1 progress = 0 if(sparse){ fit=switch (penalty, "lasso" = QBLSS(y,g,c,max.steps,hatb,hatEta,hatTau,hatV,hatSg2,ss2,invSigb0, hatPiEta,hatEtaSq2, theta, r,a ,b ,sh0,sh1, progress), "elastic net" = Qenetss(y,g,c, theta, max.steps) ) }else{ fit=switch (penalty, "lasso" = QBL(y,g,c,max.steps,hatb,hatEta,hatTau,hatV,hatSg2,invSigb0, hatEtaSq2, theta, r,a ,b, progress), "elastic net" = Qenet(y,g,c, theta, max.steps) ) } out = list( GS.alpha = fit$GS.b, GS.beta = fit$GS.beta) if(sparse){ class(out)=c("Sparse", "RBVS") }else{ class(out)=c("NonSparse", "RBVS") } out }
/scratch/gouwar.j/cran-all/cranData/Bayenet/R/robust.R
BayesARIMAX<-function(Y,X,sd=10,iter=100,burnIn=40,nc=2,p=1,d=1,q=1) { requireNamespace("coda") requireNamespace("forecast") model_arimax<-arima(Y,order = c(p,d,q),xreg =X, include.mean = TRUE, method = c( "ML"),kappa = 1e+06) par<-model_arimax$coef names(par) <- NULL para<-0 paraprior<-0 prior_total<-0 l<-length(par) llike<-model_arimax$loglik prior <- function(param) { List <- list() for(j in 1:l){ para[j]= param[j] paraprior[j] = dnorm(para[j], sd, log = T) List[[j]] <- paraprior[j] prior_total<-prior_total+List[[j]] } return(prior_total) } posterior <- function(param) { return (llike + prior(param)) } proposalfunction <- function(param){ return(rnorm(l,mean = param, sd)) } run_metropolis_MCMC <- function(startvalue, iterations){ chain = array(dim = c(iterations+1,l)) chain[1,] = startvalue for (i in 1:iterations){ proposal = proposalfunction(chain[i,]) probab = exp(posterior(proposal) - posterior(chain[i,])) if (runif(1) < probab){ chain[i+1,] = proposal }else{chain[i+1,] = chain[i,] } } return(mcmc(chain)) } List <- list() for(i in 1:nc){ chain= run_metropolis_MCMC(par, iter) acceptance = 1-mean(duplicated(chain[-(1:burnIn),])) List[[i]] <- chain } summary(List[[i]]) Diagnostic<-gelman.diag(List, confidence = 0.99, transform=FALSE, autoburnin=TRUE, multivariate=TRUE) gelman.plot(List) return_list<-list(model_arimax,summary(chain),summary(List[[1]]),Diagnostic,gelman.plot(List)) return(return_list) }
/scratch/gouwar.j/cran-all/cranData/BayesARIMAX/R/BayesianARIMAX.R
BayesianBEKK<-function(X,sd=10,iter=100,burnIn=40) { pop<-X k=dim(pop)[2] nT=dim(pop)[1] RTN<-pop[,1:k] COV1=cov(RTN) m1=BEKK11(pop) par<-m1$estimates AO=matrix(c(par[2],par[3],0,par[4]),2,2) AOAOt=AO%*%t(AO) A1=matrix(c(par[6:9]),2,2) B1=matrix(c(par[10:13]),2,2) resi=cbind(RTN[,1]-par[1],RTN[,2]-par[2]) Sig=matrix(c(COV1),1,4) res=resi%*%t(A1) A1at<-function(x) { x=as.matrix(x) Prod1=NULL for(i in 1:nrow(x)) { Prod1=rbind(Prod1,kronecker(x[i,],x[i,])) } Prod1 } ArchP=A1at(res) llike=0 for(t in 2:nT) { Sigt=AOAOt+matrix(ArchP[t-1,],k,k)+B1%*% matrix(Sig[t-1,],k,k)%*%t(B1) Sigt=(Sigt+t(Sigt))/2 Sig=rbind(Sig,c(Sigt)) dl=dmvnorm(resi[t,],mean=rep(0,k),Sigt,log=TRUE) llike=llike-dl } llike prior <- function(param) { mu1 = param[1] mu2 = param[2] a011 = param[3] a021 = param[4] a022 = param[5] a11 = param[6] a21 = param[7] a12 = param[8] a22 = param[9] b11 = param[10] b21 = param[11] b12 = param[12] b22 = param[13] mu1prior = dnorm(mu1, sd, log = T) mu2prior = dnorm(mu2, sd, log = T) a011prior = dnorm(a011, sd, log = T) a021prior = dnorm(a021, sd, log = T) a022prior = dnorm(a022, sd, log = T) a11prior = dnorm(a11, sd, log = T) a21prior = dnorm(a21, sd, log = T) a12prior = dnorm(a12, sd, log = T) a22prior = dnorm(a22, sd, log = T) b11prior = dnorm(b11, sd, log = T) b21prior = dnorm(b21, sd, log = T) b12prior = dnorm(b12, sd, log = T) b22prior = dnorm(b22, sd, log = T) return(mu1prior + mu2prior + a011prior+a021prior + a022prior + a11prior +a21prior + a12prior + a22prior + b11prior + b21prior + b12prior + b22prior) } posterior <- function(param) { return (llike + prior(param)) } proposalfunction <- function(param){ return(rnorm(13,mean = param,sd)) } run_metropolis_MCMC <- function(startvalue, iterations){ chain = array(dim = c(iterations+1,13)) chain[1,] = startvalue for (i in 1:iterations){ proposal = proposalfunction(chain[i,]) probab = exp(posterior(proposal) - posterior(chain[i,])) if (runif(1) < probab){ chain[i+1,] = proposal }else{ chain[i+1,] = chain[i,] } } return(mcmc(chain)) } chain= run_metropolis_MCMC(par, iter) acceptance = 1-mean(duplicated(chain[-(1:burnIn),])) return(summary(chain)) }
/scratch/gouwar.j/cran-all/cranData/BayesBEKK/R/BayesianBEKK.R
#'@title Bayesian estimation using two dimensions Bernstein polynomial #'@description This function runs Metropolis-Hasting algorithm which is given setting prior and data.This algorithm starts storing coefficients when it runs halfway,so we use second halves of coefficients compute Rhat to check convergence. #'@import parallel iterators stats utils #'@references Li-Chu Chien,Yuh-Jenn Wu,Chao A. Hsiung,Lu-Hai Wang,I-Shou Chang(2015).Smoothed Lexis Diagrams With Applications to Lung and Breast Cancer Trends in Taiwan,Journal of the American Statistical Association, Taylor & Francis Journals, vol. 110(511), pages 1000-1012, September. #'@param prior prior=(n0,alpha,L) where alpha is a Poisson parameter,n0 is upper bound of alpha #'L can be every number which is bigger than one. #'@param disease Disease matrix. #'@param population Population matrix. #'@param ages Range of ages. #'@param years Range of years. #'@param Iterations Iterations of chain. #'@param n_chain Number of Markov chain. #'@param RJC Control parameter for transfer dimension. #'@param nn The parameter nn is lower bound of alpha. #'@param seed Set seed yes or not. #'@param set Choose seed.(defaults:set=1) #'@param n_cluster This parameter means number of cores, five cores is recommended.(default: n_cluster=1). #'@param interval Each hundreds save one coefficient. #'@param double If R.hat >1.1 then double the iterations of times. #'@return #' This function will return Bayesian estimate of incidence,Stored parameters,posterior mean,posterior max and table. #'\item{Fhat}{Bayesian estimate of incidence.} #'\item{chain}{Bayesian estimate of posterior p-value mean.} #'\item{maxchain}{Bayesian estimate of posterior p-value max.} #'\item{store_coefficients}{Two dimensional Bernstein coefficients.} #'\item{output}{When M-H algorithm ends,contruct the table which contains norm,mean of Fhat,maximum of Fhat,R.hat,iterations,P-value and elasped time.} #' #'@examples #'\donttest{ #'# ---------------------------------------- # #'library(BayesBP) #'ages<-35:85 #'years<-1988:2007 #'prior<-c(10,5,2) #'data(simulated_data_1) #'disease<-simulated_data_1$disease #'population<-simulated_data_1$population #'result<-BP2D(prior,ages,years,disease,population) #'# ---------------------------------------- # #'# Bernstein basis #'basis<-BPbasis(ages,years,10) #'pdbasis1<-PD_BPbasis(ages,years,10,by = 1) #'pdbasis2<-PD_BPbasis(ages,years,10,by = 2) #'# Bernstein polynomial #'coef<-result$store_coefficients$chain_1[[1]] #'BPFhat(coef,ages,years,basis) #'PD_BPFhat(coef,ages,years,pdbasis1,by = 1) #'PD_BPFhat(coef,ages,years,pdbasis2,by = 2) #'# Credible interval #'Credible_interval(result) #'PD_Credible_interval(result,by = 1) #'PD_Credible_interval(result,by = 2) #'# ---------------------------------------- # #'# Given four prior set #'ages<-35:85 #'years<-1988:2007 #'data(simulated_data_2) #'disease<-simulated_data_2$disease #'population<-simulated_data_2$population #'p<-expand.grid(n0=c(10,20),alpha=c(5,10),LL=c(2,4)) #'prior_set<-p[p$n0==p$alpha*2,] #'result_list<-paste0('result',1:nrow(prior_set)) #'for (i in seq_len(nrow(prior_set))) { #' prior<-prior_set[i,] #' assign(result_list[i],BP2D(prior,ages,years,disease,population)) #' write.BP(get(result_list[i]),sprintf('%s.xlsx',result_list[i])) #'} #'tab<-BP2D_table(result_list) #'write.BPtable(tab,'result_table.xlsx') #'# ---------------------------------------- # #'} #'@export BP2D #'@family Bayesain estimate BP2D <- function(prior, ages, years, disease, population, Iterations = 2e+05, n_chain = 5, n_cluster = 1, nn = 2, interval = 100, RJC = 0.35, seed = TRUE, set = 1, double = 4) { if ((prior[1] < prior[2]) || (length(prior) != 3)) { stop("'prior' is not correct!") } else if (RJC > 0.5 || RJC < 0) { stop("'RJC' is not correct!") } else if (nn < 1 && (!round(nn) == nn)) { stop("'nn' is not correct!") } else if (n_cluster > detectCores()) { n_cluster <- max(detectCores() - 1, 1) } else if (!round(double) == double) { stop("'double' should be integer!") } else if (n_chain %in% c(0, 1)) { stop("'n_chain' should bigger then one") } prior <- unlist(prior) n0 <- prior[1] alpha <- prior[2] LL <- max(prior[3], 1) basis <- BPbasis(ages, years, n0) disease <- as.matrix(disease) population <- as.matrix(population) rate <- disease/population lx <- length(ages) ly <- length(years) l1 <- LL * max(rate[1, ], na.rm = T) l2 <- LL * max(rate[nrow(rate), ], na.rm = T) l3 <- LL * max(rate[, 1], na.rm = T) l4 <- LL * max(rate[, ncol(rate)], na.rm = T) ld <- c(l1, l2, l3, l4) M2 <- LL * max(rate, na.rm = T) M1 <- 0 if (seed == TRUE) { set.seed(set) } else { rm(set) } P1 <- sum(dpois(0:nn, alpha)) Pn <- sapply((nn + 1):(n0 - 1), function(x) dpois(x, alpha)) P <- c(P1, Pn, 1 - sum(Pn) - P1) n1 <- sample(nn:n0, n_chain, P, replace = T) P <- c(rep(0, nn - 1), P, 0) initialvalue <- lapply(n1, function(n) { h1 <- runif(n + 1, M1, l1) h2 <- matrix(c(runif(n - 1, M1, l3), runif((n - 1)^2, M1, M2), runif(n - 1, M1, l4)), nrow = n - 1, ncol = n + 1) h3 <- runif(n + 1, M1, l2) ret <- rbind(h1, h2, h3) return(ret) }) BP <- function(a) { a <- as.vector(a) n <- sqrt(length(a)) est <- colSums(a * basis[[n - 1]]) return(matrix(est, lx, ly)) } logLF <- function(a) { M <- BP(a) * population sum(disease * log(M) - M, na.rm = T) } MHRJ_Algorithm <- function(initialvalue, kk = 0.5) { iter <- kk * Iterations store_coef <- list() storeF <- 0 chain <- c() maxchain <- c() Pmax <- c() Pmean <- c() nx <- nrow(initialvalue) - 1 X <- initialvalue start <- (ifelse(kk == 0.5, 1, kk * Iterations + 1)) end <- (2 * kk * Iterations) for (i in start:end) { RJP <- c(min(1, P[nx - 1]/P[nx]), min(1, P[nx + 1]/P[nx])) RJP <- c(RJC * RJP[1], 1 - sum(RJC * RJP), RJC * RJP[2]) if (RJP[1] == 0) { H <- sample(c(1, 2), 1, prob = RJP[2:3]) } else if (RJP[3] == 0) { H <- sample(c(0, 1), 1, prob = RJP[1:2]) } else { H <- sample(c(0, 1, 2), 1, prob = RJP) } Y <- X if (H == 0) { ny <- nx - 1 delete <- sample(0:nx + 1, 2, replace = T) Y <- X[-delete[1], -delete[2]] Jcb <- sum(log(ld - M1)) - log(M2 - M1) * (2 * ny - 3) rio <- logLF(Y) - logLF(X) + log(P[ny]/P[nx]) - Jcb } else if (H == 2) { ny <- nx + 1 Y <- matrix(0, ny + 1, ny + 1) s <- sample(2:ny, 2, replace = T) Y[-s[1], -s[2]] <- X Y[s[1], ] <- c(runif(1, M1, l1), runif(nx, M1, M2), runif(1, M1, l2)) Y[, s[2]] <- c(runif(1, M1, l3), runif(nx, M1, M2), runif(1, M1, l4)) Jcb <- sum(log(ld - M1)) + log(M2 - M1) * (2 * ny - 1) rio <- logLF(Y) - logLF(X) - log(P[ny]/P[nx]) + Jcb } else { Y <- X ny <- nx n <- nrow(Y) if (ny == 1) { state <- sample(1:4, 1) } else { state <- sample(1:9, 1) } if (state == 1) { Y[1, 1] <- runif(1, M1, l1) } else if (state == 2) { Y[1, n] <- runif(1, M1, l1) } else if (state == 3) { Y[n, 1] <- runif(1, M1, l2) } else if (state == 4) { Y[n, n] <- runif(1, M1, l2) } else if (state == 5) { Y[1, 2:(n - 1)] <- runif(n - 2, M1, l1) } else if (state == 6) { Y[n, 2:(n - 1)] <- runif(n - 2, M1, l2) } else if (state == 7) { Y[2:(n - 1), 1] <- runif(n - 2, M1, l3) } else if (state == 8) { Y[2:(n - 1), n] <- runif(n - 2, M1, l4) } else { ch <- sample(2:ny, 1) Y[ch, 2:(n - 1)] <- runif(n - 2, M1, M2) } rio <- logLF(Y) - logLF(X) } if (rio > 0) { nnext <- ny Xnext <- Y } else { if (log(runif(1)) < rio) { nnext <- ny Xnext <- Y } else { nnext <- nx Xnext <- X } } X <- Xnext nx <- nnext condition <- ifelse(interval == 1, i > iter, i > iter && (i%%iter%%interval == 1)) if (condition) { est <- BP(Xnext) chain[length(chain) + 1] <- mean(est) maxchain[length(maxchain) + 1] <- max(est) Rp <- rpois(lx * ly, est * population)/population EZR1 <- max(abs(est - Rp), na.rm = T) EZR2 <- abs(mean(est, na.rm = T) - mean(Rp, na.rm = T)) ZR1 <- max(abs(est - rate), na.rm = T) ZR2 <- abs(mean(est, na.rm = T) - mean(rate, na.rm = T)) Pmax[length(Pmax) + 1] <- EZR1 > ZR1 Pmean[length(Pmean) + 1] <- EZR2 > ZR2 store_coef[[length(store_coef) + 1]] <- Xnext storeF <- storeF + est } } return(list(chain = chain, maxchain = maxchain, store_coef = store_coef, storeF = storeF/iter * interval, Pmax = Pmax, Pmean = Pmean)) } kk <- 0.5 out.put <- list() cl <- makeCluster(n_cluster) t1 <- Sys.time() pr <- paste0("n0=", prior[1], ",alpha=", prior[2], ",max=", prior[3]) message("Prior: ", pr) repeat { result <- parLapply(cl, 1:n_chain, function(i) { if (seed == T) { set.seed(set) a <- sample(-10000:10000,n_chain) set.seed(a[i]) } MHRJ_Algorithm(initialvalue[[i]], kk = kk) }) chain <- rbind(sapply(1:n_chain, function(i) result[[i]]$chain)) maxchain <- rbind(sapply(1:n_chain, function(i) result[[i]]$maxchain)) R.hat <- Rhat(chain, burn.in = 0) Fprime <- 0 for (j in 1:n_chain) { Fprime <- Fprime + (result[[j]]$storeF)/n_chain } Px <- rbind(sapply(1:n_chain, function(i) result[[i]]$Pmax)) Pn <- rbind(sapply(1:n_chain, function(i) result[[i]]$Pmean)) Fhat.mean <- mean(Fprime) * 10^5 Fhat.max <- max(Fprime) * 10^5 L1norm <- mean(abs(rate - Fprime), na.rm = T) * 10^5 supnorm <- max(abs(rate - Fprime), na.rm = T) * 10^5 Pvalue.mean <- mean(Pn) Pvalue.max <- mean(Px) t2 <- Sys.time() out.put[[length(out.put) + 1]] <- cbind(L1_norm = L1norm, sup_norm = supnorm, Fhat.mean, Fhat.max, R.hat, Iterations = Iterations * kk * 2, Pvalue.mean, Pvalue.max, time.mins = difftime(t2, t1, units = "mins")) message("Iterations: ", Iterations * kk * 2) message("Time: ", round(difftime(t2, t1, units = "mins"), digits = 3), " mins") message("R.hat: ", round(R.hat, digits = 6)) if (R.hat < 1.1) { message("Markov chains is convergence.\n") break } else if (kk == 2^double/2) { message("Markov chains is not convergence.\n") break } else { message("Markov chains is not convergence.") message("Double the number of iterations.") kk <- kk * 2 initialvalue <- sapply(1:n_chain, function(i) tail(result[[i]]$store_coef, 1)) } } stopCluster(cl) storeparameter <- lapply(1:n_chain, function(i) result[[i]]$store_coef) names(storeparameter) <- colnames(chain) <- colnames(maxchain) <- paste0("chain_", 1:n_chain) output <- do.call(rbind, out.put) rownames(output) <- rep(pr, dim(output)[1]) row.names(Fprime) <- ages colnames(Fprime) <- years r <- list(Fhat = Fprime, chain = chain, maxchain = maxchain, store_coefficients = storeparameter, output = output) class(r) <- "BP2D_result" return(r) }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/BP2D.R
#'@title Getting coefficeint from BP2D result. #'@description This function will return coefficient and length of each set of coefficeint. #'@param result This is output of BP2D. #'@return Coefficients table. #'@family Bayesain estimate #'@export BP2D_coef BP2D_coef <- function(result) { if (class(result) == "BP2D_result") { len_coef <- list() for (j in seq_len(length(result$store_coefficient))) { len_coef[[j]] <- sapply(result$store_coefficient[[j]], length) } len_coef <- do.call(cbind, len_coef) store_coef <- lapply(result$store_coef, unlist) max_len <- max(sapply(store_coef, length)) store_coef <- sapply(store_coef, function(x) c(x, rep(NA, max_len - length(x)))) colnames(len_coef) <- colnames(store_coef) <- names(result$store_coefficient) row.names(len_coef) <- seq_len(nrow(len_coef)) row.names(store_coef) <- seq_len(nrow(store_coef)) return(list(store_coefficient = store_coef, len_coefficient = len_coef)) } else { stop("Please check your input and try again") } }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/BP2Dcoef.R
#'@title Table and Criterion. #'@description If you give more groups of prior,you can use this function to get the table and T criterion. #'@param results_list A vector of characters. #'@return Table and criterion T. #'@family Bayesain estimate #'@export BP2D_table #' BP2D_table <- function(results_list) { if (class(results_list) == "character") { l <- length(results_list) if (l > 1) { allFhat <- lapply(1:l, function(x) get(results_list[x])$Fhat) T. <- list() for (i in 1:l) { for (j in i:l) { if (i != j) { T.[[length(T.) + 1]] <- data.frame(paste0("(", i, ",", j, ")"), 10^5 * max(abs(allFhat[[i]] - allFhat[[j]]))) } } } T. <- do.call(rbind, T.) output <- lapply(1:l, function(x) { tmp <- cbind(x, get(results_list[x])$output) colnames(tmp)[1] <- "set of priors" tmp }) output <- do.call(rbind, output) colnames(T.) <- c("set of priors", "T") rownames(T.) <- seq_len(nrow(T.)) r <- list(output = output, T. = T.) class(r) <- "BPtable" return(r) } else if (l == 1) { r <- get(results_list)$output class(r) <- "BPtable" return(r) } } else { stop("Please check resultlist again") } }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/BP2Dtable.R
#'Two dimensional Bernstein polynomial #'@description Given Bernstein polynomial coeffients to compute Fhat. #'@param coef Bernstein polynomial coefficients. #'@param ages Range of ages. #'@param years Range of years. #'@param basis Bernstein polynomial basis. #'@return This function return outer Bernstein polynomial using coefficients. #'@examples #'coef <- runif(9) #'ages <- 35:85 #'years <- 1988:2007 #'list.basis <- BPbasis(ages,years,10) #'BPFhat(coef,ages,years,list.basis) #'@family outer Bernstein polynomial #'@export BPFhat BPFhat <- function(coef, ages, years, basis) { coef <- as.vector(coef) lx <- length(ages) ly <- length(years) n <- sqrt(length(coef)) if (round(n) != n) { stop("length(coef) should be square number") } d <- sapply(basis, dim) chs <- which(d[1, ] == (n * n)) est <- colSums(coef * basis[[chs]]) return(matrix(est, lx, ly)) }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/BPFhat.R
#'Bernstein polynomial basis. #'@description This function build two dimensional Bernstein polynomial basis. #'@param ages Range of ages. #'@param years Range of years. #'@param n0 Upper bound of possion random variable. #'@param N Lower bound of possion random variable. #'@return Bernstein basis. #'@examples #'ages <- 35:85 #'years <- 1988:2007 #'list.basis <- BPbasis(ages,years,10) #'list.basis #'@family Bernstein basis #'@export BPbasis BPbasis <- function(ages, years, n0, N = 1) { x <- scale_to_01(ages) y <- scale_to_01(years) xy <- expand.grid(x, y) basis_list <- list() for (n in N:n0) { i <- j <- 0:n g <- array(0, dim = c(n + 1, n + 1, nrow(xy))) for (k in seq_len(nrow(xy))) { g[, , k] <- outer(i, j, function(i, j) { bin(n, i, xy[k, 1]) * bin(n, j, xy[k, 2]) }) } parameter <- matrix(as.vector(g), nrow = (n + 1)^2, ncol = nrow(xy)) basis_list[[length(basis_list) + 1]] <- parameter } class(basis_list) <- "BPbasis" return(basis_list) }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/BPbasis.R
#'Credible interval. #'@description Builing two dimensional Bernstein polynomial credible interval. #'@param result This is output of BP2D. #'@param n_cluster Muticores is remmended.(default:n_cluster=1) #'@param alpha Level of significance. #'@references L.H. Chien, T.J. Tseng, C.H. Chen, H.F. Jiang, F.Y. Tsai, T.W. Liu, C.A. Hsiung, I.S. Chang Comparison of annual percentage change in breast cancer incidence rate between Taiwan and the United States-A smoothed Lexis diagram approach. #'@return Bayesian credible interval with level of significance. #'@family Credible interval #'@export Credible_interval #' Credible_interval <- function(result, n_cluster = 1, alpha = 0.05) { if (class(result) != "BP2D_result") { stop("'result' is not correct!") } else { coef_list <- unlist(result$store_coefficient, recursive = F) ages <- as.numeric(rownames(result$Fhat)) years <- as.numeric(colnames(result$Fhat)) lx <- length(ages) ly <- length(years) n0 <- max(sqrt(unique(sapply(coef_list, length)))) basis <- BPbasis(ages, years, n0) LU <- c(alpha/2, 1 - alpha/2) cl <- makeCluster(n_cluster) clusterExport(cl, c("BPFhat", "scale_to_01")) ret <- parSapply(cl, coef_list, function(x) BPFhat(x, ages, years, basis)) ret <- t(parApply(cl, ret, 1, function(x) c(quantile(x, LU), mean(x)))) stopCluster(cl) lowerCI <- matrix(ret[, 1], lx, ly) upperCI <- matrix(ret[, 2], lx, ly) M <- matrix(ret[, 3], lx, ly) row.names(lowerCI) <- row.names(M) <- row.names(upperCI) <- ages colnames(lowerCI) <- colnames(M) <- colnames(upperCI) <- years ret <- list(lowerCI, AVG = M, upperCI) names(ret)[c(1, 3)] <- paste0(LU * 100, "%CI") return(ret) } }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/Credible_interval.R
#'Two dimensional Bernstein polynomial #'@description Given Bernstein polynomial coeffients to compute Fhat. #'@param coef Bernstein polynomial coefficients. #'@param ages Range of ages. #'@param years Range of years. #'@param pdbasis Partial differential Bernstein polynomial basis. #'@param by 1: partial differential by ages; 2: partial differential by years. #'@return Partial differential Bernstein polynomial given coefficients. #'@examples #'coef <- runif(9) #'ages <- 35:85 #'years <- 1988:2007 #'pdbasis <- PD_BPbasis(ages,years,10,N=1,by=1) #'PD_BPFhat(coef,ages,years,pdbasis,by=1) #'@family outer Bernstein polynomial #'@export PD_BPFhat PD_BPFhat <- function(coef, ages, years, pdbasis, by = 1) { coef <- as.vector(coef) lx <- length(ages) ly <- length(years) n <- sqrt(length(coef)) if (round(n) != n) { stop("length(coef) should be square number") } coef <- matrix(coef, n, n) d <- sapply(pdbasis, dim) chs <- which(d[1, ] == (n * n - n)) if (by == 1) { coef <- coef[2:n, ] - coef[1:(n - 1), ] coef <- as.vector(coef) est <- colSums(coef * pdbasis[[chs]]) } else if (by == 2) { coef <- coef[, 2:n] - coef[, 1:(n - 1)] coef <- as.vector(coef) est <- colSums(coef * pdbasis[[chs]]) } return(matrix(est, lx, ly)) }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/PD_BPFhat.R
#'Partial differential Bernstein polynomial basis. #'@description This function build two dimensional Bernstein polynomial basis. #'@param ages Range of ages. #'@param years Range of years. #'@param n0 Upper bound of possion random variable. #'@param N Lower bound of possion random variable. #'@param by 1: partial differential by ages; 2: partial differential by years. #'@return Partial differential Bernstein basis. #'@examples #'ages <- 35:85 #'years <- 1988:2007 #'pdbasis <- PD_BPbasis(ages,years,10,by = 1) #'pdbasis #'@family Bernstein basis #'@export PD_BPbasis PD_BPbasis <- function(ages, years, n0, N = 1, by = 1) { x <- scale_to_01(ages) y <- scale_to_01(years) xy <- expand.grid(x, y) basis_list <- list() for (n in N:n0) { if (by == 1) { i <- 0:(n - 1) j <- 0:n g <- array(0, dim = c(n, n + 1, nrow(xy))) for (k in seq_len(nrow(xy))) { g[, , k] <- outer(i, j, function(i, j) { n * bin(n - 1, i, xy[k, 1]) * bin(n, j, xy[k, 2]) }) } } else if (by == 2) { i <- 0:n j <- 0:(n - 1) g <- array(0, dim = c(n + 1, n, nrow(xy))) for (k in seq_len(nrow(xy))) { g[, , k] <- outer(i, j, function(i, j) { n * bin(n, i, xy[k, 1]) * bin(n, j - 1, xy[k, 2]) }) } } else { stop("Error") } parameter <- matrix(as.vector(g), nrow = (n + 1) * n, nrow(xy)) basis_list[[length(basis_list) + 1]] <- parameter rm(g, parameter) } class(basis_list) <- "BPbasis" return(basis_list) }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/PD_BPbasis.R
#'Credible interval. #'@description Builing two dimensional Bernstein polynomial credible interval. #'@param result This is output of BP2D. #'@param n_cluster Muticores is remmended.(default:n_cluster=1) #'@param alpha Level of significance. #'@param by 1: partial differential by ages; 2: partial differential by years. #'@references L.H. Chien, T.J. Tseng, C.H. Chen, H.F. Jiang, F.Y. Tsai, T.W. Liu, C.A. Hsiung, I.S. Chang Comparison of annual percentage change in breast cancer incidence rate between Taiwan and the United States-A smoothed Lexis diagram approach. #'@return Bayesian credible interval with level of significance. #'@family Credible interval #'@export PD_Credible_interval #' PD_Credible_interval <- function(result, n_cluster = 1, alpha = 0.05, by = 1) { if (class(result) != "BP2D_result") { stop("'result' is not correct!") } else { coef_list <- unlist(result$store_coefficient, recursive = F) ages <- as.numeric(rownames(result$Fhat)) years <- as.numeric(colnames(result$Fhat)) lx <- length(ages) ly <- length(years) n0 <- max(sqrt(unique(sapply(coef_list, length)))) pdbasis <- PD_BPbasis(ages, years, n0) LU <- c(alpha/2, 1 - alpha/2) cl <- makeCluster(n_cluster) clusterExport(cl, c("PD_BPFhat", "scale_to_01")) ret <- parSapply(cl, coef_list, function(x) PD_BPFhat(x, ages, years, pdbasis, by)) ret <- t(parApply(cl, ret, 1, function(x) c(quantile(x, LU), mean(x)))) stopCluster(cl) lowerCI <- matrix(ret[, 1], lx, ly) upperCI <- matrix(ret[, 2], lx, ly) M <- matrix(ret[, 3], lx, ly) row.names(lowerCI) <- row.names(M) <- row.names(upperCI) <- ages colnames(lowerCI) <- colnames(M) <- colnames(upperCI) <- years ret <- list(lowerCI, AVG = M, upperCI) names(ret)[c(1, 3)] <- paste0(LU * 100, "%CI") return(ret) } }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/PD_Credible_interval.R
#'Gelman Rubin statistics. #'@description Check Markov chains for convergence. #'@param M An n x m numeric matrix of Markov Chains. #'@param burn.in The default value 0.5 means that the second halves of chains will be used to compute. #'@return Gelman Rubin statistics. #'@references Gelman A.,Carlin J.B.,Stern H.S.,and Rubin D.B.(2004),Bayesian Data Analysis,Boca Raton,FL:Chapman&Hall/CRC. #'@export Rhat #' Rhat <- function(M, burn.in = 0.5) { m <- ncol(M) x <- M[round(((burn.in * nrow(M)) + 1), 0):nrow(M), ] n <- nrow(x) phibar <- mean(x) phi <- colMeans(x) B <- n/(m - 1) * sum((phi - phibar)^2) W <- mean(apply(x, 2, var)) post.var <- (n - 1)/n * W + B/n r <- sqrt(post.var/W) r <- ifelse(r < 1, 1, r) return(r) }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/Rhat.R
#'Scale to [0,1] #'@examples #'scale_to_01(35:85) #'(35:85-35)/(85-35) #'scale_to_01(runif(10)) #'@param x Vector. #'@export scale_to_01 scale_to_01 <- function(x) { a <- min(x) b <- max(x) return((x - a)/(b - a)) } NULL #'Binomial function #'@param n Integer. #'@param i Integer(i < n). #'@param x Numeric(0<= x <=1). #'@examples #'bin(5,3,.5) #'@export bin bin <- function(n, i, x) { choose(n, i) * x^i * (1 - x)^(n - i) } NULL
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/scale_to_01.R
#'Risky population function #'@param x Numeric. #'@param y Numeric. #'@keywords datasets #'@export M M <- function(x, y) { r0 = 152040 r1 = -285270 r2 = 110410 r3 = 173900 r4 = -49950 r5 = -33630 r6 = -19530 r7 = -110330 r8 = 88840 r9 = -7990 population <- r0 + r1 * x + r2 * y + r3 * x^2 + r4 * x * y + r5 * y^2 + r6 * x^3 + r7 * x^2 * y + r8 * x * y^2 + r9 * y^3 return(population) } NULL #'Generated data #'@param ages Ages. #'@param years Years. #'@param FT Rate function. #'@param M Population function. #'@keywords datasets #'@export gen_data gen_data <- function(ages, years, FT, M) { x <- scale_to_01(ages) y <- scale_to_01(years) disease <- outer(x, y, M) * outer(x, y, FT) population <- outer(x, y, M) row.names(disease) <- row.names(population) <- ages colnames(disease) <- colnames(population) <- years return(list(disease = disease, population = population)) } NULL #'Generate simulated data 1 #'@description Given rate function 1 generated data. #'@docType data #'@keywords datasets #'@name simulated_data_1 #'@usage data(simulated_data_1) #'@format list of matrix #'@examples #'ages <- 35:85 #'years <- 1988:2007 #'FT1 <- function(x,y){0.00148*sin(0.5*pi*x*y)+0.00002} #'simulated_data_1 <- gen_data(ages,years,FT1,M) NULL #'Generate simulated data 2 #'@description Given rate function 2 generated data. #'@docType data #'@keywords datasets #'@name simulated_data_2 #'@usage data(simulated_data_2) #'@format list of matrix #'@examples #'ages <- 35:85 #'years <- 1988:2007 #'FT2 <- function(x,y){0.00148*sin(0.5*pi*x*(y+0.2))+0.00002} #'simulated_data_2 <- gen_data(ages,years,FT2,M) NULL
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/simulated_data.R
#'Write xlsx file #'@description This function will write result of BP2D to xlsx file. #'@import openxlsx #'@param writedata result of BP2D(character or list). #'@param filename xlsx file name. #'@export write.BP write.BP <- function(writedata, filename) { wb <- createWorkbook() if (is.character(writedata)) { writedata <- get(writedata) } else if (class(writedata) != "BP2D_result") { stop("writedata is not correct!") } a1 <- writedata$Fhat temp <- BP2D_coef(writedata) a2 <- temp$store_coefficient a3 <- temp$len_coefficient rm(temp) a4 <- writedata$chain a5 <- writedata$maxchain a6 <- writedata$output addWorksheet(wb, "Fhat") writeData(wb, sheet = 1, a1, rowNames = T) addWorksheet(wb, "Store_coefficient") writeData(wb, sheet = 2, a2) addWorksheet(wb, "len_coefficient") writeData(wb, sheet = 3, a3) addWorksheet(wb, "chain") writeData(wb, sheet = 4, a4) addWorksheet(wb, "maxchain") writeData(wb, sheet = 5, a5) addWorksheet(wb, "output") writeData(wb, sheet = 6, a6, rowNames = T) setColWidths(wb, sheet = 6, cols = 1:10, widths = c(19, rep(12, 9))) saveWorkbook(wb, filename, overwrite = TRUE) return(invisible()) }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/writeBP.R
#'Write BPtalbe as xlsx file #'@description If your environment has some result of BP2D,then you can use this function to store BPTable. #'@import openxlsx #'@param BPtable output of BP2D_table. #'@param filename xlsx file name. #'@export write.BPtable write.BPtable <- function(BPtable, filename) { wb <- createWorkbook() if (class(BPtable) != "BPtable") { stop("BPtable is not correct!") } else { a1 <- BPtable$output addWorksheet(wb, "Output") writeData(wb, sheet = 1, a1, rowNames = T) setColWidths(wb, sheet = 1, cols = 1:10, widths = c(22, rep(13, 9))) if ("T." %in% names(BPtable)) { a2 <- BPtable$T. addWorksheet(wb, "Criterion") setColWidths(wb, sheet = 2, cols = 1:3, widths = c(5, 13, 9)) writeData(wb, sheet = 2, a2, rowNames = T) } saveWorkbook(wb, filename, overwrite = TRUE) return(invisible()) } }
/scratch/gouwar.j/cran-all/cranData/BayesBP/R/writeBPtable.R
#library('label.switching') #library('doParallel') #library('foreach') #library('coda') myDirichlet <- function(alpha){ k <- length(alpha) theta <- rgamma(k, shape = alpha, rate = 1) return(theta/sum(theta)) } toSolve <- function(a,n,p0){ myVals <- exp(lgamma(2*a) - lgamma(a) + lgamma(a+n) - lgamma(2*a + n) + log(2)) l <- abs(myVals - p0) return(a[which(l == min(l))][1]) } complete.loglikelihood<-function(x,z,pars){ g <- dim(pars)[1] n <- dim(x)[1] J <- dim(pars)[2] d <- dim(x)[2] logl <- rep(0, n) logpi <- log(pars[,J]) z <- as.numeric(z) for (j in 1:d){ logl <- logl + dbinom(x[,j], size = 1, prob = pars[,j][z], log = TRUE) } logl <- logl + logpi[z] return(sum(logl)) } gibbsBinMix <- function(alpha,beta,gamma,K,m,burn,data,thinning,z.true,outputDir){ if (missing(K)) {stop(cat(paste(" [ERROR]: number of clusters (K) not provided."), "\n"))} if (missing(m)) {stop(cat(paste(" [ERROR]: number of MCMC iterations (m) not provided."), "\n"))} if (missing(thinning)) {thinning <- 5} if (K < 2) { stop(cat(paste(" [ERROR]: number of clusters (K) should be at least equal to 2."), "\n")) } d <- dim(data)[2] if (burn > m - 1) { stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n")) } if (burn < 0) { stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n")) } if (thinning > m) { stop(cat(paste(" [ERROR]: thinning not valid."), "\n")) } if (m < 1) { stop(cat(paste(" [ERROR]: mcmc iterations (m) not valid."), "\n")) } if (missing(alpha)) {alpha <- 1} if (missing(beta)) {beta <- 1} if (missing(gamma)) {gamma <- rep(1,K)} if (missing(data)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))} n <- dim(data)[1] x <- data dir.create(outputDir) setwd(outputDir) p <- myDirichlet(rep(1,K)) # initial values for cluster probabilities theta <- array(data = runif(K*d), dim = c(K,d)) # initial values for response probabilities z <- sample(K,n,replace=TRUE,prob = p) s <- l <- newL <- numeric(K) sx <- array(data = 0, dim = c(K,d)) #output theta.file <- "theta.txt" z.file <- "z.txt" p.file <- "p.txt" conTheta = file(theta.file,open = "w") conZ = file(z.file,open = "w") conP = file(p.file,open = "w") for (iter in 1:m){ #update cluster allocations (z) s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(i in 1:n){ for(k in 1:K){ #l[k] <- p[k]*prod((theta[k,]^x[i,])*((1-theta[k,])^(1-x[i,]))) l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,])) } for(k in 1:K){ newL[k] <- 1/sum(exp(l - l[k])) } z[i] <- sample(K,1,prob = newL) #z[i] <- sample(K,1,prob = l) s[z[i]] <- s[z[i]] + 1 sx[z[i],] <- sx[z[i],] + x[i,] } p <- myDirichlet(gamma + s) for(k in 1:K){ theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,]) } if((iter %% thinning == 0)&(iter > burn)){ cat(theta,"\n",file=conTheta) cat(z,"\n",file=conZ) cat(p,"\n",file=conP) } if(iter %% (m/100) == 0){ cat(paste("Running Gibbs: ",100*round(iter/m,3),"% completed.",sep=""),"\n"); } } close(conTheta) close(conP) close(conZ) cat(paste("Gibbs finished."),"\n") cat("\n") cat(paste("Dealing with Label Switching..."),"\n") tt <- read.table("theta.txt") m <- dim(tt)[1] d <- dim(x)[2] J <- d + 1 mcmc <- array(data = NA, dim = c(m,K,J)) for (j in 1:d){ for(k in 1:K){ mcmc[,k,j] <- tt[,(j-1)*K + k] } } tt <- read.table("p.txt") for(k in 1:K){ mcmc[,k,J] <- tt[,k] } allocations <- as.matrix(read.table("z.txt",as.is = TRUE)) m <- dim(mcmc)[1] iter <- 1 ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) maxLL <- ll maxIter <- iter for (iter in 1:m){ ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")} } # classification probs pMatrix <- array(data = NA, dim = c(m,n,K)) for (iter in 1:m){ p <- mcmc[iter,,J] theta <- array( mcmc[iter,,1:(J-1)],dim = c(K,J-1) ) for(i in 1:n){ for(k in 1:K){ #pMatrix[iter,i,k] <- p[k]*prod((theta[k,]^x[i,])*((1-theta[k,])^(1-x[i,]))) l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,])) } #pMatrix[iter,i,] <- pMatrix[iter,i,]/sum(pMatrix[iter,i,]) for(k in 1:K){ pMatrix[iter,i,k] <- 1/sum(exp(l - l[k])) if(is.na(pMatrix[iter,i,k]) == TRUE){pMatrix[iter,i,k] = 0} } } if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");} } if(missing(z.true)==TRUE){ ls <- label.switching( K = K, method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations, complete = complete.loglikelihood, data = x, mcmc = mcmc,prapivot = mcmc[maxIter,,], p = pMatrix) }else{ ls <- label.switching( K = K, method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations, complete = complete.loglikelihood, data = x, mcmc = mcmc,p = pMatrix,groundTruth = z.true) } #reordering allocations allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations for (i in 1:m){ myPerm <- order(ls$permutations$"ECR"[i,]) allocationsECR[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"STEPHENS"[i,]) allocationsKL[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,]) allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]] } write.table(allocationsECR, file = "z.ECR.txt") write.table(allocationsKL, file = "z.KL.txt") write.table(allocationsECR.ITERATIVE1, file = "z.ECR-ITERATIVE1.txt") reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output tt <- read.table("theta.txt") write.table(reordered.mcmc, file = "reorderedMCMC-ECR.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output write.table(reordered.mcmc, file = "reorderedMCMC-ECR-ITERATIVE1.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output write.table(reordered.mcmc, file = "reorderedMCMC-STEPHENS.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(mcmc, file = "rawMCMC.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(file = "reorderedSingleBestClusterings.txt",t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep=".")) file.remove("p.txt") file.remove("theta.txt") cat(paste("raw MCMC parameters written to: \'rawMCMC.txt\' "),"\n") cat(paste("raw MCMC latent allocations written to: \'z.txt\' "),"\n") cat(paste("reordered MCMC output written to: "),"\n") cat(paste(" (Method 1): \'reorderedMCMC-ECR.txt\'"),"\n") cat(paste(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.txt\'"),"\n") cat(paste(" (Method 3): \'reorderedMCMC-STEPHENS.txt\'"),"\n") cat(paste("reordered single best clusterings written to: \'reorderedSingleBestClusterings.txt\' "),"\n") cat(paste("reordered MCMC latent allocations written to: "),"\n") cat(paste(" (Method 1): \'z.ECR.txt\'"),"\n") cat(paste(" (Method 2): \'z.KL.txt\'"),"\n") cat(paste(" (Method 3): \'z.ECR-ITERATIVE1.txt\'"),"\n") setwd("../") } collapsedGibbsBinMix <- function(alpha,beta,gamma,K,m,burn,data,thinning,z.true,outputDir){ if (missing(K)) {stop(cat(paste(" [ERROR]: number of clusters (K) not provided."), "\n"))} if (missing(m)) {stop(cat(paste(" [ERROR]: number of MCMC iterations (m) not provided."), "\n"))} if (missing(thinning)) {thinning <- 5} d <- dim(data)[2] if (burn > m - 1) { stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n")) } if (burn < 0) { stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n")) } if (thinning > m) { stop(cat(paste(" [ERROR]: thinning not valid."), "\n")) } if (m < 1) { stop(cat(paste(" [ERROR]: mcmc iterations (m) not valid."), "\n")) } if (missing(alpha)) {alpha <- 1} if (missing(beta)) {beta <- 1} if (missing(gamma)) {gamma <- rep(1,K)} if (missing(data)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))} d <- dim(data)[2] n <- dim(data)[1] x <- data dir.create(outputDir) setwd(outputDir) p <- myDirichlet(rep(1,K)) # initial values for cluster probabilities theta <- array(data = runif(K*d), dim = c(K,d)) # initial values for response probabilities z <- sample(K,n,replace=TRUE,prob = p) s <- l <- newL <- numeric(K) sx <- array(data = 0, dim = c(K,d)) #output theta.file <- "theta.collapsed.txt" z.file <- "z.collapsed.txt" p.file <- "p.collapsed.txt" conTheta = file(theta.file,open = "w") conZ = file(z.file,open = "w") conP = file(p.file,open = "w") # initialization with standard Gibbs for (iter in 1:100){ s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(i in 1:n){ for(k in 1:K){ l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,])) } for(k in 1:K){ newL[k] <- 1/sum(exp(l - l[k])) } z[i] <- sample(K,1,prob = newL) s[z[i]] <- s[z[i]] + 1 sx[z[i],] <- sx[z[i],] + x[i,] } p <- myDirichlet(gamma + s) for(k in 1:K){ theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,]) } } # collapsed sampler nMatrix <- array(data = 0, dim = c(n,K)) sMatrix <- array(data = 0, dim = c(n,K,d)) for (i in 1:n){ nMatrix[i,] <- s sMatrix[i,,] <- sx } for (i in 1:n){ nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1 for (j in 1:d){ sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j] } } reallocationAcceptanceRatio <- 0 reallocationAcceptanceRatio2 <- 0 a1 <- a2 <- 1 #parameters of Beta for the reallocation proposal lar <- c() for(iter in 1:m){ zOld <- z for(i in 1:n){ nMatrix[i,1:K] <- s[1:K] sMatrix[i,1:K,] <- sx[1:K,] nMatrix[i,z[i]] <- s[z[i]] - 1 sMatrix[i,z[i],] <- sx[z[i],] - x[i,] A1 <- which(x[i,] == 1) A0 <- which(x[i,] == 0) for(k in 1:K){ newL[k] <- log(nMatrix[i,k] + gamma[k]) - d*log(alpha + beta + nMatrix[i,k]) if(length(A1 > 0)){ newL[k] <- newL[k] + sum(log(alpha + sMatrix[i,k,A1])) } if(length(A0 > 0)){ newL[k] <- newL[k] + sum(log(beta + nMatrix[i,k] - sMatrix[i,k,A0])) } } newL[1:K] <- exp(newL[1:K]) z[i] <- sample(K,1,prob = newL[1:K]) #if( zOld[i] != z[i] ){ sx[zOld[i],] <- sx[zOld[i],] - x[i,] sx[z[i],] <- sx[z[i],] + x[i,] s[zOld[i]] <- s[zOld[i]] - 1 s[z[i]] <- s[z[i]] + 1 } # reallocation proposal 1 if (K > 1){ myPair <- sample(K,2,replace = FALSE) propZ <- z set1 <- which(z == myPair[1]) set2 <- which(z == myPair[2]) myP <- rbeta(1,shape1 = gamma[myPair[1]],shape2 = gamma[myPair[2]]) propZ[c(set1,set2)] <- myPair[sample(2,length(set1) + length(set2), replace = TRUE,prob = c(myP,1-myP) )] newSet1 <- which(propZ == myPair[1]) newSet2 <- which(propZ == myPair[2]) nNew <- c(length(newSet1),length(newSet2)) nOld <- c(length(set1),length(set2)) if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))} if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))} sOld <- rbind(sOld1,sOld2) if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))} if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))} sNew <- rbind(sNew1,sNew2) logAR <- 0 for (i in 1:2){ logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,])) } if( log(runif(1)) < logAR ){ reallocationAcceptanceRatio <- reallocationAcceptanceRatio + 1 z <- propZ s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(i in 1:n){ s[z[i]] <- s[z[i]] + 1 sx[z[i],] <- sx[z[i],] + x[i,] } for(i in 1:n){ nMatrix[i,] <- s sMatrix[i,,] <- sx } for (i in 1:n){ nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1 for (j in 1:d){ sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j] } } } } # end of reallocation proposal 1 # reallocation proposal2 if(K > 1){ myPair <- sample(K,2,replace = FALSE) set1 <- which(z == myPair[1]) set2 <- which(z == myPair[2]) nOld <- c(length(set1),length(set2)) propZ <- z if(nOld[1] > 0){ randomSize <- 1 + floor(nOld[1]*runif(1)) randomIndex <- set1[sample(nOld[1],randomSize,replace = FALSE)] propZ[randomIndex] <- rep(myPair[2],randomSize) newSet1 <- which(propZ == myPair[1]) newSet2 <- which(propZ == myPair[2]) nNew <- c(length(newSet1),length(newSet2)) if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))} if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))} sOld <- rbind(sOld1,sOld2) if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))} if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))} sNew <- rbind(sNew1,sNew2) logAR <- log(nOld[1]) - log(nOld[2] + randomSize) -( lgamma(nOld[1] - randomSize + 1) + lgamma(nOld[2]+ randomSize + 1) - lgamma(nOld[2] + 1) - lgamma(nOld[1] + 1)) for(i in 1:2){ logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,])) } logAR <- logAR + sum(lgamma(gamma[myPair] + nNew)) - sum(lgamma(gamma[myPair] + nOld)) if( log(runif(1)) < logAR ){ reallocationAcceptanceRatio2 <- reallocationAcceptanceRatio2 + 1 z <- propZ s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(i in 1:n){ s[z[i]] <- s[z[i]] + 1 sx[z[i],] <- sx[z[i],] + x[i,] } for(i in 1:n){ nMatrix[i,] <- s sMatrix[i,,] <- sx } for (i in 1:n){ nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1 for (j in 1:d){ sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j] } } } } } # end of reallocation proposal 2 if((iter %% thinning == 0)&(iter > burn)){ for(k in 1:K){ myIndex <- which(z == k) s[k] <- length(myIndex) if(s[k] > 1){ sx[k,] <- colSums(x[myIndex,]) }else{ if(s[k] == 1){ sx[k,] <- x[myIndex,] }else{ sx[k,] <- rep(0,d) } } theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,]) } p <- myDirichlet(gamma + s) cat(theta,"\n",file=conTheta) cat(z,"\n",file=conZ) cat(p,"\n",file=conP) } if(iter %% (m/100) == 0){cat(paste("Running collapsed Gibbs: ",100*round(iter/m,3),"% completed. Reallocation proposal acceptance rates: ", 100*round(reallocationAcceptanceRatio/iter,3),"%, ",100*round(reallocationAcceptanceRatio2/iter,3),"%.",sep=""),"\n"); #matplot(read.table("p.collapsed.txt"),type = "l",lty = 1) } } close(conTheta) close(conP) close(conZ) cat(paste("Collapsed Gibbs finished."),"\n") cat("\n") if(K > 1){ cat(paste("Dealing with Label Switching..."),"\n") tt <- read.table("theta.collapsed.txt") m <- dim(tt)[1] d <- dim(x)[2] J <- d + 1 mcmc <- array(data = NA, dim = c(m,K,J)) for (j in 1:d){ for(k in 1:K){ mcmc[,k,j] <- tt[,(j-1)*K + k] } } tt <- read.table("p.collapsed.txt") for(k in 1:K){ mcmc[,k,J] <- tt[,k] } allocations <- as.matrix(read.table("z.collapsed.txt",as.is = TRUE)) m <- dim(mcmc)[1] iter <- 1 ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) maxLL <- ll maxIter <- iter for (iter in 1:m){ ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")} } # classification probs pMatrix <- array(data = NA, dim = c(m,n,K)) for (iter in 1:m){ p <- mcmc[iter,,J] theta <- array( mcmc[iter,,1:(J-1)],dim = c(K,J-1) ) for(i in 1:n){ for(k in 1:K){ l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,])) } for(k in 1:K){ pMatrix[iter,i,k] <- 1/sum(exp(l - l[k])) if(is.na(pMatrix[iter,i,k]) == TRUE){pMatrix[iter,i,k] = 0} } } if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");} } if(missing(z.true)==TRUE){ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix) }else{ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true) } reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output tt <- read.table("theta.collapsed.txt") write.table(reordered.mcmc, file = "reorderedMCMC-ECR.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output write.table(reordered.mcmc, file = "reorderedMCMC-ECR-ITERATIVE1.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output write.table(reordered.mcmc, file = "reorderedMCMC-STEPHENS.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(mcmc, file = "rawMCMC.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(file = "reorderedSingleBestClusterings.collapsed.txt",t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep=".")) file.remove("p.collapsed.txt") file.remove("theta.collapsed.txt") cat(paste("raw MCMC parameters written to: \'rawMCMC.collapsed.txt\' "),"\n") cat(paste("raw MCMC latent allocations written to: \'z.collapsed.txt\' "),"\n") cat(paste("reordered MCMC output written to: "),"\n") cat(paste(" (Method 1): \'reorderedMCMC-ECR.collapsed.txt\'"),"\n") cat(paste(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.collapsed.txt\'"),"\n") cat(paste(" (Method 3): \'reorderedMCMC-STEPHENS.collapsed.txt\'"),"\n") cat(paste("reordered single best clusterings written to: \'reorderedSingleBestClusterings.collapsed.txt\' "),"\n") } setwd("../") } ###################################################### allocationSamplerBinMix <- function(Kmax, alpha,beta,gamma,m,burn,data,thinning,z.true,ClusterPrior,ejectionAlpha,Kstart,outputDir,metropolisMoves,reorderModels,heat,zStart,LS, rsX, originalX, printProgress){ # if(dir.exists(outputDir) == TRUE){ # stop(cat(paste(" [ERROR]: directory exists, please provide different name."), "\n")) # } #dir.create(outputDir) setwd(outputDir) cat(paste0("changing working directory to ",outputDir),"\n") if (missing(m)) {stop(cat(paste(" [ERROR]: number of MCMC iterations (m) not provided."), "\n"))} if (missing(thinning)) {thinning <- 5} if (missing(LS)) {LS <- TRUE} if (missing(printProgress)) { printProgress <- FALSE } if (missing(ejectionAlpha)) {ejectionAlpha <- 1} if (burn > m - 1) { stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n")) } if (burn < 0) { stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n")) } if (thinning > m) { stop(cat(paste(" [ERROR]: thinning not valid."), "\n")) } if (m < 1) { stop(cat(paste(" [ERROR]: mcmc iterations (m) not valid."), "\n")) } if (missing(alpha)) {alpha <- 1} if (missing(beta)) {beta <- 1} if (missing(data)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))} x <- data d <- dim(data)[2] n <- dim(data)[1] if (missing(Kmax)) {Kmax <- floor((d + 1)/2)} if (missing(gamma)) {gamma <- rep(1,Kmax)} if (length(table(gamma)) > 1){ stop(cat(paste(" [ERROR]: Dirichlet prior parameters should be the same."), "\n")) } birthProbs <- rep(1,Kmax) birthProbs[2:(Kmax - 1)] <- rep(0.5,Kmax - 2) birthProbs[Kmax] <- 0 deathProbs <- 1 - birthProbs # define uniform or truncated poisson(1) prior on K priorK <- numeric(Kmax) if (missing(ClusterPrior)) {stop(cat(paste(" [ERROR]: ClusterPrior not defined (uniform of poisson)."), "\n"))} if (missing(ejectionAlpha)) {stop(cat(paste(" [ERROR]: ejectionAlpha not defined (0 < a < 1)."), "\n"))} if (ejectionAlpha < 0) {stop(cat(paste(" [ERROR]: ejectionAlpha error (0 < a < 1)."), "\n"))} if (ejectionAlpha > 1) {stop(cat(paste(" [ERROR]: ejectionAlpha error (0 < a < 1)."), "\n"))} if(ClusterPrior == "uniform"){ priorK <- rep(log(1/Kmax),Kmax) } if(ClusterPrior == "poisson"){ denom <- log(ppois(Kmax, lambda = 1, lower.tail = TRUE) - dpois(0,lambda = 1)) for (k in 1:Kmax){ priorK[k] <- dpois(k,lambda = 1, log = TRUE) - denom } } if(missing(Kstart)){ Kstart <- 1 } K <- Kstart p <- myDirichlet(rep(1,K)) # initial values for cluster probabilities theta <- array(data = runif(Kmax*d), dim = c(Kmax,d)) # initial values for response probabilities s <- l <- newL <- numeric(Kmax) sx <- array(data = 0, dim = c(Kmax,d)) if(missing(zStart) == TRUE){ cat(paste("Initializing..."),"\n") cat("\n") z <- sample(K,n,replace=TRUE,prob = p) cat(paste("Allocation sampler running..."),"\n") cat("\n") }else{ z <- zStart s[1:K] <- rep(0,K) sx[1:K,] <- array(data = 0, dim = c(K,d)) for(i in 1:n){ s[z[i]] <- s[z[i]] + 1 sx[z[i],] <- sx[z[i],] + x[i,] } } #output k.file <- "K.txt" theta.file <- "theta.varK.txt" z.file <- "z.varK.txt" p.file <- "p.varK.txt" conK = file(k.file,open = "w") conTheta = file(theta.file,open = "w") conZ = file(z.file,open = "w") conP = file(p.file,open = "w") # initialization with standard Gibbs #print("here1") #par(mfrow = c(1,1)) if(missing(zStart) == TRUE){ for (iter in 1:5){ s[1:K] <- rep(0,K) sx[1:K,] <- array(data = 0, dim = c(K,d)) for(i in 1:n){ for(k in 1:K){ l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,])) } for(k in 1:K){ newL[k] <- 1/sum(exp(l[1:K] - l[k])) } if(is.nan(sum(newL[1:K]))==TRUE){newL[1:K]<-rep(1,K)} z[i] <- sample(K,1,prob = newL[1:K]) s[z[i]] <- s[z[i]] + 1 sx[z[i],] <- sx[z[i],] + x[i,] } p <- myDirichlet(heat*gamma[1:K] + heat*s[1:K] + 1 - heat) for(k in 1:K){ theta[k,] <- rbeta(d, shape1 = heat*alpha + heat*sx[k,] + 1 - heat, shape2 = heat*beta + heat*s[k] - heat*sx[k,] + 1 - heat) } } } # collapsed sampler nMatrix <- array(data = 0, dim = c(n,Kmax)) sMatrix <- array(data = 0, dim = c(n,Kmax,d)) #print("here2") for (i in 1:n){ nMatrix[i,1:K] <- s[1:K] sMatrix[i,1:K,] <- sx[1:K,] } for (i in 1:n){ nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1 for (j in 1:d){ sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j] } } reallocationAcceptanceRatio <- 0 reallocationAcceptanceRatio2 <- 0 reallocationAcceptanceRatio3 <- 0 reallocationAcceptanceRatio4 <- 0 a1 <- a2 <- 1 #parameters of Beta for the reallocation proposal pZERO <- ejectionAlpha constLGAMMA <- 2*lgamma(ejectionAlpha) - lgamma(2*ejectionAlpha) kValues <- c() #plot(c(1,m),c(0,1),type = "n") if(missing(metropolisMoves) == TRUE){metropolisMoves <- c('M1','M2','M3','M4')} lmm <- 1/length(metropolisMoves) if( printProgress == TRUE){ cat(paste(" Reallocation proposal acceptance rates: Move 1, Move 2, Move 3, Move 4"),"\n") } for(iter in 1:m){ zOld <- z sOld <- s sxOld <- sx if(K > 1){ myPair <- sample(K,2,replace = FALSE) j1 <- myPair[1] j2 <- myPair[2] set1 <- which(z == j1) set2 <- which(z == j2) zOld[set1] = rep(j2,length(set1)) zOld[set2] = rep(j1,length(set2)) z <- zOld sOld[j1] <- s[j2] sOld[j2] <- s[j1] sxOld[j1,] <- sx[j2,] sxOld[j2,] <- sx[j1,] s <- sOld sx <- sxOld } for(i in 1:n){ nMatrix[i,1:K] <- s[1:K] sMatrix[i,1:K,] <- sx[1:K,] nMatrix[i,z[i]] <- s[z[i]] - 1 sMatrix[i,z[i],] <- sx[z[i],] - x[i,] A1 <- which(x[i,] == 1) A0 <- which(x[i,] == 0) for(k in 1:K){ newL[k] <- heat*log(nMatrix[i,k] + gamma[k]) - heat*d*log(alpha + beta + nMatrix[i,k]) if(length(A1 > 0)){ newL[k] <- newL[k] + heat*sum(log(alpha + sMatrix[i,k,A1])) } if(length(A0 > 0)){ newL[k] <- newL[k] + heat*sum(log(beta + nMatrix[i,k] - sMatrix[i,k,A0])) } } newL[1:K] <- exp(newL[1:K]) if( max(newL[1:K]) == 0){newL[1:K] <- rep(1,K);cat("oops","\n")} z[i] <- sample(K,1,prob = newL[1:K]) #if( zOld[i] != z[i] ){ sx[zOld[i],] <- sx[zOld[i],] - x[i,] sx[z[i],] <- sx[z[i],] + x[i,] s[zOld[i]] <- s[zOld[i]] - 1 s[z[i]] <- s[z[i]] + 1 #nMatrix[,z[i]] <- s[z[i]] - 1 #sMatrix[,z[i],] <- sx[z[i],] - x[i,] #nMatrix[,zOld[i]] <- nMatrix[,zOld[i]] - 1 #nMatrix[,z[i]] <- nMatrix[,z[i]] + 1 #myMat <- matrix(rep(x[i,],n),nrow = n,byrow=TRUE) #sMatrix[,zOld[i],] <- sMatrix[,zOld[i],] - myMat #sMatrix[,z[i],] <- sMatrix[,z[i],] + myMat #} } mNumber <- sample(metropolisMoves,1) #mNumber <- 5 if(mNumber == 'M1'){ # if(1 > 2){ # reallocation proposal 1 if (K > 1){ myPair <- sample(K,2,replace = FALSE) propZ <- z set1 <- which(z == myPair[1]) set2 <- which(z == myPair[2]) myP <- rbeta(1,shape1 = gamma[myPair[1]],shape2 = gamma[myPair[2]]) propZ[c(set1,set2)] <- myPair[sample(2,length(set1) + length(set2), replace = TRUE,prob = c(myP,1-myP) )] newSet1 <- which(propZ == myPair[1]) newSet2 <- which(propZ == myPair[2]) nNew <- c(length(newSet1),length(newSet2)) nOld <- c(length(set1),length(set2)) if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))} if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))} sOld <- rbind(sOld1,sOld2) if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))} if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))} sNew <- rbind(sNew1,sNew2) logAR <- 0 for (i in 1:2){ logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,])) } if(is.finite(logAR)){ if( log(runif(1)) < logAR ){ reallocationAcceptanceRatio <- reallocationAcceptanceRatio + 1 z <- propZ s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(k in 1:K){ ind <- which(z == k) tmpV <- numeric(n) tmpM <- array(data = 0,dim = c(n,d)) s[k] <- length(ind) if(s[k] > 0){ tmpV[ind] <- rep(1,s[k]) tmpM[ind,] <- x[ind,] sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d))) } nMatrix[,k] <- rep(s[k],n) - tmpV sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM } } } } } # end of reallocation proposal 1 if(mNumber == 'M2'){ # reallocation proposal2 if(K > 1){ myPair <- sample(K,2,replace = FALSE) set1 <- which(z == myPair[1]) set2 <- which(z == myPair[2]) nOld <- c(length(set1),length(set2)) propZ <- z if(nOld[1] > 0){ randomSize <- 1 + floor(nOld[1]*runif(1)) randomIndex <- set1[sample(nOld[1],randomSize,replace = FALSE)] propZ[randomIndex] <- rep(myPair[2],randomSize) newSet1 <- which(propZ == myPair[1]) newSet2 <- which(propZ == myPair[2]) nNew <- c(length(newSet1),length(newSet2)) if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))} if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))} sOld <- rbind(sOld1,sOld2) if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))} if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))} sNew <- rbind(sNew1,sNew2) logAR <- log(nOld[1]) - log(nOld[2] + randomSize) -( lgamma(nOld[1] - randomSize + 1) + lgamma(nOld[2]+ randomSize + 1) - lgamma(nOld[2] + 1) - lgamma(nOld[1] + 1)) for(i in 1:2){ logAR <- logAR + heat*d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + heat*sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,])) } logAR <- logAR + heat*sum(lgamma(gamma[myPair] + nNew)) - heat*sum(lgamma(gamma[myPair] + nOld)) if(is.finite(logAR)){ if( log(runif(1)) < logAR ){ reallocationAcceptanceRatio2 <- reallocationAcceptanceRatio2 + 1 z <- propZ s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(k in 1:K){ ind <- which(z == k) tmpV <- numeric(n) tmpM <- array(data = 0,dim = c(n,d)) s[k] <- length(ind) if(s[k] > 0){ tmpV[ind] <- rep(1,s[k]) tmpM[ind,] <- x[ind,] sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d))) } nMatrix[,k] <- rep(s[k],n) - tmpV sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM } } } } } } # end of reallocation proposal 2 # } #remove this # update the number of clusters if(mNumber == 'M3'){ if ( runif(1) < birthProbs[K] ){ # BIRTH MOVE birth = TRUE myPair <- c(sample(K,1),K + 1) # myPair[1]: ejecting component # myPair[2]: ejected component set1 <- which(z == myPair[1]) nOld <- c(length(set1),0) ejectionAlpha <- toSolve(seq(0.0001,2,length = 500),nOld[1],pZERO);constLGAMMA <- 2*lgamma(ejectionAlpha) - lgamma(2*ejectionAlpha) propZ <- z myP <- rbeta(1,shape1 = ejectionAlpha,shape2 = ejectionAlpha) propZ[set1] <- myPair[sample(2,nOld[1], replace = TRUE,prob = c(1-myP,myP) )] newSet1 <- which(propZ == myPair[1]) newSet2 <- which(propZ == myPair[2]) nNew <- c(length(newSet1),length(newSet2)) if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))} if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))} sOld <- rbind(sOld1,sOld2) if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))} if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))} sNew <- rbind(sNew1,sNew2) logAR <- log( (1 - birthProbs[K+1])/birthProbs[K] ) + constLGAMMA + lgamma(2*ejectionAlpha + nOld[1]) - lgamma(ejectionAlpha + nNew[1]) - lgamma(ejectionAlpha + nNew[2]) + heat*priorK[K+1] - heat*priorK[K] logAR <- logAR + heat*d*( lgamma(alpha + beta + nOld[1]) - lgamma(alpha + beta + nNew[1]) - lgamma(alpha + beta + nNew[2]) ) logAR <- logAR + heat*sum( lgamma(alpha + sNew[1,]) + lgamma(beta + nNew[1] - sNew[1,]) + lgamma(alpha + sNew[2,]) + lgamma(beta + nNew[2] - sNew[2,]) - lgamma(alpha + sOld[1,]) - lgamma(beta + nOld[1] - sOld[1,]) ) # for(i in 1:2){ # logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,])) # } logAR <- logAR + heat*sum(lgamma(gamma[myPair] + nNew)) - heat*sum(lgamma(gamma[myPair[1]] + nOld[1])) + heat*lgamma(sum(gamma[1:(K+1)])) - heat*lgamma(sum(gamma[1:K])) - heat*lgamma(sum(gamma[1:(K+1)]) + n) + heat*lgamma(sum(gamma[1:K]) + n) - heat*lgamma(gamma[K+1]) - heat*d*lbeta(alpha, beta) }else{ # DEATH MOVE birth = FALSE myPair <- c(sample(K - 1,1),K) set1 <- which(z == myPair[1]) set2 <- which(z == myPair[2]) nOld <- c(length(set1),length(set2)) propZ <- z propZ[c(set1,set2)] <- rep(myPair[1],sum(nOld)) newSet1 <- which(propZ == myPair[1]) nNew <- c(length(newSet1),0) ejectionAlpha <- toSolve(seq(0.0001,2,length = 500),nNew[1],pZERO);constLGAMMA <- 2*lgamma(ejectionAlpha) - lgamma(2*ejectionAlpha) if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))} if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))} sOld <- rbind(sOld1,sOld2) if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))} sNew2 <- rep(0,d) sNew <- rbind(sNew1,sNew2) logAR <- - (log( (1 - birthProbs[K])/birthProbs[K - 1] ) + constLGAMMA + lgamma(2*ejectionAlpha + nNew[1]) - lgamma(ejectionAlpha + nOld[1]) - lgamma(ejectionAlpha + nOld[2]))+ heat*priorK[K - 1] - heat*priorK[K] logAR <- logAR + heat*d*( lgamma(alpha + beta + nOld[1]) + lgamma(alpha + beta + nOld[2]) - lgamma(alpha + beta + nNew[1]) ) logAR <- logAR + heat*sum( lgamma(alpha + sNew[1,]) + lgamma(beta + nNew[1] - sNew[1,]) - lgamma(alpha + sOld[1,]) - lgamma(beta + nOld[1] - sOld[1,]) - lgamma(alpha + sOld[2,]) - lgamma(beta + nOld[2] - sOld[2,]) ) # for(i in 1:2){ # logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,])) # } logAR <- logAR + heat*lgamma(gamma[myPair[1]] + nNew[1]) - heat*sum(lgamma(gamma[myPair] + nOld)) + heat*lgamma(sum(gamma[1:(K-1)])) - heat*lgamma(sum(gamma[1:K])) - heat*lgamma(sum(gamma[1:(K-1)]) + n) + heat*lgamma(sum(gamma[1:K]) + n) + heat*lgamma(gamma[K]) + heat*d*lbeta(alpha, beta) } if(is.finite(logAR)){ if( log(runif(1)) < logAR ){ reallocationAcceptanceRatio3 <- reallocationAcceptanceRatio3 + 1 z <- propZ if(birth == TRUE){K <- K + 1}else{K <- K - 1} s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(k in 1:K){ ind <- which(z == k) tmpV <- numeric(n) tmpM <- array(data = 0,dim = c(n,d)) s[k] <- length(ind) if(s[k] > 0){ tmpV[ind] <- rep(1,s[k]) tmpM[ind,] <- x[ind,] sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d))) } nMatrix[,k] <- rep(s[k],n) - tmpV sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM } } } } # end of update for the number of clusters if(mNumber == 'M4'){ # reallocation proposal from conditional probs if(K > 1){ myPair <- sample(K,2,replace = FALSE) propZ <- z set1 <- which(z == myPair[1]) set2 <- which(z == myPair[2]) union12 <- c(set1,set2) processed <- c() notProcessed <- setdiff(union12,processed) n1New <- n2New <- 0 s1New <- s2New <- numeric(d) n1 <- n2 <- 0 s1 <- s2 <- numeric(d) j1 <- myPair[1] j2 <- myPair[2] alreadyInJ1 <- alreadyInJ2 <- c() proposalRatio <- 0 checkCondition <- TRUE while ( length(notProcessed) > 0 ){ i <- notProcessed[1] processed <- c(processed,i) # propose reallocation u <- log(gamma[j1] + n1New) - log(gamma[j2] + n2New) + sum( lgamma(alpha + x[i,] + s1New) + lgamma(beta + 1 + n1New - s1New - x[i,]) ) - d*sum(lgamma(alpha+beta+n1New+1)) + sum( lgamma(alpha + s2New) + lgamma(beta + n2New - s2New) ) - d*sum(lgamma(alpha+beta+n2New)) - sum( lgamma(alpha + s1New) + lgamma(beta + n1New - s1New) ) + d*sum(lgamma(alpha+beta+n1New)) - sum( lgamma(alpha + x[i,] + s2New) + lgamma(beta + 1 + n2New - s2New - x[i,]) ) + d*sum(lgamma(alpha+beta+n2New+1)) u <- exp(u) proposalProbabities <- u/(1 + u) if( is.finite(proposalProbabities) == FALSE ){checkCondition <- FALSE; proposalProbabities <- 0.5} if( runif(1) < proposalProbabities ){ propZ[i] <- j1 proposalRatio <- proposalRatio - log(proposalProbabities) n1New <- n1New + 1 s1New <- s1New + x[i,] }else{ propZ[i] <- j2 proposalRatio <- proposalRatio - log(1 - proposalProbabities) n2New <- n2New + 1 s2New <- s2New + x[i,] } # compute inverse move u <- log(gamma[j1] + n1) - log(gamma[j2] + n2) + sum( lgamma(alpha + x[i,] + s1) + lgamma(beta + 1 + n1 - s1 - x[i,]) ) - d*sum(lgamma(alpha+beta+n1+1)) + sum( lgamma(alpha + s2) + lgamma(beta + n2 - s2) ) - d*sum(lgamma(alpha+beta+n2)) - sum( lgamma(alpha + s1) + lgamma(beta + n1 - s1) ) + d*sum(lgamma(alpha+beta+n1)) - sum( lgamma(alpha + x[i,] + s2) + lgamma(beta + 1 + n2 - s2 - x[i,]) ) + d*sum(lgamma(alpha+beta+n2+1)) u <- exp(u) u <- u/(1 + u) if(z[i] == j1){ proposalRatio <- proposalRatio + log(u) n1 <- n1 + 1 s1 <- s1 + x[i,] }else{ proposalRatio <- proposalRatio + log(1 - u) n2 <- n2 + 1 s2 <- s2 + x[i,] } notProcessed <- setdiff(union12,processed) } newSet1 <- which(propZ == myPair[1]) newSet2 <- which(propZ == myPair[2]) nNew <- c(length(newSet1),length(newSet2)) nOld <- c(length(set1),length(set2)) if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))} if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))} sOld <- rbind(sOld1,sOld2) if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))} if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))} sNew <- rbind(sNew1,sNew2) logAR <- proposalRatio for (i in 1:2){ logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,])) } logAR <- logAR + sum(lgamma(gamma[myPair] + nNew)) - sum(lgamma(gamma[myPair] + nOld)) if(is.finite(logAR)){ if( (log(runif(1)) < logAR) && (checkCondition == TRUE) ){ reallocationAcceptanceRatio4 <- reallocationAcceptanceRatio4 + 1 z <- propZ s <- rep(0,K) sx <- array(data = 0, dim = c(K,d)) for(k in 1:K){ ind <- which(z == k) tmpV <- numeric(n) tmpM <- array(data = 0,dim = c(n,d)) s[k] <- length(ind) if(s[k] > 0){ tmpV[ind] <- rep(1,s[k]) tmpM[ind,] <- x[ind,] sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d))) } nMatrix[,k] <- rep(s[k],n) - tmpV sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM } } } } # end of reallocation proposal from conditional probs } if(iter %% thinning == 0){ kValues <- c(kValues,K) if(iter > burn){ cat(K,"\n",file=conK) cat(z,"\n",file=conZ) if (heat == 1){ #produce parameter values only for cold chain for(k in 1:K){ myIndex <- which(z == k) s[k] <- length(myIndex) if(s[k] > 1){ sx[k,] <- colSums(x[myIndex,]) }else{ if(s[k] == 1){ sx[k,] <- x[myIndex,] }else{ sx[k,] <- rep(0,d) } } theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,]) } # in case of missing values if( length(rsX) > 0){ for(i in rsX){ na.index <- which(is.na(originalX[i,]) == TRUE) x[i, na.index] <- rbinom(n = length(na.index), size = 1, prob = theta[z[i],na.index]) } write.table(x,file = "currentX.txt", quote = FALSE, row.names = FALSE, col.names = FALSE) } p <- myDirichlet(gamma[1:K] + s[1:K]) cat(theta,"\n",file=conTheta) cat(p,"\n",file=conP) } } } if( printProgress == TRUE){ if(iter %% (m/100) == 0){ cat(paste(" ",100*round(iter/m,3),"% completed. ", 100*round(lmm*reallocationAcceptanceRatio/iter,3),"%, ", 100*round(lmm*reallocationAcceptanceRatio2/iter,3),"%, ", 100*round(lmm*reallocationAcceptanceRatio4/iter,3),"%, ", 100*round(lmm*reallocationAcceptanceRatio3/iter,3),"%", sep=""),"\n");} } } close(conK) close(conTheta) close(conP) close(conZ) cat(paste("Allocation Sampler finished."),"\n") cat("\n") #if(K < 1){ if(LS == TRUE){ kFile <- read.table("K.txt")[,1] cat("\n") print(table(kFile)/length(kFile)) K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]]) cat("\n") cat(paste("Most probable model: K = ",K," with P(K = ",K,") = ",max(table(kFile)/length(kFile)),sep=""),"\n") cat("\n") if(missing(reorderModels)==TRUE){reorderModels <- 'onlyMAP'} if(reorderModels == 'onlyMAP'){kRange <- K}else{ kRange <- as.numeric(names(table(kFile)/length(kFile))) } for ( K in kRange ){ if (K > 1){ cat(paste("Dealing with Label Switching for K =",K),"\n") tt <- read.table("theta.varK.txt") index <- which(kFile == K) d <- dim(x)[2] J <- d + 1 m <- length(index) mcmc <- array(data = NA, dim = c(m,K,J)) Kmax <- (dim(tt)/d)[2] for (j in 1:d){ for(k in 1:K){ mcmc[,k,j] <- tt[index,(j-1)*Kmax + k] } } conP = file(p.file,open = "r") i <- 0 j <- 0 while (length(oneLine <- readLines(conP, n = 1, warn = FALSE)) > 0) { i <- i + 1 if(kFile[i] == K){ j <- j + 1 mcmc[j,,J] <- as.numeric(strsplit(oneLine,split = " ")[[1]]) } } close(conP) allocations <- as.matrix(read.table("z.varK.txt",as.is = TRUE)[index,]) iter <- 1 ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) maxLL <- ll maxIter <- iter for (iter in 1:m){ ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")} } # classification probs pMatrix <- array(data = NA, dim = c(m,n,K)) l <- numeric(K) for (iter in 1:m){ p <- mcmc[iter,,J] theta <- array( mcmc[iter,,1:(J-1)],dim = c(K,J-1) ) for(i in 1:n){ for(k in 1:K){ l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,])) } for(k in 1:K){ pMatrix[iter,i,k] <- 1/sum(exp(l - l[k])) if(is.na(pMatrix[iter,i,k]) == TRUE){pMatrix[iter,i,k] = 0} } } if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");} } if(missing(z.true)==TRUE){ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix) }else{ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true) } reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-STEPHENS.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(mcmc, file = paste("rawMCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(file = paste("reorderedSingleBestClusterings.mapK.",K,".txt",sep=""),t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep=".")) #reordering allocations allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations for (i in 1:m){ myPerm <- order(ls$permutations$"ECR"[i,]) allocationsECR[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"STEPHENS"[i,]) allocationsKL[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,]) allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]] } write.table(allocationsECR, file = paste("z.ECR.mapK.",K,".txt",sep="")) write.table(allocationsKL, file = paste("z.KL.mapK.",K,".txt",sep="")) write.table(allocationsECR.ITERATIVE1, file = paste("z.ECR-ITERATIVE1.mapK.",K,".txt",sep="")) #file.remove("p.collapsed.txt") #file.remove("theta.collapsed.txt") cat(paste0("raw MCMC parameters for most probable K written to: \'rawMCMC.mapK.",K,".txt\' "),"\n") cat(paste0("raw MCMC latent allocations for most probable K written to: \'z.mapK.",K,".txt\' "),"\n") cat(paste0("reordered MCMC output written to: "),"\n") cat(paste0(" (Method 1): \'reorderedMCMC-ECR.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 3): \'reorderedMCMC-STEPHENS.mapK.",K,".txt\'"),"\n") cat(paste0("reordered single best clusterings written to: \'reorderedSingleBestClusterings.mapK.",K,".txt\' "),"\n") cat(paste0("reordered MCMC latent allocations for most probable K written to: "),"\n") cat(paste0(" (Method 1): \'z.ECR.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 2): \'z.KL.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 3): \'z.ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n") } } } setwd("../") cat(paste0("back to working directory now."),"\n") return(kValues) } coupledMetropolis <- function(Kmax, nChains,heats,binaryData,outPrefix,ClusterPrior,m, alpha, beta, gamma, z.true, ejectionAlpha, burn){ if(missing(nChains) == TRUE){stop(cat(paste(" [ERROR]: number of chains not provided."), "\n"))} if(missing(heats) == TRUE){ heats <- seq(1,0.1,length = nChains) }else{ if(heats[1] != 1){stop(cat(paste(" [ERROR]: `heats[1]` should be equal to one."), "\n"))} } if(length(heats) != nChains){ stop(cat(paste(" [ERROR]: `length(heats)` should be equal to `nChains`."), "\n")) } if(missing(ClusterPrior) == TRUE){ClusterPrior <- 'poisson'} if (missing(alpha)) {alpha <- 1} if (missing(beta)) {beta <- 1} if (missing(binaryData)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))} if (missing(gamma)) {gamma <- rep(1,Kmax)} if (length(table(gamma)) > 1){ stop(cat(paste(" [ERROR]: Dirichlet prior parameters should be the same."), "\n")) } d <- dim(binaryData)[2]; n <- dim(binaryData)[1]; priorK <- numeric(Kmax) if(ClusterPrior == "uniform"){ priorK <- rep(log(1/Kmax),Kmax) } if(ClusterPrior == "poisson"){ denom <- log(ppois(Kmax, lambda = 1, lower.tail = TRUE) - dpois(0,lambda = 1)) for (k in 1:Kmax){ priorK[k] <- dpois(k,lambda = 1, log = TRUE) - denom } } if(missing(ejectionAlpha) == TRUE){ejectionAlpha <- 0.2} x <- binaryData rsX <- which(is.na(rowSums(x)) == TRUE) originalX <- x if(length(rsX) > 0){ cat(paste(" [NOTE]: Found ",length(rsX) ," rows with missing values."), "\n") for(i in rsX){ na.index <- which(is.na(x[i,]) == TRUE) x[i,na.index] <- rbinom(n = length(na.index), size = 1, prob = alpha/(alpha + beta)) } } currentZ <- array(data = NA, dim = c(nChains,n)) currentK <- numeric(nChains) # check if dir exists and stop in this case myCheck <- match(outPrefix,list.files()) if(is.na(myCheck) == FALSE){ stop(cat(paste(" [ERROR]: directory exists, please provide different name to outPrefix."), "\n")) } if( missing(z.true) ){ z.true <- NULL } if(missing(burn)){burn = 0} if(burn > m - 1){ stop(cat(paste(" [ERROR]: Burn-in period not valid: \'burn\' should be less than \'m\'."), "\n")) } if(nChains < 2){ if(length(rsX) > 0){ stop(cat(paste(" [ERROR]: At least two chains should be used."), "\n"))} cat(paste(" Only 1 chain? Well."),"\n") dir.create(outPrefix) myHeat <- 1 asr <- allocationSamplerBinMix( alpha = alpha, beta = beta, gamma = gamma, m = 10*m, burn= 10*burn, data = x, thinning = 10,Kmax = Kmax, ClusterPrior = ClusterPrior,ejectionAlpha = ejectionAlpha, outputDir = outPrefix,Kstart = 1,heat=myHeat,metropolisMoves = c('M1','M2','M3','M4'),LS = FALSE, rsX = rsX, originalX = originalX)} else{ registerDoParallel(cores = nChains) #registerDoMC(nChains) outputDirs <- paste0(outPrefix,1:nChains) temperatures <- heats myChain <- 1 for(i in 1:nChains){ cat(paste0(" Create temporary directory: \'",outPrefix,i,"\'."), "\n") } cat(paste0(" [NOTE]: screen output from multiple threads is redirected to \'",outPrefix,"-sampler.log\'."), "\n") sink(paste0(outPrefix,'-sampler.log')) foreach(myChain=1:nChains, .export=ls(envir=globalenv()) ) %dopar% { outDir <- outputDirs[myChain] dir.create(outDir) myHeat <- temperatures[myChain] asr <- allocationSamplerBinMix( alpha = alpha, beta = beta, gamma = gamma, m = 10, burn= 9, data = x, thinning = 1,Kmax = Kmax, ClusterPrior = ClusterPrior,ejectionAlpha = ejectionAlpha, outputDir = outDir,Kstart=1,heat=myHeat,metropolisMoves='M3',LS = FALSE, rsX = rsX, originalX = originalX) } ITERATIONS <- m sampledK <- array(data = 0, dim = c(ITERATIONS,nChains)) dir.create(outPrefix) k.file <- paste0(outPrefix,"/K.txt") theta.file <- paste0(outPrefix,"/theta.varK.txt") z.file <- paste0(outPrefix,"/z.varK.txt") p.file <- paste0(outPrefix,"/p.varK.txt") x.file <- paste0(outPrefix,"/x.txt") conK = file(k.file,open = "w") conTheta = file(theta.file,open = "w") conZ = file(z.file,open = "w") conP = file(p.file,open = "w") if(length(rsX) > 0){ # in case of missing values, the augmented data will be written to the file: conX <- file(x.file, open = "w") } ar <- 0 metMoves <- vector('list',length = nChains) metMoves[[1]] <- c('M1','M2','M3','M4') for(j in 2:nChains){metMoves[[j]] <- c('M2','M3')} localAR <- 0 #every 10 iterations for(iter in 1:ITERATIONS){ if(length(rsX) > 0){ x <- as.matrix(read.table(paste0(outPrefix,1,'/currentX.txt'))) } for(myChain in 1:nChains){ currentZ[myChain,] <- as.numeric(read.table(paste0(outPrefix,myChain,'/z.varK.txt'))[1,]) currentK[myChain] <- read.table(paste0(outPrefix,myChain,'/K.txt'))[1,] } sampledK[iter,] <- currentK myPair <- sample(nChains,2,replace = FALSE) j1 <- myPair[1] j2 <- myPair[2] z1 <- currentZ[j1,] z2 <- currentZ[j2,] K1 <- currentK[j1] K2 <- currentK[j2] s1 <- rep(0,K1) sx1 <- array(data = 0, dim = c(K1,d)) for(k in 1:K1){ ind <- which(z1 == k) s1[k] <- length(ind) if(s1[k] > 0){ sx1[k,] <- colSums(array(x[ind,],dim = c(s1[k],d))) } } s2 <- rep(0,K2) sx2 <- array(data = 0, dim = c(K2,d)) for(k in 1:K2){ ind <- which(z2 == k) s2[k] <- length(ind) if(s2[k] > 0){ sx2[k,] <- colSums(array(x[ind,],dim = c(s2[k],d))) } } #compute log-posterior for 1st log.posterior <- priorK[K1] + sum(lgamma( gamma[1:K1] + s1 )) - d*sum(lgamma(alpha+beta+s1)) - lgamma(n + sum(gamma[1:K1])) for(k in 1:K1){ log.posterior <- log.posterior + sum(lgamma(alpha + sx1[k,]) + lgamma(beta + s1[k] - sx1[k,])) } #prior constants1: log.posterior <- log.posterior + lgamma(sum(gamma[1:K1])) - sum(lgamma(gamma[1:K1])) - K1*d*lbeta(alpha, beta) logAR <- (temperatures[j2] - temperatures[j1])*log.posterior #compute log-posterior for 2nd log.posterior <- priorK[K2] + sum(lgamma( gamma[1:K2] + s2 )) - d*sum(lgamma(alpha+beta+s2)) - lgamma(n + sum(gamma[1:K2])) for(k in 1:K2){ log.posterior <- log.posterior + sum(lgamma(alpha + sx2[k,]) + lgamma(beta + s2[k] - sx2[k,])) } #prior constants2: log.posterior <- log.posterior + lgamma(sum(gamma[1:K2])) - sum(lgamma(gamma[1:K2])) - K2*d*lbeta(alpha, beta) logAR <- logAR + (temperatures[j1] - temperatures[j2])*log.posterior #write(paste0('logAR = ',logAR),stderr()) #cat(paste('logAR =',logAR),'\n') if( log(runif(1)) < logAR ){ ar <- ar + 1 localAR <- localAR + 1 currentZ[j1,] <- z2 currentZ[j2,] <- z1 currentK[j1] <- K2 currentK[j2] <- K1 #cat(paste('switching.'),'\n') } myChain <- 1 foreach(myChain=1:nChains, .export=ls(envir=globalenv()) ) %dopar% { outDir <- outputDirs[myChain] myHeat <- temperatures[myChain] Kstart <- currentK[myChain] zStart <- currentZ[myChain,] allocationSamplerBinMix( alpha = alpha, beta = beta, gamma = gamma, m = 10, burn= 9, data = x, thinning = 1,Kmax = Kmax, ClusterPrior = ClusterPrior,ejectionAlpha = ejectionAlpha, outputDir = outDir,Kstart=Kstart,zStart = zStart, heat=myHeat, metropolisMoves = metMoves[[myChain]],LS = FALSE, rsX = rsX, originalX = originalX) } if(iter %% (m/100) == 0){ matplot(sampledK[1:iter,],type = "l",lty = 1,lwd = 2, col = topo.colors(nChains)) points(sampledK[1:iter,1], type = "b",col = topo.colors(nChains)[1]) legend('topleft',paste0('f(z,K|data)^{',round(heats,3),'}'),lty = 1, lwd = 2, col = topo.colors(nChains)) write(paste0(100*iter/m,'% completed. Chain switching acceptance rate: ',100*round(ar/iter,3),'%.'),stderr()) } if(iter > burn){ kk <- as.numeric(read.table(paste0(outPrefix,"1/K.txt"))[1,]) cat(kk,"\n",file=conK) theta <- as.numeric(read.table(paste0(outPrefix,"1/theta.varK.txt"))[1,]) cat(theta,"\n",file=conTheta) z <- as.numeric(read.table(paste0(outPrefix,"1/z.varK.txt"))[1,]) cat(z,"\n",file=conZ) p <- as.numeric(read.table(paste0(outPrefix,"1/p.varK.txt"))[1,]) cat(p,"\n",file=conP) if(length(rsX) > 0){cat(x,"\n",file=conX)} } } close(conK) close(conTheta) close(conP) close(conZ) if(nChains > 1){ swapAcceptanceRate <- 100*round(ar/iter,3) }else{ swapAcceptanceRate <- 'NA' } if(length(rsX) > 0){ close(conX) } write.table(sampledK, file = paste0(outPrefix,"/K.allChains.txt"), col.names = paste0('chain.',1:nChains),quote=FALSE,row.names = FALSE) for(k in 1:nChains){ unlink(paste0(outPrefix,k), recursive=TRUE) } sink() stopImplicitCluster() } if(length(rsX) == 0){ # x contains no missing values if(is.null(z.true) == TRUE){ dealWithLabelSwitching(outDir = outPrefix, binaryData = binaryData) }else{ dealWithLabelSwitching(outDir = outPrefix, binaryData = binaryData, z.true = z.true) } }else{ # x contains missing values if(is.null(z.true) == TRUE){ dealWithLabelSwitchingMissing(outDir = outPrefix, binaryData = binaryData) }else{ dealWithLabelSwitchingMissing(outDir = outPrefix, binaryData = binaryData, z.true = z.true) } } # returning mcmc objects from coda package for the most probable number of clusters if(nChains > 1){ kFile <- sampledK[(burn+1):ITERATIONS,1] }else{ kFile <- read.table(paste0(outPrefix,"/K.txt")) ITERATIONS <- m swapAcceptanceRate <- 0 } K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]]) K.mcmc <- mcmc(kFile, start = 10*burn + 10, end = 10*ITERATIONS, thin = 10) if( K > 1 ){ parameters.ecr.mcmc <- read.table(paste0(outPrefix,"/reorderedMCMC-ECR.mapK.",K,".txt"), header = TRUE) allocations.ecr.mcmc <- read.table(paste0(outPrefix,"/z.ECR.mapK.",K,".txt"), header = TRUE) clusterMembershipPerMethod <- read.table(paste0(outPrefix,"/reorderedSingleBestClusterings.mapK.",K,".txt"), header = TRUE) classificationProbabilities.ecr <- read.csv(paste0(outPrefix,"/classificationProbabilities.mapK.",K,".csv")) }else{ parameters.ecr.mcmc <- read.table(paste0(outPrefix,"/MCMC.mapK.",K,".txt"), header = TRUE) allocations.ecr.mcmc <- rep(1, dim(parameters.ecr.mcmc)[1] ) classificationProbabilities.ecr <- array(data = 1, dim = c(n,1)) clusterMembershipPerMethod <- array(data = 1, dim = c(n,3)) colnames(clusterMembershipPerMethod) <- c('ECR','STEPHENS','ECR-ITERATIVE-1') } parameters.ecr.mcmc <- mcmc( parameters.ecr.mcmc ) allocations.ecr.mcmc <- mcmc( allocations.ecr.mcmc ) colnames(classificationProbabilities.ecr) <- paste('cluster',1:K) bbm.output <- vector('list', length = 7) bbm.output[[1]] <- K.mcmc bbm.output[[2]] <- parameters.ecr.mcmc bbm.output[[3]] <- allocations.ecr.mcmc bbm.output[[4]] <- classificationProbabilities.ecr bbm.output[[5]] <- clusterMembershipPerMethod if(nChains > 1){ sampledK <- array(sampledK, dim = c(ITERATIONS, nChains)) colnames(sampledK) <- paste0("chain.", 1:nChains) colnames(sampledK)[1] <- paste0(colnames(sampledK)[1],"_(target)") }else{ sampledK <- asr write.table(sampledK, file = paste0(outPrefix,"/K.allChains.txt"), col.names = 'chain.1',quote=FALSE,row.names = FALSE) } bbm.output[[6]] <- sampledK bbm.output[[7]] <- c(nChains, swapAcceptanceRate, m, burn) names(bbm.output) <- c('K.mcmc', 'parameters.ecr.mcmc', 'allocations.ecr.mcmc', 'classificationProbabilities.ecr', 'clusterMembershipPerMethod', 'K.allChains', 'chainInfo') class(bbm.output) <- c('list', 'bbm.object') return(bbm.output) } dealWithLabelSwitching <- function(outDir,reorderModels, binaryData,z.true){ setwd(outDir) x <- binaryData kFile <- read.table("K.txt")[,1] theta.file <- "theta.varK.txt" z.file <- "z.varK.txt" p.file <- "p.varK.txt" cat("\n") print(table(kFile)/length(kFile)) K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]]) cat("\n") cat(paste("Most probable model: K = ",K," with P(K = ",K,") = ",max(table(kFile)/length(kFile)),sep=""),"\n") cat("\n") if(missing(reorderModels)==TRUE){reorderModels <- 'onlyMAP'} if(reorderModels == 'onlyMAP'){kRange <- K}else{ kRange <- as.numeric(names(table(kFile)/length(kFile))) } for ( K in kRange ){ tt <- read.table("theta.varK.txt") index <- which(kFile == K) d <- dim(x)[2] n <- dim(x)[1] J <- d + 1 m <- length(index) mcmc <- array(data = NA, dim = c(m,K,J)) Kmax <- (dim(tt)/d)[2] for (j in 1:d){ for(k in 1:K){ mcmc[,k,j] <- tt[index,(j-1)*Kmax + k] } } conP = file(p.file,open = "r") i <- 0 j <- 0 while (length(oneLine <- readLines(conP, n = 1, warn = FALSE)) > 0) { i <- i + 1 if(kFile[i] == K){ j <- j + 1 mcmc[j,,J] <- as.numeric(strsplit(oneLine,split = " ")[[1]]) } } close(conP) if (K > 1){ cat(paste("Dealing with Label Switching for K =",K),"\n") allocations <- as.matrix(read.table("z.varK.txt",as.is = TRUE)[index,]) iter <- 1 ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) maxLL <- ll maxIter <- iter for (iter in 1:m){ ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")} } # classification probs ptm <- proc.time() pMatrix <- array(data = NA, dim = c(m,n,K)) l <- array(data = 0, dim = c(n,K)) for (iter in 1:m){ LOG.P <- log(mcmc[iter,,J]) LOG.THETA <- array(log(mcmc[iter,,1:(J-1)]),dim = c(K,J-1) ) LOG.1_MINUS_THETA <- array(log(1 - mcmc[iter,,1:(J-1)]),dim = c(K,J-1) ) for(k in 1:K){ l[,k] <- LOG.P[k] + rowSums( x * matrix(LOG.THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE) + (1-x)*matrix(LOG.1_MINUS_THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE)) } for(k in 1:K){ pMatrix[iter,,k] <- apply(l,1,function(y){return(1/sum(exp(y - y[k])))} ) ind <- which(is.na(pMatrix[iter,,k]) == TRUE) nInd <- length(ind) if(nInd > 0){pMatrix[iter,ind,k] <- rep(0,nInd)} } if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");} } cat(paste0("proc.time for classification probabilities: ", round(as.numeric((proc.time() - ptm)[3]),2)),"\n") if(missing(z.true)==TRUE){ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix) }else{ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true) } reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-STEPHENS.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(mcmc, file = paste("rawMCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(file = paste("reorderedSingleBestClusterings.mapK.",K,".txt",sep=""),t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep=".")) #reordering allocations allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations for (i in 1:m){ myPerm <- order(ls$permutations$"ECR"[i,]) allocationsECR[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"STEPHENS"[i,]) allocationsKL[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,]) allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]] } MeanReorderedpMatrix <- array(data = 0, dim = c(n,K)) # define object that will contain the classification probs for (i in 1:m){ myPerm <- ls$permutations$"ECR"[i,] # this is the permutation of labels for iteration i according to ECR algorithm MeanReorderedpMatrix <- MeanReorderedpMatrix + pMatrix[i, ,myPerm] # apply myPerm to the columns of pMatrix for given iteration and add the permuted matrix to MeanReorderedpMatrix } MeanReorderedpMatrix <- MeanReorderedpMatrix/m # this is the final estimate of classification probabilities. write.csv(MeanReorderedpMatrix, file = paste0("classificationProbabilities.mapK.",K,".csv"), row.names = FALSE) write.table(allocationsECR, file = paste("z.ECR.mapK.",K,".txt",sep="")) write.table(allocationsKL, file = paste("z.KL.mapK.",K,".txt",sep="")) write.table(allocationsECR.ITERATIVE1, file = paste("z.ECR-ITERATIVE1.mapK.",K,".txt",sep="")) #file.remove("p.collapsed.txt") #file.remove("theta.collapsed.txt") cat(paste0("raw MCMC parameters for most probable K written to: \'rawMCMC.mapK.",K,".txt\' "),"\n") cat(paste0("raw MCMC latent allocations for most probable K written to: \'z.mapK.",K,".txt\' "),"\n") cat(paste0("reordered MCMC output written to: "),"\n") cat(paste0(" (Method 1): \'reorderedMCMC-ECR.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 3): \'reorderedMCMC-STEPHENS.mapK.",K,".txt\'"),"\n") cat(paste0("reordered single best clusterings written to: \'reorderedSingleBestClusterings.mapK.",K,".txt\' "),"\n") cat(paste0("reordered MCMC latent allocations for most probable K written to: "),"\n") cat(paste0(" (Method 1): \'z.ECR.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 2): \'z.KL.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 3): \'z.ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n") }else{ cat(paste0('[NOTE]: Most probable model corresponds to 1 cluster so the label-switching algorithms are not applied.',"\n")) write.table(mcmc, file = paste("MCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) cat(paste0("MCMC output corresponding to most probable model (K = 1) written to: \'", paste("MCMC.mapK.",K,".txt",sep=""),"\'"),"\n") } } setwd("../") } dealWithLabelSwitchingMissing <- function(outDir,reorderModels, binaryData, z.true){ setwd(outDir) x <- binaryData d <- dim(x)[2] n <- dim(x)[1] x.file <- "x.txt" kFile <- read.table("K.txt")[,1] theta.file <- "theta.varK.txt" z.file <- "z.varK.txt" p.file <- "p.varK.txt" cat("\n") print(table(kFile)/length(kFile)) K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]]) cat("\n") cat(paste("Most probable model: K = ",K," with P(K = ",K,") = ",max(table(kFile)/length(kFile)),sep=""),"\n") cat("\n") if(missing(reorderModels)==TRUE){reorderModels <- 'onlyMAP'} if(reorderModels == 'onlyMAP'){kRange <- K}else{ kRange <- as.numeric(names(table(kFile)/length(kFile))) } for ( K in kRange ){ tt <- read.table("theta.varK.txt") index <- which(kFile == K) J <- d + 1 m <- length(index) mcmc <- array(data = NA, dim = c(m,K,J)) Kmax <- (dim(tt)/d)[2] for (j in 1:d){ for(k in 1:K){ mcmc[,k,j] <- tt[index,(j-1)*Kmax + k] } } conP = file(p.file,open = "r") i <- 0 j <- 0 while (length(oneLine <- readLines(conP, n = 1, warn = FALSE)) > 0) { i <- i + 1 if(kFile[i] == K){ j <- j + 1 mcmc[j,,J] <- as.numeric(strsplit(oneLine,split = " ")[[1]]) } } close(conP) if (K > 1){ cat(paste("Dealing with Label Switching for K =",K),"\n") conX <- file(x.file, open = "r") allocations <- as.matrix(read.table("z.varK.txt",as.is = TRUE)[index,]) pMatrix <- array(data = NA, dim = c(m,n,K)) l <- array(data = 0, dim = c(n,K)) ptm <- proc.time() iter <- 0 xEstimated <- array(data = 0, dim = c(n,d)) for(xLine in 1:length(kFile)){ xC <- readLines(conX, n = 1, warn = FALSE) if( is.na(match(xLine,index)) == FALSE){ x <- as.numeric(strsplit(xC,split = " ")[[1]]) x <- matrix(x,nrow = n, ncol = d) xEstimated <- xEstimated + x iter <- iter + 1 # cat(paste0("line = ",xLine, ", index = ",iter, ", rsX = ", sum(x)),"\n") # finding MLE ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,]) if(iter == 1){ maxLL <- ll; maxIter <- iter } if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")} # classification probs LOG.P <- log(mcmc[iter,,J]) LOG.THETA <- array(log(mcmc[iter,,1:(J-1)]),dim = c(K,J-1) ) LOG.1_MINUS_THETA <- array(log(1 - mcmc[iter,,1:(J-1)]),dim = c(K,J-1) ) for(k in 1:K){ l[,k] <- LOG.P[k] + rowSums( x * matrix(LOG.THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE) + (1-x)*matrix(LOG.1_MINUS_THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE)) } for(k in 1:K){ pMatrix[iter,,k] <- apply(l,1,function(y){return(1/sum(exp(y - y[k])))} ) ind <- which(is.na(pMatrix[iter,,k]) == TRUE) nInd <- length(ind) if(nInd > 0){pMatrix[iter,ind,k] <- rep(0,nInd)} } if(iter %% 100 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");} } } xEstimated <- xEstimated/iter write.table(file = "xEstimated.txt", xEstimated, quote = FALSE) close(conX) cat(paste0("proc.time for classification probabilities: ", round(as.numeric((proc.time() - ptm)[3]),2)),"\n") cat(paste0("estimated missing data file written to: \'xEstimated.txt\'"),"\n") if(missing(z.true)==TRUE){ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix) }else{ ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"), zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x, prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true) } reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output write.table(reordered.mcmc, file = paste("reorderedMCMC-STEPHENS.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(mcmc, file = paste("rawMCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) write.table(file = paste("reorderedSingleBestClusterings.mapK.",K,".txt",sep=""),t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep=".")) #reordering allocations allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations for (i in 1:m){ myPerm <- order(ls$permutations$"ECR"[i,]) allocationsECR[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"STEPHENS"[i,]) allocationsKL[i,] <- myPerm[allocations[i,]] myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,]) allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]] } MeanReorderedpMatrix <- array(data = 0, dim = c(n,K)) # define object that will contain the classification probs for (i in 1:m){ myPerm <- ls$permutations$"ECR"[i,] # this is the permutation of labels for iteration i according to ECR algorithm MeanReorderedpMatrix <- MeanReorderedpMatrix + pMatrix[i, ,myPerm] # apply myPerm to the columns of pMatrix for given iteration and add the permuted matrix to MeanReorderedpMatrix } MeanReorderedpMatrix <- MeanReorderedpMatrix/m # this is the final estimate of classification probabilities. write.csv(MeanReorderedpMatrix, file = paste0("classificationProbabilities.mapK.",K,".csv"), row.names = FALSE) write.table(allocationsECR, file = paste("z.ECR.mapK.",K,".txt",sep="")) write.table(allocationsKL, file = paste("z.KL.mapK.",K,".txt",sep="")) write.table(allocationsECR.ITERATIVE1, file = paste("z.ECR-ITERATIVE1.mapK.",K,".txt",sep="")) #file.remove("p.collapsed.txt") #file.remove("theta.collapsed.txt") cat(paste0("raw MCMC parameters for most probable K written to: \'rawMCMC.mapK.",K,".txt\' "),"\n") cat(paste0("raw MCMC latent allocations for most probable K written to: \'z.mapK.",K,".txt\' "),"\n") cat(paste0("reordered MCMC output written to: "),"\n") cat(paste0(" (Method 1): \'reorderedMCMC-ECR.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 3): \'reorderedMCMC-STEPHENS.mapK.",K,".txt\'"),"\n") cat(paste0("reordered single best clusterings written to: \'reorderedSingleBestClusterings.mapK.",K,".txt\' "),"\n") cat(paste0("reordered MCMC latent allocations for most probable K written to: "),"\n") cat(paste0(" (Method 1): \'z.ECR.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 2): \'z.KL.mapK.",K,".txt\'"),"\n") cat(paste0(" (Method 3): \'z.ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n") }else{ cat(paste0('[NOTE]: Most probable model corresponds to 1 cluster so the label-switching algorithms are not applied.',"\n")) write.table(mcmc, file = paste("MCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep="."))) cat(paste0("MCMC output corresponding to most probable model (K = 1) written to: \'", paste("MCMC.mapK.",K,".txt",sep=""),"\'"),"\n") } } setwd("../") } #' @export print.bbm.object <- function(x, printSubset, ...){ if( missing(printSubset) ){ printSubset = TRUE } if( 'bbm.object' %in% class(x) ){ cat("\n") cat(paste0("* Run information:"),"\n") cat(paste0(" Number of parallel heated chains: ", x$chainInfo[1]),"\n") cat(paste0(" Swap acceptance rate: ", x$chainInfo[2],"%"),"\n") cat(paste0(" Total number of iterations: ", x$chainInfo[3]*10),"\n") cat(paste0(" Burn-in period: ", x$chainInfo[4]*10),"\n") cat(paste0(" Thinning: 10."),"\n") kFile <- x$K.mcmc cat("\n") cat(paste("* Estimated posterior distribution of the number of clusters:"),"\n") print(round(table(x$K.mcmc)/length(x$K.mcmc),3)) K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]]) cat("\n") cat(paste("* Most probable model: K = ",K," with P(K = ",K,"|data) = ",round(max(table(kFile)/length(kFile)),3),sep=""),"\n") cat("\n") cat(paste0("* Estimated number of observations per cluster conditionally on K = ", K," (3 label switching algorithms):"),'\n') print(apply(x$clusterMembershipPerMethod,2,table)) d <- (dim(x$parameters.ecr.mcmc)[2] - K)/K myMeans <- apply(x$parameters.ecr.mcmc,2,mean) cat('\n') if(printSubset == TRUE){ if(d > 5){ cat(paste0('* Posterior mean of probability of success per feature and cluster (ECR algorithm):'),'\n') pr <- c() for(k in 1:K){ subS <- paste0("theta.",k,".",1:d)[1:5] pr <- cbind( pr, myMeans[subS]) } colnames(pr) <- paste0("cluster_",1:K) rownames(pr) <- paste0("theta_",1:5) print(pr) cat(paste0(' <+ ',d-5,' more rows>'),'\n') } }else{ cat(paste0('* Posterior mean of probability of success per feature and cluster (ECR algorithm):'),'\n') pr <- c() for(k in 1:K){ subS <- paste0("theta.",k,".",1:d) pr <- cbind( pr, myMeans[subS]) } colnames(pr) <- paste0("cluster_",1:K) rownames(pr) <- paste0("theta_",1:d) print(pr) } }else{ cat(paste(" The input is not in class `bbm.object`"),'\n') } }
/scratch/gouwar.j/cran-all/cranData/BayesBinMix/R/coupledMetropolis.R
#' This function performs the Bayesian hierarchical model method for meta-analysis #' when the dataset has complete compliance information for all studies, #' as described in Section 2.2, "the Bayesian hierarchical model", of the package manuscript. #' @title Bayesian hierarchical models for CACE meta-analysis with complete compliance data #' @param data an input dataset with the same structure as the example data \code{epidural_c}, #' containing multiple rows referring to multiple studies in a meta-analysis. #' @param param a character string vector indicating the parameters to be tracked and estimated. #' By default the following parameters (see \code{details}) are included: \eqn{\theta^{\mathrm{CACE}}} #' (\code{CACE}), \eqn{E(u_{i1})} (\code{u1out}), \eqn{E(v_{i1})} (\code{v1out}), \eqn{E(s_{i1})} (\code{s1out}), #' \eqn{E(b_{i1})} (\code{b1out}), \eqn{\pi_a} (\code{pia}), \eqn{\pi_n} (\code{pin}), and #' \eqn{\pi_c=1-\pi_a-\pi_n} (\code{pic}). #' Users can modify the string vector to only include parameters of interest besides \eqn{\theta^{\mathrm{CACE}}}. #' @param random.effects a list of logical values indicating whether random effects are included in the model. #' The list should contain the assignment for these parameters only: \code{delta.n} (\eqn{\delta_{in}}), #' \code{delta.a} (\eqn{\delta_{ia}}), \code{delta.u} (\eqn{\delta_{iu}}), \code{delta.v} (\eqn{\delta_{iv}}), #' \code{delta.s} (\eqn{\delta_{is}}), \code{delta.b} (\eqn{\delta_{ib}}), \code{cor}. The list should be in the #' form of \code{list(delta.a = FALSE, cor = FALSE, ...)}. By default, this #' is an empty list, and all parameters are default to \code{TRUE}. Parameters that are not listed in the list #' are assumed to be \code{TRUE}. Note that \eqn{\rho} (\code{cor}) can only be included when both \eqn{\delta_{in}} #' (\code{delta.n}) and \eqn{\delta_{ia}} (\code{delta.a}) are set to \code{TRUE}. Otherwise, a warning #' occurs and the model continues running by forcing \code{delta.n = TRUE} and \code{delta.a = TRUE}. #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{alpha.n.m} and \code{alpha.n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{alpha.n}, as well as \code{alpha.a.m}, \code{alpha.a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. It also contains the shape and rate parameters of the gamma distributions #' of the standard deviation variable of \code{delta.n}, \code{delta.a}, \code{delta.u}, \code{delta.v} #' \code{delta.s}, \code{delta.b}. The shape parameters are named as \code{tau.n.h} and \code{tau.a.h}, for example, #' and the rate parameters are named as \code{tau.n.r} and \code{tau.a.r}. You do not need to specify the shape and #' rate parameters if the corresponding random effect is set to \code{FALSE} in \code{random.effects}, since they will #' not be used anyways. By default, \code{re.values} is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}, #' and the shape and rate parameters are default to \code{2}. #' @param model.code a string representation of the model code; each line should be separated. Default to constructing #' model code using the \code{model.meta.c} function with the parameters that are inputted to this function. This #' parameter is only necessary if user wishes to make functional changes to the model code, such as changing the #' probability distributions of the parameters. Default to empty string. #' @param digits number of digits. Default to \code{3}. #' @param n.adapt adapt value. Default to \code{1000}. #' @param n.iter number of iterations. Default to \code{100000}. #' @param n.burnin number of burn-in iterations. Default to \code{n.iter/2}. #' @param n.chains number of chains. Default to \code{3}. #' @param n.thin thinning rate, must be a positive integer. #' #' Default to \code{max(1,floor((n.iter-n.burnin)/100000))}. #' @param conv.diag whether or not to show convergence diagnostics. Default to \code{FALSE}. #' @param mcmc.samples whether to include JAGS samples in the final output. Default to \code{FALSE}. #' @param study.specific a logical value indicating whether to calculate the study-specific #' \eqn{\theta^{\mathrm{CACE}}_i}. If \code{TRUE}, the model will first check the logical status of arguments #' \code{delta.u} and \code{delta.v}. If both are \code{FALSE}, meaning that neither response rate \eqn{u_{i1}} #' or \eqn{v_{i1}} is modeled with a random effect, then the study-specific \eqn{\theta^{\mathrm{CACE}}_i} is #' the same across studies. The function gives a warning and continues by making \code{study.specific = FALSE}. #' Otherwise, the study-specific \eqn{\theta^{\mathrm{CACE}}_i} are estimated and saved as the parameter \code{cacei}. #' @return It returns a model object whose attribute type is \code{cace.Bayes} #' @importFrom stats update complete.cases #' @import Rdpack #' @import rjags #' @import coda #' @export #' @examples #' \donttest{ #' data("epidural_c", package = "BayesCACE") #' set.seed(123) #' out.meta.c <- cace.meta.c(data = epidural_c, conv.diag = TRUE, #' mcmc.samples = TRUE, study.specific = TRUE) #' # By calling the object smry from the output list out.meta.c, posterior estimates #' # (posterior mean, standard deviation, posterior median, 95\% credible interval, and #' # time-series standard error) are displayed. #' out.meta.c$smry #' out.meta.c$DIC #' } #' @seealso \code{\link[BayesCACE]{cace.study}}, \code{\link[BayesCACE]{cace.meta.ic}} #' @references #' \insertRef{zhou2019bayesian}{BayesCACE} #' #' \insertRef{lunn2012bugs}{BayesCACE} #' #' \insertRef{zeger1988models}{BayesCACE} #' cace.meta.c <- function(data, param = c("CACE", "u1out", "v1out", "s1out", "b1out", "pic", "pin", "pia"), random.effects = list(), re.values = list(), model.code = '', digits = 3, n.adapt = 1000, n.iter = 100000, n.burnin = floor(n.iter/2), n.chains = 3, n.thin = max(1,floor((n.iter-n.burnin)/100000)), conv.diag = FALSE, mcmc.samples = FALSE, study.specific = FALSE) { ## check the input parameters if(missing(data)) stop("Need to specify data.") if(!missing(data) ){ study.id <- data$study.id[complete.cases(data)] n000<-data$n000[complete.cases(data)] n001<-data$n001[complete.cases(data)] n010<-data$n010[complete.cases(data)] n011<-data$n011[complete.cases(data)] n100<-data$n100[complete.cases(data)] n101<-data$n101[complete.cases(data)] n110<-data$n110[complete.cases(data)] n111<-data$n111[complete.cases(data)] } if(length(study.id)!=length(n000) | length(n000)!=length(n001) | length(n001)!=length(n010) | length(n010)!=length(n011) | length(n011)!=length(n100) | length(n100)!=length(n101) | length(n101)!=length(n110) | length(n110)!=length(n111) ) stop("study.id, n000, n001, n010, n011, n100, n101, n110, and n111 have different lengths. \n") delta.n <- delta.a <- delta.u <- delta.v <- delta.s <- delta.b <- cor <- TRUE if ("delta.n" %in% names(random.effects)) {delta.n <- random.effects[['delta.n']]} if ("delta.a" %in% names(random.effects)) {delta.a <- random.effects[['delta.a']]} if ("delta.u" %in% names(random.effects)) {delta.u <- random.effects[['delta.u']]} if ("delta.v" %in% names(random.effects)) {delta.v <- random.effects[['delta.v']]} if ("delta.s" %in% names(random.effects)) {delta.s <- random.effects[['delta.s']]} if ("delta.b" %in% names(random.effects)) {delta.b <- random.effects[['delta.b']]} if ("cor" %in% names(random.effects)) {cor <- random.effects[['cor']]} if ((!(delta.n & delta.a)) & cor){ warning("'cor' can be assigned as TRUE only if both delta.n and delta.a are TRUE.\n the model is continued by forcing delta.n=TRUE and delta.a=TRUE") delta.n <- TRUE delta.a <- TRUE } if ((!(delta.u|delta.v)) & study.specific){ warning("no random effect is assigned to the response rate u1 or v1, \n study-specific CACE is the same across studies. \n the model is continued by making 'study.specific=FALSE'. \n to make a CACE forestplot, please run 'cace.study' to estimate study level CACEs. \n") study.specific <- FALSE } Ind <- rep(1, 7) if (!delta.n) Ind[1] <- 0 if (!delta.a) Ind[2] <- 0 if (!delta.u) Ind[3] <- 0 if (!delta.v) Ind[4] <- 0 if (!delta.s) Ind[5] <- 0 if (!delta.b) Ind[6] <- 0 if (!cor) Ind[7] <- 0 ## jags model if (nchar(model.code) == 0) { modelstring<-model.meta.c(random.effects = random.effects, re.values = re.values) } else {modelstring <- model.code} ## jags data Ntol <- n000+n001+n010+n011+n100+n101+n110+n111 N0 <- n000+n001+n010+n011 N1 <- n100+n101+n110+n111 R <- cbind(n000,n001,n010,n011, n100,n101,n110,n111) I <- length(Ntol) pi <- pi data.jags <- list(N0=N0, N1=N1, R=R, I=I, Ind=Ind, pi=pi) ## jags initial value rng.seeds<-sample(1000000,n.chains) init.jags <- vector("list", n.chains) for(ii in 1:n.chains){ init.jags[[ii]] <- list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = rng.seeds[ii]) } ## parameters to be paramed in jags if(!is.element("CACE",param)) param<-c("CACE",param) fullparam <- c("CACE", "u1out", "v1out", "s1out", "b1out", "pic", "pin", "pia", "alpha.n", "alpha.a", "alpha.u", "alpha.v", "alpha.s", "alpha.b", "sigma.n", "sigma.a", "rho", "Sigma.rho", "sigma.u", "sigma.v", "sigma.s", "sigma.b") if(!any(is.element(param, fullparam))) stop("parameters must be specified from the following: CACE, u1out, v1out, s1out, b1out, pic, pin, pia, alpha.n, alpha.a, alpha.u, alpha.v, alpha.s, alpha.b, sigma.n, sigma.a, rho, Sigma.rho, sigma.u, sigma.v, sigma.s, sigma.b") if(study.specific) param<-c("cacei",param) ## run jags message("Start running MCMC...\n") jags.m<-jags.model(file=textConnection(modelstring),data=data.jags,inits=init.jags, n.chains=n.chains,n.adapt=n.adapt) update(jags.m,n.iter=n.burnin) jags.out<-coda.samples.dic(model=jags.m,variable.names=param,n.iter=n.iter,thin=n.thin) out<-NULL out$Ind <- Ind out$model<-"cace.meta.c" smry<-summary(jags.out$samples) smry<-cbind(smry$statistics[,c("Mean","SD")],smry$quantiles[,c("2.5%","50%","97.5%")], smry$statistics[,c("Naive SE","Time-series SE")]) smry<-signif(smry,digits=digits) out$smry <- smry #dic dev<-jags.out$dic[[1]] # mean deviance pen<-jags.out$dic[[2]] # pD pen.dev<-dev+pen # DIC dic.stat<-rbind(dev,pen,pen.dev) rownames(dic.stat)<-c("D.bar","pD","DIC") colnames(dic.stat)<-"" out$DIC<-dic.stat for (i in 1:length(fullparam)){ if(is.element(fullparam[i],param)) {out[[fullparam[i] ]]<-smry[c(fullparam[i]), ]} } if(conv.diag){ message("MCMC convergence diagnostic statistics are calculated and saved in conv.out\n") conv.out<-gelman.diag(jags.out$samples,multivariate=FALSE) out$conv.out<-conv.out$psrf } if(mcmc.samples){ out$mcmc.samples<-jags.out$samples } attributes(out)$type<-"cace.Bayes" return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/cace.meta.c.R
#' This function also estimates \eqn{\theta^{\mathrm{CACE}}} using the Bayesian hierarchcal model #' but can accommodate studies with incomplete compliance data. #' The necessary data structure and the likelihood function are presented in Section 2.3 of the #' package manuscript, "CACE for meta-analysis with incomplete compliance information". #' @title Bayesian hierarchical models for CACE meta-analysis with incomplete compliance information #' @param data a input dataset the same structure as the example data \code{epidural_ic}, #' containing multiple rows referring to multiple studies in a meta-analysis. #' @param param the list of parameter used. #' #' Default to \code{c("CACE", "u1out", "v1out", "s1out", "b1out", "pic", "pin", "pia")}. #' @param random.effects a list of logical values indicating whether random effects are included in the model. #' The list should contain the assignment for these parameters only: \code{delta.n} (\eqn{\delta_{in}}), #' \code{delta.a} (\eqn{\delta_{ia}}), \code{delta.u} (\eqn{\delta_{iu}}), \code{delta.v} (\eqn{\delta_{iv}}), #' \code{delta.s} (\eqn{\delta_{is}}), \code{delta.b} (\eqn{\delta_{ib}}), \code{cor}. The list should be in the #' form of \code{list(delta.a = FALSE, cor = FALSE, ...)}. By default, this #' is an empty list, and all parameters are default to \code{TRUE}. Parameters that are not listed in the list #' are assumed to be \code{TRUE}. Note that \eqn{\rho} (\code{cor}) can only be included when both \eqn{\delta_{in}} #' (\code{delta.n}) and \eqn{\delta_{ia}} (\code{delta.a}) are set to \code{TRUE}. Otherwise, a warning #' occurs and the model continues running by forcing \code{delta.n = TRUE} and \code{delta.a = TRUE}. #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{alpha.n.m} and \code{alpha.n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{alpha.n}, as well as \code{alpha.a.m}, \code{alpha.a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. It also contains the shape and rate parameters of the gamma distributions #' of the standard deviation variable of \code{delta.n}, \code{delta.a}, \code{delta.u}, \code{delta.v} #' \code{delta.s}, \code{delta.b}. The shape parameters are named as \code{tau.n.h} and \code{tau.a.h}, for example, #' and the rate parameters are named as \code{tau.n.r} and \code{tau.a.r}. You do not need to specify the shape and #' rate parameters if the corresponding random effect is set to \code{FALSE} in \code{random.effects}, since they will #' not be used anyways. By default, \code{re.values} is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}, #' and the shape and rate parameters are default to \code{2}. #' @param model.code a string representation of the model code; each line should be separated. Default to constructing #' model code using the \code{model.meta.ic} function with the parameters that are inputted to this function. This #' parameter is only necessary if user wishes to make functional changes to the model code, such as changing the #' probability distributions of the parameters. Default to empty string. #' @param digits number of digits. Default to \code{3}. #' @param n.adapt adapt value. Default to \code{1000}. #' @param n.iter number of iterations. Default to \code{100000}. #' @param n.burnin number of burn-in iterations. Default to \code{n.iter/2}. #' @param n.chains number of chains. Default to \code{3}. #' @param n.thin thinning rate, must be a positive integer. #' #' Default to \code{max(1,floor((n.iter-n.burnin)/100000))}. #' @param conv.diag whether or not to show convergence diagnostics. Default to \code{FALSE}. #' @param mcmc.samples whether to include JAGS samples in the final output. Default to \code{FALSE}. #' @param study.specific a logical value indicating whether to calculate the study-specific #' \eqn{\theta^{\mathrm{CACE}}_i}. If \code{TRUE}, the model will first check the logical status of arguments #' \code{delta.u} and \code{delta.v}. If both are \code{FALSE}, meaning that neither response rate \eqn{u_{i1}} #' or \eqn{v_{i1}} is modeled with a random effect, then the study-specific \eqn{\theta^{\mathrm{CACE}}_i} is #' the same across studies. The function gives a warning and continues by making \code{study.specific = FALSE}. #' Otherwise, the study-specific \eqn{\theta^{\mathrm{CACE}}_i} are estimated and saved as the parameter \code{cacei}. #' @return It returns a model object whose attribute type is \code{cace.Bayes} #' @details #' Note that when compiling the \code{JAGS} model, the warning `adaptation incomplete' may #' occasionally occur, indicating that the number of iterations for the adaptation process #' is not sufficient. The default value of \code{n.adapt} (the number of iterations for adaptation) #' is 1,000. This is an initial sampling phase during which the samplers adapt their behavior #' to maximize their efficiency (e.g., a Metropolis--Hastings random walk algorithm may change #' its step size). The `adaptation incomplete' warning indicates the MCMC algorithm may not #' achieve maximum efficiency, but it generally has little impact on the posterior estimates #' of the treatment effects. To avoid this warning, users may increase \code{n.adapt}. #' @importFrom stats update complete.cases #' @import Rdpack #' @import rjags #' @import coda #' @export #' @examples #' \donttest{ #' data("epidural_ic", package = "BayesCACE") #' set.seed(123) #' out.meta.ic <- cace.meta.ic(data = epidural_ic, conv.diag = TRUE, #' mcmc.samples = TRUE, study.specific = TRUE) #' } #' @seealso \code{\link[BayesCACE]{cace.study}}, \code{\link[BayesCACE]{cace.meta.c}} #' @references #' \insertRef{zhou2019bayesian}{BayesCACE} #' cace.meta.ic <- function(data, param = c("CACE", "u1out", "v1out", "s1out", "b1out", "pic", "pin", "pia"), random.effects = list(), re.values = list(), model.code = '', digits = 3, n.adapt = 1000, n.iter = 100000, n.burnin = floor(n.iter/2), n.chains = 3, n.thin = max(1,floor((n.iter-n.burnin)/100000)), conv.diag = FALSE, mcmc.samples = FALSE, study.specific = FALSE) { ## check the input parameters if(missing(data)) stop("need to specify data") if(!missing(data) ){ data$miss.r0 <- ifelse((data$n000==0 & data$n001==0 & data$n010==0 & data$n011==0), 1, 0) data$miss.r1 <- ifelse((data$n100==0 & data$n101==0 & data$n110==0 & data$n111==0), 1, 0) data$miss <- ifelse((data$miss.r0==1|data$miss.r1==1), 1, 0) temp <- data[order(data$miss.r0, data$miss.r1),] study.id <- temp$study.id[complete.cases(temp)] n000<-temp$n000[complete.cases(temp)] n001<-temp$n001[complete.cases(temp)] n010<-temp$n010[complete.cases(temp)] n011<-temp$n011[complete.cases(temp)] n100<-temp$n100[complete.cases(temp)] n101<-temp$n101[complete.cases(temp)] n110<-temp$n110[complete.cases(temp)] n111<-temp$n111[complete.cases(temp)] n0s0<-temp$n0s0[complete.cases(temp)] n0s1<-temp$n0s1[complete.cases(temp)] n1s0<-temp$n1s0[complete.cases(temp)] n1s1<-temp$n1s1[complete.cases(temp)] miss.r0<-temp$miss.r0[complete.cases(temp)] miss.r1<-temp$miss.r1[complete.cases(temp)] miss<-temp$miss[complete.cases(temp)] } if(length(study.id)!=length(n000) | length(n000)!=length(n001) | length(n001)!=length(n010) | length(n010)!=length(n011) | length(n011)!=length(n100) | length(n100)!=length(n101) | length(n101)!=length(n110) | length(n110)!=length(n111) | length(n111)!=length(n0s0) | length(n0s0)!=length(n0s1) | length(n0s1)!=length(n1s0) | length(n1s0)!=length(n1s1) ) stop("study.id, n000, n001, n010, n011, n100, n101, n110, n111, n0s0, n0s1, n1s0, and n1s1 have different lengths. \n") delta.n <- delta.a <- delta.u <- delta.v <- delta.s <- delta.b <- cor <- TRUE if ("delta.n" %in% names(random.effects)) {delta.n <- random.effects[['delta.n']]} if ("delta.a" %in% names(random.effects)) {delta.a <- random.effects[['delta.a']]} if ("delta.u" %in% names(random.effects)) {delta.u <- random.effects[['delta.u']]} if ("delta.v" %in% names(random.effects)) {delta.v <- random.effects[['delta.v']]} if ("delta.s" %in% names(random.effects)) {delta.s <- random.effects[['delta.s']]} if ("delta.b" %in% names(random.effects)) {delta.b <- random.effects[['delta.b']]} if ("cor" %in% names(random.effects)) {cor <- random.effects[['cor']]} if ((!(delta.n & delta.a)) & cor){ warning("'cor' can be assigned as TRUE only if both delta.n and delta.a are TRUE.\n the model is continued by forcing delta.n=TRUE and delta.a=TRUE") delta.n <- TRUE delta.a <- TRUE } if (!(delta.u|delta.v)){ warning("no random effect is assigned to the response rate u1 or v1, \n study-specific CACE is the same across studies. \n a CACE forestplot cannot be made. \n") study.specific <- FALSE } Ind <- rep(1, 7) if (!delta.n) Ind[1] <- 0 if (!delta.a) Ind[2] <- 0 if (!delta.u) Ind[3] <- 0 if (!delta.v) Ind[4] <- 0 if (!delta.s) Ind[5] <- 0 if (!delta.b) Ind[6] <- 0 if (!cor) Ind[7] <- 0 ## jags model if (nchar(model.code) == 0) { modelstring<-model.meta.ic(random.effects = random.effects, re.values = re.values) } else {modelstring <- model.code} ## jags data n1 <- sum(miss.r0==0 & miss.r1==0) # 4+4 n2 <- sum(miss.r0==0 & miss.r1==1) # 4+2 n3 <- sum(miss.r0==1 & miss.r1==0) # 2+4 n4 <- sum(miss.r0==1 & miss.r1==1) # 4+4 n <- length(study.id) N0_4 <- n000+n001+n010+n011 N0_2 <- n0s1+n0s0 N1_4 <- n100+n101+n110+n111 N1_2 <- n1s1+n1s0 R0_4 <- cbind(n000,n001,n010,n011) R0_2 <- cbind(n0s0,n0s1) R1_4 <- cbind(n100,n101,n110,n111) R1_2 <- cbind(n1s0,n1s1) R1 <- cbind(R0_4, R1_4) R2 <- cbind(R0_4, R1_2) R3 <- cbind(R0_2, R1_4) R4 <- cbind(R0_2, R1_2) pi <- pi data.jags <- list(N0_4=N0_4, N0_2=N0_2, N1_4=N1_4, N1_2=N1_2, R0_4=R0_4, R0_2=R0_2, R1_4=R1_4, R1_2=R1_2, n1=n1, n2=n2, n3=n3, n4=n4, Ind=Ind, pi=pi) ## jags initial value rng.seeds<-sample(1000000,n.chains) init.jags <- vector("list", n.chains) for(ii in 1:n.chains){ init.jags[[ii]] <- list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = rng.seeds[ii]) } ## parameters to be paramed in jags if(!is.element("CACE",param)) param<-c("CACE",param) fullparam <- c("CACE", "u1out", "v1out", "s1out", "b1out", "pic", "pin", "pia", "alpha.n", "alpha.a", "alpha.u", "alpha.v", "alpha.s", "alpha.b", "sigma.n", "sigma.a", "rho", "Sigma.rho", "sigma.u", "sigma.v", "sigma.s", "sigma.b") if(!any(is.element(param, fullparam))) stop("parameters must be specified from the following: CACE, u1out, v1out, s1out, b1out, pic, pin, pia, alpha.n, alpha.a, alpha.u, alpha.v, alpha.s, alpha.b, sigma.n, sigma.a, rho, Sigma.rho, sigma.u, sigma.v, sigma.s, sigma.b") if(study.specific) param<-c("cacei",param) ## run jags message("Start running MCMC...\n") jags.m<-jags.model(file=textConnection(modelstring),data=data.jags,inits=init.jags, n.chains=n.chains,n.adapt=n.adapt) update(jags.m,n.iter=n.burnin) jags.out<-coda.samples.dic(model=jags.m,variable.names=param,n.iter=n.iter,thin=n.thin) out<-NULL out$Ind <- Ind out$model<-"cace.meta.ic" smry<-summary(jags.out$samples) smry<-cbind(smry$statistics[,c("Mean","SD")],smry$quantiles[,c("2.5%","50%","97.5%")], smry$statistics[,c("Naive SE","Time-series SE")]) smry<-signif(smry,digits=digits) out$smry <- smry #dic dev<-jags.out$dic[[1]] # mean deviance pen<-jags.out$dic[[2]] # pD pen.dev<-dev+pen # DIC dic.stat<-rbind(dev,pen,pen.dev) rownames(dic.stat)<-c("D.bar","pD","DIC") colnames(dic.stat)<-"" out$DIC<-dic.stat for (i in 1:length(fullparam)){ if(is.element(fullparam[i],param)) {out[[fullparam[i] ]]<-smry[c(fullparam[i]), ]} } if(conv.diag){ message("MCMC convergence diagnostic statistics are calculated and saved in conv.out\n") conv.out<-gelman.diag(jags.out$samples,multivariate=FALSE) out$conv.out<-conv.out$psrf } if(mcmc.samples){ out$mcmc.samples<-jags.out$samples } attributes(out)$type<-"cace.Bayes" return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/cace.meta.ic.R
#' This function performs CACE analysis for a single study using the #' likelihood and model specified in Section 2.1 of the package manuscript, or a two-step #' approach for meta-analysis with complete compliance information as #' described in Section 2.2, "the two-step approach". #' @title CACE analysis for a single study, or a two-step approach for meta-analysis #' with complete complice information #' @param data a input dataset the same structure as the example data \code{epidural_c}, #' containing either one row of observations for a single study, or multiple rows referring #' to multiple studies in a meta-analysis. #' @param param a character string vector indicating the parameters to be tracked and estimated. #' By default all parameters in the model (see \code{details}) are included: \eqn{\theta^{\mathrm{CACE}}} #' (\code{CACE}), \eqn{u_1} (\code{u1}), \eqn{v_1} (\code{v1}), \eqn{s_1} (\code{s1}), \eqn{b_1} (\code{b1}), #' \eqn{\pi_a} (\code{pi.a}), \eqn{\pi_n} (\code{pi.n}), and \eqn{\pi_c=1-\pi_a-\pi_n} (\code{pi.c}). #' Users can modify the string vector to only include parameters of interest besides #' \eqn{\theta^{\mathrm{CACE}}}. #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{n.m} and \code{n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{n}, as well as \code{a.m}, \code{a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. By default, this is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}. #' @param model.code a string representation of the model code; each line should be separated. Default to constructing #' model code using the \code{model.meta.ic} function with the parameters that are inputted to this function. This #' parameter is only necessary if user wishes to make functional changes to the model code, such as changing the #' probability distributions of the parameters. Default to empty string. #' @param digits a positive integer specifying the digits after the decimal point for #' the effect size estimates. The default is \code{3}. #' @param n.adapt the number of iterations for adaptation in Markov chain Monte Carlo (MCMC) algorithm; #' it is used to maximize the sampling efficiency. #' The default is \code{1,000}. If a warning "adaptation incomplete" appears, users may increase #' \code{n.adapt}. This argument and the following \code{n.iter}, \code{n.burnin}, \code{n.chains}, #' \code{n.thin} are passed to the functions in R package \code{rjags}. #' @param n.iter the number of iterations of each MCMC chain. #' The default is \code{100,000}. #' @param n.burnin the number of iterations for burn-in period. The default is #' the largest integer not greater than \code{n.iter/2}. #' @param n.chains the number of MCMC chains. The default is \code{3}. #' @param n.thin a positive integer indicating thinning rate for MCMC chains, which is used to #' avoid potential high auto-correlation and to save computer memory when \code{n.iter} is #' large. The default is set as \code{1} or the largest integer not greater than #' \code{((n.iter - n.burnin)/1e+05)}, whichever is larger. #' @param conv.diag a logical value indicating whether to compute the Gelman and Rubin #' convergence statistic (\eqn{\hat{R}}) of each parameter as a convergence diagnostic. #' It is considered the chains are well mixed and have converged to the target distribution #' if \eqn{\hat{R} \le 1.1}. The default is \code{FALSE}. If \code{TRUE}, \code{n.chains} must be greater than 1, #' and the function saves each chain's MCMC samples for all parameters, which can be used #' to produce trace, posterior density, and auto-correlation plots by calling the function #' \code{plt.cacebayes}. #' @param mcmc.samples a logical value indicating whether to save MCMC posterior samples #' in the output object. The default is \code{FALSE}. If \code{TRUE}, the output object list #' includes each chain's MCMC samples for all parameters. They can be used in the function #' \code{plt.cacebayes} to generate the trace, posterior density, and auto-correlation plots #' for further model diagnostics. #' @param two.step a logical value indicating whether to conduct a two-step meta-analysis. #' If \code{two.step = TRUE}, the posterior mean and standard deviation of study-specific #' \eqn{\theta^{\mathrm{CACE}}_i} are used to perform a standard meta-analysis, using the R package \code{metafor}. #' @param method the method used in meta-analysis if \code{two.step = TRUE}. The default estimation #' method is the REML (restricted maximum-likelihood estimator) method for the random-effects #' model. Users can change the argument \code{method} to obtain different meta-analysis #' estimators from either a random-effects model or a fixed-effect model, e.g., #' \code{method = 'DL'} refers to the DerSimonian--Laird estimator, #' \code{method = 'HE'} returns the Hedges estimator, and \code{method = 'HS'} gives the Hunter--Schmidt #' estimator. More details are available from the documentation of the function \code{metafor::rma}. #' If the input data include only one study, the meta-analysis result is just the same as #' the result from the single study. #' @return It returns a model object whose attribute type is \code{cace.Bayes} #' @details #' The likelihood \deqn{\log L({\boldsymbol{\beta}}) = N_{000}\log\{\pi_{c}(1-v_1)+\pi_{n}(1-s_1)\}+N_{001} #' \log(\pi_{c}v_1+\pi_{n}s_1)+N_{010}\log\{{\pi}_{a}(1-b_1)\}} #' \deqn{+ N_{011}\log\{\pi_{a}b_1\}+ N_{100} #' \log\{\pi_{n}(1-s_1)\}+N_{101}\log({\pi}_{n}s_1) + N_{110}\log\{(\pi_{c}(1-u_1)} #' \deqn{+ \pi_{a}(1-b_1)\}+{N_{111}\log(\pi_{c}u_1+\pi_{a}b_1)} + constant}. #' If the input \code{data} includes more than one study, the study-specific CACEs will be #' estimated by retrieving data row by row. #' By default, the function \code{cace.study()} returns a list #' including posterior estimates (posterior mean, standard deviation, median, and a 95\% #' credible interval (CrI) with 2.5\% and 97.5\% quantiles as the lower and upper bounds), #' and the deviance information criterion (DIC) statistic for each study. #' @importFrom stats update complete.cases #' @import rjags #' @import coda #' @import metafor #' @import Rdpack #' @export #' @examples #' \donttest{ #' data("epidural_c", package = "BayesCACE") #' set.seed(123) #' out.study <- cace.study(data = epidural_c, conv.diag = TRUE, #' mcmc.samples = TRUE, two.step = TRUE) #' # Show the estimates of theta for each single study (posterior mean and #' # standard deviation, posterior median, 95% credible interval, and time-series #' # standard error): #' out.study$CACE #' # If the argument conv.diag is specified as TRUE, the output list contains #' # a sub-list conv.out, which outputs the Gelman and Rubin convergence statistic, #' # labelled Point est.) calculated for each parameter from each single study, and #' # their upper confidence limits (labelled Upper C.I.). #' out.study$conv.out[[1]] #' } #' @seealso \code{\link[BayesCACE]{cace.meta.c}}, \code{\link[BayesCACE]{cace.meta.ic}} #' cace.study <- function(data, param = c("CACE", "u1", "v1", "s1", "b1", "pi.c", "pi.n", "pi.a"), re.values = list(), model.code = '', digits = 3, n.adapt = 1000, n.iter = 100000, n.burnin = floor(n.iter/2), n.chains = 3, n.thin = max(1,floor((n.iter-n.burnin)/1e+05)), conv.diag = FALSE, mcmc.samples = FALSE, two.step = FALSE, method = "REML") { ## check the input parameters Mean <- SD <- NULL if(missing(data)) stop("need to specify data") if(!missing(data) ){ study.id <- data$study.id[complete.cases(data)] n000<-data$n000[complete.cases(data)] n001<-data$n001[complete.cases(data)] n010<-data$n010[complete.cases(data)] n011<-data$n011[complete.cases(data)] n100<-data$n100[complete.cases(data)] n101<-data$n101[complete.cases(data)] n110<-data$n110[complete.cases(data)] n111<-data$n111[complete.cases(data)] } if(length(study.id)!=length(n000) | length(n000)!=length(n001) | length(n001)!=length(n010) | length(n010)!=length(n011) | length(n011)!=length(n100) | length(n100)!=length(n101) | length(n101)!=length(n110) | length(n110)!=length(n111) ) stop("study.id, n000, n001, n010, n011, n100, n101, n110, and n111 have different lengths. \n") ## jags model if (nchar(model.code) == 0) { modelstring<-model.study(re.values) } else {modelstring <- model.code} ## data prep Ntol <- n000+n001+n010+n011+n100+n101+n110+n111 N0 <- n000+n001+n010+n011 N1 <- n100+n101+n110+n111 R <- cbind(n000,n001,n010,n011, n100,n101,n110,n111) I <- length(Ntol) ## parameters to be paramed in jags if(!is.element("CACE",param)) param<-c("CACE",param) fullparam <- c("CACE", "u1", "v1", "s1", "b1", "pi.c", "pi.n", "pi.a") if(!any(is.element(param, fullparam))) stop("parameters must be specified from the following: CACE, u1, v1, s1, b1, pi.c, pi.n, pi.a \n") out<-NULL out$model<-"cace.single" for (i in 1:I) { data.jags <- list(N0=N0[i], N1=N1[i], R=R[i,]) ## jags initial value rng.seeds<-sample(1000000,n.chains) init.jags <- vector("list", n.chains) for(ii in 1:n.chains){ init.jags[[ii]] <- list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = rng.seeds[ii]) } ## run jags jags.m<-jags.model(file=textConnection(modelstring),data=data.jags,inits=init.jags, n.chains=n.chains,n.adapt=n.adapt) update(jags.m,n.iter=n.burnin) jags.out<-coda.samples.dic(model=jags.m,variable.names=param,n.iter=n.iter,thin=n.thin) smry<-summary(jags.out$samples) smry<-cbind(smry$statistics[,c("Mean","SD")],smry$quantiles[,c("2.5%","50%","97.5%")], smry$statistics[,c("Naive SE","Time-series SE")]) smry<-signif(smry,digits=digits) out$smry[[i]] <- smry for (j in 1:length(fullparam)){ if(is.element(fullparam[j],param)) { out[[fullparam[j] ]]<-rbind(out[[fullparam[j] ]], smry[c(fullparam[j]), ]) } } #dic dev<-jags.out$dic[[1]] # mean deviance pen<-jags.out$dic[[2]] # pD pen.dev<-dev+pen # DIC dic.stat<-rbind(dev,pen,pen.dev) rownames(dic.stat)<-c("D.bar","pD","DIC") colnames(dic.stat)<-"" out$DIC[[i]]<-dic.stat if(conv.diag){ message("MCMC convergence diagnostic statistics are calculated and saved in conv.out\n") conv.out<-gelman.diag(jags.out$samples,multivariate=FALSE) out$conv.out[[i]]<-conv.out$psrf } if(mcmc.samples){ out$mcmc.samples[[i]]<-jags.out$samples } } if (two.step) { out$meta <- rma(yi=Mean, sei=SD, data=out$CACE, method = method) } attributes(out)$type<-"cace.Bayes" return(out) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/cace.study.R
#' Meta-analysis data with full compliance information #' #' The data contains a meta analysis of the association between using epidural #' analgesia in labor and the risk of cesarean section. It contains 10 trials #' with full compliance information, each with 8 observed counts. #' #' @docType data #' #' @usage data(epidural_c) #' #' @keywords dataset #' #' @references #' \insertRef{bannister-tyrrell2015data}{BayesCACE} #' #' @source \url{https://pubmed.ncbi.nlm.nih.gov/25592169/} #' @examples #' data(epidural_c) "epidural_c"
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/epidural_c-data.R
#' Meta-analysis data without full compliance information #' #' The data contains a meta analysis of the association between using epidural #' analgesia in labor and the risk of cesarean section. It contains 27 studies, #' only 10 out of which have full compliance information. #' #' @docType data #' #' @usage data(epidural_ic) #' #' @keywords dataset #' #' @references #' \insertRef{bannister-tyrrell2015data}{BayesCACE} #' #' @source \url{https://pubmed.ncbi.nlm.nih.gov/25592169/} #' @examples #' data(epidural_ic) "epidural_ic"
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/epidural_ic-data.R
#' This is a wrapper function for \code{jags.samples} which sets a trace #' monitor for all requested nodes, updates the model, and coerces the #' output to a single \code{mcmc.list} object. It also converts to the output #' to dic format. This function is based on the \code{coda.samples} function #' from the \code{rjags} library, and modified by Prof. Matthias Mittner. #' #' @title Generate posterior samples in mcmc.list format #' @param model a jags model object #' @param variable.names a character vector giving the names of variables #' to be monitored #' @param n.iter number of iterations to monitor #' @param thin thinning interval for monitors #' @param ... optional arguments that are passed to the \code{jags.samples} method #' from the \code{rjags} library, for jags model objects #' @return It returns the output to the input model object, and in dic format. #' @import rjags #' @import coda #' @export #' @references #' \insertRef{plummer2021rjags}{BayesCACE} #' #' \url{https://ihrke.github.io/post/2014/10/07/dicjags/} coda.samples.dic <- function (model, variable.names, n.iter, thin, ...) { load.module('dic') # necessary for pD and deviance monitor start <- model$iter() + thin varnames=c(variable.names, c('deviance', 'pD')) out <- jags.samples(model, varnames, n.iter, thin, type = "trace", ...) deviance <- out$deviance pD <- out$pD out$deviance <- NULL out$pD <- NULL ans <- vector("list", model$nchain()) for (ch in 1:model$nchain()) { ans.ch <- vector("list", length(out)) vnames.ch <- NULL for (i in seq(along = out)) { varname <- names(out)[[i]] d <- dim(out[[i]]) if (length(d) < 3) { stop("Invalid dimensions for sampled output") } vardim <- d[1:(length(d) - 2)] nvar <- prod(vardim) niter <- d[length(d) - 1] nchain <- d[length(d)] values <- as.vector(out[[i]]) var.i <- matrix(NA, nrow = niter, ncol = nvar) for (j in 1:nvar) { var.i[, j] <- values[j + (0:(niter - 1)) * nvar + (ch - 1) * niter * nvar] } vnames.ch <- c(vnames.ch, coda.names(varname, vardim)) ans.ch[[i]] <- var.i } ans.ch <- do.call("cbind", ans.ch) colnames(ans.ch) <- vnames.ch ans[[ch]] <- mcmc(ans.ch, start = start, thin = thin) } dic <- list(deviance = mean(as.vector(deviance)), penalty = mean(as.vector(pD)), type = 'pD') class(dic) <- "dic" return(list(samples=mcmc.list(ans), dic=dic)) } #' This is a helper function from the \code{rjags} library in order to get the names of the individual elements #' of a node array. See the package \code{rjags} for more details. #' @title Get names of node array #' @param basename the node names #' @param dim dimension of the nodes #' @return It returns a list of the names of individual elements #' @import rjags #' @import coda #' @export #' @references #' \insertRef{plummer2021rjags}{BayesCACE} coda.names <- function(basename, dim) { ## Utility function used to get the names of the individual elements ## of a node array if (prod(dim) == 1) return(basename) ##Default lower and upper limits ndim <- length(dim) lower <- rep(1, ndim) upper <- dim ##If the node name is a subset, we try to parse it to get the ##names of its elements. For example, if basename is "A[2:3]" ##we want to return names "A[2]", "A[3]" not "A[2:3][1]", "A[2:3][2]". pn <- parse.varname(basename) if (!is.null(pn) && !is.null(pn$lower) && !is.null(pn$upper)) { if (length(pn$lower) == length(pn$upper)) { dim2 <- pn$upper - pn$lower + 1 if (isTRUE(all.equal(dim[dim!=1], dim2[dim2!=1], check.attributes=FALSE))) { basename <- pn$name lower <- pn$lower upper <- pn$upper ndim <- length(dim2) } } } indices <- as.character(lower[1]:upper[1]) if (ndim > 1) { for (i in 2:ndim) { indices <- outer(indices, lower[i]:upper[i], FUN=paste, sep=",") } } paste(basename,"[",as.vector(indices),"]",sep="") } #' This is a helper function from the \code{rjags} library in order to parse the string of form #' "a" or "a[n,p:q,r]". See the package \code{rjags} for more details. #' @title Parse strings of specific form #' @param varname string name of variable #' @return It returns a list of parsed parameters #' @import rjags #' @import coda #' @export #' @references #' \insertRef{plummer2021rjags}{BayesCACE} parse.varname <- function(varname) { ## Try to parse string of form "a" or "a[n,p:q,r]" where "a" is a ## variable name and n,p,q,r are integers v <- try(parse(text=varname, n=1), silent=TRUE) if (!is.expression(v) || length(v) != 1) return(NULL) v <- v[[1]] if (is.name(v)) { ##Full node array requested return(list(name=deparse(v))) } else if (is.call(v) && identical(deparse(v[[1]]), "[") && length(v) > 2) { ##Subset requested ndim <- length(v) - 2 lower <- upper <- numeric(ndim) if (any(nchar(sapply(v, deparse)) == 0)) { ##We have to catch empty indices here or they will cause trouble ##below return(NULL) } for (i in 1:ndim) { index <- v[[i+2]] if (is.numeric(index)) { ##Single index lower[i] <- upper[i] <- index } else if (is.call(index) && length(index) == 3 && identical(deparse(index[[1]]), ":") && is.numeric(index[[2]]) && is.numeric(index[[3]])) { ##Index range lower[i] <- index[[2]] upper[i] <- index[[3]] } else return(NULL) } if (any(upper < lower)) return (NULL) return(list(name = deparse(v[[2]]), lower=lower, upper=upper)) } return(NULL) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/fun.coda.dic.R
#' This function generates part of the model code for meta-analysis #' when the dataset has complete compliance information for all studies, #' as described in Section 2.2, "the Bayesian hierarchical model" of the package manuscript. #' This function will be called internally if user uses the \code{cace.meta.c} function. #' @title Bayesian hierarchical model code for CACE meta-analysis with complete compliance data #' @param random.effects a list of logical values indicating whether random effects are included in the model. #' The list should contain the assignment for these parameters only: \code{delta.n} (\eqn{\delta_{in}}), #' \code{delta.a} (\eqn{\delta_{ia}}), \code{delta.u} (\eqn{\delta_{iu}}), \code{delta.v} (\eqn{\delta_{iv}}), #' \code{delta.s} (\eqn{\delta_{is}}), \code{delta.b} (\eqn{\delta_{ib}}), \code{cor}. The list should be in the #' form of \code{list(delta.a = FALSE, cor = FALSE, ...)}. By default, this #' is an empty list, and all parameters are default to \code{TRUE}. Parameters that are not listed in the list #' are assumed to be \code{TRUE}. Note that \eqn{\rho} (\code{cor}) can only be included when both \eqn{\delta_{in}} #' (\code{delta.n}) and \eqn{\delta_{ia}} (\code{delta.a}) are set to \code{TRUE}. Otherwise, a warning #' occurs and the model continues running by forcing \code{delta.n = TRUE} and \code{delta.a = TRUE}. #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{alpha.n.m} and \code{alpha.n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{alpha.n}, as well as \code{alpha.a.m}, \code{alpha.a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. It also contains the shape and rate parameters of the gamma distributions #' of the standard deviation variable of \code{delta.n}, \code{delta.a}, \code{delta.u}, \code{delta.v} #' \code{delta.s}, \code{delta.b}. The shape parameters are named as \code{tau.n.h} and \code{tau.a.h}, for example, #' and the rate parameters are named as \code{tau.n.r} and \code{tau.a.r}. You do not need to specify the shape and #' rate parameters if the corresponding random effect is set to \code{FALSE} in \code{random.effects}, since they will #' not be used anyways. By default, \code{re.values} is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}, #' and the shape and rate parameters are default to \code{2}. #' @return It returns a model string #' @export #' @examples #' # use default settings #' model.string <- model.meta.c() model.meta.c <- function(random.effects = list(), re.values = list()){ # model string mod.string <- "model{ for (i in 1:I) { prob[i, 1] <- (pi.n[i]*(1-s1[i]) + pi.c[i]*(1-v1[i])) prob[i, 2] <- (pi.n[i]*s1[i] + pi.c[i]*v1[i]) prob[i, 3] <- (pi.a[i]*(1-b1[i])) prob[i, 4] <- (pi.a[i]*b1[i]) prob[i, 5] <- (pi.n[i]*(1-s1[i])) prob[i, 6] <- (pi.n[i]*s1[i]) prob[i, 7] <- (pi.c[i]*(1-u1[i])+pi.a[i]*(1-b1[i])) prob[i, 8] <- (pi.c[i]*u1[i]+pi.a[i]*b1[i]) R[i, 1:4] ~ dmulti(prob[i, 1:4], N0[i]) R[i, 5:8] ~ dmulti(prob[i, 5:8], N1[i]) n[i] <- alpha.n + Ind[1]*delta.n[i] a[i] <- alpha.a + Ind[2]*delta.a[i] pi.n[i] <- exp(n[i])/(1+exp(n[i])+exp(a[i])) pi.a[i] <- exp(a[i])/(1+exp(n[i])+exp(a[i])) pi.c[i] <- 1-pi.a[i]-pi.n[i] probit(u1[i]) <- alpha.u + Ind[3]*delta.u[i] probit(v1[i]) <- alpha.v + Ind[4]*delta.v[i] logit(s1[i]) <- alpha.s + Ind[5]*delta.s[i] logit(b1[i]) <- alpha.b + Ind[6]*delta.b[i] cacei[i] <- u1[i]-v1[i] " prior.string <- prior.meta(random.effects = random.effects, re.values = re.values) modelstring <- paste(mod.string, prior.string, sep="\n") return(modelstring) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/model.meta.c.R
#' This function generates the model code for meta-analysis #' when the dataset has incomplete compliance information for all studies, #' as described in Section 2.2.2, "the Bayesian hierarchical model" of the package manuscript. #' This function will be called internally if user uses the \code{cace.meta.ic} function. #' @title Bayesian hierarchical model code for CACE meta-analysis with complete compliance data #' @param random.effects a list of logical values indicating whether random effects are included in the model. #' The list should contain the assignment for these parameters only: \code{delta.n} (\eqn{\delta_{in}}), #' \code{delta.a} (\eqn{\delta_{ia}}), \code{delta.u} (\eqn{\delta_{iu}}), \code{delta.v} (\eqn{\delta_{iv}}), #' \code{delta.s} (\eqn{\delta_{is}}), \code{delta.b} (\eqn{\delta_{ib}}), \code{cor}. The list should be in the #' form of \code{list(delta.a = FALSE, cor = FALSE, ...)}. By default, this #' is an empty list, and all parameters are default to \code{TRUE}. Parameters that are not listed in the list #' are assumed to be \code{TRUE}. Note that \eqn{\rho} (\code{cor}) can only be included when both \eqn{\delta_{in}} #' (\code{delta.n}) and \eqn{\delta_{ia}} (\code{delta.a}) are set to \code{TRUE}. Otherwise, a warning #' occurs and the model continues running by forcing \code{delta.n = TRUE} and \code{delta.a = TRUE}. #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{alpha.n.m} and \code{alpha.n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{alpha.n}, as well as \code{alpha.a.m}, \code{alpha.a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. It also contains the shape and rate parameters of the gamma distributions #' of the standard deviation variable of \code{delta.n}, \code{delta.a}, \code{delta.u}, \code{delta.v} #' \code{delta.s}, \code{delta.b}. The shape parameters are named as \code{tau.n.h} and \code{tau.a.h}, for example, #' and the rate parameters are named as \code{tau.n.r} and \code{tau.a.r}. You do not need to specify the shape and #' rate parameters if the corresponding random effect is set to \code{FALSE} in \code{random.effects}, since they will #' not be used anyways. By default, \code{re.values} is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}, #' and the shape and rate parameters are default to \code{2}. #' @return It returns a model string #' @export #' @examples #' # use default settings #' model.string <- model.meta.ic() model.meta.ic <- function(random.effects = list(), re.values = list()){ # model string mod.string <- "model{ for (i in 1:n1) { R0_4[i, ] ~ dmulti(prob0[i, ], N0_4[i]) prob0[i, 1] <- pi.n[i]*(1-s1[i]) + pi.c[i]*(1-v1[i]) prob0[i, 2] <- pi.n[i]*s1[i] + pi.c[i]*v1[i] prob0[i, 3] <- pi.a[i]*(1-b1[i]) prob0[i, 4] <- pi.a[i]*b1[i] R1_4[i, ] ~ dmulti(prob1[i, ], N1_4[i]) prob1[i, 1] <- pi.n[i]*(1-s1[i]) prob1[i, 2] <- pi.n[i]*s1[i] prob1[i, 3] <- pi.c[i]*(1-u1[i])+pi.a[i]*(1-b1[i]) prob1[i, 4] <- pi.c[i]*u1[i]+pi.a[i]*b1[i] } for (i in (n1+1):(n1+n2)) { R0_4[i, ] ~ dmulti(prob0[i, ], N0_4[i]) prob0[i, 1] <- pi.n[i]*(1-s1[i]) + pi.c[i]*(1-v1[i]) prob0[i, 2] <- pi.n[i]*s1[i] + pi.c[i]*v1[i] prob0[i, 3] <- pi.a[i]*(1-b1[i]) prob0[i, 4] <- pi.a[i]*b1[i] R1_2[i, 2] ~ dbin(p1[i], N1_2[i]) p1[i] <- pi.n[i]*s1[i] + pi.c[i]*u1[i] + pi.a[i]*b1[i] } for (i in (n1+n2+1):(n1+n2+n3)) { R0_2[i, 2] ~ dbin(p0[i], N0_2[i]) p0[i] <- pi.n[i]*s1[i] + pi.c[i]*v1[i] + pi.a[i]*b1[i] R1_4[i, ] ~ dmulti(prob1[i, ], N1_4[i]) prob1[i, 1] <- pi.n[i]*(1-s1[i]) prob1[i, 2] <- pi.n[i]*s1[i] prob1[i, 3] <- pi.c[i]*(1-u1[i])+pi.a[i]*(1-b1[i]) prob1[i, 4] <- pi.c[i]*u1[i]+pi.a[i]*b1[i] } for (i in (n1+n2+n3+1):(n1+n2+n3+n4)) { R0_2[i, 2] ~ dbin(p0[i], N0_2[i]) p0[i] <- pi.n[i]*s1[i] + pi.c[i]*v1[i] + pi.a[i]*b1[i] R1_2[i, 2] ~ dbin(p1[i], N1_2[i]) p1[i] <- pi.n[i]*s1[i] + pi.c[i]*u1[i] + pi.a[i]*b1[i] } for (i in 1:(n1+n2+n3+n4)) { n[i] <- alpha.n + Ind[1]*delta.n[i] a[i] <- alpha.a + Ind[2]*delta.a[i] pi.n[i] <- exp(n[i])/(1+exp(n[i])+exp(a[i])) pi.a[i] <- exp(a[i])/(1+exp(n[i])+exp(a[i])) pi.c[i] <- 1-pi.a[i]-pi.n[i] probit(u1[i]) <- alpha.u + Ind[3]*delta.u[i] probit(v1[i]) <- alpha.v + Ind[4]*delta.v[i] logit(s1[i]) <- alpha.s + Ind[5]*delta.s[i] logit(b1[i]) <- alpha.b + Ind[6]*delta.b[i] cacei[i] <- u1[i]-v1[i] " prior.string <- prior.meta(random.effects = random.effects, re.values = re.values) modelstring <- paste(mod.string, prior.string, sep="\n") return(modelstring) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/model.meta.ic.R
#' This function generates the model code for a single study using the #' likelihood and model specified in Section 2.1, or a two-step #' approach for meta-analysis with complete compliance information as #' described in Section 2.2, "The two-step approach" of the package manuscript. #' This function will be called internally if user uses the \code{cace.study} function. #' @title Model code of CACE analysis for a single study, or a two-step approach for meta-analysis #' with complete complice information #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{n.m} and \code{n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{n}, as well as \code{a.m}, \code{a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. By default, this is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}. #' @return It returns a model string #' @export #' @examples #' model.string <- model.study() model.study <- function(re.values = list()){ mod.string <- "model{ prob[1] <- (pi.n*(1-s1) + pi.c*(1-v1)) prob[2] <- (pi.n*s1 + pi.c*v1) prob[3] <- (pi.a*(1-b1)) prob[4] <- (pi.a*b1) prob[5] <- (pi.n*(1-s1)) prob[6] <- (pi.n*s1) prob[7] <- (pi.c*(1-u1)+pi.a*(1-b1)) prob[8] <- (pi.c*u1+pi.a*b1) R[1:4] ~ dmulti(prob[1:4], N0) R[5:8] ~ dmulti(prob[5:8], N1) pi.n <- exp(n)/(1+exp(n)+exp(a)) pi.a <- exp(a)/(1+exp(n)+exp(a)) pi.c <- 1-pi.a-pi.n probit(u1) <- alpha.u probit(v1) <- alpha.v logit(s1) <- alpha.s logit(b1) <- alpha.b CACE <- u1-v1 " prior.string <- prior.study(re.values = re.values) modelstring <- paste(mod.string, prior.string, sep="\n") return(modelstring) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/model.study.R
#' This function creates a traceplot for a model object with the type attribute \code{cace.Bayes}. #' @title this plot function creates a traceplot #' @param obj a model object, returned by \code{cace.meta.c}, \code{cace.meta.ic}, #' or \code{cace.study} #' @param param list of parameters to plot #' @param trialnumber indicator for which trial number of the mcmc samples #' to use. The default is \code{1} #' @param ... optional parameters to pass into the \code{plot} function #' @return It returns a traceplot in an \code{R} plot window. #' @importFrom grDevices rainbow #' @importFrom graphics plot par #' @importFrom methods is #' @export #' @examples #' \donttest{ #' out.meta.c <- cace.meta.c(data = epidural_c, conv.diag = TRUE, #' mcmc.samples = TRUE, study.specific = TRUE) #' plt.trace(obj=out.meta.c) #' } plt.trace <- function(obj, param = c("CACE"), trialnumber = 1, ...) { if(missing(obj)) stop("need to specify obj, the object generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.\n") if (!(attributes(obj)$type) == "cace.Bayes") stop("Use only with 'cace.Bayes' objects, the output generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.\n") if(is.null(obj$mcmc.samples)) stop("'obj$mcmc.samples' is missing. please set mcmc.samples=TRUE when running the function cace.study, cace.meta.c or cace.meta.ic.") if(!is(obj$mcmc.samples, "mcmc.list") & !is(obj$mcmc.samples, "list")) stop("'obj$mcmc.samples' must be a mcmc.list or list generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.") if(is(obj$mcmc.samples, "mcmc.list")) {x <- obj$mcmc.samples} if(is(obj$mcmc.samples, "list")) { if(!trialnumber %in% c(1:length(obj$mcmc.samples))) stop("'trialnumber' should be the trial number to be plotted \n") else {x <- obj$mcmc.samples[[trialnumber]]} } param <- param n.chains <- length(x) cols<-rainbow(n.chains,s=0.6,v=0.6) # make sure parameter is reset upon function exit oldpar <- par(no.readonly = TRUE) on.exit(par(oldpar)) old.mfrowpar <- par(mfrow=c(n.chains,1)) for(j in 1:n.chains){ temp<-as.vector(x[[j]][,param]) traceplot <- plot(temp,type="l",col="red",ylab=param,xlab="Iterations", main = paste("Trace Plot of", param,", Chain",j), lwd=1,cex.axis=1.2,cex.lab=1.4, ...) } on.exit(par(old.mfrowpar)) } #' This function creates a density plot for a model object with the type attribute \code{cace.Bayes}. #' @title this plot function creates a density plot #' @param obj a model object, returned by \code{cace.meta.c}, \code{cace.meta.ic}, #' or \code{cace.study} #' @param param list of parameters to plot #' @param trialnumber indicator for which trial number of the mcmc samples #' to use. The default is \code{1} #' @param ... optional parameters to pass into the \code{plot} function #' @return It returns a density plot in an \code{R} plot window. #' @importFrom grDevices rainbow #' @importFrom graphics plot #' @importFrom stats bw.SJ density #' @importFrom methods is #' @export #' @examples #' \donttest{ #' out.meta.c <- cace.meta.c(data = epidural_c, conv.diag = TRUE, #' mcmc.samples = TRUE, study.specific = TRUE) #' plt.density(obj=out.meta.c) #' } plt.density <- function(obj, param = c("CACE"), trialnumber = 1, ...) { if(missing(obj)) stop("need to specify obj, the object generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.\n") if (!(attributes(obj)$type) == "cace.Bayes") stop("Use only with 'cace.Bayes' objects, the output generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.\n") if(is.null(obj$mcmc.samples)) stop("'obj$mcmc.samples' is missing. please set mcmc.samples=TRUE when running the function cace.study, cace.meta.c or cace.meta.ic.") if(!is(obj$mcmc.samples, "mcmc.list") & !is(obj$mcmc.samples, "list")) stop("'obj$mcmc.samples' must be a mcmc.list or list generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.") if(is(obj$mcmc.samples, "mcmc.list")) {x <- obj$mcmc.samples} if(is(obj$mcmc.samples, "list")) { if(!trialnumber %in% c(1:length(obj$mcmc.samples))) stop("'trialnumber' should be the trial number to be plotted \n") else {x <- obj$mcmc.samples[[trialnumber]]} } param <- param n.chains <- length(x) cols<-rainbow(n.chains,s=0.6,v=0.6) if (n.chains==1) { nams <- dimnames(x)[[2]] if(is.element(param, nams)) { temp<-as.vector(x[,param]) bw <- bw.SJ(temp) * 1.5 densplot <- plot(density(temp, bw = bw), xlab = param, main = paste("Density of", param), ...) } } else if (n.chains >1) { nams <- dimnames(x[[1]])[[2]] if(is.element(param, nams)) { temp<-NULL for(j in 1:n.chains){ temp<-c(temp, as.vector(x[[j]][,param])) } bw <- bw.SJ(temp) * 1.5 densplot <- plot(density(temp, bw = bw), xlab = param, main = paste("Density of", param), ...) } } } #' This function creates an acf (Autocorrelation Function) plot for a model object with the type attribute \code{cace.Bayes}. #' @title this plot function creates an acf plot #' @param obj a model object, returned by \code{cace.meta.c}, \code{cace.meta.ic}, #' or \code{cace.study} #' @param param list of parameters to plot #' @param trialnumber indicator for which trial number of the mcmc samples #' to use. The default is \code{1} #' @param ... optional parameters to pass into the \code{acf} function #' from the \code{stats} library. #' @return It returns an acf plot in an \code{R} plot window. #' @importFrom grDevices rainbow #' @importFrom graphics plot #' @importFrom stats acf #' @importFrom methods is #' @export #' @examples #' \donttest{ #' out.meta.c <- cace.meta.c(data = epidural_c, conv.diag = TRUE, #' mcmc.samples = TRUE, study.specific = TRUE) #' plt.acf(obj=out.meta.c) #' } plt.acf <- function(obj, param = c("CACE"), trialnumber = 1, ...) { if(missing(obj)) stop("need to specify obj, the object generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.\n") if (!(attributes(obj)$type) == "cace.Bayes") stop("Use only with 'cace.Bayes' objects, the output generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.\n") if(is.null(obj$mcmc.samples)) stop("'obj$mcmc.samples' is missing. please set mcmc.samples=TRUE when running the function cace.study, cace.meta.c or cace.meta.ic.") if(!is(obj$mcmc.samples, "mcmc.list") & !is(obj$mcmc.samples, "list")) stop("'obj$mcmc.samples' must be a mcmc.list or list generated from one of the following functions:\n cace.study, cace.meta.c, cace.meta.ic.") if(is(obj$mcmc.samples, "mcmc.list")) {x <- obj$mcmc.samples} if(is(obj$mcmc.samples, "list")) { if(!trialnumber %in% c(1:length(obj$mcmc.samples))) stop("'trialnumber' should be the trial number to be plotted \n") else {x <- obj$mcmc.samples[[trialnumber]]} } param <- param n.chains <- length(x) cols<-rainbow(n.chains,s=0.6,v=0.6) if (n.chains==1) { nams <- dimnames(x)[[2]] if(is.element(param, nams)) { temp<-as.vector(x[,param]) acfplot <- acf(temp, ylab = param, main = paste("Series", param), ...) } } else if (n.chains >1) { nams <- dimnames(x[[1]])[[2]] if(is.element(param, nams)) { temp<-NULL for(j in 1:n.chains){ temp<-c(temp, as.vector(x[[j]][,param])) } acfplot <- acf(temp, ylab = param, main = paste("Series", param), ...) } } }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/plt.cacebayes.R
#' This function provides a visual overview (forest plot) for a model object and corresponding dataset. #' @title this plot function makes a forest plot. #' @param data an input dataset with the same structure as the example data \code{epidural_c}, #' containing multiple rows referring to multiple studies in a meta-analysis. #' @param obj a model object returned by \code{cace.meta.c}, \code{cace.meta.ic}, #' or \code{cace.study} #' @param ... optional parameters passed into the \code{forestplot} function from the #' \code{forestplot} library #' @return It returns a forestplot object in an \code{R} plot window. #' @importFrom graphics par plot #' @importFrom grid gpar #' @importFrom methods is #' @import forestplot #' @export #' @examples #' \donttest{ #' data("epidural_c", package = "BayesCACE") #' out.meta.c <- cace.meta.c(data = epidural_c, conv.diag = TRUE, #' mcmc.samples = TRUE, study.specific = TRUE) #' plt.forest(data=epidural_c, obj=out.meta.c) #' } plt.forest <- function(data, obj, ...) { if(missing(obj)) stop("need to specify obj, the object generated from one of the following functions: cace.study, cace.meta.c, cace.meta.ic.\n") if (!(attributes(obj)$type) == "cace.Bayes") stop("Use only with 'cace.Bayes' objects, the output generated from one of the following functions: cace.study, cace.meta.c, cace.meta.ic.\n") if(missing(data)) stop("need to specify data") if(!is(obj$smry, "matrix") & !is(obj$smry, "list") ){ stop("'obj$smry' must be a matrix or list generated from one of the following functions: cace.study, cace.meta.c, cace.meta.ic.") } if (is(obj$smry, "matrix")){ x <- obj$smry outcacei <- x[substr(row.names(x), start=1, stop=4)=="cace", ] } else if (is(obj$smry, "list")){ outcacei <- obj$CACE if (nrow(outcacei) == 1) stop("forestplot cannot be made for a single study") x <- cbind(obj$meta$beta, obj$meta$beta, obj$meta$ci.lb, obj$meta$ci.ub) row.names(x) <- "CACE" colnames(x) <- c("Mean", "50%", "2.5%", "97.5%") } if(!nrow(data)==nrow(outcacei)) stop("data and study-specific CACE have different lengths") data$miss.r0 <- ifelse((data$n000==0 & data$n001==0 & data$n010==0 & data$n011==0), 1, 0) data$miss.r1 <- ifelse((data$n100==0 & data$n101==0 & data$n110==0 & data$n111==0), 1, 0) data$miss <- ifelse((data$miss.r0==1|data$miss.r1==1), 1, 0) tmp1 <- data[order(data$miss.r0, data$miss.r1),] tmp2 <- cbind(tmp1, outcacei) tmp3 <- tmp2[order(tmp2$study.id),] study.name <- tmp3$study.name study.id <- tmp3$study.id cace_median <- round(as.vector(tmp3[, "50%"]), 3) cace_mean <- round(as.vector(tmp3[, "Mean"]), 3) cace_lower <- round(as.vector(tmp3[, "2.5%"]), 3) cace_upper <- round(as.vector(tmp3[, "97.5%"]), 3) values <- list( median = c(NA, NA, cace_median, x["CACE", "50%"]), mean = c(NA, NA, cace_mean, x["CACE", "Mean"]), lower = c(NA, NA, cace_lower, x["CACE", "2.5%"]), upper = c(NA, NA, cace_upper, x["CACE", "97.5%"]) ) tabletext<-cbind( c("", "Study", paste(study.name), "Overall"), c("", "CACE", paste(formatC(cace_mean, format='f', digits=3 ), " (", formatC(cace_lower, format='f', digits=3 ),", ", formatC(cace_upper, format='f', digits=3 ), ")", sep="") , paste(round(x["CACE", "Mean"], 3), " (", round(x["CACE", "2.5%"], 3), ", ", round(x["CACE", "97.5%"], 3), ")", sep="" ) ) ) xticks <- seq(from = min(cace_lower), to = max(cace_upper), by = (max(cace_upper)-min(cace_lower))/6) xticks_3 <- round(xticks, 3) xtlab <- rep(c(TRUE, FALSE), length.out = length(xticks)) attr(xticks_3, "labels") <- xtlab own.f <- fpTxtGp(ticks = gpar(cex=0.85), xlab = gpar(cex = 0.95)) if(obj$model %in% c("cace.single", "cace.meta.c")) { forestplot(tabletext, boxsize = .2, hrzl_lines = gpar(lwd=1, col="#444444"), mean = values$mean, lower = values$lower, upper = values$upper, new_page = TRUE, is.summary=c(TRUE, TRUE, rep(FALSE,nrow(outcacei)), TRUE), clip=c(-1.0, 1.0), xticks = xticks_3, txt_gp = own.f, col=fpColors(box="royalblue",lines="darkblue", summary="royalblue", ...) ) } else if (obj$model=="cace.meta.ic") { missind <- c(NA, NA, tmp3$miss, 1) CACE.complete <- CACE.marginal <- values CACE.marginal$mean[missind==0] <- CACE.marginal$median[missind==0] <- CACE.marginal$lower[missind==0] <- CACE.marginal$upper[missind==0] <- NA CACE.complete$mean[missind==1] <- CACE.complete$median[missind==1] <- CACE.complete$lower[missind==1] <- CACE.complete$upper[missind==1] <- NA forestplot(tabletext, boxsize = .2, hrzl_lines = gpar(lwd=1, col="#444444"), mean = cbind(CACE.complete$mean, CACE.marginal$mean), lower = cbind(CACE.complete$lower, CACE.marginal$lower), upper = cbind(CACE.complete$upper, CACE.marginal$upper), new_page = TRUE, is.summary=c(TRUE, TRUE, rep(FALSE,nrow(outcacei)), TRUE, TRUE), clip=c(-1.0, 1.0), lty.ci = c(1, 5), xticks = xticks_3, txt_gp = own.f, col=fpColors(box="royalblue",lines="darkblue", summary="royalblue", ...) ) } }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/plt.forest.R
#' This function provides a visual overview (forest plot) of study-specific #' noncompliance rates in both randomization arms. #' @title Plotting noncompliance rates for a given dataset #' @param data a dataset with structure like the example \code{epidural_c} or \code{epidural_ic} #' @param overall a logical value indicating whether a summary estimate of the compliance rates #' per randomization group is provided. The default is \code{TRUE}. This overall rate is estimated #' using a logit generalized linear mixed model. #' @param ... optional parameters passed into the \code{forestplot} function from the #' \code{forestplot} library #' @return A forest plot of noncompliance rates in an \code{R} plot window #' @description Provides a forest plot of noncompliance rates in an \code{R} plot window. #' @details Only studies with full compliance information are included in this plot #' because noncompliance rates cannot be calculated without compliance data. In the generated #' plot, the red dot with its horizontal line shows the study-specific noncompliance rate #' with its 95\% exact confidence interval for the patients randomized to the treatment arm, #' and the blue square with its horizontal line represents that rate and interval for those #' in the control arm. The confidence intervals are calculated by the Clopper--Pearson exact #' method, which is based on the cumulative distribution function of the binomial distribution. #' @import forestplot #' @importFrom graphics par plot #' @importFrom stats acf binom.test binomial coef confint #' @importFrom lme4 glmer VarCorr #' @export #' @examples #' data("epidural_c", package = "BayesCACE") #' plt.noncomp(data=epidural_c, overall = TRUE) plt.noncomp <- function(data, overall=TRUE, ...) { if(missing(data)) stop("need to specify a data set with complete compliance information. \n") if (any((data$n000==0 & data$n001==0 & data$n010==0 & data$n011==0) | (data$n100==0 & data$n101==0 & data$n110==0 & data$n111==0)) ) { warning("noncompliance plot can only be made for studies with complete data. \n only trials with full compliance information are kept. \n") data <- data[ !((data$n000==0 & data$n001==0 & data$n010==0 & data$n011==0) | (data$n100==0 & data$n101==0 & data$n110==0 & data$n111==0)),] } data$n00s <- data$n000+data$n001 data$n01s <- data$n010+data$n011 data$n10s <- data$n100+data$n101 data$n11s <- data$n110+data$n111 data$n0ss <- data$n00s+data$n01s data$n1ss <- data$n10s+data$n11s data$p10 <- data$n01s/data$n0ss # P(T=1|R=0) data$p01 <- data$n10s/data$n1ss # P(T=0|R=1) tmp.b <- t(sapply(split(data, data$study.id), function(x) binom.test(x$n01s, x$n0ss)$conf.int)) tmp.a <- t(sapply(split(data, data$study.id), function(x) binom.test(x$n10s, x$n1ss)$conf.int)) data$lower.p10 <- tmp.b[,1] data$upper.p10 <- tmp.b[,2] data$lower.p01 <- tmp.a[,1] data$upper.p01 <- tmp.a[,2] expit <- function(x){y=exp(x)/(1+exp(x)) return(y)} C <- 16*sqrt(3)/(15*pi) m10 <- glmer(cbind(n01s, n00s) ~ (1 | study.id), data = data, family = binomial) mu10 <- c(coef(summary(m10))[1], confint(m10, method="Wald")["(Intercept)", c("2.5 %", "97.5 %")]) sd10 <- as.data.frame(VarCorr(m10))[1, "sdcor"] outp10 <- expit(mu10/sqrt(1+C^2*sd10^2)) p10_out <- paste(formatC(round(outp10[1], 3), format='f', digits=3 ), " (", formatC(round(outp10[2], 3), format='f', digits=3 ), ",", formatC(round(outp10[3], 3), format='f', digits=3 ), ")", sep="") m01 <- glmer(cbind(n10s, n11s) ~ (1 | study.id), data = data, family = binomial) mu01 <- c(coef(summary(m01))[1], confint(m01, method="Wald")["(Intercept)", c("2.5 %", "97.5 %")]) sd01 <- as.data.frame(VarCorr(m01))[1, "sdcor"] outp01 <- expit(mu01/sqrt(1+C^2*sd01^2)) p01_out <- paste(formatC(round(outp01[1], 3), format='f', digits=3 ), " (", formatC(round(outp01[2], 3), format='f', digits=3 ), ",", formatC(round(outp01[3], 3), format='f', digits=3 ), ")", sep="") if (overall) { tabletext<-cbind( c("Study (Author, Year)", paste(data$study.name), "Overall"), c("P(T=0|R=1)", paste(formatC(round(data$p01, 3), format='f', digits=3 ), " (", formatC(round(data$lower.p01, 3), format='f', digits=3 ),",", formatC(round(data$upper.p01, 3), format='f', digits=3 ), ")", sep=""), p01_out ), c("P(T=1|R=0)", paste(formatC(round(data$p10, 3), format='f', digits=3 ), " (", formatC(round(data$lower.p10, 3), format='f', digits=3 ),",", formatC(round(data$upper.p10, 3), digits=3 ), ")", sep=""), p10_out ) ) # tabletext<-cbind(c("Study (Author, Year)", paste(data$study.name), "Overall")) xticks <- seq(from = 0, to = max(data$upper.p01, data$upper.p10), by = 0.1) xtlab <- rep(c(TRUE, FALSE), length.out = length(xticks)) attr(xticks, "labels") <- xtlab own.f <- fpTxtGp(ticks = gpar(cex=0.85), xlab = gpar(cex = 0.95)) forestplot(tabletext, graph.pos = 3, hrzl_lines = gpar(lwd=1, col="#444444"), legend_args = fpLegend(pos = list("top")), legend = c("P(T=0|R=1)", "P(T=1|R=0)"), fn.ci_norm = c(fpDrawCircleCI, fpDrawNormalCI), boxsize = .15, # We set the box size to better visualize the type line.margin = .36, # We need to add this to avoid crowding is.summary=c(TRUE, rep(FALSE, nrow(data)), TRUE), mean = cbind(c(NA, data$p01, round(outp01[1], 3)), c(NA, data$p10, round(outp10[1], 3))), lower = cbind(c(NA, data$lower.p01, round(outp01[2], 3)), c(NA, data$lower.p10, round(outp10[2], 3))), upper = cbind(c(NA, data$upper.p01, round(outp01[3], 3)), c(NA, data$upper.p10, round(outp10[3], 3))), clip =c(0, 1), col=fpColors(box=c("darkred", "blue"), summary=c("darkred", "blue")), grid = structure(c(0, 0.5), gp = gpar(lty = 2, col = "#CCCCFF")), xticks = xticks, txt_gp = own.f, xlab="Nocompliance Rates", ...) } else { tabletext<-cbind( c("Study (Author, Year)", paste(data$study.name)), c("P(T=0|R=1)", paste(formatC(round(data$p01, 3), format='f', digits=3 ), " (", formatC(round(data$lower.p01, 3), format='f', digits=3 ),",", formatC(round(data$upper.p01, 3), format='f', digits=3 ), ")", sep="") ), c("P(T=1|R=0)", paste(formatC(round(data$p10, 3), format='f', digits=3 ), " (", formatC(round(data$lower.p10, 3), format='f', digits=3 ),",", formatC(round(data$upper.p10, 3), digits=3 ), ")", sep="") ) ) xticks <- seq(from = 0, to = max(data$upper.p01, data$upper.p10), by = 0.1) xtlab <- rep(c(TRUE, FALSE), length.out = length(xticks)) attr(xticks, "labels") <- xtlab own.f <- fpTxtGp(ticks = gpar(cex=0.85), xlab = gpar(cex = 0.95)) forestplot(tabletext, graph.pos = 3, hrzl_lines = gpar(lwd=1, col="#444444"), legend_args = fpLegend(pos = list("top")), legend = c("P(T=0|R=1)", "P(T=1|R=0)"), fn.ci_norm = c(fpDrawCircleCI, fpDrawNormalCI), boxsize = .15, # We set the box size to better visualize the type line.margin = .36, # We need to add this to avoid crowding is.summary=c(TRUE, rep(FALSE, nrow(data))), mean = cbind(c(NA, data$p01), c(NA, data$p10)), lower = cbind(c(NA, data$lower.p01), c(NA, data$lower.p10)), upper = cbind(c(NA, data$upper.p01), c(NA, data$upper.p10)), clip =c(0, 1), col=fpColors(box=c("darkred", "blue"), summary=c("darkred", "blue")), grid = structure(c(0, 0.5), gp = gpar(lty = 2, col = "#CCCCFF")), xticks = xticks, txt_gp = own.f, xlab="Nocompliance Rates", ...) } }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/plt.noncomp.R
#' This function returns a partially complete prior string. Used internally - cannot #' be directly used. #' @title The function returns a custom string that specifies part of the model. #' @param random.effects a list of logical values indicating whether random effects are included in the model. #' The list should contain the assignment for these parameters only: \code{delta.n} (\eqn{\delta_{in}}), #' \code{delta.a} (\eqn{\delta_{ia}}), \code{delta.u} (\eqn{\delta_{iu}}), \code{delta.v} (\eqn{\delta_{iv}}), #' \code{delta.s} (\eqn{\delta_{is}}), \code{delta.b} (\eqn{\delta_{ib}}), \code{cor}. The list should be in the #' form of \code{list(delta.a = FALSE, cor = FALSE, ...)}. By default, this #' is an empty list, and all parameters are default to \code{TRUE}. Parameters that are not listed in the list #' are assumed to be \code{TRUE}. Note that \eqn{\rho} (\code{cor}) can only be included when both \eqn{\delta_{in}} #' (\code{delta.n}) and \eqn{\delta_{ia}} (\code{delta.a}) are set to \code{TRUE}. Otherwise, a warning #' occurs and the model continues running by forcing \code{delta.n = TRUE} and \code{delta.a = TRUE}. #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{alpha.n.m} and \code{alpha.n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{alpha.n}, as well as \code{alpha.a.m}, \code{alpha.a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. It also contains the shape and rate parameters of the gamma distributions #' of the standard deviation variable of \code{delta.n}, \code{delta.a}, \code{delta.u}, \code{delta.v} #' \code{delta.s}, \code{delta.b}. The shape parameters are named as \code{tau.n.h} and \code{tau.a.h}, for example, #' and the rate parameters are named as \code{tau.n.r} and \code{tau.a.r}. You do not need to specify the shape and #' rate parameters if the corresponding random effect is set to \code{FALSE} in \code{random.effects}, since they will #' not be used anyways. By default, \code{re.values} is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}, #' and the shape and rate parameters are default to \code{2}. #' @return custom prior string #' @export #' @examples #' model.string <- prior.meta() prior.meta <- function(random.effects = list(), re.values = list()){ delta.n <- delta.a <- delta.u <- delta.v <- delta.s <- delta.b <- cor <- TRUE if ("delta.n" %in% names(random.effects)) {delta.n <- random.effects[['delta.n']]} if ("delta.a" %in% names(random.effects)) {delta.a <- random.effects[['delta.a']]} if ("delta.u" %in% names(random.effects)) {delta.u <- random.effects[['delta.u']]} if ("delta.v" %in% names(random.effects)) {delta.v <- random.effects[['delta.v']]} if ("delta.s" %in% names(random.effects)) {delta.s <- random.effects[['delta.s']]} if ("delta.b" %in% names(random.effects)) {delta.b <- random.effects[['delta.b']]} if ("cor" %in% names(random.effects)) {cor <- random.effects[['cor']]} if ((!(delta.n & delta.a)) & cor){ warning("'cor' can be assigned as TRUE only if both delta.n and delta.a are TRUE.\n the model is continued by forcing delta.n=TRUE and delta.a=TRUE") delta.n <- TRUE delta.a <- TRUE } Ind <- rep(1, 7) if (!delta.n) Ind[1] <- 0 if (!delta.a) Ind[2] <- 0 if (!delta.u) Ind[3] <- 0 if (!delta.v) Ind[4] <- 0 if (!delta.s) Ind[5] <- 0 if (!delta.b) Ind[6] <- 0 if (!cor) Ind[7] <- 0 alpha.n.m <- alpha.a.m <- alpha.s.m <- alpha.b.m <- alpha.u.m <- alpha.v.m <- 0 alpha.n.s <- alpha.a.s <- 0.16 alpha.s.s <- alpha.b.s <- alpha.u.s <- alpha.v.s <- 0.25 if ("alpha.n.m" %in% names(re.values)) {alpha.n.m <- re.values[['alpha.n.m']]} if ("alpha.n.s" %in% names(re.values)) {alpha.n.s <- re.values[['alpha.n.s']]} if ("alpha.a.m" %in% names(re.values)) {alpha.a.m <- re.values[['alpha.a.m']]} if ("alpha.a.s" %in% names(re.values)) {alpha.a.s <- re.values[['alpha.a.s']]} if ("alpha.s.m" %in% names(re.values)) {alpha.s.m <- re.values[['alpha.s.m']]} if ("alpha.s.s" %in% names(re.values)) {alpha.s.s <- re.values[['alpha.s.s']]} if ("alpha.b.m" %in% names(re.values)) {alpha.b.m <- re.values[['alpha.b.m']]} if ("alpha.b.s" %in% names(re.values)) {alpha.b.s <- re.values[['alpha.b.s']]} if ("alpha.u.m" %in% names(re.values)) {alpha.u.m <- re.values[['alpha.u.m']]} if ("alpha.u.s" %in% names(re.values)) {alpha.u.s <- re.values[['alpha.u.s']]} if ("alpha.v.m" %in% names(re.values)) {alpha.v.m <- re.values[['alpha.v.m']]} if ("alpha.v.s" %in% names(re.values)) {alpha.v.s <- re.values[['alpha.v.s']]} string3 <- sprintf( "pin <- exp(alpha.n)/(1+exp(alpha.n)+exp(alpha.a)) pia <- exp(alpha.a)/(1+exp(alpha.n)+exp(alpha.a)) pic <- 1-pia-pin # priors alpha.n ~ dnorm(%s, %s) alpha.a ~ dnorm(%s, %s) alpha.s ~ dnorm(%s, %s) alpha.b ~ dnorm(%s, %s) alpha.u ~ dnorm(%s, %s) alpha.v ~ dnorm(%s, %s) ", alpha.n.m, alpha.n.s, alpha.a.m, alpha.a.s, alpha.s.m, alpha.s.s, alpha.b.m, alpha.b.s, alpha.u.m, alpha.u.s, alpha.v.m, alpha.v.s) if(Ind[7]==1){ string2_0 <- "delta.n[i] <- delta.rho[1, i] delta.a[i] <- delta.rho[2, i] delta.rho[1:2, i] ~ dmnorm(c(0, 0), Omega.rho)" string4_0 <- "II[1,1] <- 1 II[2,2] <- 1 II[1,2] <- 0 II[2,1] <- 0 Omega.rho ~ dwish (II[,], 3) Sigma.rho <- inverse(Omega.rho) sigma.n <- Sigma.rho[1, 1] sigma.a <- Sigma.rho[2, 2] rho <- Sigma.rho[1, 2]" string2_1 <- string2_2 <- "" string4_1 <- string4_2 <- "" } else if (Ind[7]==0){ string2_0 <- string4_0 <- "" if(Ind[1]==1){ tau.n.h <- tau.n.r <- 2 if ("tau.n.h" %in% names(re.values)) {tau.n.h <- re.values[['tau.n.h']]} if ("tau.n.r" %in% names(re.values)) {tau.n.r <- re.values[['tau.n.r']]} string2_1 <- "delta.n[i] ~ dnorm(0, tau.n)" string4_1 <- sprintf( "tau.n ~ dgamma(%s, %s) sigma.n <- 1/sqrt(tau.n)", tau.n.h, tau.n.r) } else if (Ind[1]==0){ string2_1 <- "" string4_1 <- "" } if(Ind[2]==1){ tau.a.h <- tau.a.r <- 2 if ("tau.a.h" %in% names(re.values)) {tau.a.h <- re.values[['tau.a.h']]} if ("tau.a.r" %in% names(re.values)) {tau.a.r <- re.values[['tau.a.r']]} string2_2 <- "delta.a[i] ~ dnorm(0, tau.a)" string4_2 <- sprintf( "tau.a ~ dgamma(%s, %s) sigma.a <- 1/sqrt(tau.a)", tau.a.h, tau.a.r) } else if (Ind[2]==0){ string2_2 <- "" string4_2 <- "" } } if(Ind[3]==1){ tau.u.h <- tau.u.r <- 2 if ("tau.u.h" %in% names(re.values)) {tau.u.h <- re.values[['tau.u.h']]} if ("tau.u.r" %in% names(re.values)) {tau.u.r <- re.values[['tau.u.r']]} string2_3 <- "delta.u[i] ~ dnorm(0, tau.u)" string4_3 <- sprintf( "u1out <- phi(alpha.u/sqrt(1+sigma.u^2)) tau.u ~ dgamma(%s, %s) sigma.u <- 1/sqrt(tau.u)", tau.u.h, tau.u.r) } else if (Ind[3]==0){ string2_3 <- "" string4_3 <- "u1out <- phi(alpha.u)" } if(Ind[4]==1){ tau.v.h <- tau.v.r <- 2 if ("tau.v.h" %in% names(re.values)) {tau.v.h <- re.values[['tau.v.h']]} if ("tau.v.r" %in% names(re.values)) {tau.v.r <- re.values[['tau.v.r']]} string2_4 <- "delta.v[i] ~ dnorm(0, tau.v)" string4_4 <- sprintf( "v1out <- phi(alpha.v/sqrt(1+sigma.v^2)) CACE <- u1out-v1out tau.v ~ dgamma(%s, %s) sigma.v <- 1/sqrt(tau.v)", tau.v.h, tau.v.r) } else if (Ind[4]==0){ string2_4 <- "" string4_4 <- "v1out <- phi(alpha.v) CACE <- u1out-v1out" } if(Ind[5]==1){ tau.s.h <- tau.s.r <- 2 if ("tau.s.h" %in% names(re.values)) {tau.s.h <- re.values[['tau.s.h']]} if ("tau.s.r" %in% names(re.values)) {tau.s.r <- re.values[['tau.s.r']]} string2_5 <- "delta.s[i] ~ dnorm(0, tau.s)" string4_5 <- sprintf( "s1out <- ilogit(alpha.s/sqrt(1 + (16^2*3/(15^2*pi^2))*sigma.s^2)) tau.s ~ dgamma(%s, %s) sigma.s <- 1/sqrt(tau.s)", tau.s.h, tau.s.r) } else if (Ind[5]==0){ string2_5 <- "" string4_5 <- "s1out <- ilogit(alpha.s)" } if(Ind[6]==1){ tau.b.h <- tau.b.r <- 2 if ("tau.b.h" %in% names(re.values)) {tau.b.h <- re.values[['tau.b.h']]} if ("tau.b.r" %in% names(re.values)) {tau.b.r <- re.values[['tau.b.r']]} string2_6 <- "delta.b[i] ~ dnorm(0, tau.b) }" string4_6 <- sprintf( "b1out <- ilogit(alpha.b/sqrt(1 + (16^2*3/(15^2*pi^2))*sigma.b^2)) tau.b ~ dgamma(%s, %s) sigma.b <- 1/sqrt(tau.b) }", tau.b.h, tau.b.r) } else if (Ind[6]==0){ string2_6 <- " }" string4_6 <- "b1out <- ilogit(alpha.b) }" } modelstring <- paste(string2_0, string2_1, string2_2, string2_3, string2_4, string2_5, string2_6, string3, string4_0, string4_1, string4_2, string4_3, string4_4, string4_5, string4_6, sep="\n") return(modelstring) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/prior.meta.R
#' This function returns a partially complete prior string. Used internally - cannot #' be directly used. #' @title The function returns a custom string that specifies part of the model (single-study). #' @param re.values a list of parameter values for the random effects. It should contain the assignment for these #' parameters only: \code{n.m} and \code{n.s}, which refer to the mean and standard deviation used #' in the normal distribution estimation of \code{n}, as well as \code{a.m}, \code{a.s}, #' \code{alpha.s.m}, \code{alpha.s.s}, \code{alpha.b.m}, \code{alpha.b.s}, \code{alpha.u.m}, \code{alpha.u.s}, #' \code{alpha.v.m}, \code{alpha.v.s}. By default, this is an empty list, and all the mean are set to \code{0}, and #' \code{alpha.n.s = alpha.a.s = 0.16}, and \code{alpha.s.s = alpha.b.s = alpha.u.s = alpha.v.s = 0.25}. #' @return custom model string #' @export #' @examples #' model.string <- prior.study() prior.study <- function(re.values = list()){ n.m <- a.m <- alpha.s.m <- alpha.b.m <- alpha.u.m <- alpha.v.m <- 0 n.s <- a.s <- 0.16 alpha.s.s <- alpha.b.s <- alpha.u.s <- alpha.v.s <- 0.25 if ("n.m" %in% names(re.values)) {n.m <- re.values[['n.m']]} if ("n.s" %in% names(re.values)) {n.s <- re.values[['n.s']]} if ("a.m" %in% names(re.values)) {a.m <- re.values[['a.m']]} if ("a.s" %in% names(re.values)) {a.s <- re.values[['a.s']]} if ("alpha.s.m" %in% names(re.values)) {alpha.s.m <- re.values[['alpha.s.m']]} if ("alpha.s.s" %in% names(re.values)) {alpha.s.s <- re.values[['alpha.s.s']]} if ("alpha.b.m" %in% names(re.values)) {alpha.b.m <- re.values[['alpha.b.m']]} if ("alpha.b.s" %in% names(re.values)) {alpha.b.s <- re.values[['alpha.b.s']]} if ("alpha.u.m" %in% names(re.values)) {alpha.u.m <- re.values[['alpha.u.m']]} if ("alpha.u.s" %in% names(re.values)) {alpha.u.s <- re.values[['alpha.u.s']]} if ("alpha.v.m" %in% names(re.values)) {alpha.v.m <- re.values[['alpha.v.m']]} if ("alpha.v.s" %in% names(re.values)) {alpha.v.s <- re.values[['alpha.v.s']]} prior.string <- sprintf( "# priors n ~ dnorm(%s, %s) a ~ dnorm(%s, %s) alpha.s ~ dnorm(%s, %s) alpha.b ~ dnorm(%s, %s) alpha.u ~ dnorm(%s, %s) alpha.v ~ dnorm(%s, %s) }", n.m, n.s, a.m, a.s, alpha.s.m, alpha.s.s, alpha.b.m, alpha.b.s, alpha.u.m, alpha.u.s, alpha.v.m, alpha.v.s) return(prior.string) }
/scratch/gouwar.j/cran-all/cranData/BayesCACE/R/prior.study.R
#' @export #' #' @title Bayesian Analysis of Censored Regression Models Under Scale Mixture of Skew Normal Distributions #' #' @description \code{Bayes.CR} Propose a parametric fit for censored linear regression models based on #' SMSN distributions, from a Bayesian perspective. #' #' @param cc Vector of censoring indicators. For each observation: 0 if non-censored, 1 if censored. #' @param x Matrix or vector of covariates. #' @param y Vector of responses in case of right/left censoring. #' @param cens "left" for left censoring, "right" for right censoring. #' @param dist Distribution to be used: "Normal" for Normal model, "T" for Student-t model, #' "Slash" for slash model, "NormalC" for contaminated Normal model, "SN" for Skew-Normal model, #' "ST" for Skew-t model and "SSL" for Skew-Slash model. #' @param criteria "TRUE" or "FALSE". Indicates if model selection #' criteria (LPML, DIC, EAIC, EBIC and WAIC) should be computed. #' @param influence "TRUE" or "FALSE". Indicates if the divergence measures #' (KL divergence, J, L and Chi Distance) should be computed. #' @param spacing Should only be specified if at least one of "influence" or "criteria" is TRUE. #' This is the lag between observations of the final chain (after burn-in and thinning) used #' to compute these measures. If spacing=1, all the chain is used. #' @param prior Prior distribution to be used for the degrees of freedom under Student-t model: #' "Exp" for exponential distribution, "Jeffreys" for Jeffreys prior, "Unif" for Uniforme #' distribution and "Hierar" for Hierarchical prior (exponential with a parameter that follows a #' uniform distribution). Must be "NULL" for other models. #' @param hyper Value of hyperparameter for the exponential prior. #' Must not be provided in case of others prior distributions. #' @param n.thin Lag for posterior sample. #' @param burnin Burn-in for posterior sample. #' @param n.iter The number of iterations to be considered (before burnin and thinning). #' @param n.chains The number of chains to be considered. It must be less than 5. #' @param chain If "TRUE", all the posterior chains are stored for posterior analysis. #' #' @details Specification of the priors distributions is given in reference papers #' (Garay et. al 2013 and Cancho et. al 2010). See Gelman et. al for the difference between #' the two versions of WAIC criterion. Calculations under the Skew-slash model may take a while, #' as it involves numerical integrations - you may want to specify big values to "spacing" under #' this model. For the Contaminated Normal model, a observation y comes from a normal distribution #' with mean "x beta" and variance "sigma2/rho" with probabilty "nu" and comes from a normal #' distribution with mean "x beta" and variance "sigma2" with probability 1-"nu". #' #' @return \describe{ \item{Mean}{ Posterior mean for the parameters. } #' \item{Sd}{ Standard deviations for the parameters. } #' \item{HPD}{ HPD(95\%) interval for the parameters. } #' \item{LPML}{ Log-marginal pseudo likelihood for model selection. } #' \item{DIC}{ DIC criterion for model selection. } #' \item{EAIC}{ EAIC criterion for model selection. } #' \item{EBIC}{ EBIC criterion for model selection. } #' \item{WAIC1}{First version of Watanabe-Akaike information criterion. } #' \item{WAIC2}{Second version of Watanabe-Akaike information criterion. } } #' #' @seealso \code{\link{rSMSN}}, \code{\link{motorettes}} #' #' ##Load the data #' #' data(motorettes) #' #' attach(motorettes) #' #' ##Set design matrix #' #' x <- cbind(1,x) #' #' ##Fits a right censored normal model #' #' Normal <- Bayes.CR(cc,x,y,cens="right",dist="Normal",n.thin=10,burnin=200,n.iter=800, #' n.chains=1,chain="TRUE") Bayes.CR <- function(cc, x,y,cens="left",dist="Normal",criteria="FALSE",influence="FALSE",spacing="NULL",prior=NULL,hyper=NULL,n.thin=10,burnin=100,n.iter=2000,n.chains=2,chain="TRUE") { if(criteria == "TRUE" || influence == "TRUE"){ if(spacing == "NULL"){ stop("spacing must be specified if influence or criteria is TRUE") } } if(dist=="SSL") { print("Calculations may take a while due to numerical integrations. You may want to disable options criteria and/or influence or specify a big number to spacing") } type <- dist if(cens==1){cens <- "left"} if(cens==2){cens <- "right"} namesx <- ('x1') if(ncol(as.matrix(x))>1){ for(i in 2:ncol(as.matrix(x))){namesx <- cbind(namesx, paste("x",i," ",sep=""))} } if(n.chains > 4) stop("The number of chains must be less than 5") if(ncol(as.matrix(y)) > 1) stop("Only univariate linear regression supported!") if(ncol(as.matrix(cc)) > 1) stop("Only univariate linear regression supported!") if( length(y) != nrow(as.matrix(x)) ) stop("X variable does not have the same number of lines than y") if( (length(x) == 0) | (length(y) == 0) ) stop("All parameters must be provided.") if( (dist != "T") && (dist != "Normal") && (dist != "Slash") && (dist != "NormalC") && (dist != "SN") && (dist != "ST") && (dist != "SSL")) stop("Distribution family not supported. Check documentation!") if( (cens != "left") && (cens != "right")) stop("Censored type not supported. 'left' for left censoring and 'right' for right censoring.") if ((burnin >= n.iter)|| burnin < 1) { stop("Invalid burnin number") } if (!is.numeric(n.iter) || n.iter < 1) { stop("Invalid number of iterations") } if (n.thin >= n.iter) { stop("Invalid number of lag (n.thin) for posterior sample") } if(type == "T") { if(length(prior) == 0) stop("The nu prior must be provided.") if( (prior != "Exp") && (prior != "Jeffreys") && (prior != "Hierar") && (prior != "Unif")) stop("Prior distribution not supported. Check documentation.") if(prior == "Exp") { if(length(hyper) == 0) stop("The hyper parameter must be provided.") if(!is.numeric(hyper)) stop("Invalid value of hyper parameter") if(hyper<=0) stop("The hyper parameter must be positive.") } } M <- n.iter p <- ncol(as.matrix(x)) namespar <- colnames(x) colx <- ncol(as.matrix(x)) if(length(namespar)==0)namespar <- namesx[1:colx] if(dist == "Normal") { out <- GibbsTruncSMN(cc,y,x,n.iter,n.thin,burnin,type=type, cens=cens, prior, hyper, n.chains=n.chains) betas.f <- as.matrix(apply(out$beta,2,mean)) sigma2.f <- mean(out$sigma2) param <- rbind(betas.f,sigma2.f) se.betas <- as.matrix(apply(out$beta,2,sd)) se.sigma2 <- sd(out$sigma2) se <- rbind(se.betas,se.sigma2) HPD <- matrix(0,nrow=p,ncol=2) for (i in 1:p) { HPD[i,]<- hpd(out$beta[,i],alpha=0.05) } HPDS2 <- hpd(out$sigma2,alpha=0.05) HPDTot <- rbind(HPD,HPDS2) ver<-LogVerosCens(cc,y,apply(out$mu,2,mean),mean(out$sigma2),0,1,type=dist, cens=cens) if(n.chains>1) { RBeta <- Rhat1(out$beta,n.iter,burnin,n.chains,n.thin) Rsigma <- Rhat1(out$sigma2,n.iter,burnin,n.chains,n.thin) RhatFin <- rbind(RBeta,Rsigma) paramT <- round(cbind(param, se, HPDTot,RhatFin),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2)),c("Mean", "Sd", " HPD(95%)","","Rhat")) }else{ paramT <- round(cbind(param, se, HPDTot),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2)),c("Mean", "Sd", " HPD(95%)","")) } } if((dist == "T") | (dist == "Slash") ) { out <- GibbsTruncSMN(cc,y,x,n.iter,n.thin,burnin,type=type, cens=cens, prior, hyper, n.chains=n.chains) betas.f <- as.matrix(apply(out$beta,2,mean)) sigma2.f <- mean(out$sigma2) nu.f <- mean(out$nu) param <- rbind(betas.f,sigma2.f,nu.f) se.betas <- as.matrix(apply(out$beta,2,sd)) se.sigma2 <- sd(out$sigma2) se.nu <- sd(out$nu) se <- rbind(se.betas,se.sigma2,se.nu) HPD <- matrix(0,nrow=p,ncol=2) for (i in 1:p) { HPD[i,]<- hpd(out$beta[,i],alpha=0.05) } HPDS2 <- hpd(out$sigma2,alpha=0.05) HPDnu <- hpd(out$nu,alpha=0.05) HPDTot <- rbind(HPD,HPDS2,HPDnu) mu.f <- mean(out$mu) ver<-LogVerosCens(cc,y,apply(out$mu,2,mean),mean(out$sigma2),0,mean(out$nu),type=dist, cens=cens) if(n.chains>1) { RBeta <- Rhat1(out$beta,n.iter,burnin,n.chains,n.thin) Rsigma <- Rhat1(out$sigma2,n.iter,burnin,n.chains,n.thin) Rnu <- Rhat1(out$nu,n.iter,burnin,n.chains,n.thin) RhatFin <- rbind(RBeta,Rsigma,Rnu) paramT <- round(cbind(param, se, HPDTot,RhatFin),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(nu)),c("Mean", "Sd", " HPD(95%)","", "Rhat")) }else{ paramT <- round(cbind(param, se, HPDTot),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(nu)),c("Mean", "Sd", " HPD(95%)","")) } } if(dist=="NormalC") { out <- GibbsTruncSMN(cc,y,x,n.iter,n.thin,burnin,type=type, cens=cens, prior, hyper, n.chains=n.chains) betas.f <- as.matrix(apply(out$beta,2,mean)) sigma2.f <- mean(out$sigma2) nu.f <- mean(out$nu) rho.f <- mean(out$rho) param <- rbind(betas.f,sigma2.f,nu.f,rho.f) se.betas <- as.matrix(apply(out$beta,2,sd)) se.sigma2 <- sd(out$sigma2) se.nu <- sd(out$nu) se.rho <- sd(out$rho) se <- rbind(se.betas,se.sigma2,se.nu,se.rho) HPD <- matrix(0,nrow=p,ncol=2) for (i in 1:p) { HPD[i,]<- hpd(out$beta[,i],alpha=0.05) } HPDS2 <- hpd(out$sigma2,alpha=0.05) HPDnu <- hpd(out$nu,alpha=0.05) HPDrho <- hpd(out$rho,alpha=0.05) HPDTot <- rbind(HPD,HPDS2,HPDnu,HPDrho) ver<-LogVerosCens(cc,y,apply(out$mu,2,mean),mean(out$sigma2),0,c(mean(out$nu),mean(out$rho)),type=dist, cens=cens) if(n.chains>1) { RBeta <- Rhat1(out$beta,n.iter,burnin,n.chains,n.thin) Rsigma <- Rhat1(out$sigma2,n.iter,burnin,n.chains,n.thin) Rrho <- Rhat1(out$rho,n.iter,burnin,n.chains,n.thin) Rnu <- Rhat1(out$nu,n.iter,burnin,n.chains,n.thin) RhatFin <- rbind(RBeta,Rsigma,Rnu,Rrho) paramT <- round(cbind(param, se, HPDTot,RhatFin),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(nu),expression(rho)),c("Mean", "Sd", " HPD(95%)","", "Rhat")) }else{ paramT <- round(cbind(param, se, HPDTot),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(nu),expression(rho)),c("Mean", "Sd", " HPD(95%)","")) } } if(dist == "SN") { out <- Gibbs(y,x,cc,dist,cens,n.iter,burnin,n.thin,n.chains) betas.f <- as.matrix(apply(out$beta,2,mean)) sigma2.f <- mean(out$sigma2) lambda.f <- mean(out$lambda) param <- rbind(betas.f,sigma2.f,lambda.f) se.betas <- as.matrix(apply(out$beta,2,sd)) se.sigma2 <- sd(out$sigma2) se.lambda <- sd(out$lambda) se <- rbind(se.betas,se.sigma2,se.lambda) HPD <- matrix(0,nrow=p,ncol=2) for (i in 1:p) { HPD[i,]<- hpd(out$beta[,i],alpha=0.05) } HPDS2 <- hpd(out$sigma2,alpha=0.05) HPDlambda <- hpd(out$lambda,alpha=0.05) HPDTot <- rbind(HPD,HPDS2,HPDlambda) ver<-LogVerosCens(cc,y,apply(out$mu,2,mean),mean(out$sigma2),mean(out$lambda),0,type="SN",cens=cens) if(n.chains>1) { RBeta <- Rhat1(out$beta,n.iter,burnin,n.chains,n.thin) Rsigma <- Rhat1(out$sigma2,n.iter,burnin,n.chains,n.thin) Rlambda <- Rhat1(out$lambda,n.iter,burnin,n.chains,n.thin) RhatFin <- rbind(RBeta,Rsigma,Rlambda) paramT <- round(cbind(param, se, HPDTot,RhatFin),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(lambda)),c("Mean", "Sd", " HPD(95%)","", "Rhat")) }else{ paramT <- round(cbind(param, se, HPDTot),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(lambda)),c("Mean", "Sd", " HPD(95%)","")) } } if((dist == "ST") | (dist == "SSL")) { out <- Gibbs(y,x,cc,dist,cens,n.iter,burnin,n.thin,n.chains) betas.f <- as.matrix(apply(out$beta,2,mean)) sigma2.f <- mean(out$sigma2) lambda.f <- mean(out$lambda) nu.f <- mean(out$nu) param <- rbind(betas.f,sigma2.f,lambda.f,nu.f) se.betas <- as.matrix(apply(out$beta,2,sd)) se.sigma2 <- sd(out$sigma2) se.lambda <- sd(out$lambda) se.nu <- sd(out$nu) se <- rbind(se.betas,se.sigma2,se.lambda,se.nu) HPD <- matrix(0,nrow=p,ncol=2) for (i in 1:p) { HPD[i,]<- hpd(out$beta[,i],alpha=0.05) } HPDS2 <- hpd(out$sigma2,alpha=0.05) HPDlambda <- hpd(out$lambda,alpha=0.05) HPDnu <- hpd(out$nu,alpha=0.05) HPDTot <- rbind(HPD,HPDS2,HPDlambda,HPDnu) ver <- LogVerosCens(cc,y,apply(out$mu,2,mean),mean(out$sigma2),mean(out$lambda),mean(out$nu),type=dist,cens=cens) if(n.chains>1) { RBeta <- Rhat1(out$beta,n.iter,burnin,n.chains,n.thin) Rsigma <- Rhat1(out$sigma2,n.iter,burnin,n.chains,n.thin) Rlambda <- Rhat1(out$lambda,n.iter,burnin,n.chains,n.thin) Rnu <- Rhat1(out$nu,n.iter,burnin,n.chains,n.thin) RhatFin <- rbind(RBeta,Rsigma,Rlambda,Rnu) paramT <- round(cbind(param, se, HPDTot,RhatFin),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(lambda),expression(nu)),c("Mean", "Sd", " HPD(95%)","", "Rhat")) }else{ paramT <- round(cbind(param, se, HPDTot),digits=5) dimnames(paramT) <- list(c(namespar,expression(sigma^2),expression(lambda),expression(nu)),c("Mean", "Sd", " HPD(95%)","")) } } logver <- sum(log(ver)) cat('\n') cat('-------------------------------------------------------------\n') cat('Posterior mean(Mean), standard deviation(Sd) and HPD interval\n') cat('-------------------------------------------------------------\n') print(paramT) cat('-------------------------------------------------------------\n') cat('Log-likelihood') print(logver) cat('-------------------------------------------------------------\n') cat('\r \n') x <- as.matrix(x) param <- ncol(x) if(criteria=="TRUE") { if(influence=="FALSE") { crit <- criterios(cc,y,espac=spacing,cadeia=out,type=type, cens=cens, p=length(param),influence="FALSE") }else{ crit <- criterios(cc,y,espac=spacing,cadeia=out,type=type, cens=cens, p=length(param),influence="TRUE") KL <- crit$KL JDist <- crit$JDist LDist <- crit$LDist ChiDist <- crit$ChiDist } critFin <- c(crit$CPO, crit$DIC, crit$EAIC, crit$EBIC,crit$WAIC1,crit$WAIC2) critFin <- round(t(as.matrix(critFin)),digits=3) dimnames(critFin) <- list(c("Value"),c("LPML", "DIC", "EAIC","EBIC","WAIC1","WAIC2")) cat('\n') cat('Model selection criteria\n') cat('-------------------------------------------------------------\n') print(critFin) cat('-------------------------------------------------------------\n') cat('\r \n') }else{ if(influence=="TRUE") { crit <- criterios(cc,y,espac=spacing,cadeia=out,type=type, cens=cens, p=length(param),influence="TRUE") KL <- crit$KL JDist <- crit$JDist LDist <- crit$LDist ChiDist <- crit$ChiDist } } if(influence=="TRUE") { if(chain=="TRUE") { if(dist=="Normal") { return(list(beta=out$beta[,],sigma2=out$sigma2,KL=KL,JDist=JDist,LDist=LDist,ChiDist=ChiDist)) } if((dist == "T") | (dist == "Slash")) { return(list(beta=out$beta[,],sigma2=out$sigma2,nu=out$nu,KL=KL,JDist=JDist,LDist=LDist,ChiDist=ChiDist)) } if(dist=="NormalC") { return(list(beta=out$beta[,],sigma2=out$sigma2,nu=out$nu,rho=out$rho,KL=KL,JDist=JDist,LDist=LDist,ChiDist=ChiDist)) } if((dist == "ST") | (dist == "SSL")) { return(list(beta=out$beta[,],sigma2=out$sigma2,lambda=out$lambda,nu=out$nu,KL=KL,JDist=JDist,LDist=LDist,ChiDist=ChiDist)) } if(dist == "SN") { return(list(beta=out$beta[,],sigma2=out$sigma2,lambda=out$lambda,KL=KL,JDist=JDist,LDist=LDist,ChiDist=ChiDist)) } }else{ return(list(KL=KL,JDist=JDist,LDist=LDist,ChiDist=ChiDist)) } }else{ if(chain=="TRUE") { if(dist=="Normal") { return(list(beta=out$beta[,],sigma2=out$sigma2)) } if((dist == "T") | (dist == "Slash")) { return(list(beta=out$beta[,],sigma2=out$sigma2,nu=out$nu)) } if(dist=="NormalC") { return(list(beta=out$beta[,],sigma2=out$sigma2,nu=out$nu,rho=out$rho)) } if((dist == "ST") | (dist == "SSL")) { return(list(beta=out$beta[,],sigma2=out$sigma2,lambda=out$lambda,nu=out$nu)) } if(dist == "SN") { return(list(beta=out$beta[,],sigma2=out$sigma2,lambda=out$lambda)) } } } }
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/Bayes.CR.r
#' @title BayesCR: Bayesian Analysis of Censored Regression Models Under Scale Mixture of Skew Normal Distributions #' #' @description Propose a parametric fit for censored linear regression models based on SMSN distributions, from a Bayesian perspective. Also, generates SMSN random variables. #' #' @references #' Monique B. Massuia, Aldo M. Garay, Celso R. Cabral and Victor H. Lachos. "Bayesian analysis of censored linear regression models with scale mixtures of skew-normal distributions". Statistics and Its Interface, 2017, vol. 10, pages 425-439 #' #' @author #' Aldo M. Garay \email{[email protected]}, Monique B. Massuia \email{[email protected]}, #' Victor H. Lachos \email{[email protected]} and Eraldo B. Anjos Filho \email{[email protected]} #' #' Maintainer: Aldo M. Garay \email{[email protected]} #' #' @seealso \code{\link{Bayes.CR}}, \code{\link{rSMSN}}, \code{\link{motorettes}} #' #' @importFrom stats coefficients cov deriv dnorm dt integrate lm pnorm pt qnorm rbeta rbinom rlnorm rnorm rt runif sd var #' @importFrom utils setTxtProgressBar txtProgressBar #' @importFrom stats pgamma qgamma rgamma #' @import rootSolve #' @import truncdist #' @import mvtnorm #' @import mnormt #' #' @docType package #' @name BayesCR #' "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/BayesCR.R
Gibbs <- function(y, x, cc, distribution, cens, M, burnin, n.thin, n.chains) { n.iter <- M cad <- 0 set1 <- set <- c() n <- length(y) p <- ncol(x) Cont <- ceiling(M/10) M <- Cont * 10 if (cens == "right") { lower <- y upper <- rep(Inf, n) } if (cens == "left") { lower <- rep(-Inf, n) upper <- y } y1 <- y beta <- matrix(0, ncol = p, nrow = M * n.chains) delta <- matrix(0, ncol = 1, nrow = M * n.chains) tau <- matrix(0, ncol = 1, nrow = M * n.chains) q <- 1 nu <- matrix(0, ncol = 1, nrow = M * n.chains) u <- matrix(0, ncol = 1, nrow = n) t <- matrix(0, ncol = 1, nrow = n) gama <- matrix(0, ncol = 1, nrow = M * n.chains) media <- matrix(0, nrow = M * n.chains, ncol = n) mu.beta <- rep(0, p) sigma.beta <- 10 * diag(p) mu.delta <- 0 sigma.delta <- 10 a.tau <- 2.1 b.tau <- 3 if (distribution == "ST") { a.gamma <- 0.02 b.gamma <- 0.49 } if (distribution == "SSL") { a.gamma <- 0.02 b.gamma <- 0.9 } cat("% of iterations \n") while (cad < n.chains) { cad <- cad + 1 Lin <- n.iter * (cad - 1) W <- seq(Cont + Lin, n.iter * cad, Cont) z <- 1 reg <- lm(y1[cc == 0] ~ x[cc == 0, 1:p] - 1) beta[1 + Lin, ] <- as.vector(coefficients(reg), mode = "numeric") m1 <- mean(y1[cc == 0]) m2 <- mean((y1[cc == 0] - m1)^2) m3 <- mean((y1[cc == 0] - m1)^3) t <- rnorm(n, mean = 10, sd = 10) if (distribution == "SN") { u <- rep(1, n) k1 <- k2 <- k3 <- 1 } if (distribution == "ST") { nu[1 + Lin] <- 4.7 #nu[1 + Lin] <- 5.1 u <- rgamma(n, shape = 15, rate = 0.5) #shape=.1 rate=.01 k1 <- sqrt(nu[1 + Lin]/2) * gamma((nu[1 + Lin] - 1)/2)/gamma(nu[1 + Lin]/2) k2 <- (nu[1 + Lin]/2) * gamma((nu[1 + Lin] - 2)/2)/gamma(nu[1 + Lin]/2) k3 <- ((nu[1 + Lin]/2)^(3/2)) * gamma((nu[1 + Lin] - 3)/2)/gamma(nu[1 + Lin]/2) gama[1 + Lin] <- (a.gamma + b.gamma)/2 #0.25 } if (distribution == "SSL") { nu[1 + Lin] <- 4 u <- runif(n) k1 <- 2 * nu[1 + Lin]/(2 * nu[1 + Lin] - 1) k2 <- 2 * nu[1 + Lin]/(2 * nu[1 + Lin] - 2) k3 <- 2 * nu[1 + Lin]/(2 * nu[1 + Lin] - 3) gama[1 + Lin] <- (a.gamma + b.gamma)/2 } f.ini <- function(w) { s2.ini <- m2/(k2 - 2 * k1^2 * w^2/pi) m.ini <- m1 - k1 * sqrt(2/pi) * s2.ini * w p1 <- sqrt(s2.ini) * w * sqrt(2/pi) resp <- m3 - (m.ini^3 + p1 * (3 * m.ini^2 * k1 - k3 - 3 * s2.ini) + 3 * m.ini * k2 * s2.ini + 2 * p1^3) return(resp) } #d.ini <- uniroot.all(f = f.ini, interval = c(-1, 1), tol = .Machine$double.eps, #maxiter = 1e+07) #d.ini <- skewness(y1)/sqrt(1+(skewness(y1)^2)) d.ini = 0.5 f <- f.ini(d.ini) d.ini <- d.ini[abs(f.ini(d.ini)) == min(abs(f))] sigma2.ini <- m2/(k2 - 2 * k1^2 * d.ini^2/pi) delta[1 + Lin] <- d.ini * sqrt(sigma2.ini) tau[1 + Lin] <- (1 - d.ini^2) * sigma2.ini y <- y1 cat("\n") Fil <- 2 + Lin Col <- n.iter * cad for (k in Fil:Col) { if (distribution == "SN") { k1 <- 1 } if (distribution == "ST") { k1 <- sqrt(nu[k - 1]/2) * gamma((nu[k - 1] - 1)/2)/gamma(nu[k - 1]/2) } if (distribution == "SSL") { k1 <- nu[k - 1]/(nu[k - 1] - 0.5) } b1 <- (-sqrt(2/pi) * k1) mu <- x %*% beta[k - 1, ] mean.t <- (delta[k - 1]/(delta[k - 1]^2 + tau[k - 1])) * (y -mu + b1 * tau[k - 1]/delta[k - 1]) var.t <- tau[k - 1]/(u * (delta[k - 1]^2 + tau[k - 1])) t <- c() for(w in 1:n){ #t[w] <- TSMNgenerator(n = 1, mu = mean.t[w], sigma2 = var.t[w], lower = b1, #upper = Inf, dist = "Normal") if(distribution == "ST"){ if(mean.t[w] < b1){ #stop("In this case, use another distribution") } } t[w] <- rtrunc(1, "norm", a = b1, b = Inf, mean = mean.t[w], sd = sqrt(var.t[w])) } mean.y <- mu + delta[k - 1] * t var.y <- tau[k - 1]/u for (i in 1:n) { if (cc[i] == 1) { y[i] <- rtrunc(1, "norm", a = lower[i], b = upper[i], mean = mean.y[i], sd = sqrt(var.y[i])) } } x.ast <- sqrt(diag(u)) %*% x y.ast <- y * sqrt(u) t.ast <- t * sqrt(u) var.beta <- solve((t(x.ast) %*% x.ast/tau[k - 1]) + solve(sigma.beta)) ind <- lower.tri(var.beta) var.beta[ind] <- t(var.beta)[ind] mean.beta <- var.beta %*% (solve(sigma.beta) %*% mu.beta + (t(x.ast) %*% y.ast/tau[k - 1]) - (delta[k - 1] * t(x.ast) %*% t.ast/tau[k - 1])) beta[k, ] <- rmvnorm(1, mean = mean.beta, sigma = var.beta, method = "chol") mu <- x %*% beta[k, ] var.delta <- 1/(sum(u * t * t)/tau[k - 1] + 1/sigma.delta) mean.delta <- var.delta * (mu.delta/sigma.delta + (sum(u * t * (y - mu)))/tau[k - 1]) delta[k] <- rnorm(1, mean = mean.delta, sd = sqrt(var.delta)) shape.tau <- a.tau + 0.5 * n rate.tau <- b.tau + 0.5 * sum(u * (y - mu - delta[k] * t)^2) tau[k] <- 1/rgamma(1, shape = shape.tau, rate = rate.tau) media[k, ] <- mu - delta[k] * sqrt(2/pi) * k1 if (distribution == "ST") { A <- (y - mu - delta[k] * t)^2/tau[k] + (t - b1)^2 for (i in 1:n) { u[i] <- rgamma(1, shape = (0.5 * nu[k - 1] + 1), rate = ((nu[k - 1] + A[i])/2)) } gama[k] <- rtrunc(1, "gamma", a = a.gamma, b = b.gamma, shape = 2, scale = (1/nu[k - 1])) mh <- MHnuST(nu[k - 1], u, gama[k]) nu[k] <- mh$last } if (distribution == "SSL") { A <- (y - mu - delta[k] * t)^2/tau[k] + (t - b1)^2 for(i in 1:n){ #shape = (nu[k - 1] + 1.1) u[i] <- rtrunc(1, "gamma", a = 0.001, b = 1, shape = 5, scale = 1/(0.5 * A[i])) } gama[k] <- rtrunc(1, "gamma", a = a.gamma, b = b.gamma, shape = 2, scale = (1/nu[k - 1])) nu[k] <- rtrunc(1, "gamma", a = 1.001, b = Inf, shape = (n + 1), scale = 1/(gama[k] - sum(log(u)))) } if (k == W[z]) { z <- z + 1 BayCens(Fil, Col, k, cad) } } cat("\r") initial <- burnin set1 <- seq(initial + n.thin + n.iter * (cad - 1), n.iter * cad, n.thin) set <- c(set, set1) } lambda <- delta/sqrt(tau) sigma2 <- tau * (1 + lambda^2) if (distribution == "SN") { resposta <- list(beta = beta[set, ], sigma2 = sigma2[set], lambda = lambda[set], mu = media[set, ]) } else { resposta <- list(beta = beta[set, ], sigma2 = sigma2[set], lambda = lambda[set], nu = nu[set], mu = media[set, ]) } return(resposta) }
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/gibbs_assim.R
GibbsTruncSMN <- function(cc, y, x, n.iter, n.thin, burnin, type = "normal", cens = "1", prior = "Jeffreys", hyper = hyper, n.chains = n.chains) { n <- length(y) if (cens == "left") { cens <- "1" } if (cens == "right") { cens <- "2" } if (cens == "2") { lower <- y upper <- rep(Inf, n) } if (cens == "1") { lower <- rep(-Inf, n) upper <- y } cad <- 0 x <- as.matrix(x) p <- ncol(x) n <- nrow(x) sigma2 <- lambda <- Aux <- V <- rho <- matrix(0, n.iter * n.chains, 1) media <- matrix(0, n.iter * n.chains, n) beta <- matrix(0, n.iter * n.chains, p) y1 <- y mu0 <- matrix(0, p, 1) Sigma0 <- 1000 * diag(p) alfa1 <- 0.1 alfa2 <- 0.01 a <- r1 <- 0.02 b <- s1 <- 0.5 cat("% of iterations \n") if (type == "T") { U <- matrix(0, n.iter * n.chains, n) nu <- matrix(0, n.iter * n.chains, 1) set1 <- set <- c() while (cad < n.chains) { cad <- cad + 1 Cont <- ceiling(n.iter/10) n.iter <- Cont * 10 Lin <- n.iter * (cad - 1) W <- seq(Cont + Lin, n.iter * cad, Cont) reg <- lm(y ~ x[, 2:p]) z <- 1 lambda[1 + Lin] <- 1 beta[1 + Lin, ] <- as.vector(coefficients(reg), mode = "numeric") sigma2[1 + Lin] <- sum((y - x %*% (beta[1 + Lin, ]))^2)/(n - p) media[1 + Lin, ] <- x %*% (beta[1 + Lin, ]) U[1 + Lin, ] <- 1/rgamma(1, 1) nu[1 + Lin] <- 6 cat("\n") Fil <- 2 + Lin Col <- n.iter * cad for (j in Fil:Col) { for (i in 1:n) { if (cc[i] == 1) { y[i] <- rtrunc(1, "norm", a = lower[i], b = upper[i], mean = media[j - 1, i], sd = sqrt((U[j - 1, i])^(-1) * sigma2[j - 1])) } } sigma2[j] <- 1/rgamma(1, shape = alfa1 + n/2, rate = (sum(U[j - 1, ] * (y - media[j - 1, ])^2)/2 + alfa2)) ### Densid de sigma2/Resto xast <- sqrt(U[j - 1, ]) * x yast <- sqrt(U[j - 1, ]) * y SigmaA <- solve(solve(Sigma0) + t(xast) %*% (xast)/sigma2[j]) muA <- SigmaA %*% (solve(Sigma0) %*% mu0 + t(xast) %*% yast/sigma2[j]) beta[j, ] <- rmvnorm(1, muA, SigmaA) ### Densid de beta/Resto media[j, ] <- x %*% (beta[j, ]) meany2 <- (y - media[j, ])^2/sigma2[j - 1] par2gam <- (meany2 + nu[j - 1])/2 U[j, ] <- rgamma(n, nu[j - 1]/2 + 0.5, par2gam) ### Densid de U/Resto Aux[j] <- runif(1, 0, 1) V[j] <- pgamma(a, nu[j - 1]) + (pgamma(b, 2, nu[j - 1]) - pgamma(a, 2, nu[j - 1])) * Aux[j] lambda[j] <- qgamma(V[j], 2, nu[j - 1]) nu[j] <- MHnu(nu[j - 1], U[j, ], lambda[j], prior, hyper) ### Densid de Nu/Resto if (j == W[z]) { z <- z + 1 BayCens(Fil, Col, j, cad) } } cat("\r") initial <- burnin set1 <- seq(initial + n.thin + n.iter * (cad - 1), n.iter * cad, n.thin) set <- c(set, set1) } return(list(beta = beta[set, ], sigma2 = sigma2[set], U = U[set, ], nu = nu[set], mu = media[set, ])) } if (type == "Normal") { set1 <- set <- c() while (cad < n.chains) { cad <- cad + 1 Cont <- ceiling(n.iter/10) n.iter <- Cont * 10 Lin <- n.iter * (cad - 1) W <- seq(Cont + Lin, n.iter * cad, Cont) reg <- lm(y ~ x[, 2:p]) z <- 1 beta[1 + Lin, ] <- as.vector(coefficients(reg), mode = "numeric") sigma2[1 + Lin] <- sum((y - x %*% (beta[1 + Lin, ]))^2)/(n - p) media[1 + Lin, ] <- x %*% (beta[1 + Lin, ]) cat("\n") Fil <- 2 + Lin Col <- n.iter * cad for (j in Fil:Col) { for (i in 1:n) { if (cc[i] == 1) { y[i] <- rtrunc(1, "norm", a = lower[i], b = upper[i], mean = media[j - 1, i], sd = sqrt(sigma2[j - 1])) } } sigma2[j] <- 1/rgamma(1, alfa1 + n/2, rate = (sum((y - media[j - 1, ])^2)/2 + alfa2)) ### Densid de sigma2/Resto xast <- x yast <- y SigmaA <- solve(solve(Sigma0) + t(xast) %*% (xast)/sigma2[j]) muA <- SigmaA %*% (solve(Sigma0) %*% mu0 + t(xast) %*% yast/sigma2[j]) beta[j, ] <- rmvnorm(1, muA, SigmaA) ### Densidade de beta/Resto media[j, ] <- x %*% (beta[j, ]) if (j == W[z]) { z <- z + 1 BayCens(Fil, Col, j, cad) } } cat("\r") initial <- burnin set1 <- seq(initial + n.thin + n.iter * (cad - 1), n.iter * cad, n.thin) set <- c(set, set1) } return(list(beta = beta[set, ], sigma2 = sigma2[set], mu = media[set, ])) } if (type == "Slash") { U <- matrix(0, n.iter * n.chains, n) nu <- matrix(0, n.iter * n.chains, 1) set1 <- set <- c() while (cad < n.chains) { r1 <- 0.01 s1 <- 1 cad <- cad + 1 Cont <- ceiling(n.iter/10) n.iter <- Cont * 10 Lin <- n.iter * (cad - 1) W <- seq(Cont + Lin, n.iter * cad, Cont) W reg <- lm(y ~ x[, 2:p]) z <- 1 beta[1 + Lin, ] <- as.vector(coefficients(reg), mode = "numeric") sigma2[1 + Lin] <- sum((y - x %*% (beta[1 + Lin, ]))^2)/(n - p) media[1 + Lin, ] <- x %*% (beta[1 + Lin, ]) U[1 + Lin, ] <- rbeta(n, 1, 1) nu[1 + Lin] <- 1.5 cat("\n") Fil <- 2 + Lin Col <- n.iter * cad for (j in Fil:Col) { for (i in 1:n) { if (cc[i] == 1) { y[i] <- rtrunc(1, "norm", a = lower[i], b = upper[i], mean = media[j - 1, i], sd = sqrt((U[j - 1, i])^(-1) * sigma2[j - 1])) } } sigma2[j] <- 1/rgamma(1, alfa1 + n/2, rate = (sum(U[j - 1, ] * (y - media[j - 1, ])^2)/2 + alfa2)) ### Densid de sigma2/Resto xast <- sqrt(U[j - 1, ]) * x yast <- sqrt(U[j - 1, ]) * y SigmaA <- solve(solve(Sigma0) + t(xast) %*% (xast)/sigma2[j]) muA <- SigmaA %*% (solve(Sigma0) %*% mu0 + t(xast) %*% yast/sigma2[j]) beta[j, ] <- rmvnorm(1, muA, SigmaA) ### Densid de beta/Resto media[j, ] <- x %*% (beta[j, ]) meany2 <- (y - media[j, ])^2/sigma2[j - 1] par2gam <- (meany2)/2 for(i in 1:n){ U[j, i] <- rtrunc(1, "gamma", a = 0.001, b = 1, shape = nu[j - 1] + 0.5, scale = 1/par2gam[i]) ### Densid de U/Resto } rho[j] <- rtrunc(1, "gamma", a = r1, b = s1, shape = 2, scale = 1/nu[j - 1]) nu[j] <- rgamma(1, shape = n + 1, rate = rho[j] - sum(log(U[j, ]))) ### Densidade de Nu/Resto if (j == W[z]) { z <- z + 1 BayCens(Fil, Col, j, cad) } } cat("\r") initial <- burnin set1 <- seq(initial + n.thin + n.iter * (cad - 1), n.iter * cad, n.thin) set <- c(set, set1) } return(list(beta = beta[set, ], sigma2 = sigma2[set], U = U[set, ], nu = nu[set], mu = media[set, ])) } if (type == "NormalC") { U <- matrix(0, n.iter * n.chains, n) nu <- rho <- rho1 <- matrix(0, n.iter * n.chains, 1) p1 <- p2 <- ptot <- A <- matrix(0, n.iter * n.chains, n) set1 <- set <- c() while (cad < n.chains) { AuxCN <- matrix(0, n, 1) v0 <- s0 <- 2 v1 <- s1 <- 2 cad <- cad + 1 Cont <- ceiling(n.iter/10) n.iter <- Cont * 10 Lin <- n.iter * (cad - 1) W <- seq(Cont + Lin, n.iter * cad, Cont) W reg <- lm(y ~ x[, 2:p]) z <- 1 beta[1 + Lin, ] <- as.vector(coefficients(reg), mode = "numeric") sigma2[1 + Lin] <- sum((y - x %*% (beta[1 + Lin, ]))^2)/(n - p) media[1 + Lin, ] <- x %*% (beta[1 + Lin, ]) U[1 + Lin, ] <- 1 rho[1 + Lin] <- nu[1 + Lin] <- 0.4 cat("\n") Fil <- 2 + Lin Col <- n.iter * cad cont <- c() for (j in Fil:Col) { for (i in 1:n) { if (cc[i] == 1) { y[i] <- rtrunc(1, "norm", a = lower[i], b = upper[i], mean = media[j - 1, i], sd = sqrt((U[j - 1, i])^(-1) * sigma2[j - 1])) } } sigma2[j] <- 1/rgamma(1, alfa1 + n/2, rate = (sum(U[j - 1, ] * (y - media[j - 1, ])^2)/2 + alfa2)) ### Densid de sigma2/Resto xast <- sqrt(U[j - 1, ]) * x yast <- sqrt(U[j - 1, ]) * y SigmaA <- solve(solve(Sigma0) + t(xast) %*% (xast)/sigma2[j]) muA <- SigmaA %*% (solve(Sigma0) %*% mu0 + t(xast) %*% yast/sigma2[j]) beta[j, ] <- rmvnorm(1, muA, SigmaA) ### Densid de beta/Resto media[j, ] <- x %*% (beta[j, ]) meany2 <- (y - media[j, ])^2/sigma2[j - 1] par2gam <- (meany2)/2 p1[j, ] <- nu[j - 1] * sqrt(rho[j - 1]) * exp(-0.5 * rho[j - 1] * meany2) p2[j, ] <- (1 - nu[j - 1]) * exp(-0.5 * meany2) ptot[j, ] <- p1[j, ] + p2[j, ] A[j, ] <- p1[j, ]/ptot[j, ] AuxCN <- rbinom(n = n, size = 1, prob = A[j, ]) U[j, ] <- rho[j - 1] * AuxCN + (1 - AuxCN) ### Densid de U/Resto cont <- sum(U[j, ] == rho[j - 1]) nu[j] <- rbeta(1, v0 + cont, v1 + n - cont) ### Densid de Nu/Resto rho1[j] <- MHrhoCN(rho[j - 1], meany2, cc, sigma2[j], c(nu[j], rho[j - 1]), s0, s1, cens) rho[j] <- rho1[j]/(1 + rho1[j]) if (j == W[z]) { z <- z + 1 BayCens(Fil, Col, j, cad) } } cat("\r") initial <- burnin set1 <- seq(initial + n.thin + n.iter * (cad - 1), n.iter * cad, n.thin) set <- c(set, set1) } return(list(beta = beta[set, ], sigma2 = sigma2[set], U = U[set, ], nu = nu[set], rho = rho[set], mu = media[set, ])) } }
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/gibbs_sim.r
#' Accelerated Life Tests On Electrical Insulation #' #' Accelerated life tests on electrical insulation in motorettes with censoring times. #' #' @format A data frame with 40 observed times of life tests on electrical insulation in motorettes at #' four different temperatures (150C, 170c, 190c and 200c). y corresponds to log10 of the failure time #' (or end of study time, in case of right censored observations), x corresponds to (100/(temperature + 273.2)) #' and cc is a indicator of censoring (1 if censored, 0 if not). #' #' @source Tan, M., Tian, G. L. and Ng, K. W. (2009). Bayesian Missing Data Problems: EM, Data Augmentation and Noniterative Computation. #' "motorettes"
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/motorettes.R
#' @export #' #' @title Generate SMSN Random Variables #' #' @description \code{rSMSN} Generate random variables with one of the following distributions: #' Normal, Student-t, Contaminated Normal, Slash, Skew-Normal, Skew-t and Skew-Slash. #' #' @param n Number of observations to be generated. #' @param mu Location parameter. #' @param sigma2 Scale parameter. #' @param lambda Shape parameter (control skewness). Only must be provided for Skew-Normal, #' Skew-t and Skew-Slash distributions. #' @param nu Degree of freedom. Must not be provided for Normal and Skew-Normal distribution. #' Must be a vector of length 2 for Contaminated-Normal distribution. #' @param dist Distribution to be used: "Normal" for Normal model, "T" for Student-t model, #' "Slash" for slash model, "NormalC" for contaminated Normal model, "SN" for Skew-Normal model, #' "ST" for Skew-t model and "SSL" for Skew-Slash model. #' #' @details If Y follows a Contaminated Normal model, than a observation y comes from a normal #' distribution with mean "mu"" and variance "sigma2/rho" with probabilty "nu" #' and comes from a normal distribution with mean "mu" and variace "sigma2" #' with probability "1-nu". #' #' @seealso \code{\link{Bayes.CR}}, \code{\link{motorettes}} #' #' @examples # Generate a sample with 100 observations of a symmetric Student-t distribution #' #' sample <- rSMSN(n=100,mu=5,sigma2=2,lambda=0,nu=3,dist="T") rSMSN <- function(n, mu, sigma2, lambda, nu, dist) { if (dist == "T" | dist == "Slash" | dist == "NormalC" | dist == "ST" | dist == "SSL") { if (length(nu) == 0) stop("nu must be provided.") } if (dist == "NormalC") { if (length(nu) != 2) stop("nu must be a vector of size 2.") } if (dist == "SN" | dist == "SSL" | dist == "ST") { if (length(lambda) == 0) stop("lambda must be provided.") } q <- length(beta) if (dist == "Normal") { y <- mu + rnorm(n, 0, sd = sqrt(sigma2)) } if (dist == "T") { y <- mu + sqrt(sigma2) * rt(n, df = nu) } if (dist == "NormalC") { p <- runif(n) u <- rep(1, n) u[p < nu[1]] <- nu[2] y <- mu + rnorm(n, mean = 0, sd = sqrt(sigma2))/sqrt(u) } if (dist == "Slash") { u <- rbeta(n = n, shape1 = nu, shape2 = 1) y <- mu + rnorm(n, mean = 0, sd = sqrt(sigma2))/sqrt(u) } if (dist == "SN" | dist == "ST" | dist == "SSL") { y <- rep(0, n) if (dist == "SN") { u <- rep(1, n) } if (dist == "ST") { u <- rgamma(n = n, shape = nu/2, rate = nu/2) } if (dist == "SSL") { u <- rbeta(n = n, shape1 = nu, shape2 = 1) } deltinha <- lambda/sqrt(1 + lambda^2) Delta <- sqrt(sigma2) * deltinha tau <- sigma2 * (1 - deltinha^2) T1 <- rnorm(n) T0 <- rnorm(n) T <- abs(T0) * u^(-1/2) y <- mu + Delta * T + u^(-1/2) * sqrt(tau) * T1 } return(y) }
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/rSMSN.R
LogVerosCens <- function(cc, y, mu, sigmae, lambda, nu, type = "Normal", cens = "right") { if (cens == "left") { cens <- "1" } if (cens == "right") { cens <- "2" } m <- length(y) ver <- matrix(0, m, 1) sigma2 <- sigmae censtype <- cens auxy <- matrix(0, m, 1) if (type == "Normal") { auxy <- (y - mu)/sqrt(sigmae) if (cens == "2") { ver[cc == 0] <- dnorm(auxy[cc == 0])/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- pnorm(-auxy[cc == 1]) } } if (cens == "1") { ver[cc == 0] <- dnorm(auxy[cc == 0])/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- pnorm(auxy[cc == 1]) } } } if (type == "T") { auxy <- (y - mu)/sqrt(sigmae) if (cens == "2") { ver[cc == 0] <- dt(auxy[cc == 0], df = nu)/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- pt(-auxy[cc == 1], df = nu) } } if (cens == "1") { ver[cc == 0] <- dt(auxy[cc == 0], df = nu)/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- pt(auxy[cc == 1], df = nu) } } } if (type == "Slash") { auxy <- (y - mu)/sqrt(sigmae) if (cens == "2") { ver[cc == 0] <- dSlash(auxy[cc == 0], 0, 1, nu)/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- AcumSlash(-auxy[cc == 1], 0, 1, nu) } } if (cens == "1") { ver[cc == 0] <- dSlash(auxy[cc == 0], 0, 1, nu)/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- AcumSlash(auxy[cc == 1], 0, 1, nu) } } } if (type == "NormalC") { auxy <- (y - mu)/sqrt(sigmae) if (cens == "2") { ver[cc == 0] <- dNormalC(auxy[cc == 0], 0, 1, nu)/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- AcumNormalC(-auxy[cc == 1], 0, 1, nu) } } if (cens == "1") { ver[cc == 0] <- dNormalC(auxy[cc == 0], 0, 1, nu)/sqrt(sigmae) if (sum(cc) > 0) { ver[cc == 1] <- AcumNormalC(auxy[cc == 1], 0, 1, nu) } } } if (type == "SN") { ver[cc == 0] <- pdfSNI(y[cc == 0], mu[cc == 0], sigma2, lambda, 0, type = "SN") if (cens == 1) { if (sum(cc) > 0) { ver[cc == 1] <- cdfSNI(y[cc == 1], mu[cc == 1], sigma2, lambda, 0, type = "SN") } } if (cens == "2") { if (sum(cc) > 0) { ver[cc == 1] <- (1 - cdfSNI(y[cc == 1], mu[cc == 1], sigma2, lambda, 0, type = "SN")) } } } if (type == "ST") { ver[cc == 0] <- pdfSNI(y[cc == 0], mu[cc == 0], sigma2, lambda, nu, type = "ST") if (cens == "1") { if (sum(cc) > 0) { ver[cc == 1] <- cdfSNI(y[cc == 1], mu[cc == 1], sigma2, lambda, nu, type = "ST") } } if (cens == "2") { if (sum(cc) > 0) { ver[cc == 1] <- 1 - cdfSNI(y[cc == 1], mu[cc == 1], sigma2, lambda, nu, type = "ST") } } } if (type == "SSL") { for (j in 1:m) { slash <- cdfSNI(y[j], mu[j], sigma2, lambda, nu, type = "SSL") if (cc[j] == 0) { ver[j] <- slash$pdf } if (sum(cc) > 0) { if (cc[j] == 1) { if (cens == "1") { ver[j] <- slash$cdf } if (cens == "2") { ver[j] <- 1 - slash$cdf } } } } } return(ver) } criterios <- function(cc, y, espac = 20, cadeia, type = "T", cens = "2", p = p, influence) { m <- length(y) if (type == "Normal") { ver <- LogVerosCens(cc, y, apply(cadeia$mu, 2, mean), mean(cadeia$sigma2), 0, 1, type = type, cens = cens) n.iter <- length(cadeia$sigma2)/espac iter <- n.iter Loglikaux <- matrix(0, m, n.iter) CPOaux <- matrix(0, m, n.iter) for (k in 1:n.iter) { i <- espac * k fss <- cadeia$mu[k, ] sigma2es <- cadeia$sigma2[k] Loglikaux[, k] <- LogVerosCens(cc, y, fss, sigma2es, 0, 50, type = type, cens = cens) CPOaux[, k] <- 1/Loglikaux[, k] } Np <- p + 1 } if (type == "T") { ver <- LogVerosCens(cc, y, apply(cadeia$mu, 2, mean), mean(cadeia$sigma2), 0, mean(cadeia$nu), type = type, cens = cens) n.iter <- length(cadeia$sigma2)/espac iter <- n.iter Loglikaux <- matrix(0, m, n.iter) CPOaux <- matrix(0, m, n.iter) for (k in 1:n.iter) { i <- espac * k fss <- cadeia$mu[k, ] sigma2es <- cadeia$sigma2[k] nuss <- cadeia$nu[k] Loglikaux[, k] <- LogVerosCens(cc, y, fss, sigma2es, 0, nuss, type = type, cens = cens) CPOaux[, k] <- 1/Loglikaux[, k] } Np <- p + 2 } if (type == "Slash") { ver <- LogVerosCens(cc, y, apply(cadeia$mu, 2, mean), mean(cadeia$sigma2), 0, mean(cadeia$nu), type = type, cens = cens) n.iter <- length(cadeia$sigma2)/espac iter <- n.iter Loglikaux <- matrix(0, m, n.iter) CPOaux <- matrix(0, m, n.iter) for (k in 1:n.iter) { i <- espac * k fss <- cadeia$mu[k, ] sigma2es <- cadeia$sigma2[k] nuss <- cadeia$nu[k] Loglikaux[, k] <- LogVerosCens(cc, y, fss, sigma2es, 0, nuss, type = type, cens = cens) CPOaux[, k] <- 1/Loglikaux[, k] } Np <- p + 2 } if (type == "NormalC") { ver <- LogVerosCens(cc, y, apply(cadeia$mu, 2, mean), mean(cadeia$sigma2), 0, c(mean(cadeia$nu), mean(cadeia$rho)), type = type, cens = cens) n.iter <- length(cadeia$sigma2)/espac iter <- n.iter Loglikaux <- matrix(0, m, n.iter) CPOaux <- matrix(0, m, n.iter) for (k in 1:n.iter) { i <- espac * k fss <- cadeia$mu[k, ] sigma2es <- cadeia$sigma2[k] nuss <- c(cadeia$nu[k], cadeia$rho[k]) Loglikaux[, k] <- LogVerosCens(cc, y, fss, sigma2es, 0, nuss, type = type, cens = cens) CPOaux[, k] <- 1/Loglikaux[, k] } Np <- p + 3 } if (type == "SN") { ver <- LogVerosCens(cc, y, apply(cadeia$mu, 2, mean), mean(cadeia$sigma2), mean(cadeia$lambda), 0, type = "SN", cens = cens) n.iter <- length(cadeia$sigma2)/espac iter <- n.iter Loglikaux <- matrix(0, m, n.iter) CPOaux <- matrix(0, m, n.iter) for (k in 1:n.iter) { i <- espac * k fss <- cadeia$mu[k, ] sigma2es <- cadeia$sigma2[k] lambdas <- cadeia$lambda[k] Loglikaux[, k] <- LogVerosCens(cc, y, fss, sigma2es, lambdas, 50, type = "SN", cens = cens) CPOaux[, k] <- 1/Loglikaux[, k] } Np <- p + 2 } if (type == "ST") { ver <- LogVerosCens(cc, y, apply(cadeia$mu, 2, mean), mean(cadeia$sigma2), mean(cadeia$lambda), mean(cadeia$nu), type = "ST", cens = cens) n.iter <- length(cadeia$sigma2)/espac iter <- n.iter Loglikaux <- matrix(0, m, iter) CPOaux <- matrix(0, m, iter) for (k in 1:iter) { i <- espac * k fss <- cadeia$mu[k, ] sigma2es <- cadeia$sigma2[k] lambdas <- cadeia$lambda[k] nuss <- cadeia$nu[k] Loglikaux[, k] <- LogVerosCens(cc, y, fss, sigma2es, lambdas, nuss, type = "ST", cens = cens) CPOaux[, k] <- 1/Loglikaux[, k] } Np <- p + 3 } if (type == "SSL") { ver <- LogVerosCens(cc, y, apply(cadeia$mu, 2, mean), mean(cadeia$sigma2), mean(cadeia$lambda), mean(cadeia$nu), type = "SSL", cens = cens) n.iter <- length(cadeia$sigma2)/espac iter <- n.iter Loglikaux <- matrix(0, m, iter) CPOaux <- matrix(0, m, iter) for (k in 1:iter) { i <- espac * k fss <- cadeia$mu[k, ] sigma2es <- cadeia$sigma2[k] lambdas <- cadeia$lambda[k] nuss <- cadeia$nu[k] Loglikaux[, k] <- LogVerosCens(cc, y, fss, sigma2es, lambdas, nuss, type = "SSL", cens = cens) CPOaux[, k] <- 1/Loglikaux[, k] } Np <- p + 3 } mean.log.p <- apply(log(Loglikaux), 1, mean) mean.p <- apply(Loglikaux, 1, mean) var.log <- matrix(0, m, iter) for (k in 1:iter) { var.log[, k] <- (log(Loglikaux[, k]) - mean.log.p)^2 } var.log.p <- apply(var.log, 1, sum)/(iter - 1) CPO <- sum(log(1/(apply(CPOaux, 1, mean)))) pdic <- 2 * (sum(log(ver)) - sum(mean.log.p)) DIC <- 2 * pdic - 2 * sum(log(ver)) EAIC <- -2 * sum(log(ver)) + 2 * Np EBIC <- -2 * sum(log(ver)) + log(m) * Np WAIC1 <- -2 * (sum(log(mean.p)) - 2 * sum(log(mean.p) - mean.log.p)) WAIC2 <- -2 * (sum(log(mean.p)) - sum(var.log.p)) if (influence == "FALSE") { return(list(CPO = CPO, DIC = DIC, EAIC = EAIC, EBIC = EBIC, WAIC1 = WAIC1, WAIC2 = WAIC2)) } else { aa <- exp(log(apply(CPOaux, 1, mean)) + log(Loglikaux)) IL <- apply(log(aa), 1, mean) JL <- apply((aa - 1) * log(aa), 1, mean) LL <- apply(abs(aa - 1), 1, mean) CHL <- apply((aa - 1)^2, 1, mean) return(list(CPO = CPO, DIC = DIC, EAIC = EAIC, EBIC = EBIC, WAIC1 = WAIC1, WAIC2 = WAIC2, KL = IL, JDist = JL, LDist = LL, ChiDist = CHL)) } } BayCens <- function(start.iter, end.iter, j, cad, ...) { pb <- txtProgressBar(start.iter, end.iter, initial = start.iter, style = 3, width = 10, char = ifelse((cad == 1 || cad == 3), "+", "*")) Sys.sleep(0.5) setTxtProgressBar(pb, j) cat("\r") cat("\r") }
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/utility.R
cdfSNI <- function(x, mu, sigma2, lambda, nu, type = "SN") { n <- length(x) resp <- matrix(0, n, 1) if (type == "Normal") { resp <- pnorm((x - mu)/sqrt(sigma2)) return(resp) } if (type == "T") { resp <- pt((x - mu)/sqrt(sigma2), df = nu) return(resp) } if (type == "SN") { delta <- lambda/sqrt(1 + lambda^2) SIGMA <- matrix(c(sigma2, -delta * sqrt(sigma2), -delta * sqrt(sigma2), 1), byrow = TRUE, ncol = 2, nrow = 2) if (length(mu) == 1) { MU <- cbind(rep(mu, n), 0) } if (length(mu) == n) { MU <- cbind(mu, 0) } Y <- cbind(x, 0) for (i in 1:n) { resp[i] <- 2 * pmnorm(x = Y[i, ], mean = MU[i, ], varcov = SIGMA) } return(resp) } if (type == "ST") { delta <- lambda/sqrt(1 + lambda^2) SIGMA <- matrix(c(sigma2, -delta * sqrt(sigma2), -delta * sqrt(sigma2), 1), byrow = TRUE, ncol = 2, nrow = 2) if (length(mu) == 1) { MU <- cbind(rep(mu, n), 0) } if (length(mu) == n) { MU <- cbind(mu, 0) } Y <- cbind(x, 0) nu <- round(nu) for (i in 1:n) { resp[i] <- 2 * pmt(x = Y[i, ], mean = MU[i, ], S = SIGMA, df = nu) } return(resp) } if (type == "SSL") { cdf <- function(y) { f <- function(u) 2 * nu * u^(nu - 1) * dnorm(y, mu, sqrt(u^(-1) * sigma2)) * pnorm(u^(1/2) * lambda * (y - mu)/sqrt(sigma2)) cdf <- integrate(Vectorize(f), 0, 1)$value } densidade <- as.numeric(cdf(x)) resp <- as.numeric(integrate(Vectorize(cdf), -Inf, x)$value) return(list(pdf = densidade, cdf = resp)) } } pdfSNI <- function(y, mu, sigma2, lambda, nu, type = "SN") { resp <- matrix(0, length(y), 1) if (type == "Normal") { resp <- dnorm((y - mu)/sqrt(sigma2))/sqrt(sigma2) } if (type == "T") { resp <- dt((y - mu)/sqrt(sigma2), df = nu)/sqrt(sigma2) } if (type == "SN") { resp <- 2 * dnorm((y - mu)/sqrt(sigma2)) * pnorm(lambda * (y - mu)/sqrt(sigma2))/sqrt(sigma2) } if (type == "ST") { z = (y - mu)/sqrt(sigma2) resp = 2 * dt(z, df = nu) * pt(sqrt(nu + 1) * lambda * z/sqrt(nu + z^2), df = nu + 1)/sqrt(sigma2) } if (type == "SSL") { f <- function(u) { 2 * nu * u^(nu - 1) * dnorm(y, mu, sqrt(u^(-1) * sigma2)) * pnorm(u^(1/2) * lambda * (y - mu)/sqrt(sigma2)) } resp <- integrate(Vectorize(f), 0, 1)$value } return(resp) } dt.ls <- function(x, loc, sigma2 = 1, shape = 1, nu = 4) { d <- (x - loc)/sqrt(sigma2) dens <- 2 * dt(d, df = nu) * pt(sqrt((1 + nu)/(d^2 + nu)) * d * shape, 1 + nu)/sqrt(sigma2) return(dens) } MHnuST <- function(last, U, lambda) { gHierar <- function(nu, U, lambda) { n <- length(U) ff <- (-lambda * nu) + 0.5 * n * nu * log(nu/2) + (0.5 * nu) * sum(log(U) - U) - n * log(gamma(nu/2)) return(ff) } n <- length(U) Fonseca1 <- deriv(~(-lambda * nu) + 0.5 * n * nu * log(nu/2) - n * log(gamma(nu/2)), c("nu"), function(nu) { }, hessian = TRUE) Fonseca2 <- deriv(~(0.5 * nu) * (log(U) - U), c("nu"), function(U, nu) { }, hessian = TRUE) aux1 <- Fonseca1(last) aux2 <- Fonseca2(U, last) q1 <- attr(aux1, "gradient")[1] + sum(attr(aux2, "gradient")) q2 <- attr(aux1, "hessian")[1] + sum(attr(aux2, "hessian")) aw <- last - q1/q2 bw <- max(0.001, -1/q2) cand <- rtrunc(1, spec = "norm", a = 2.1, b = 50, mean = aw, sd = sqrt(bw)) alfa <- (exp(gHierar(cand, U, lambda))/exp(gHierar(last, U, lambda))) * (dtrunc(last, spec = "norm", a = 2.1, b = 50, mean = aw, sd = sqrt(bw))/dtrunc(cand, spec = "norm", a = 2.1, b = 50, mean = aw, sd = sqrt(bw))) ifelse(runif(1) < min(alfa, 1), last <- cand, last <- last) rejeitou <- 0 ifelse(runif(1) < min(alfa, 1), rejeitou <- 0, rejeitou <- 1) return(list(last = last, rejeitou = rejeitou)) }
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/utility_assim.R
AcumSlash <- function(y, mu, sigma2, nu) { Acum <- z <- vector(mode = "numeric", length = length(y)) z <- (y - mu)/sqrt(sigma2) for (i in 1:length(y)) { f1 <- function(u) { nu * u^(nu - 1) * pnorm(z[i] * sqrt(u)) } Acum[i] <- integrate(f1, 0, 1)$value } return(Acum) } AcumNormalC <- function(y, mu, sigma2, nu) { Acum <- vector(mode = "numeric", length = length(y)) eta <- nu[1] gama <- nu[2] Acum <- eta * pnorm(y, mu, sqrt(sigma2/gama)) + (1 - eta) * pnorm(y, mu, sqrt(sigma2)) return(Acum) } dSlash <- function(y, mu, sigma2, nu) { resp <- z <- vector(mode = "numeric", length = length(y)) z <- (y - mu)/sqrt(sigma2) for (i in 1:length(y)) { f1 <- function(u) { nu * u^(nu - 0.5) * dnorm(z[i] * sqrt(u))/sqrt(sigma2) } resp[i] <- integrate(f1, 0, 1)$value } return(resp) } dNormalC <- function(y, mu, sigma2, nu) { Acum <- vector(mode = "numeric", length = length(y)) eta <- nu[1] gama <- nu[2] Acum <- eta * dnorm(y, mu, sqrt(sigma2/gama)) + (1 - eta) * dnorm(y, mu, sqrt(sigma2)) return(Acum) } verosCN <- function(auxf, cc, cens, sigma2, nu) { auxf1 <- sqrt(auxf) if (cens == "1") { ver1 <- (sum(log(dNormalC(auxf1[cc == 0], 0, 1, nu)/sqrt(sigma2))) + sum(log(AcumNormalC(auxf1[cc == 1], 0, 1, nu)))) } if (cens == "2") { ver1 <- (sum(log(dNormalC(auxf1[cc == 0], 0, 1, nu)/sqrt(sigma2))) + sum(log(AcumNormalC(auxf1[cc == 1], 0, 1, nu)))) } return(ver1) } Rhat1 <- function(param, n.iter, burnin, n.chains, n.thin) { param <- as.matrix(param) efect <- (n.iter - burnin)/n.thin p <- ncol(param) mat <- matrix(param, nrow = efect, ncol = n.chains * p) rhat <- matrix(0, nrow = p, ncol = 1) for (i in 1:p) { l1 <- 2 * (i - 1) + 1 c1 <- 2 * i rhat[i, 1] <- Rhat(mat[, l1:c1]) } return(rhat = rhat) } Rhat <- function(mat) { m <- ncol(mat) n <- nrow(mat) b <- apply(mat, 2, mean) B <- sum((b - mean(mat))^2) * n/(m - 1) w <- apply(mat, 2, var) W <- mean(w) s2hat <- (n - 1)/n * W + B/n Vhat <- s2hat + B/m/n covWB <- n/m * (cov(w, b^2) - 2 * mean(b) * cov(w, b)) varV <- (n - 1)^2/n^2 * var(w)/m + (m + 1)^2/m^2/n^2 * 2 * B^2/(m - 1) + 2 * (m - 1) * (n - 1)/m/n^2 * covWB df <- 2 * Vhat^2/varV R <- sqrt((df + 3) * Vhat/(df + 1)/W) return(R) } hpd <- function(x, alpha) { n <- length(x) m <- max(1, ceiling(alpha * n)) y <- sort(x) a <- y[1:m] b <- y[(n - m + 1):n] i <- order(b - a)[1] structure(c(a[i], b[i]), names = c("Lower Bound", "Upper Bound")) } MHnu <- function(last, U, lambda, prior = "Jeffreys", hyper) { n <- length(U) if (prior == "Jeffreys") { gJeffreys <- function(nu, U) { n <- length(U) ff <- log(sqrt(nu/(nu + 3)) * sqrt(trigamma(nu/2) - trigamma((nu + 1)/2) - 2 * (nu + 3)/((nu) * (nu + 1)^2))) + 0.5 * n * nu * log(nu/2) + (0.5 * nu) * sum(log(U) - U) - n * log(gamma(nu/2)) return(ff) } Fonseca1 <- deriv(~log(sqrt(nu/(nu + 3)) * sqrt(trigamma(nu/2) - trigamma((nu + 1)/2) - 2 * (nu + 3)/((nu) * (nu + 1)^2))) + 0.5 * n * nu * log(nu/2) - n * log(gamma(nu/2)), c("nu"), function(nu) { }, hessian = TRUE) Fonseca2 <- deriv(~(0.5 * nu) * (log(U) - U), c("nu"), function(U, nu) { }, hessian = TRUE) aux1 <- Fonseca1(last) aux2 <- Fonseca2(U, last) q1 <- attr(aux1, "gradient")[1] + sum(attr(aux2, "gradient")) q2 <- attr(aux1, "hessian")[1] + sum(attr(aux2, "hessian")) aw <- last - q1/q2 bw <- max(0.001, -1/q2) cand <- rtrunc(1, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw)) alfa <- (exp(gJeffreys(cand, U))/exp(gJeffreys(last, U))) * (dtrunc(last, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))/dtrunc(cand, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))) } if (prior == "Exp") { gExp <- function(nu, U, hyper) { n <- length(U) ff <- (-hyper * nu) + 0.5 * n * nu * log(nu/2) + (0.5 * nu) * sum(log(U) - U) - n * log(gamma(nu/2)) return(ff) } Fonseca1 <- deriv(~(-hyper * nu) + 0.5 * n * nu * log(nu/2) - n * log(gamma(nu/2)), c("nu"), function(nu) { }, hessian = TRUE) Fonseca2 <- deriv(~(0.5 * nu) * (log(U) - U), c("nu"), function(U, nu) { }, hessian = TRUE) aux1 <- Fonseca1(last) aux2 <- Fonseca2(U, last) q1 <- attr(aux1, "gradient")[1] + sum(attr(aux2, "gradient")) q2 <- attr(aux1, "hessian")[1] + sum(attr(aux2, "hessian")) aw <- last - q1/q2 bw <- max(0.001, -1/q2) cand <- rtrunc(1, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw)) alfa <- (exp(gExp(cand, U, hyper))/exp(gExp(last, U, hyper))) * (dtrunc(last, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))/dtrunc(cand, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))) } if (prior == "Unif") { gUnif <- function(nu, U) { n <- length(U) ff <- 0.5 * n * nu * log(nu/2) + (0.5 * nu) * sum(log(U) - U) - n * log(gamma(nu/2)) return(ff) } Fonseca1 <- deriv(~0.5 * n * nu * log(nu/2) - n * log(gamma(nu/2)), c("nu"), function(nu) { }, hessian = TRUE) Fonseca2 <- deriv(~(0.5 * nu) * (log(U) - U), c("nu"), function(U, nu) { }, hessian = TRUE) aux1 <- Fonseca1(last) aux2 <- Fonseca2(U, last) q1 <- attr(aux1, "gradient")[1] + sum(attr(aux2, "gradient")) q2 <- attr(aux1, "hessian")[1] + sum(attr(aux2, "hessian")) aw <- last - q1/q2 bw <- max(0.001, -1/q2) cand <- rtrunc(1, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw)) alfa <- (exp(gUnif(cand, U))/exp(gUnif(last, U))) * (dtrunc(last, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))/dtrunc(cand, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))) } if (prior == "Hierar") { gHierar <- function(nu, U) { n <- length(U) ff <- (-lambda * nu) + 0.5 * n * nu * log(nu/2) + (0.5 * nu) * sum(log(U) - U) - n * log(gamma(nu/2)) return(ff) } Fonseca1 <- deriv(~(-lambda * nu) + 0.5 * n * nu * log(nu/2) - n * log(gamma(nu/2)), c("nu"), function(nu) { }, hessian = TRUE) Fonseca2 <- deriv(~(0.5 * nu) * (log(U) - U), c("nu"), function(U, nu) { }, hessian = TRUE) aux1 <- Fonseca1(last) aux2 <- Fonseca2(U, last) q1 <- attr(aux1, "gradient")[1] + sum(attr(aux2, "gradient")) q2 <- attr(aux1, "hessian")[1] + sum(attr(aux2, "hessian")) aw <- last - q1/q2 bw <- max(0.001, -1/q2) cand <- rtrunc(1, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw)) alfa <- (exp(gHierar(cand, U))/exp(gHierar(last, U))) * (dtrunc(last, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))/dtrunc(cand, spec = "norm", a = 2.1, b = 100, mean = aw, sd = sqrt(bw))) } ifelse(runif(1) < min(alfa, 1), last <- cand, last <- last) return(last) } MHrhoCN <- function(last, U, cc, sigma2, nu, s0, s1, cens) { last1 <- last/(1 - last) desv <- 0.001 cand <- rlnorm(1, meanlog = log(last1), sdlog = sqrt(desv)) ver <- verosCN(U, cc, cens = cens, sigma2, nu) g <- function(r, ver) { r1 <- r/(1 + r) ff <- (r1)^(s0 - 1) * (1 - r1)^(s1 - 1) * ver * (1/(1 + r)^2) return(ff) } alfa <- g(cand, ver) * cand/(g(last1, ver) * last1) ifelse(runif(1) < min(alfa, 1), last <- cand, last <- last) return(last) }
/scratch/gouwar.j/cran-all/cranData/BayesCR/R/utility_sim.r
#' Two Arm Bayesian Clinical Trial Simulation with Historical Data #' #' \code{historic_sim()} returns an S3 object of class \code{bayes_ctd_array}, which #' will contain simulation results for power, statistic estimation, bias, #' variance, and mse as requested by user. #' #' The object \code{bayes_ctd_array} has 6 elements: a list containing simulation #' results (\code{data}), copies of the 4 function arguments \code{subj_per_arm}, #' \code{a0_vals}, \code{effect_vals}, and \code{rand_control_diff}, and finally #' a \code{objtype} value indicating that \code{historic_sim()} was used. Each element of #' \code{data} is a four-dimensional array, where each dimension is determined by the #' length of parameters \code{subj_per_arm}, \code{a0_vals}, \code{effect_vals}, and #' \code{rand_control_diff}. The size of \code{data} depends on which results are #' requested by the user. At a minimum, at least one of \code{subj_per_arm}, #' \code{a0_vals}, \code{effect_vals}, or \code{rand_control_diff} must contain at #' least 2 values, while the other three must contain at least 1 value. The \code{data} #' list will always contain two elements: an array of power results (\code{power}) and #' an array of estimation results (\code{est}). In addition to \code{power} and #' \code{est}, data may also contain elements \code{var}, \code{bias}, or \code{mse}, #' depending on the values of \code{get_var}, \code{get_bias}, and \code{get_mse}. The #' values returned in \code{est} are in the form of hazard ratios, mean ratios, odds #' ratios, or mean differences depending on the value of \code{outcome_type}. For a #' Gaussian outcome, the estimation results are differences in group means (experimental #' group minus control group). For a logistic outcome, the estimation results are odds #' ratios (experimental group over control group). For lognormal and Poisson outcomes, #' the estimation results are mean ratios (experimental group over control group). For a #' piecewise exponential or a Weibull outcome, the estimation results are hazard #' ratios (experimental group over control group). The values returned in \code{bias}, #' \code{var}, and \code{mse} are on the scale of the values returned in #' \code{est}. #' #' The object \code{bayes_ctd_array} has two primary methods, \code{print()} and #' \code{plot()}, for printing and plotting slices of the arrays contained in #' \code{bayes_ctd_array$data}. #' #' As dimensions of the four dimensional array increases, the time required to complete #' the simulation will increase; however, it will be faster than a similar simulation #' based on repeated calls to MCMC routines to analyze each simulated trial. #' #' The meaning of the estimation results, and the test used to generate power results, #' depends on the outcome used. In all cases, power is based on a two-sided test #' involving a (1-alpha)100\% credible interval, where the interval is used to determine #' if the null hypothesis should be rejected (null value outside of the interval) or #' not rejected (null value inside the interval). For a Gaussian outcome, the 95\% #' credible interval is an interval for the difference in group means #' (experimental group minus control group), and the test determines if 0 is in or #' outside of the interval. For a Bernoulli outcome, the 95\% credible interval #' is an interval for the odds ratio (experimental group over control group), #' and the test determines if 1 is in or outside of the interval. For a lognormal or #' a Poisson outcome, the 95\% credible interval is an interval for the mean ratio #' (experimental group over control group), and the test determines if 1 is in or #' outside of the interval. Finally, for a piecewise exponential or a Weibull outcome, #' the 95\% credible interval is an interval for the hazard ratio (experimental group #' over control group), and the test determines if 1 is in or outside of the interval. #' #' Please refer to the examples for illustration of package use. #' #' @param trial_reps Number of trials to replicate within each combination of #' \code{a0_vals}, \code{subj_per_arm}, \code{effect_vals}, and \code{rand_control_parms}. #' As the number of trials increases, the precision of the estimate will increase. #' Default is 100. #' @param outcome_type Outcome distribution. Must be equal to \code{weibull}, #' \code{lognormal}, \code{pwe} (Piecewise Exponential), \code{gaussian}, #' \code{bernoulli}, or \code{poisson}. Default is \code{weibull}. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. Default is \code{c(50, 100, 150, 200, 250)}. #' @param a0_vals A vector of power prior parameters ranging from 0 to 1, where 0 #' implies no information from historical data should be used, and 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' Default is \code{c(0, 0.33, 0.67, 1)}. #' @param effect_vals A vector of effects that should be reasonable for the #' outcome_type being studied, hazard ratios for Weibull, odds ratios for #' Bernoulli, mean ratios for Poisson, etc.. When \code{effect_vals} contain #' the null effect for a given \code{outcome_type}, the \code{power} component #' of \code{data} will contain an estimate of Type One Error. In order to #' have a good set of Type One Error estimates, \code{trial_reps} need to be #' at least 10,000. In such a case, if the total number of combinations #' made up from \code{subj_per_arm}, \code{a0_vals}, \code{effect_vals}, and #' \code{rand_control_diff} is very large, the time to complete the simulation #' can be substantial. Default is \code{c(0.6, 1, 1.4)}. #' @param rand_control_diff For piecewise exponential and Weibull outcomes, this is #' a vector of hazard ratios (randomized controls over historical controls) #' representing differences between historical and randomized controls. For #' lognormal and Poisson outcomes, this is a vector of mean ratios (randomized #' controls over historical controls). For a Bernoulli outcome, this is a vector #' of odds ratios (randomized controls over historical controls). For a Gaussian #' outcome, this is a vector of mean differences (randomized minus historical #' controls). Default is \code{c(0.8, 1, 1.2)}. #' @param hist_control_data A dataset of historical data. Default is \code{NULL}. #' For survival outcomes, historical datasets must have 4 columns: id, treatment, #' event_time, and status. The value of treatment should be 0. For other #' outcomes, historical datasets must have columns: id, treatment, and y. #' @param time_vec A vector of time values which are used to create time periods #' within which the exponential hazard is constant. Only used for piecewise #' exponential models. Default is \code{NULL}. #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Used with survival outcomes. #' Default is \code{NULL}, where \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param seedval A seed value for pseudo-random number generation. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{historic_sim()} returns an S3 object of class \code{bayes_ctd_array}. #' As noted in details, an object of class \code{bayes_ctd_array }has 6 elements: a #' list of simulation results (\code{data}), copies of the 4 function arguments #' \code{subj_per_arm}, \code{a0_vals}, \code{effect_vals}, and #' \code{rand_control_diff}, and finally \code{objtype} indicating that \code{historic_sim()} #' was used. See details for a discussion about the contents of #' \code{data}. Results from the simulation contained in the \code{bayes_ctd_array} #' object can be printed or plotted using the \code{print()} and #' \code{plot()} methods. The results can also be accessed using basic list #' element identification and array slicing. For example, to get the 4-dimensional #' array of power results from a simulation, one could use the code #' \code{bayes_ctd_array$data$power}, where \code{bayes_ctd_array} is replaced #' with the name of the variable containing the \code{bayes_ctd_array} object. If #' one wanted a table of power for sample size by a0, while holding effect equal to #' the first considered value and control differences equal to the second considered #' value, then the code is \code{bayes_ctd_array$data$power[,,1,2]}, where #' \code{bayes_ctd_array} is replaced with the name of the variable containing the #' \code{bayes_ctd_array} object. #' #' @references Eggleston et al. BayesCTDesign: An R Package for Bayesian Trial Design Using Historical Control Data. \emph{Journal of Statistical Software}, November 2021, Volume 100, Issue 21, <doi:10.18637/jss.v100.i21>. #' #' @examples #' #Generate a sample of historical data for use in example. #' set.seed(2250) #' SampleHistData <- genweibulldata(sample_size=60, scale1=2.82487, #' hazard_ratio=0.6, common_shape=3, #' censor_value=3) #' histdata <- subset(SampleHistData, subset=(treatment==0)) #' histdata$id <- histdata$id+10000 #' #' #Run a Weibull simulation, using historic_sim(). #' #For meaningful results, trial_reps needs to be much larger than 2. #' weibull_test <- historic_sim(trial_reps = 2, outcome_type = "weibull", #' subj_per_arm = c(50, 100, 150), #' a0_vals = c(0, 0.50, 1), #' effect_vals = c(0.6, 1), #' rand_control_diff = c(0.8, 1), #' hist_control_data = histdata, time_vec = NULL, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' #' #Tabulate the simulation results for power. #' test_table <- print(x=weibull_test, measure="power", #' tab_type="WX|YZ", effect_val=0.6, #' rand_control_diff_val=1.0) #' print(test_table) #' #' \donttest{ #' #Create a plot of the power simulation results. #' plot(x=weibull_test, measure="power", tab_type="WX|YZ", #' smooth=FALSE, plot_out=TRUE, effect_val=0.6, #' rand_control_diff_val=1.0) #' #Create a plot of the estimated hazard ratio simulation results. #' plot(x=weibull_test, measure="est", tab_type="WX|YZ", #' smooth=FALSE, plot_out=TRUE, effect_val=0.6, #' rand_control_diff_val=1.0) #' #Create a plot of the hazard ratio variance simulation results. #' plot(x=weibull_test, measure="var", tab_type="WX|YZ", #' smooth=FALSE, plot_out=TRUE, effect_val=0.6, #' rand_control_diff_val=1.0) #' #Create a plot of the hazard ratio bias simulation results. #' plot(x=weibull_test, measure="bias", tab_type="WX|YZ", #' smooth=FALSE, plot_out=TRUE, effect_val=0.6, #' rand_control_diff_val=1.0) #' #Create a plot of the hazard ratio mse simulation results. #' plot(x=weibull_test, measure="mse", tab_type="WX|YZ", #' smooth=FALSE, plot_out=TRUE, effect_val=0.6, #' rand_control_diff_val=1.0) #' #' #Create other power plots using different values for tab_type #' plot(x=weibull_test, measure="power", tab_type="XY|WZ", #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=150, #' rand_control_diff_val=1.0) #' #' plot(x=weibull_test, measure="power", tab_type="XZ|WY", #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=150, effect_val=0.6) #' #' plot(x=weibull_test, measure="power", tab_type="YZ|WX", #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=150, a0_val=0.5) #' #' plot(x=weibull_test, measure="power", tab_type="WY|XZ", #' smooth=FALSE, plot_out=TRUE, rand_control_diff_val=1, a0_val=0.5) #' #' plot(x=weibull_test, measure="power", tab_type="WZ|XY", #' smooth=FALSE, plot_out=TRUE, effect_val=0.6, a0_val=0.5) #' } #' #' \donttest{ #' #Run Poisson simulation, using historic_sim(), but set two design characteristic #' # parameters to only 1 value. #' #Note: historic_sim() can take a while to run. #' #Generate a sample of historical poisson data for use in example. #' set.seed(2250) #' samplehistdata <- genpoissondata(sample_size=60, mu1=1, mean_ratio=1.0) #' histdata <- subset(samplehistdata, subset=(treatment==0)) #' histdata$id <- histdata$id+10000 #' #' #For meaningful results, trial_reps needs to be larger than 100. #' poisson_test <- historic_sim(trial_reps = 100, outcome_type = "poisson", #' subj_per_arm = c(50, 75, 100, 125, 150, 175, 200, 225, 250), #' a0_vals = c(1), #' effect_vals = c(0.6), #' rand_control_diff = c(0.6, 1, 1.6), #' hist_control_data = histdata, time_vec = NULL, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' #' #Tabulate the simulation results for power. #' test_table <- print(x=poisson_test, measure="power", #' tab_type=NULL) #' print(test_table) #' #' #Create a plot of the power simulation results. #' plot(x=poisson_test, measure="power", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE) #' } #' #' \donttest{ #' #At least one of subj_per_arm, a0_vals, effect_vals, or rand_control_diff #' #must contain at least 2 values. #' #Generate a sample of historical lognormal data for use in example. #' set.seed(2250) #' samplehistdata <- genlognormaldata(sample_size=60, mu1=1.06, mean_ratio=0.6, common_sd=1.25, #' censor_value=3) #' histdata <- subset(samplehistdata, subset=(treatment==0)) #' histdata$id <- histdata$id+10000 #' #' #Run a Lognormal simulation, using historic_sim(). #' #For meaningful results, trial_reps needs to be larger than 100. #' lognormal_test <- historic_sim(trial_reps = 100, outcome_type = "lognormal", #' subj_per_arm = c(25,50,75,100,125,150,175,200,225,250), #' a0_vals = c(1.0), #' effect_vals = c(0.6), #' rand_control_diff = c(1.8), #' hist_control_data = histdata, time_vec = NULL, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' #' test_table <- print(x=lognormal_test, measure="power", #' tab_type=NULL) #' print(test_table) #' #Create a plot of the power simulation results. #' plot(x=lognormal_test, measure="power", tab_type=NULL, #' smooth=TRUE, plot_out=TRUE) #' } #' #' @export historic_sim <- function(trial_reps = 100, outcome_type = "weibull", subj_per_arm = c(50, 100, 150, 200, 250), a0_vals = c(0, 0.33, 0.67, 1), effect_vals = c(0.6, 1, 1.4), rand_control_diff = c(0.8, 1, 1.2), hist_control_data = NULL, time_vec = NULL, censor_value = NULL, alpha = 0.05, get_var = FALSE, get_bias = FALSE, get_mse = FALSE, seedval=NULL, quietly=TRUE){ #set random seed set.seed(seedval) #------------- Go through all the high level checks for proper input. -------------# global_error_checks(outcome_type, a0_vals, subj_per_arm, hist_control_data, rand_control_diff, get_var, get_bias, get_mse) #-- Given outcome type go through low level checks for proper input and run simulation --# if (tolower(outcome_type) == "weibull") { weibull_error_checks(effect_vals, hist_control_data, rand_control_diff, censor_value, alpha) results <- weibull_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, hist_control_data = hist_control_data, censor_value = censor_value, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "lognormal") { lognormal_error_checks(effect_vals, hist_control_data, rand_control_diff, censor_value, alpha) results <- lognormal_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, hist_control_data = hist_control_data, censor_value = censor_value, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "pwe") { pwe_error_checks(effect_vals, hist_control_data, rand_control_diff, time_vec, censor_value, alpha) results <- pwe_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, hist_control_data = hist_control_data, time_vec_val = time_vec, censor_value = censor_value, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "gaussian") { gaussian_error_checks(effect_vals, hist_control_data, rand_control_diff, alpha) results <- gaussian_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, hist_control_data = hist_control_data, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "bernoulli") { bernoulli_error_checks(effect_vals, hist_control_data, rand_control_diff, alpha) results <- bernoulli_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, hist_control_data = hist_control_data, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "poisson") { poisson_error_checks(effect_vals, hist_control_data, rand_control_diff, alpha) results <- poisson_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, hist_control_data = hist_control_data, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } if ((length(subj_per_arm) == 1 & length(a0_vals) == 1 & length(effect_vals) == 1) | (length(subj_per_arm) == 1 & length(a0_vals) == 1 & length(rand_control_diff) == 1) | (length(subj_per_arm) == 1 & length(effect_vals) == 1 & length(rand_control_diff) == 1) | (length(a0_vals) == 1 & length(effect_vals) == 1 & length(rand_control_diff) == 1)){ results$objtype <- 'realsimple' } results } #' Two Arm Bayesian Clinical Trial Simulation without Historical Data #' #' \code{simple_sim()} returns an S3 object of class \code{bayes_ctd_array}, which #' will contain simulation results for power, statistic estimation, bias, variance, #' and mse as requested by user. #' #' The object \code{bayes_ctd_array} has 6 elements: a list containing simulation #' results (\code{data}), copies of the 4 function arguments \code{subj_per_arm}, #' \code{a0_vals}, \code{effect_vals}, and \code{rand_control_diff}, and finally #' a \code{objtype} value indicating that \code{simple_sim()} was used. Each element of #' \code{data} is a four-dimensional array, where each dimension is determined by the #' length of parameters \code{subj_per_arm}, \code{a0_vals}, \code{effect_vals}, and #' \code{rand_control_diff}. The size of \code{data} depends on which results are #' requested by the user. At a minimum, at least one of \code{subj_per_arm}, #' \code{a0_vals}, \code{effect_vals}, or \code{rand_control_diff} must contain at #' least 2 values, while the other three must contain at least 1 value. The \code{data} #' list will always contain two elements: an array of power results (\code{power}) and #' an array of estimation results (\code{est}). In addition to \code{power} and #' \code{est}, \code{data} may also contain elements \code{var}, \code{bias}, or #' \code{mse}, depending on the values of \code{get_var}, \code{get_bias}, and #' \code{get_mse}. The values returned in \code{est} are in the form of hazard ratios, #' mean ratios, odds ratios, or mean differences depending on the value of #' \code{outcome_type}. For a Gaussian outcome, the estimation results are #' differences in group means (experimental group minus control group). For a #' logistic outcome, the estimation results are odds ratios (experimental group over #' control group). For lognormal and Poisson outcomes, the estimation results are mean #' ratios (experimental group over control group). For a piecewise exponential or a #' Weibull outcome, the estimation results are hazard ratios (experimental group over #' control group). The values returned in \code{bias}, \code{var}, and \code{mse} are #' on the scale of the values returned in \code{est}. #' #' The object \code{bayes_ctd_array} has two primary methods, \code{print()} and #' \code{plot()}, for printing and plotting slices of the arrays contained in #' \code{bayes_ctd_array$data}. #' #' As dimensions of the four dimensional array increases, the time required to complete #' the simulation will increase; however, it will be faster than a similar simulation #' based on repeated calls to MCMC routines to analyze each simulated trial. #' #' The meaning of the estimation results, and the test used to generate power results, #' depends on the outcome used. In all cases, power is based on a two-sided test #' involving a (1-alpha)100\% credible interval, where the interval is used to determine #' if the null hypothesis should be rejected (null value outside of the interval) or #' not rejected (null value inside the interval). For a Gaussian outcome, the 95\% #' credible interval is an interval for the difference in group means #' (experimental group minus control group), and the test determines if 0 is in or #' outside of the interval. For a Bernoulli outcome, the 95\% credible interval #' is an interval for the odds ratio (experimental group over control group), #' and the test determines if 1 is in or outside of the interval. For a lognormal or #' a Poisson outcome, the 95\% credible interval is an interval for the mean ratio #' (experimental group over control group), and the test determines if 1 is in or #' outside of the interval. Finally, for a piecewise exponential or a Weibull outcome, #' the 95\% credible interval is an interval for the hazard ratio (experimental group #' over control group), and the test determines if 1 is in or outside of the interval. #' #' For a Gaussian outcome, the \code{control_parms} values should be \code{(mean, sd)}, #' where mean is the mean parameter for the control group used in a call to \code{rnorm()}, #' and sd is the common sd parameter for both groups used in a call to\code{rlnorm()}. #' #' For a Bernoulli outcome, the \code{control_parms} values should be \code{(prob)}, where #' prob is the event probability for the control group used in a call to \code{rbinom()}. #' #' For a lognormal outcome, the \code{control_parms} values should be \code{(meanlog, sdlog)}, #' where meanlog is the meanlog parameter for the control group used in a call to #' \code{rlnorm()}, and sdlog is the common sdlog parameter for both groups used in #' a call to \code{rlnorm()}. #' #' For a Poisson outcome, the \code{control_parms} value should be \code{(lambda)}, where #' lambda is the lambda parameter for the control group used in a call to \code{rpois()} and #' is equal to the mean of a Poisson distribution. #' #' For a Weibull outcome, the \code{control_parms} values should be \code{(scale, shape)}, #' where scale is the scale parameter for the control group used in a call to #' \code{rweibull()}, and shape is the common shape parameter for both groups used in #' a call to \code{rweibull()}. #' #' For a piecewise exponential outcome, the \code{control_parms} values should be a vector #' of lambdas used in a call to \code{eha::rpch()}. Each element in \code{control_parms} #' is a hazard for an interval defined by the \code{time_vec} parameter. #' #' Please refer to the examples for illustration of package use. #' #' @param trial_reps Number of trials to replicate within each combination of #' \code{a0_vals}, \code{subj_per_arm}, \code{effect_vals}, and \code{rand_control_parms}. #' As the number of trials increases, the precision of the estimate will increase. #' Default is 100. #' @param outcome_type Outcome distribution. Must be equal to \code{weibull}, #' \code{lognormal}, \code{pwe} (Piecewise Exponential), \code{gaussian}, #' \code{bernoulli}, or \code{poisson}. Default is \code{weibull}. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. Default is \code{c(50, 100, 150, 200, 250)}. #' @param effect_vals A vector of effects that should be reasonable for the #' outcome_type being studied, hazard ratios for Weibull, odds ratios for #' Bernoulli, mean ratios for Poisson, etc.. When \code{effect_vals} contain #' the null effect for a given \code{outcome_type}, the \code{power} component #' of \code{data} will contain an estimate of Type One Error. In order to #' have a good set of Type One Error estimates, \code{trial_reps} need to be #' at least 10,000. In such a case, if the total number of combinations #' made up from \code{subj_per_arm}, \code{a0_vals}, \code{effect_vals}, and #' \code{rand_control_diff} is very large, the time to complete the simulation #' can be substantial. Default is \code{c(0.6, 1, 1.4)}. #' @param control_parms A vector of parameter values defining the outcome #' distribution for randomized controls. See Details for what is required for #' each \code{outcome_type}. #' @param time_vec A vector of time values that are used to create time periods #' within which the exponential hazard is constant. Only used for piecewise #' exponential models. Default is \code{NULL}. #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Used with survival outcomes. #' Default is \code{NULL}, where \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param seedval A seed value for pseudo-random number generation. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{simple_sim()} returns an S3 object of class \code{bayes_ctd_array}. #' As noted in Details, an object of class \code{bayes_ctd_array} has 6 elements: a #' list containing simulation results (\code{data}), copies of the 4 function #' arguments \code{subj_per_arm}, \code{a0_vals}, \code{effect_vals}, and #' \code{rand_control_diff}, and finally \code{objtype} indicating that \code{simple_sim()} #' was used. See Details for a discussion about the contents of #' \code{data}. Results from the simulation contained in the \code{bayes_ctd_array} #' object can be printed or plotted using the \code{print()} and #' \code{plot()} methods. The results can also be accessed using basic list #' element identification and array slicing. For example, to get the power results #' from a simulation, one could use the code \code{bayes_ctd_array$data$power}, where #' \code{bayes_ctd_array} is replaced with the name of the variable containing the #' \code{bayes_ctd_array} object. Even though this is a 4-dimensional array, the power #' results only occupy a single 2-dimensional table. To print this 2-dimensional table, #' one would use the code \code{bayes_ctd_array$data$power[,1,,1]}, where #' \code{bayes_ctd_array} is replaced with the name of the variable containing the #' \code{bayes_ctd_array} object. #' #' @references Eggleston et al. (2021). BayesCTDesign: An R Package for Bayesian Trial Design Using Historical Control Data. \emph{Journal of Statistical Software}, November 2021, Volume 100, Issue 21, <doi:10.18637/jss.v100.i21>. #' #' #' @examples #' #Run a Weibull simulation, using simple_sim(). #' #For meaningful results, trial_reps needs to be much larger than 2. #' weibull_test <- simple_sim(trial_reps = 2, outcome_type = "weibull", #' subj_per_arm = c(50, 100, 150, 200), #' effect_vals = c(0.6, 1, 1.4), #' control_parms = c(2.82487,3), time_vec = NULL, #' censor_value = NULL, alpha = 0.05, #' get_var = TRUE, get_bias = TRUE, get_mse = TRUE, #' seedval=123, quietly=TRUE) #' #' #Tabulate the simulation results for power. #' test_table <- print(x=weibull_test, measure="power", #' tab_type=NULL, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL) #' print(test_table) #' #' #Create a plot of the power simulation results. #' plot(x=weibull_test, measure="power", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE) #' #Create a plot of the estimated hazard ratio simulation results. #' plot(x=weibull_test, measure="est", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE) #' #Create a plot of the hazard ratio variance simulation results. #' plot(x=weibull_test, measure="var", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE) #' #Create a plot of the hazard ratio bias simulation results. #' plot(x=weibull_test, measure="bias", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE) #' #Create a plot of the hazard ratio mse simulation results. #' plot(x=weibull_test, measure="mse", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE) #' @export simple_sim <- function(trial_reps = 100, outcome_type = "weibull", subj_per_arm = c(50, 100, 150, 200, 250), effect_vals = c(0.6,1, 1.4), control_parms = NULL, time_vec = NULL, censor_value = NULL, alpha = 0.05, get_var = FALSE, get_bias = FALSE, get_mse = FALSE, seedval=NULL, quietly=TRUE) { #set random seed set.seed(seedval) #------------- Go through all the high level checks for proper input. -------------# global_error_checks_simple(outcome_type, subj_per_arm, get_var, get_bias, get_mse) #-- Given outcome type go through low level checks for proper input and run simulation --# if (tolower(outcome_type) == "weibull") { weibull_error_checks_simple(effect_vals, control_parms, censor_value, alpha) results <- simple_weibull_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, effect_vals = effect_vals, scale1_value = control_parms[1], common_shape_value = control_parms[2], censor_value = censor_value, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "lognormal") { lognormal_error_checks_simple(effect_vals, control_parms, censor_value, alpha) results <- simple_lognormal_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, effect_vals = effect_vals, mu1_val = control_parms[1], common_sd_val = control_parms[2], censor_value = censor_value, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "pwe") { pwe_error_checks_simple(effect_vals, time_vec, control_parms, censor_value, alpha) results <- simple_pwe_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, effect_vals = effect_vals, time_vec_val = time_vec, rc_hazards = control_parms, censor_value = censor_value, alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "gaussian") { gaussian_error_checks_simple(effect_vals, control_parms, alpha) results <- simple_gaussian_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, effect_vals = effect_vals, mu1_val = control_parms[1], common_sd_val = control_parms[2], alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "bernoulli") { bernoulli_error_checks_simple(effect_vals, control_parms, alpha) results <- simple_bernoulli_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, effect_vals = effect_vals, prob1_val = control_parms[1], alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } else if (tolower(outcome_type) == "poisson") { poisson_error_checks_simple(effect_vals, control_parms, alpha) results <- simple_poisson_sim(trial_reps = trial_reps, subj_per_arm = subj_per_arm, effect_vals = effect_vals, mu1_val = control_parms[1], alpha = alpha, get_var = get_var, get_bias = get_bias, get_mse = get_mse, quietly=quietly) } } #' Print Data from Two Arm Bayesian Clinical Trial Simulation. #' #' \code{print.bayes_ctd_array()} takes an S3 object of class \code{bayes_ctd_array}, and #' prints a two dimensional slice from the data generated by a clinical trial simulation #' using \code{historic_sim()} or \code{simple_sim()}. #' #' If the object of class \code{bayes_ctd_array} is created by \code{historic_sim()}, #' then the function \code{print()} allows the user to print user-specified 1- and 2- #' dimensional slices of the simulation results based on slicing code described #' below. If the object of class \code{bayes_ctd_array} is created by #' \code{simple_sim()}, a basic table of characteristic by sample size and effect is created. #' #' If the object of class \code{bayes_ctd_array} is created by \code{simple_sim()}, then #' all four trial characteristics (\code{subj_per_arm_val}, \code{a0_vals}, #' \code{effect_val}, and \code{rand_control_diff_val}) can be ignored, as can the #' parameter defining what type of table to print, \code{tab_type}. A call to #' \code{print()} will require the user to specify a measure (power, est, var, bias, #' or mse). #' #' If the object of class \code{bayes_ctd_array} is created by \code{historic_sim()}, #' a call to \code{print()} will require the user to specify a measure #' (power, est, var, bias, or mse) and may require the user to specify a table type. #' A table type, \code{tab_type}, will be required if 3 of the 4 trial characteristics #' are equal to a vector of 2 or more values. The table type specification #' uses the letters W, X, Y, and Z. The letter W represents the subject per arm #' dimension. The letter X represents the a0 dimension. The letter Y represents #' the effect dimension. The letter Z represents the control difference dimension. #' To define a slice of the 4-dimensional array, these letters are put into an AB|CD #' pattern. The two letters to the right of the vertical bar define which variables #' are held constant. The two letters to the left of the vertical bar define which #' variables are going to show up in the rows (first letter) and in the columns (second #' letter). For example if tab_type equals \code{WX|YZ}, then effect and control #' differences will be held constant, while sample size will be represented by the rows #' in the generated table and a0 values will be represented by the columns. The actual #' values that are printed in the tables depend on what measure is requested in the #' parameter \code{measure}. #' #' \itemize{ #' \item \code{tab_type='WX|YZ'}, Sample Size by a0 #' \item \code{tab_type='WY|XZ'}, Sample Size by Effect #' \item \code{tab_type='WZ|XY'}, Sample Size by Control Differences #' \item \code{tab_type='XY|WZ'}, a0 by Effect #' \item \code{tab_type='XZ|WY'}, a0 by Control Differences #' \item \code{tab_type='YZ|WX'}, Effect by Control Differences #' \item \code{tab_type='ZX|WY'}, Control Differences by a0 #' \item \code{tab_type='XW|YZ'}, a0 by Sample Size #' \item \code{tab_type='YW|XZ'}, Effect by Sample Size #' \item \code{tab_type='YX|WZ'}, Effect by a0 #' \item \code{tab_type='ZW|XY'}, Control Differences by Sample Size #' \item \code{tab_type='ZY|WX'}, Control Differences by Effect #' } #' #' It is very important to populate the values of \code{subj_per_arm_val}, #' \code{a0_vals}, \code{effect_val}, and \code{rand_control_diff_val} correctly given #' the value of tab_type, when the object of class \code{bayes_ctd_array} is created by #' \code{historic_sim()} and at least 3 of the four parameters have more than one #' value. On the other hand, if 2 or more of the four parameters have only one value, #' then \code{subj_per_arm_val}, \code{a0_vals}, \code{effect_val}, #' \code{rand_control_diff_val}, as well as \code{tab_type} can be ignored. If the last #' two letters are \code{YZ}, then \code{effect_val} and \code{rand_control_diff_val} #' must be populated. If the last two letters are \code{XZ}, then \code{a0_vals} and #' \code{rand_control_diff_val} must be populated. If the last two letters are #' \code{XY}, then \code{a0_vals} and \code{effect_val} must be populated. If the last #' two letters are \code{WZ}, then \code{sample_val} and \code{rand_control_diff_val} #' must be populated. If the last two letters are \code{WY}, then \code{sample_size_val} #' and \code{effect_val} must be populated. If the last two letters are \code{WX}, then #' \code{sample_size_val} and \code{a0_vals} must be populated. #' #' If the object of class \code{bayes_ctd_array} is created by \code{simple_sim()}, the #' parameters \code{tab_type}, \code{subj_per_arm_val}, \code{a0_vals}, \code{effect_val}, #' and \code{rand_control_diff_val} are ignored. #' #' @param x Name of object of class \code{bayes_ctd_array} containing #' data from clinical trial simulation. #' @param measure Must be equal to \code{power}, \code{est}, \code{var}, \code{bias}, #' or \code{mse}. Default is \code{power}. Case does not matter. #' @param tab_type A character string that must equal \code{WX|YZ}, \code{WY|XZ}, #' \code{WZ|XY}, \code{XY|WZ}, \code{XZ|WY}, \code{YZ|WX}, \code{ZX|WY}, \code{XW|YZ}, #' \code{YW|XZ}, \code{YX|WZ}, \code{ZW|XY}, \code{ZX|WY}, \code{ZY|WX} when #' \code{x} is generated by \code{historic_sim()}. Default is #' \code{WX|YZ}. When \code{x} is generated by \code{simple_sim()}, #' \code{tab_type} is ignored. #' @param subj_per_arm_val Must be non-missing, if \code{x} is generated #' by \code{historic_sim()} and sample size is being held constant. #' If \code{x} is generated by \code{historic_sim()} and sample size #' is being held constant, \code{subj_per_arm_val} must equal a value submitted #' to \code{historic_sim()} within the \code{subj_per_arm} parameter. When #' \code{x} is generated by \code{simple_sim()}, \code{subj_per_arm_val} #' is ignored. #' @param a0_val Must be non-missing, if \code{x} is generated #' by \code{historic_sim()} and a0, the power prior parameter, is being held #' constant. If \code{x} is generated by \code{historic_sim()} and #' a0 is being held constant, \code{a0_val} must equal a value submitted #' to \code{historic_sim()} within the \code{a0_vals} parameter. When #' \code{x} is generated by \code{simple_sim()}, \code{a0_val} is #' ignored. #' @param effect_val Must be non-missing, if \code{x} is generated #' by \code{historic_sim()} and effect is being held constant. If #' \code{x} is generated by \code{historic_sim()} and effect is being #' held constant, \code{effect_val} must equal a value submitted to #' \code{historic_sim()} within the \code{effect_vals} parameter. When #' \code{x} is generated by \code{simple_sim()}, \code{effect_val} is #' ignored. #' @param rand_control_diff_val Must be non-missing, if \code{x} is #' generated by \code{historic_sim()} and differences between randomized #' and historical controls are being held constant. If \code{x} #' is generated by \code{historic_sim()} and control differences are being #' held constant, \code{rand_control_diff_val} must equal a value submitted to #' \code{historic_sim()} within the \code{rand_control_diff} parameter. When #' \code{x} is generated by \code{simple_sim()}, #' \code{rand_control_diff_val} is ignored. #' @param print_chg_warn A parameter not used by the user, but is used by #' \code{plot()} to ensure warnings are not printed twice. #' @param ... further arguments passed to or from other methods. #' #' @return \code{print()} returns a two dimensional array of simulation results. #' #' @references Eggleston et al. BayesCTDesign: An R Package for Bayesian Trial Design Using Historical Control Data. \emph{Journal of Statistical Software}, November 2021, Volume 100, Issue 21, <doi:10.18637/jss.v100.i21>. #' #' @examples #' #Run a Weibull simulation, using simple_sim(). #' #For meaningful results, trial_reps needs to be much larger than 2. #' weibull_test <- simple_sim(trial_reps = 2, outcome_type = "weibull", #' subj_per_arm = c(50, 100, 150, 200), #' effect_vals = c(0.6, 1, 1.4), #' control_parms = c(2.82487,3), #' time_vec = NULL, censor_value = NULL, #' alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, #' seedval=123, quietly=TRUE) #' #' #Tabulate the simulation results for power. #' test_table <- print(x=weibull_test, measure="power", #' tab_type=NULL, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL) #' print(test_table) #' #' #Tabulate the simulation results for estimates. #' print(x=weibull_test, measure="est") #' #' #Tabulate the simulation results for variance. #' print(x=weibull_test, measure="var") #' #' #Tabulate the simulation results for bias. #' print(x=weibull_test, measure="bias") #' #' #Tabulate the simulation results for mse. #' print(x=weibull_test, measure="mse") #' #' \donttest{ #' #Run another weibull simulation, using historic_sim(). #' #Note: historic_sim() can take a while to run. #' #Generate a sample of historical data for use in example. #' set.seed(2250) #' SampleHistData <- genweibulldata(sample_size=60, scale1=2.82487, #' hazard_ratio=0.6, common_shape=3, #' censor_value=3) #' histdata <- subset(SampleHistData, subset=(treatment==0)) #' histdata$id <- histdata$id+10000 #' #' #For meaningful results, trial_reps needs to be larger than 100. #' weibull_test2 <- historic_sim(trial_reps = 100, outcome_type = "weibull", #' subj_per_arm = c(50, 100, 150, 200, 250), #' a0_vals = c(0, 0.33, 0.67, 1), #' effect_vals = c(0.6, 1, 1.4), #' rand_control_diff = c(0.8, 1, 1.2), #' hist_control_data = histdata, time_vec = NULL, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' #' #Tabulate the simulation results for power. #' test_table <- print(x=weibull_test2, measure="power", #' tab_type="WX|YZ", effect_val=0.6, #' rand_control_diff_val=1.0) #' print(test_table) #' #' #Tabulate the simulation results for estimates. #' print(x=weibull_test2, measure="est", tab_type="WX|YZ", #' effect_val=0.6, rand_control_diff_val=1.0) #' #' #Tabulate the simulation results for variance. #' print(x=weibull_test2, measure="var", tab_type="WX|YZ", #' effect_val=0.6, rand_control_diff_val=1.0) #' #' #Tabulate the simulation results for bias. #' print(x=weibull_test2, measure="bias", tab_type="WX|YZ", #' effect_val=0.6, rand_control_diff_val=1.0) #' #' #Tabulate the simulation results for mse. #' print(x=weibull_test2, measure="mse", tab_type="WX|YZ", #' effect_val=0.6, rand_control_diff_val=1.0) #' } #' #' \donttest{ #' #Run a Bernoulli simulation, using historic_sim(). #' #Generate a sample of historical Bernoulli data for use in example. #' set.seed(2250) #' samplehistdata <- genbernoullidata(sample_size=60, prob1=0.6, odds_ratio=0.6) #' histdata <- subset(samplehistdata, subset=(treatment==0)) #' histdata$id <- histdata$id+10000 #' #' #For meaningful results, trial_reps needs to be larger than 100. #' bernoulli_test <- historic_sim(trial_reps = 100, outcome_type = "bernoulli", #' subj_per_arm = c(150), #' a0_vals = c(1.0), #' effect_vals = c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0), #' rand_control_diff = c(1.8), #' hist_control_data = histdata, time_vec = NULL, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' test_table <- print(x=bernoulli_test, measure="power", #' tab_type=NULL, effect_val=NULL, #' subj_per_arm_val=NULL) #' print(test_table) #' #' #If only one or two of the subj_per_arm, a0_vals, effect_vals, or #' #rand_control_diff parameters have length greater than 1, then #' #only bayes_ctd_array and measure parameters are needed. #' #Tabulate the simulation results for estimates. #' print(x=bernoulli_test, measure="est") #' #' #Tabulate the simulation results for variance. #' print(x=bernoulli_test, measure="var") #' #' #Tabulate the simulation results for bias. #' print(x=bernoulli_test, measure="bias") #' #' #Tabulate the simulation results for mse. #' print(x=bernoulli_test, measure="mse") #' } #' #' @export print.bayes_ctd_array <- function(x = NULL, measure = "power", tab_type = "WX|YZ", subj_per_arm_val = NULL, a0_val = NULL, effect_val = NULL, rand_control_diff_val = NULL, print_chg_warn = 1, ...) { # (W): subj_per_arm, # (X): a0_val, # (Y): effect_val, # (Z): rand_control_diff # tab_type='WX|YZ', Table of Design Characteristics: Sample Size by a0 # tab_type='WY|XZ', Table of Design Characteristics: Sample Size by Effect # tab_type='WZ|XY', Table of Design Characteristics: Sample Size by Control Differences # tab_type='XY|WZ', Table of Design Characteristics: a0 by Effect # tab_type='XZ|WY', Table of Design Characteristics: a0 by Control Diffferences # tab_type='YZ|WX', Table of Design Characteristics: Effect by Control Diffferences # tab_type='ZX|WY', Table of Design Characteristics: Control Diffferences by a0 # tab_type='XW|YZ', Table of Design Characteristics: a0 by Sample Size # tab_type='YW|XZ', Table of Design Characteristics: Effect by Sample Size # tab_type='YX|WZ', Table of Design Characteristics: Effect by a0 # tab_type='ZW|XY', Table of Design Characteristics: Control Differences by Sample Size # tab_type='ZY|WX', Table of Design Characteristics: Control Differences by Effect #Add simple code to help out the user with tab_type on matters where order is #not important and can be easily fixed. tab_type = toupper(tab_type) if (!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if (x$objtype == 'historic') { if (tab_type=='WX|ZY') tab_type <- 'WX|YZ' if (tab_type=='WY|ZX') tab_type <- 'WY|XZ' if (tab_type=='WZ|YX') tab_type <- 'WZ|XY' if (tab_type=='XY|ZW') tab_type <- 'XY|WZ' if (tab_type=='XZ|YW') tab_type <- 'XZ|WY' if (tab_type=='YZ|XW') tab_type <- 'YZ|WX' if (tab_type=='ZX|YW') tab_type <- 'ZX|WY' if (tab_type=='XW|ZY') tab_type <- 'XW|YZ' if (tab_type=='YW|ZX') tab_type <- 'YW|XZ' if (tab_type=='YX|ZW') tab_type <- 'YX|WZ' if (tab_type=='ZW|YX') tab_type <- 'ZW|XY' if (tab_type=='ZY|XW') tab_type <- 'ZY|WX' } } #Do the same for measure measure = tolower(measure) #The above code was added very late in initial production, so time was not # available to go through all code and remove code no longer necessary. #------------- Go through all the high level checks for proper input. -------------# if (x$objtype == 'simple') { tab_type <- "WY|XZ" a0_val <- 0 rand_control_diff_val <- 1 subj_per_arm_val <- x$subj_per_arm[1] effect_val <- x$effect_vals[1] if (print_chg_warn == 1) { print("Since simple_sim was used, tab_type was set to WY|XZ") print("Values for tab_type, subj_per_arm_val, a0_val, effect_val, and rand_control_diff_val were ignored") print("This works towards putting all results in a single table, effect by sample size") } } if (x$objtype == 'realsimple') { if (length(x$subj_per_arm) > 1) { if (print_chg_warn == 1) { print("Since only subj_per_arm vector has more than 1 element, tab_type was set to WX|YZ") print("This works towards putting all results in a single table") } tab_type <- "WX|YZ" a0_val <- x$a0_vals[1] effect_val <- x$effect_vals[1] rand_control_diff_val <- x$rand_control_diff[1] } if (length(x$a0_vals) > 1) { if (print_chg_warn == 1) { print("Since only a0_vals vector has more than 1 element, tab_type was set to XY|WZ") print("This works towards putting all results in a single table") } tab_type <- "XY|WZ" subj_per_arm_val <- x$subj_per_arm[1] effect_val <- x$effect_vals[1] rand_control_diff_val <- x$rand_control_diff[1] } if (length(x$effect_vals) > 1) { if (print_chg_warn == 1) { print("Since only effect_vals vector has more than 1 element, tab_type was set to YZ|WX") print("This works towards putting all results in a single table") } tab_type <- "YZ|WX" subj_per_arm_val <- x$subj_per_arm[1] a0_val <- x$a0_vals[1] rand_control_diff_val <- x$rand_control_diff[1] } if (length(x$rand_control_diff) > 1) { if (print_chg_warn == 1) { print("Since only rand_control_diff vector has more than 1 element, tab_type was set to ZX|WY") print("This works towards putting all results in a single table") } tab_type <- "ZX|WY" subj_per_arm_val <- x$subj_per_arm[1] a0_val <- x$a0_vals[1] effect_val <- x$effect_vals[1] } } # Check to see if two dimensions of bayes_ctd_array have only 1 element each. Is so set tab_type to an appropriate # value. if (x$objtype == 'historic') { if (length(x$effect_vals) == 1 & length(x$rand_control_diff) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "WX|YZ") & (tab_type != "XW|YZ")) { tab_type <- "WX|YZ" chkflag1 <- 1 } } if( (length(tab_type)== 0) && (typeof(tab_type) == "character") ){ tab_type <- "WX|YZ" chkflag1 <- 1 } effect_val <- x$effect_vals[1] rand_control_diff_val <- x$rand_control_diff[1] if (print_chg_warn == 1 & chkflag1 == 1) { print("Since effect_vals and rand_control_diff vectors only have 1 element each and tab_type not equal to 'WX|YZ' or 'XW|YZ', tab_type was set to WX|YZ") print("This works towards putting all results in a single table") } } if (length(x$a0_vals) == 1 & length(x$rand_control_diff) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "WY|XZ") & (tab_type != "YW|XZ")) { tab_type <- "WY|XZ" chkflag1 <- 1 } } if((length(tab_type)== 0) && (typeof(tab_type) == "character")){ tab_type <- "WY|XZ" chkflag1 <- 1 } a0_val <- x$a0_vals[1] rand_control_diff_val <- x$rand_control_diff[1] if (print_chg_warn == 1 & chkflag1 == 1) { print("Since a0 and rand_control_diff vectors only have 1 element each and tab_type not equal to 'WY|XZ' or 'YW|XZ', tab_type was set to WY|XZ") print("This works towards putting all results in a single table") } } if (length(x$subj_per_arm) == 1 & length(x$rand_control_diff) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "XY|WZ") & (tab_type != "YX|WZ")) { tab_type <- "XY|WZ" chkflag1 <- 1 } } if((length(tab_type)== 0) && (typeof(tab_type) == "character")){ tab_type <- "XY|WZ" chkflag1 <- 1 } subj_per_arm_val <- x$subj_per_arm rand_control_diff_val <- x$rand_control_diff if (print_chg_warn == 1 & chkflag1 == 1) { print("Since sample size and rand_control_diff vectors only have 1 element each and tab_type not equal to 'XY|WZ' or 'YX|WZ', tab_type was set to XY|WZ") print("This works towards putting all results in a single table") } } if (length(x$subj_per_arm) == 1 & length(x$effect_vals) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "XZ|WY") & (tab_type != "ZX|WY")) { tab_type <- "XZ|WY" chkflag1 <- 1 } } if((length(tab_type)== 0) && (typeof(tab_type) == "character")){ tab_type <- "XZ|WY" chkflag1 <- 1 } subj_per_arm_val <- x$subj_per_arm effect_val <- x$effect_vals if (print_chg_warn == 1 & chkflag1 == 1) { print("Since sample size and effect_vals vectors only have 1 element each and tab_type not equal to 'XZ|WY' or 'ZX|WY', tab_type was set to XZ|WY") print("This works towards putting all results in a single table") } } if (length(x$subj_per_arm) == 1 & length(x$a0_vals) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "YZ|WX") & (tab_type != "ZY|WX")) { tab_type <- "YZ|WX" chkflag1 <- 1 } } if((length(tab_type)== 0) && (typeof(tab_type) == "character")){ tab_type <- "YZ|WX" chkflag1 <- 1 } subj_per_arm_val <- x$subj_per_arm a0_val <- x$a0_vals if (print_chg_warn == 1 & chkflag1 == 1) { print("Since sample size and a0 vectors only have 1 element each and tab_type not equal to 'YZ|WX' or 'ZY|WX', tab_type was set to YZ|WX") print("This works towards putting all results in a single table") } } if (length(x$a0_vals) == 1 & length(x$effect_vals) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "WZ|XY") & (tab_type != "ZW|XY")) { tab_type <- "WZ|XY" chkflag1 <- 1 } } if((length(tab_type)== 0) && (typeof(tab_type) == "character")){ tab_type <- "WZ|XY" chkflag1 <- 1 } a0_val <- x$a0_vals effect_val <- x$effect_vals if (print_chg_warn == 1 & chkflag1 == 1) { print("Since a0 and effect_vals vectors only have 1 element each and tab_type not equal to 'WZ|XY' or 'ZW|XY', tab_type was set to WZ|XY") print("This works towards putting all results in a single table") } } } print_error_checks(x, measure, tab_type, subj_per_arm_val, a0_val, effect_val, rand_control_diff_val) #Select the data array depending on user defined value of measure. if (tolower(measure) == "power") dataarray <- x$data$power if (tolower(measure) == "est") dataarray <- x$data$est if (tolower(measure) == "var") dataarray <- x$data$var if (tolower(measure) == "bias") dataarray <- x$data$bias if (tolower(measure) == "mse") dataarray <- x$data$mse if (toupper(tab_type) == "WX|YZ") { # Table of Design Characteristics: Sample Size by a0 effect_val_levels <- x$effect_vals rand_control_diff_levels <- x$rand_control_diff # check to make sure effect_val is in effect_vals and # rand_control_diff_val is in rand_control_diff effect_val_loc <- match(effect_val, effect_val_levels) rand_control_diff_loc <- match(rand_control_diff_val, rand_control_diff_levels) return_table <- dataarray[,, effect_val_loc, rand_control_diff_loc] } if (toupper(tab_type) == "WY|XZ") { # Table of Design Characteristics: Sample Size by Effect a0_val_levels <- x$a0_vals rand_control_diff_levels <- x$rand_control_diff # check to make sure a0_val is in a0_vals and # rand_control_diff_val is in rand_control_diff a0_val_loc <- match(a0_val, a0_val_levels) rand_cntrl_diff_loc <- match(rand_control_diff_val, rand_control_diff_levels) return_table <- dataarray[, a0_val_loc,, rand_cntrl_diff_loc] } if (toupper(tab_type) == "WZ|XY") { # Table of Design Characteristics: Sample Size by Control Differences a0_val_levels <- x$a0_vals effect_val_levels <- x$effect_vals # check to make sure effect_val is in effect_vals and # a0_val is in a0_vals a0_val_loc <- match(a0_val, a0_val_levels) effect_val_loc <- match(effect_val, effect_val_levels) return_table <- dataarray[, a0_val_loc, effect_val_loc, ] } if (toupper(tab_type) == "XY|WZ") { # Table of Design Characteristics: a0 by Effect subj_per_arm_levels <- x$subj_per_arm rand_control_diff_levels <- x$rand_control_diff # check to make sure subj_per_arm_val is in subj_per_arm and # rand_control_diff_val is in rand_control_diff subj_per_arm_loc <- match(subj_per_arm_val, subj_per_arm_levels) rand_control_diff_loc <- match(rand_control_diff_val, rand_control_diff_levels) return_table <- dataarray[subj_per_arm_loc,,, rand_control_diff_loc] } if (toupper(tab_type) == "XZ|WY") { # Table of Design Characteristics: a0 by Control Diffferences subj_per_arm_levels <- x$subj_per_arm effect_val_levels <- x$effect_vals # check to make sure effect_val is in effect_vals and # subj_per_arm_val is in subj_per_arm subj_per_arm_loc <- match(subj_per_arm_val, subj_per_arm_levels) effect_val_loc <- match(effect_val, effect_val_levels) return_table <- dataarray[subj_per_arm_loc,, effect_val_loc, ] } if (toupper(tab_type) == "YZ|WX") { # Table of Design Characteristics: Effect by Control Diffferences subj_per_arm_levels <- x$subj_per_arm a0_val_levels <- x$a0_vals # check to make sure subj_per_arm_val is in subj_per_arm and # a0_val is in a0_vals subj_per_arm_loc <- match(subj_per_arm_val, subj_per_arm_levels) a0_val_loc <- match(a0_val, a0_val_levels) return_table <- dataarray[subj_per_arm_loc, a0_val_loc,, ] } if (toupper(tab_type) == "XW|YZ") { # Table of Design Characteristics: a0 by sample size effect_val_levels <- x$effect_vals rand_control_diff_levels <- x$rand_control_diff # check to make sure rand_control_diff_val is in rand_control_diff and # effect_val is in effect_vals effect_val_loc <- match(effect_val, effect_val_levels) rand_control_diff_loc <- match(rand_control_diff_val, rand_control_diff_levels) return_table <- t(dataarray[,,effect_val_loc,rand_control_diff_loc]) } if (toupper(tab_type) == "YW|XZ") { # Table of Design Characteristics: Effect by sample size a0_val_levels <- x$a0_vals rand_control_diff_levels <- x$rand_control_diff # check to make sure rand_control_diff_val is in rand_control_diff and # a0_val is in a0_vals a0_val_loc <- match(a0_val, a0_val_levels) rand_control_parm_loc <- match(rand_control_diff_val, rand_control_diff_levels) return_table <- t(dataarray[,a0_val_loc,,rand_control_parm_loc]) } if (toupper(tab_type) == "YX|WZ") { # Table of Design Characteristics: Effect by a0 subj_per_arm_levels <- x$subj_per_arm rand_control_diff_levels <- x$rand_control_diff # check to make sure subj_per_arm_val is in subj_per_arm and # rand_control_diff_val is in rand_control_diff subj_per_arm_loc <- match(subj_per_arm_val, subj_per_arm_levels) rand_control_parm_loc <- match(rand_control_diff_val, rand_control_diff_levels) return_table <- dataarray[subj_per_arm_loc,,,rand_control_parm_loc] } if (toupper(tab_type) == "ZW|XY") { # Table of Design Characteristics: Control Differences by sample size a0_val_levels <- x$a0_vals effect_val_levels <- x$effect_vals # check to make sure a0_val is in a0_vals and # effect_val is in effect_vals a0_val_loc <- match(a0_val, a0_val_levels) effect_val_loc <- match(effect_val, effect_val_levels) return_table <- t(dataarray[,a0_val_loc,effect_val_loc, ]) } if (toupper(tab_type) == "ZX|WY") { # Table of Design Characteristics: Control Differences by a0 subj_per_arm_levels <- x$subj_per_arm effect_val_levels <- x$effect_vals # check to make sure subj_per_arm_val is in subj_per_arm and # effect_val is in effect_vals subj_per_arm_loc <- match(subj_per_arm_val, subj_per_arm_levels) effect_val_loc <- match(effect_val, effect_val_levels) return_table <- t(dataarray[subj_per_arm_loc,,effect_val_loc, ]) } if (toupper(tab_type) == "ZY|WX") { # Table of Design Characteristics: Control Differences by Effect subj_per_arm_levels <- x$subj_per_arm a0_val_levels <- x$a0_vals # check to make sure subj_per_arm_val is in subj_per_arm and # a0_val is in a0_vals subj_per_arm_loc <- match(subj_per_arm_val, subj_per_arm_levels) a0_val_loc <- match(a0_val, a0_val_levels) return_table <- t(dataarray[subj_per_arm_loc,a0_val_loc,, ]) } if (toupper(tab_type) == "YX|WZ") { # Table of Design Characteristics: Effect by a0 subj_per_arm_levels <- x$subj_per_arm rand_control_diff_levels <- x$rand_control_diff # check to make sure subj_per_arm_val is in subj_per_arm and # rand_control_diff_val is in rand_control_diff subj_per_arm_loc <- match(subj_per_arm_val, subj_per_arm_levels) rand_control_diff_val_loc <- match(rand_control_diff_val, rand_control_diff_levels) return_table <- t(dataarray[subj_per_arm_loc,,,rand_control_diff_val_loc ]) } return_table } #' Plot Data from Two Arm Bayesian Clinical Trial Simulation. #' #' \code{plot.bayes_ctd_array()} takes an S3 object of class \code{bayes_ctd_array}, and #' creates a line plot from a one or two dimensional slice of the data generated by a #' clinical trial simulation using \code{historic_sim()} or \code{simple_sim()}. The #' plotted results can be smoothed or unsmoothed. #' #' If the object of class \code{bayes_ctd_array} is created by \code{historic_sim()}, #' the function \code{plot()} allows the user to create line plots of user-specified #' 1- or 2- dimensional slices of the simulation results based on slicing code #' described below. If the object of class \code{bayes_ctd_array} is created by #' \code{simple_sim()}, a basic plot of characteristic by sample size and effect is created. #' #' If the object of class \code{bayes_ctd_array} is created by \code{simple_sim()}, then #' all four trial characteristics (\code{subj_per_arm_val}, \code{a0_vals}, #' \code{effect_val}, and \code{rand_control_diff_val}) can be ignored as can the #' parameter defining what type of plot to create through the parameter \code{tab_type}. #' A call to \code{plot()} will require the user to specify a measure (power, est, #' var, bias, or mse). #' #' If the object of class \code{bayes_ctd_array} is created by \code{historic_sim()}, #' when calling \code{plot()} the user must specify a measure to plot #' (power, est, var, bias, or mse) and may be required to specify a plot type through #' the \code{tab_type} parameter. A plot type, \code{tab_type}, will be required if #' 3 of the 4 trial characteristics are equal to a vector of 2 or more values. This #' plot type specification uses the letters W, X, Y, and Z. The letter W represents #' the subject per arm dimension. The letter X represents the a0 dimension. The #' letter Y represents the effect dimension. The letter Z represents the control #' difference dimension. To plot a slice of the 4-dimensional array, these letters #' are put into an AB|CD pattern just like in \code{print()}. The two letters #' to the right of the vertical bar define which variables are held constant. The two #' letters to the left of the vertical bar define which variables are going to show up #' in the plot. The first letter defines the x-axis variable and the second letter #' defines the stratification variable. The result is a plot of power, estimate, #' variance, bias, or mse by the trial characteristic represented by the first letter. #' On this plot, one line will be created for each value of the trial characteristic #' represented by the second letter. For example if tab_type equals \code{WX|YZ}, #' then effect and control differences will be held constant, while sample size will be #' represented along the horizontal axis and a0 values will be represented by separate #' lines. The actual values that are plotted on the y-axis depend on what measure is #' requested in the parameter \code{measure}. #' #' \itemize{ #' \item \code{tab_type='WX|YZ'}, Sample Size by a0 #' \item \code{tab_type='WY|XZ'}, Sample Size by Effect #' \item \code{tab_type='WZ|XY'}, Sample Size by Control Differences #' \item \code{tab_type='XY|WZ'}, a0 by Effect #' \item \code{tab_type='XZ|WY'}, a0 by Control Differences #' \item \code{tab_type='YZ|WX'}, Effect by Control Differences #' \item \code{tab_type='ZX|WY'}, Control Differences by a0 #' \item \code{tab_type='XW|YZ'}, a0 by Sample Size #' \item \code{tab_type='YW|XZ'}, Effect by Sample Size #' \item \code{tab_type='YX|WZ'}, Effect by a0 #' \item \code{tab_type='ZW|XY'}, Control Differences by Sample Size #' \item \code{tab_type='ZY|WX'}, Control Differences by Effect #' } #' It is very important to populate the values of \code{subj_per_arm_val}, #' \code{a0_val}, \code{effect_val}, and \code{rand_control_diff_val} correctly given #' the value of tab_type, when the object of class \code{bayes_ctd_array} is created by #' \code{historic_sim()} and at least 3 of the four parameters have more than one #' value. On, the other hand, if 2 or more of the four parameters have only one value, #' then \code{subj_per_arm_val}, \code{a0_vals}, \code{effect_val}, #' \code{rand_control_diff_val}, as well as \code{tab_type} can be ignored. If the last #' two letters are \code{YZ}, then \code{effect_val} and \code{rand_control_diff_val} #' must be populated. If the last two letters are \code{XZ}, then \code{a0_val} and #' \code{rand_control_diff_val} must be populated. If the last two letters are \code{XY}, #' then \code{a0_val} and \code{effect_val} must be populated. If the last two letters #' are \code{WZ}, then \code{sample_val} and \code{rand_control_diff_val} must be #' populated. If the last two letters are \code{WY}, then \code{sample_size_val} and #' \code{effect_val} must be populated. If the last two letters are \code{WX}, then #' \code{sample_size_val} and \code{a0_val} must be populated. #' #' If the object of class \code{bayes_ctd_array} is created by \code{simple_sim()}, the #' parameters \code{tab_type}, \code{subj_per_arm_val}, \code{a0_val}, \code{effect_val}, #' and \code{rand_control_diff_val} are ignored. #' #' @param x Name of object of class \code{bayes_ctd_array} containing #' data from clinical trial simulation. #' @param measure Must be equal to \code{power}, \code{est}, \code{var}, \code{bias}, #' or \code{mse}. Default is \code{power}. Case does not matter. #' @param tab_type A character string that must equal \code{WX|YZ}, \code{WY|XZ}, #' \code{WZ|XY}, \code{XY|WZ}, \code{XZ|WY}, \code{YZ|WX}, \code{ZX|WY}, \code{XW|YZ}, #' \code{YW|XZ}, \code{YX|WZ}, \code{ZW|XY}, \code{ZX|WY}, \code{ZY|WX} when #' \code{x} is generated by \code{historic_sim()}. Default is #' \code{WX|YZ}. When \code{x} is generated by \code{simple_sim()}, #' \code{tab_type} is ignored. #' @param smooth A true/false parameter indicating whether smoothed results #' should be plotted. Note, smoothing of simulation results requires the length of #' \code{subj_per_arm_val} or \code{a0_val} or \code{effect_val} or #' \code{rand_control_diff_val}, whichever populates the x-axis on the graph to #' contain enough elements to justify the smoothing. No checking occurs to #' determine if enough elements are present to justify smoothing. Default is #' \code{FALSE}. #' @param plot_out A true/false parameter indicating whether the plot should be #' produced. This parameter is useful if the user only wants a table of smoothed #' values. Default is \code{TRUE}. #' @param subj_per_arm_val Must be non-missing, if \code{x} is generated #' by \code{historic_sim()} and sample size is being held constant. #' If \code{x} is generated by \code{historic_sim()} and sample size #' is being held constant, \code{subj_per_arm_val} must equal a value submitted #' to \code{historic_sim()} within the \code{subj_per_arm} parameter. When #' \code{x} is generated by \code{simple_sim()}, \code{subj_per_arm_val} #' is ignored. #' @param a0_val Must be non-missing, if \code{x} is generated #' by \code{historic_sim()} and a0, the power prior parameter, is being held #' constant. If \code{x} is generated by \code{historic_sim()} and #' a0 is being held constant, \code{a0_val} must equal a value submitted #' to \code{historic_sim()} within the \code{a0_val} parameter. When #' \code{x} is generated by \code{simple_sim()}, \code{a0_val} is #' ignored. #' @param effect_val Must be non-missing, if \code{x} is generated #' by \code{historic_sim()} and effect is being held constant. If #' \code{x} is generated by \code{historic_sim()} and effect is being #' held constant, \code{effect_val} must equal a value submitted to #' \code{historic_sim()} within the \code{effect_vals} parameter. When #' \code{x} is generated by \code{simple_sim()}, \code{effect_val} is #' ignored. #' @param rand_control_diff_val Must be non-missing, if \code{x} is #' generated by \code{historic_sim()} and differences between randomized #' and historical controls are being held constant. If \code{x} #' is generated by \code{historic_sim()} and control differences are being #' held constant, \code{rand_control_diff_val} must equal a value submitted to #' \code{historic_sim()} within the \code{rand_control_diff} parameter. When #' \code{x} is generated by \code{simple_sim()}, #' \code{rand_control_diff_val} is ignored. #' @param span The \code{span} parameter value for a call \code{loess()}. Default is 0.75. If #' \code{span} is a single number, then that value will be used to smooth the data in all #' columns of the table being plotted. If \code{span} is a vector, then it must have length #' equal to the number of columns being plotted. #' @param degree The \code{degree} parameter value for a call \code{loess()}. Default is 2. #' The value of \code{degree} will be used for all columns being plotted. #' @param family The \code{family} parameter value for a call \code{loess()}. Default is #' "\code{gaussian}". The value of \code{family} will be used for all columns being plotted. #' @param title Title for the plot. #' @param ylim Lower and upper limits for y-axis of plot. #' @param ... further arguments passed to or from other methods. #' #' @return \code{plot()} returns a plot for a two dimensional array of simulation #' results. If \code{smooth} is \code{TRUE}, then the plot is based on a smoothed #' version of the simulation results. If \code{smooth} is \code{FALSE}, then the plot #' is based on the raw data from the simulation results. What actually is plotted #' depends on the value of \code{measure}. If \code{plot_out} is \code{FALSE}, the #' plot is not created. This option is useful when the user wants a table of smoothed #' simulation results but does not want the plot. Smoothing of simulation results #' requires the length of \code{subj_per_arm_val} or \code{a0_val} or \code{effect_val} #' or \code{rand_control_diff_val}, whichever populates the x-axis on the graph to #' contain enough elements to justify the smoothing. No checking occurs to #' determine if enough elements are present to justify smoothing. #' #' @references Eggleston et al. (2021). BayesCTDesign: An R Package for Bayesian Trial Design Using Historical Control Data. \emph{Journal of Statistical Software}, November 2021, Volume 100, Issue 21, <doi:10.18637/jss.v100.i21>. #' #' @examples #' #Run a Weibull simulation, using simple_sim(). #' #For meaningful results, trial_reps needs to be much larger than 2. #' weibull_test <- simple_sim(trial_reps = 2, outcome_type = "weibull", #' subj_per_arm = c(50, 100, 150, 200), #' effect_vals = c(0.6, 1), #' control_parms = c(2.82487,3), time_vec = NULL, #' censor_value = NULL, alpha = 0.05, #' get_var = TRUE, get_bias = TRUE, get_mse = TRUE, #' seedval=123, quietly=TRUE) #' #' #Create a plot of the power simulation results. #' plot(x=weibull_test, measure="power", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL) #' #Create a plot of the hazard ratio simulation results. #' plot(x=weibull_test, measure="est", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL) #' #Create a plot of the hazard ratio variance simulation results. #' plot(x=weibull_test, measure="var", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL) #' #Create a plot of the hazard ratio bias simulation results. #' plot(x=weibull_test, measure="bias", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL) #' #Create a plot of the hazard ratio mse simulation results. #' plot(x=weibull_test, measure="mse", tab_type=NULL, #' smooth=FALSE, plot_out=TRUE, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL) #' #' \donttest{ #' #Run a second Weibull simulation, using simple_sim() and smooth the plot. #' #For meaningful results, trial_reps needs to be larger than 100. #' weibull_test2 <- simple_sim(trial_reps = 100, outcome_type = "weibull", #' subj_per_arm = c(50, 75, 100, 125, 150, 175, 200, 225, 250), #' effect_vals = c(0.6, 1, 1.4), #' control_parms = c(2.82487,3), time_vec = NULL, #' censor_value = NULL, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' #' #Create a plot of the power simulation results. #' plot(x=weibull_test2, measure="power", tab_type=NULL, #' smooth=TRUE, plot_out=TRUE, subj_per_arm_val=NULL, a0_val=NULL, #' effect_val=NULL, rand_control_diff_val=NULL, span=c(1,1,1)) #' } #' #' \donttest{ #' #Run a third weibull simulation, using historic_sim(). #' #Note: historic_sim() can take a while to run. #' #Generate a sample of historical data for use in example. #' set.seed(2250) #' SampleHistData <- genweibulldata(sample_size=60, scale1=2.82487, #' hazard_ratio=0.6, common_shape=3, #' censor_value=3) #' histdata <- subset(SampleHistData, subset=(treatment==0)) #' histdata$id <- histdata$id+10000 #' #' #For meaningful results, trial_reps needs to be larger than 100. #' weibull_test3 <- historic_sim(trial_reps = 100, outcome_type = "weibull", #' subj_per_arm = c(50, 100, 150, 200, 250), #' a0_vals = c(0, 0.33, 0.67, 1), #' effect_vals = c(0.6, 1, 1.4), #' rand_control_diff = c(0.8, 1, 1.2), #' hist_control_data = histdata, time_vec = NULL, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' #' #Create a plot of the power simulation results. #' plot(x=weibull_test3, measure="power", tab_type="WX|YZ", #' smooth=FALSE, plot_out=TRUE, effect_val=0.6, #' rand_control_diff_val=1.0) #' } #' #' \donttest{ #' #Run a Gaussian simulation, using historic_sim() #' #Generate a sample of historical Gaussian data for use in example. #' set.seed(2250) #' samplehistdata <- gengaussiandata(sample_size=60, mu1=25, mean_diff=0, common_sd=3) #' histdata <- subset(samplehistdata, subset=(treatment==0)) #' histdata$id <- histdata$id+10000 #' #' #For meaningful results, trial_reps needs to be larger than 100. #' gaussian_test <- historic_sim(trial_reps = 100, outcome_type = "gaussian", #' subj_per_arm = c(150), #' a0_vals = c(1.0), #' effect_vals = c(0.15), #' rand_control_diff = c(-4.0,-3.5,-3.0,-2.5,-2.0, #' -1.5,-1.0,-0.5,0,0.5,1.0), #' hist_control_data = histdata, time_vec = NULL, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' test_table <- print(x=gaussian_test, measure="power", #' tab_type=NULL, effect_val=NULL, #' subj_per_arm_val=NULL) #' print(test_table) #' #Create a plot of the power simulation results. #' plot(x=gaussian_test, measure="power", tab_type=NULL, #' smooth=TRUE, plot_out=TRUE, effect_val=NULL, #' rand_control_diff_val=NULL) #' } #' #' \donttest{ #' #Generate a sample of historical pwe data for use in example. #' set.seed(2250) #' nvalHC <- 60 #' time.vec <- c(0.3,0.9,1.5,2.1,2.4) #' lambdaHC.vec <- c(0.19,0.35,0.56,0.47,0.38,0.34) #' censor.value <- 3 #' #' SampleHistData <- genpwedata(nvalHC, lambdaHC.vec, 1.0, time.vec, censor.value) #' histdata <- subset(SampleHistData, subset=(treatment==0)) #' histdata$indicator <- 2 #If set to 2, then historical controls will be collapsed with #' #randomized controls, when time_vec is re-considered and #' #potentially restructured. If set to 1, then historical #' #controls will be treated as a separated cohort when #' #time_vec is being assessed for restructuring. #' histdata$id <- histdata$id+10000 #' #' #Run a pwe simulation, using historic_sim(). #' #For meaningful results, trial_reps needs to be larger than 100. #' pwe_test <- historic_sim(trial_reps = 100, outcome_type = "pwe", #' subj_per_arm = c(25,50,75,100,125,150,175,200,225,250), #' a0_vals = c(1.0), #' effect_vals = c(0.6), #' rand_control_diff = c(1.8), #' hist_control_data = histdata, time_vec = time.vec, #' censor_value = 3, alpha = 0.05, get_var = TRUE, #' get_bias = TRUE, get_mse = TRUE, seedval=123, #' quietly=TRUE) #' #' #Create a plot of the power simulation results. #' plot(x=pwe_test, measure="power", tab_type=NULL, #' smooth=TRUE, plot_out=TRUE, effect_val=NULL, #' rand_control_diff_val=NULL) #' } #' #' @export plot.bayes_ctd_array <- function(x = NULL, measure = "power", tab_type = "WX|YZ", smooth = FALSE, plot_out = TRUE, subj_per_arm_val = NULL, a0_val = NULL, effect_val = NULL, rand_control_diff_val = NULL, span = 0.75, degree = 2, family = "gaussian", title=NULL, ylim=NULL, ...) { # (W): subj_per_arm, # (X): a0_val, # (Y): effect_val, # (Z): rand_control_diff # tab_type='WX|YZ', Line Plot of Design Characteristics: Sample Size by a0 # tab_type='WY|XZ', Line Plot of Design Characteristics: Sample Size by Effect # tab_type='WZ|XY', Line Plot of Design Characteristics: Sample Size by Control Differences # tab_type='XY|WZ', Line Plot of Design Characteristics: a0 by Effect # tab_type='XZ|WY', Line Plot of Design Characteristics: a0 by Control Diffferences # tab_type='YZ|WX', Line Plot of Design Characteristics: Effect by Control Diffferences # tab_type='ZX|WY', Line Plot of Design Characteristics: Control Diffferences by a0 # tab_type='XW|YZ', Line Plot of Design Characteristics: a0 by Sample Size # tab_type='YW|XZ', Line Plot of Design Characteristics: Effect by Sample Size # tab_type='YX|WZ', Line Plot of Design Characteristics: Effect by a0 # tab_type='ZW|XY', Line Plot of Design Characteristics: Control Differences by Sample Size # tab_type='ZY|WX', Line Plot of Design Characteristics: Control Differences by Effect #Add simple code to help out the user with tab_type on matters where order is #not important and can be easily fixed. tab_type = toupper(tab_type) if (!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if (x$objtype == 'historic') { if (tab_type=='WX|ZY') tab_type <- 'WX|YZ' if (tab_type=='WY|ZX') tab_type <- 'WY|XZ' if (tab_type=='WZ|YX') tab_type <- 'WZ|XY' if (tab_type=='XY|ZW') tab_type <- 'XY|WZ' if (tab_type=='XZ|YW') tab_type <- 'XZ|WY' if (tab_type=='YZ|XW') tab_type <- 'YZ|WX' if (tab_type=='ZX|YW') tab_type <- 'ZX|WY' if (tab_type=='XW|ZY') tab_type <- 'XW|YZ' if (tab_type=='YW|ZX') tab_type <- 'YW|XZ' if (tab_type=='YX|ZW') tab_type <- 'YX|WZ' if (tab_type=='ZW|YX') tab_type <- 'ZW|XY' if (tab_type=='ZY|XW') tab_type <- 'ZY|WX' } } #Do the same for measure measure = tolower(measure) #The above code was added very late in initial production, so time was not # available to go through all code and remove code no longer necessary. #------------- Go through all the high level checks for proper input. -------------# if (x$objtype == 'simple') { tab_type <- "WY|XZ" a0_val <- 0 rand_control_diff_val <- 1 subj_per_arm_val <- x$subj_per_arm[1] effect_val <- x$effect_vals[1] print("Since simple_sim was used, tab_type was set to WY|XZ") print("Values for tab_type, subj_per_arm_val, a0_val, effect_val, and rand_control_diff_val were ignored") print("This works towards putting all results on a single plot, effect by sample size") } if (x$objtype == 'realsimple') { if (length(x$subj_per_arm) > 1) { print("Since only subj_per_arm vector has more than 1 element, tab_type was set to WX|YZ") print("This works towards putting all results in a single table") tab_type <- "WX|YZ" a0_val <- x$a0_vals[1] effect_val <- x$effect_vals[1] rand_control_diff_val <- x$rand_control_diff[1] } if (length(x$a0_vals) > 1) { print("Since only a0_vals vector has more than 1 element, tab_type was set to XY|WZ") print("This works towards putting all results in a single table") tab_type <- "XY|WZ" subj_per_arm_val <- x$subj_per_arm[1] effect_val <- x$effect_vals[1] rand_control_diff_val <- x$rand_control_diff[1] } if (length(x$effect_vals) > 1) { print("Since only effect_vals vector has more than 1 element, tab_type was set to YZ|WX") print("This works towards putting all results in a single table") tab_type <- "YZ|WX" subj_per_arm_val <- x$subj_per_arm[1] a0_val <- x$a0_vals[1] rand_control_diff_val <- x$rand_control_diff[1] } if (length(x$rand_control_diff) > 1) { print("Since only rand_control_diff vector has more than 1 element, tab_type was set to ZX|WY") print("This works towards putting all results in a single table") tab_type <- "ZX|WY" subj_per_arm_val <- x$subj_per_arm[1] a0_val <- x$a0_vals[1] effect_val <- x$effect_vals[1] } } if (x$objtype == 'historic') { # Check to see if two dimensions of x have only 1 element each. Is so set tab_type to an appropriate # value. if (length(x$effect_vals) == 1 & length(x$rand_control_diff) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "WX|YZ") & (tab_type != "XW|YZ")) { tab_type <- "WX|YZ" chkflag1 <- 1 } } if( (length(tab_type)== 0) && (typeof(tab_type) == "character")){ tab_type <- "WX|YZ" chkflag1 <- 1 } effect_val <- x$effect_vals[1] rand_control_diff_val <- x$rand_control_diff[1] if (chkflag1 == 1) { print("Since effect_vals and rand_control_diff vectors only have 1 element each and tab_type not equal to 'WX|YZ' or 'XW|YZ', tab_type was set to WX|YZ") print("This works towards putting all results on a single plot") } } if (length(x$a0_vals) == 1 & length(x$rand_control_diff) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "WY|XZ") & (tab_type != "YW|XZ")) { tab_type <- "WY|XZ" chkflag1 <- 1 } } if( (length(tab_type)== 0) && (typeof(tab_type) == "character") ){ tab_type <- "WY|XZ" chkflag1 <- 1 } a0_val <- x$a0_vals[1] rand_control_diff_val <- x$rand_control_diff[1] if (chkflag1 == 1) { print("Since a0 and rand_control_diff vectors only have 1 element each and tab_type not equal to 'WY|XZ' or 'YW|XZ', tab_type was set to WY|XZ") print("This works towards putting all results on a single plot") } } if (length(x$subj_per_arm) == 1 & length(x$rand_control_diff) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "XY|WZ") & (tab_type != "YX|WZ")) { tab_type <- "XY|WZ" chkflag1 <- 1 } } if( (length(tab_type)== 0) && (typeof(tab_type) == "character") ){ tab_type <- "XY|WZ" chkflag1 <- 1 } subj_per_arm_val <- x$subj_per_arm rand_control_diff_val <- x$rand_control_diff if (chkflag1 == 1) { print("Since sample size and rand_control_diff vectors only have 1 element each and tab_type not equal to 'XY|WZ' or 'YX|WZ', tab_type was set to XY|WZ") print("This works towards putting all results on a single plot") } } if (length(x$subj_per_arm) == 1 & length(x$effect_vals) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "XZ|WY") & (tab_type != "ZX|WY")) { tab_type <- "XZ|WY" chkflag1 <- 1 } } if( (length(tab_type)== 0) && (typeof(tab_type) == "character") ){ tab_type <- "XZ|WY" chkflag1 <- 1 } subj_per_arm_val <- x$subj_per_arm effect_val <- x$effect_vals if (chkflag1 == 1) { print("Since sample size and effect_vals vectors only have 1 element each and tab_type not equal to 'XZ|WY' or 'ZX|WY', tab_type was set to XZ|WY") print("This works towards putting all results on a single plot") } } if (length(x$subj_per_arm) == 1 & length(x$a0_vals) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "YZ|WX") & (tab_type != "ZY|WX")) { tab_type <- "YZ|WX" chkflag1 <- 1 } } if( (length(tab_type)== 0) && (typeof(tab_type) == "character") ){ tab_type <- "YZ|WX" chkflag1 <- 1 } subj_per_arm_val <- x$subj_per_arm a0_val <- x$a0_vals if (chkflag1 == 1) { print("Since sample size and a0 vectors only have 1 element each and tab_type not equal to 'YZ|WX' or 'ZY|WX', tab_type was set to YZ|WX") print("This works towards putting all results on a single plot") } } if (length(x$a0_vals) == 1 & length(x$effect_vals) == 1) { chkflag1 <- 0 if(!((length(tab_type)== 0) && (typeof(tab_type) == "character"))){ if ((tab_type != "WZ|XY") & (tab_type != "ZW|XY")) { tab_type <- "WZ|XY" chkflag1 <- 1 } } if( (length(tab_type)== 0) && (typeof(tab_type) == "character") ){ tab_type <- "WZ|XY" chkflag1 <- 1 } a0_val <- x$a0_vals effect_val <- x$effect_vals if (chkflag1 == 1) { print("Since a0 and effect_vals vectors only have 1 element each and tab_type not equal to 'WZ|XY' or 'ZW|XY', tab_type was set to WZ|XY") print("This works towards putting all results on a single plot") } } } plot_error_checks(x, measure, tab_type, smooth, plot_out, subj_per_arm_val, a0_val, effect_val, rand_control_diff_val, span) #If title is NULL, create a title from the two parameters that are fixed. if (is.null(title)){ # (W): subj_per_arm_val, # (X): a0_val, # (Y): effect_val, # (Z): rand_control_diff_val #WX|YZ, WY|XZ, WZ|XY, XY|WZ, XZ|WY, YZ|WX, ZX|WY, XW|YZ, YW|XZ, YX|WZ, ZW|XY, ZX|WY, or ZY|WX if (tab_type == 'WX|YZ'){ title = paste0('effect_val =', effect_val,' and rand_control_diff_val =', rand_control_diff_val) } if (tab_type == 'WY|XZ'){ title = paste0('a0_val =', a0_val,' and rand_control_diff_val =', rand_control_diff_val) } if (tab_type == 'WZ|XY'){ title = paste0('a0_val =', a0_val,' and effect_val =', effect_val) } if (tab_type == 'XY|WZ'){ title = paste0('subj_per_arm_val =', subj_per_arm_val,' and rand_control_diff_val =', rand_control_diff_val) } if (tab_type == 'XZ|WY'){ title = paste0('subj_per_arm_val =', subj_per_arm_val,' and effect_val =', effect_val) } if (tab_type == 'YZ|WX'){ title = paste0('subj_per_arm_val =', subj_per_arm_val,' and a0_val =', a0_val) } if (tab_type == 'ZX|WY'){ title = paste0('subj_per_arm_val =', subj_per_arm_val,' and effect_val =', effect_val) } if (tab_type == 'XW|YZ'){ title = paste0('effect_val =', effect_val,' and rand_control_diff_val =', rand_control_diff_val) } if (tab_type == 'YW|XZ'){ title = paste0('a0_val =', a0_val,' and rand_control_diff_val =', rand_control_diff_val) } if (tab_type == 'YX|WZ'){ title = paste0('subj_per_arm_val =', subj_per_arm_val,' and rand_control_diff_val =', rand_control_diff_val) } if (tab_type == 'ZW|XY'){ title = paste0('a0_val =', a0_val,' and effect_val =', effect_val) } if (tab_type == 'ZX|WY'){ title = paste0('subj_per_arm_val =', subj_per_arm_val,' and effect_val =', effect_val) } if (tab_type == 'ZY|WX'){ title = paste0('subj_per_arm_val =', subj_per_arm_val,' and a0_val =', a0_val) } } if (tab_type == "WX|YZ") { # Line Plot of Design Characteristics: Sample Size by a0 # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = tab_type, effect_val = effect_val, rand_control_diff_val = rand_control_diff_val, print_chg_warn = 0) table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$a0_vals), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("sample_size", "a0_val", measure) table_dat$sample_size <- as.numeric(table_dat$sample_size) #Construct proper values for the line variable. avec <- NULL if (table_dat$a0_val[1] == "table_mat") { table_dat$a0_val <- "0" } else if (table_dat$a0_val[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$a0_val <- avec table_dat$a0_val <- as.character(table_dat$a0_val) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'power', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Sample Size', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'est', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Sample Size', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'var', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Sample Size', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'bias', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Sample Size', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'mse', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Sample Size', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "WY|XZ") { # Line Plot of Design Characteristics: Sample Size by Effect # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "WY|XZ", a0_val = a0_val, rand_control_diff_val = rand_control_diff_val, print_chg_warn = 0) table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$effect_vals), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("sample_size", "effect_val", measure) table_dat$sample_size <- as.numeric(table_dat$sample_size) #Construct proper values for the line variable. avec <- NULL for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$effect_val <- avec table_dat$effect_val <- as.character(table_dat$effect_val) #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'power', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Sample Size', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'est', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Sample Size', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'var', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Sample Size', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'bias', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Sample Size', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'mse', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Sample Size', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "WZ|XY") { # Line Plot of Design Characteristics: Sample Size by Control Differences # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "WZ|XY", a0_val = a0_val, effect_val = effect_val, print_chg_warn = 0) table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$rand_control_diff), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("sample_size", "control_differences", measure) table_dat$sample_size <- as.numeric(table_dat$sample_size) #Construct proper values for the line variable. avec <- NULL if (table_dat$control_differences[1] == "table_mat") { table_dat$control_differences <- "1" } else if (table_dat$control_differences[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$control_differences <- avec table_dat$control_differences <- as.character(table_dat$control_differences) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'power', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Sample Size', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'est', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Sample Size', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'var', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Sample Size', y='Variance')+ ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'bias', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Sample Size', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'sample_size', y = 'mse', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Sample Size', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "XY|WZ") { # Line Plot of Design Characteristics: a0 by Effect # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "XY|WZ", subj_per_arm_val = subj_per_arm_val, rand_control_diff_val = rand_control_diff_val, print_chg_warn = 0) table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$effect_vals), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("a0_val", "effect_val", measure) table_dat$a0_val <- as.numeric(table_dat$a0_val) #Construct proper values for the line variable. avec <- NULL for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$effect_val <- avec table_dat$effect_val <- as.character(table_dat$effect_val) #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'power', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='a0 Value', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'est', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='a0 Value', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'var', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='a0 Value', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'bias', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='a0 Value', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'mse', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='a0 Value', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "XZ|WY") { # Line Plot of Design Characteristics: a0 by Control Diffferences # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "XZ|WY", subj_per_arm_val = subj_per_arm_val, effect_val = effect_val, print_chg_warn = 0) table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$rand_control_diff), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("a0_val", "control_differences", measure) table_dat$a0_val <- as.numeric(table_dat$a0_val) #Construct proper values for the line variable. avec <- NULL for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$control_differences <- avec table_dat$control_differences <- as.character(table_dat$control_differences) #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'power', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='a0 Value', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'est', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='a0 Value', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'var', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='a0 Value', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'bias', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='a0 Value', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'mse', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='a0 Value', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "YZ|WX") { # Line Plot of Design Characteristics: Effect by Control Diffferences # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "YZ|WX", subj_per_arm_val = subj_per_arm_val, a0_val = a0_val, print_chg_warn = 0) table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$rand_control_diff), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("effect_val", "control_differences", measure) table_dat$effect_val <- as.numeric(table_dat$effect_val) #Construct proper values for the line variable. avec <- NULL if (table_dat$control_differences[1] == "table_mat") { table_dat$control_differences <- "1" } else if (table_dat$control_differences[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$control_differences <- avec table_dat$control_differences <- as.character(table_dat$control_differences) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'power', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Effect Value', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'est', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Effect Value', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'var', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Effect Value', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'bias', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Effect Value', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'mse', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Effect Value', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "ZX|WY") { # Line Plot of Design Characteristics: Control Diffferences by a0 # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "ZX|WY", subj_per_arm_val = subj_per_arm_val, effect_val = effect_val, print_chg_warn = 0) #The following if block makes the 1D case work, if it occurs. #The return of a 1D vector from print(tab_type="ZX|WY") # which is a 1byK row vector with class=matrix causes problems #when I make it into a dataframe. The following code re-classifies #the object as a vector if necessary. if (is.matrix(table_mat) & dim(table_mat)[1]==1){ colnamevec <- colnames(table_mat) table_mat <- as.vector(table_mat) names(table_mat) <- colnamevec } table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$a0_vals), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("control_differences", "a0_val", measure) table_dat$control_differences <- as.numeric(table_dat$control_differences) #Construct proper values for the line variable. avec <- NULL if (table_dat$a0_val[1] == "table_mat") { table_dat$a0_val <- "1" } else if (table_dat$a0_val[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$a0_val <- avec table_dat$a0_val <- as.character(table_dat$a0_val) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'power', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Control Differences', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'est', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Control Differences', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'var', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Control Differences', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'bias', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Control Differences', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'mse', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Control Differences', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "XW|YZ") { # Line Plot of Design Characteristics: a0 by sample size # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "XW|YZ", effect_val = effect_val, rand_control_diff_val = rand_control_diff_val, print_chg_warn = 0) #The following if block makes the 1D case work, if it occurs. #The return of a 1D vector from print(tab_type="ZX|WY") # which is a 1byK row vector with class=matrix causes problems #when I make it into a dataframe. The following code re-classifies #the object as a vector if necessary. if (is.matrix(table_mat) & dim(table_mat)[1]==1){ colnamevec <- colnames(table_mat) table_mat <- as.vector(table_mat) names(table_mat) <- colnamevec } table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$subj_per_arm), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("a0_val", "subj_per_arm", measure) table_dat$a0_val <- as.numeric(table_dat$a0_val) #Construct proper values for the line variable. avec <- NULL if (table_dat$subj_per_arm[1] == "table_mat") { table_dat$subj_per_arm <- "1" } else if (table_dat$subj_per_arm[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$subj_per_arm <- avec table_dat$subj_per_arm <- as.character(table_dat$subj_per_arm) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'power', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='a0_val', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'est', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='a0_val', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'var', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='a0_val', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'bias', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='a0_val', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'a0_val', y = 'mse', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='a0_val', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "YW|XZ") { # Line Plot of Design Characteristics: Effect by sample size # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "YW|XZ", a0_val = a0_val, rand_control_diff_val=rand_control_diff_val, print_chg_warn = 0) #The following if block makes the 1D case work, if it occurs. #The return of a 1D vector from print(tab_type="ZX|WY") # which is a 1byK row vector with class=matrix causes problems #when I make it into a dataframe. The following code re-classifies #the object as a vector if necessary. if (is.matrix(table_mat) & dim(table_mat)[1]==1){ colnamevec <- colnames(table_mat) table_mat <- as.vector(table_mat) names(table_mat) <- colnamevec } table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$subj_per_arm), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("effect_val", "subj_per_arm", measure) table_dat$effect_val <- as.numeric(table_dat$effect_val) #Construct proper values for the line variable. avec <- NULL if (table_dat$subj_per_arm[1] == "table_mat") { table_dat$subj_per_arm <- "1" } else if (table_dat$subj_per_arm[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$subj_per_arm <- avec table_dat$subj_per_arm <- as.character(table_dat$subj_per_arm) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'power', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Effect Value', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'est', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Effect Value', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'var', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Effect Value', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'bias', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Effect Value', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'mse', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Effect Value', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "ZW|XY") { # Line Plot of Design Characteristics: Control differences by sample size # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "ZW|XY", a0_val = a0_val, effect_val=effect_val, print_chg_warn = 0) #The following if block makes the 1D case work, if it occurs. #The return of a 1D vector from print(tab_type="ZX|WY") # which is a 1byK row vector with class=matrix causes problems #when I make it into a dataframe. The following code re-classifies #the object as a vector if necessary. if (is.matrix(table_mat) & dim(table_mat)[1]==1){ colnamevec <- colnames(table_mat) table_mat <- as.vector(table_mat) names(table_mat) <- colnamevec } table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$subj_per_arm), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("control_differences", "subj_per_arm", measure) table_dat$control_differences <- as.numeric(table_dat$control_differences) #Construct proper values for the line variable. avec <- NULL if (table_dat$subj_per_arm[1] == "table_mat") { table_dat$subj_per_arm <- "1" } else if (table_dat$subj_per_arm[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$subj_per_arm <- avec table_dat$subj_per_arm <- as.character(table_dat$subj_per_arm) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'power', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Control Differences', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'est', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Control Differences', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'var', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Control Differences', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'bias', group = 'subj_per_arm', color = 'subj_per_arm')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Subjects per Arm', x='Control Differences', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'mse', group = 'control_differences', color = 'control_differences')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Control\nDifferences', x='Control Differences', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "ZY|WX") { # Line Plot of Design Characteristics: a0 by Effect # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "ZY|WX", subj_per_arm_val = subj_per_arm_val, a0_val = a0_val, print_chg_warn = 0) #The following if block makes the 1D case work, if it occurs. #The return of a 1D vector from print(tab_type="ZX|WY") # which is a 1byK row vector with class=matrix causes problems #when I make it into a dataframe. The following code re-classifies #the object as a vector if necessary. if (is.matrix(table_mat) & dim(table_mat)[1]==1){ colnamevec <- colnames(table_mat) table_mat <- as.vector(table_mat) names(table_mat) <- colnamevec } table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$effect_vals), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("control_differences", "effect_val", measure) table_dat$control_differences <- as.numeric(table_dat$control_differences) #Construct proper values for the line variable. avec <- NULL for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$effect_val <- avec table_dat$effect_val <- as.character(table_dat$effect_val) #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'power', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Control Differences', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'est', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Control Differences', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'var', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Control Differences', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'bias', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Control Differences', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'control_differences', y = 'mse', group = 'effect_val', color = 'effect_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='Effect Value', x='Control Differences', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } if (tab_type == "YX|WZ") { # Line Plot of Design Characteristics: Effect by a0 # First generate the table using a call to print. table_mat <- print(x = x, measure = measure, tab_type = "YX|WZ", subj_per_arm_val = subj_per_arm_val, rand_control_diff_val = rand_control_diff_val, print_chg_warn = 0) #The following if block makes the 1D case work, if it occurs. #The return of a 1D vector from print(tab_type="ZX|WY") # which is a 1byK row vector with class=matrix causes problems #when I make it into a dataframe. The following code re-classifies #the object as a vector if necessary. if (is.matrix(table_mat) & dim(table_mat)[1]==1){ colnamevec <- colnames(table_mat) table_mat <- as.vector(table_mat) names(table_mat) <- colnamevec } table_mat <- data.frame(table_mat) if (dim(table_mat)[2]==1){ tempcolname <- paste('X', as.character(x$a0_vals), sep='') colnames(table_mat) <- tempcolname } # Use a call to stats::loess to smooth simulation results is requested. if (smooth == TRUE) { colcnt <- dim(table_mat)[2] if (length(span) == 1) #If span is single number, then use it to smooth all columns. span <- rep(span, colcnt) y <- as.numeric(rownames(table_mat)) for (i in 1:colcnt) { loessfit <- stats::loess(table_mat[, i] ~ y, span = span[i], degree = degree, family = family) table_mat[, i] <- stats::predict(loessfit, data.frame(y = y)) } } # If no plot needed, then return the table. A user should only use this # option when they want to use the plot method to get a table of # smoothed results. if (plot_out == FALSE) { return(table_mat) } if (plot_out == TRUE) { #Shape the data for plotting. table_mat$row_names <- as.numeric(rownames(table_mat)) table_dat <- reshape2::melt(table_mat, id = "row_names") colnames(table_dat) <- c("effect_val", "a0_val", measure) table_dat$effect_val <- as.numeric(table_dat$effect_val) #Construct proper values for the line variable. avec <- NULL if (table_dat$a0_val[1] == "table_mat") { table_dat$a0_val <- "1" } else if (table_dat$a0_val[1] != "table_mat") { for (i in 1:dim(table_dat)[1]) { avec[i] <- as.numeric(unlist(strsplit(as.character(table_dat[i, 2]), split = "X", fixed = TRUE)))[2] } table_dat$a0_val <- avec table_dat$a0_val <- as.character(table_dat$a0_val) } #Create the appropriate graph depending on the value of measure. if (measure == "power") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'power', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Effect Value', y='Power') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "est") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'est', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Effect Value', y='Estimate') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "var") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'var', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Effect Value', y='Variance') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "bias") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'bias', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Effect Value', y='Bias') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } if (measure == "mse") { p <- ggplot2::ggplot(data = table_dat, ggplot2::aes_string(x = 'effect_val', y = 'mse', group = 'a0_val', color = 'a0_val')) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::labs(color='a0 Value', x='Effect Value', y='MSE') + ggplot2::ggtitle(title) if (!is.null(ylim)){ p <- p + ggplot2::ylim(ylim) } return(p) } } } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/BayesCTDesigncode.R
#' Generating function for Bernoulli Data. #' #' \code{genlogisticdata()} function used mainly internally by #' \code{logistictrialsimulator()} function to generate data for a two-arm #' clinical trial, experimental and control groups. Can be used to generate #' random trial data. #' #' @param sample_size Number of subjects per arm. #' @param prob1 prob parameter used in call to \code{rbinom()}. #' Used only in control arm. #' @param odds_ratio Desired Odds Ratio between experimental and control groups. #' #' @return \code{genlogisticdata()} returns a data frame with columns: 'id', 'treatment', #' and 'y'. #' #' @examples #' samplehistdata <- genbernoullidata(sample_size=60, prob1=0.6, odds_ratio=0.6) #' samplehistdata #' @export #' genbernoullidata <- function(sample_size, prob1, odds_ratio) { # --------------------------------------------------------------- # # The function genbernoullidata simulates a balanced clinical trial # with 'sample_size' subjects per arm using a binomial distribution. # 'prob1' is the proportion for events in controls. 'odds_ratio is # the ratio of group odds (experimental group over control group). # # In the code below y1 and prob1 are data for the control goup. # In the code below y2 and prob1 are data for the experimental # group. # --------------------------------------------------------------- # # prob1 is the bernoulli distribution event probability parameter # for the control group. Given a user specified odds ratio, I # need to calculate the event probability for the experimental # group. A <- odds_ratio * (prob1 / (1 - prob1)) prob2 <- A / (1 + A) # Create outcomes for both groups. y1 <- stats::rbinom(sample_size, size = 1, prob = prob1) y2 <- stats::rbinom(sample_size, size = 1, prob = prob2) #Take all data created above and put into a data frame that contains # the required variables. subjid <- seq(from = 1, to = 2 * sample_size) trt <- c(rep(0, sample_size), rep(1, sample_size)) y <- c(y1, y2) gendata <- data.frame(subjid, trt, y) colnames(gendata) <- c("id", "treatment", "y") return(gendata) } #' Log-likelihood function for two-arm trial with historical data using Bernoulli #' distribution. #' #' \code{bernoulliloglike()} function only used internally by #' \code{bernoullitrialsimulator()} function to estimate Bernoulli model parameters #' when clinical trial involves experimental and control groups as well as historical #' control data. The Bernoulli log-likelihood is calculated by modeling \code{data} #' as a Bernoulli random variable. Not to be called directly by user. #' #' @param params Two element vector of Bernoulli parameters. The first and second elements #' are the intercept (beta0) and treatment effect parameter (beta1), where the treatment effect is #' a log odds ratio (experimental group over control group). The prob parameter required by #' dbinom() is equal to exp(params[1] + params[2]*treatment) / (1 + exp(params[1] + params[2]*treatment)). #' It is assumed that the params[1] parameter is the same in both randomized and historical data. #' It is assumed that the prob parameter for dbinom() in the randomized and historical control data is #' equal to exp(params[1]) / (1 + exp(params[1])). #' @param randdata Dataset of randomly generated trial data. Randomized trial datasets #' must have 3 columns: id, treatment, and y. The value of treatment must be 0 (control) #' or 1 (experimental). The values of y must be 0 or 1. #' @param histdata Dataset of historical data. Historical datasets must have 3 columns: id, #' treatment, and y. The value of treatment should be 0. The values of y must be 0 or 1. #' @param a0 Power prior parameter: 0 implies historical data is ignored and 1 implies #' all information in historical data is used. #' #' @return \code{bernoulliloglike()} returns a value of the loglikelihood function #' given a set of Bernoulli parameters, randomly generated trial data, and observed #' historical data. #' #' @examples #' #None #' @keywords internal #' @noRd bernoulliloglike <- function(params, randdata, histdata, a0) { # --------------------------------------------------------------- # # This function calculates the Bernoulli log-likelihood given # a vector of parameter values, a dataset of randomized trial # data (two arms, no covariates beyond treatment), and a dataset # of historical control data. # This function has two parameters, beta0 and beta1. # beta0 is the control group log odds, and beta 1 is the log # odds ratio (experimental group over control group). # --------------------------------------------------------------- # # Get params beta0 <- params[1] beta1 <- params[2] # Calculate the logit vector for all randomized observations. # beta0 and beta1 are regression parameters linked to the event # probabilities via the logit function. beta1 is the log odds # ratio (experimental group over conrol group). beta0 is the log # odds among of the control group. logit_i <- beta0 + beta1 * randdata$treatment # Using the logit vector, calculate event probabilities for all # randomized observations. prob_i <- exp(logit_i) / (1 + exp(logit_i)) # Calculate the log-likelihood values for all randomized observations. ll_R <- stats::dbinom(randdata$y, size = 1, prob = prob_i, log = TRUE) # Calculate the event probability vector for all historical control # observations. Note that this event probability is the same # as the event probability for all randomized control observations. probH_i <- exp(beta0) / (1 + exp(beta0)) # Calculate the loglikelihood values for all historical control # observations. ll_H <- stats::dbinom(histdata$y, size = 1, prob = probH_i, log = TRUE) # Calculate the overall log likelihood by adding the randomized log-likelihood to the historical control # log-likelihood by a0, where a0 is the power prior parameter. This a0 value is defined by the # user and not estimated via object function optimization. ll <- sum(ll_R) + a0 * sum(ll_H) # Return the sum of all individual elements to the negative log-likelihood return(-ll) } #' Simulate a single randomized trial using a Bernoulli outcome and information from #' historical controls (Logistic regression model). #' #' \code{bernoullitrialsimulator()} function only used internally by #' \code{bernoulli_sim()} function to run a single trial simulation involving historical #' control data and a Bernoulli (0/1) outcome. #' #' The simulation of a trial with a Bernoulli outcome involving historical control data returns #' an estimate of the odds ratio as well as an estimate of the log odds ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{bernoullitrialsimulator()} should not be called directly by user. #' #' #' @param sample_size_val Number of subjects per arm. #' @param histdata Dataset of historical data. Historical datasets must have 3 columns: id, #' treatment, and y. The value of treatment should be 0. The values of y must be 0 or 1. #' @param prob1_val prob parameter value for randomized control arm. Used in call to \code{rbinom()}. #' @param odds_ratio_val Desired odds ratio between randomized experimental and control groups. #' @param a0_val A power prior parameter ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{bernoullitrialsimulator()} returns a vector of simulation results. The #' first element is an estimated odds ratio, the second element is the estimated #' variance of the log odds ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd bernoullitrialsimulator <- function(sample_size_val, histdata, prob1_val, odds_ratio_val, a0_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate Bernoulli trial data given the user defined trial characteristics. sampleranddata <- genbernoullidata(sample_size = sample_size_val, prob1 = prob1_val, odds_ratio = odds_ratio_val) # Generate initial values for your call to optim() initializemodel <- stats::glm(y ~ treatment, family = stats::binomial(link = "logit"), data = sampleranddata) initialbeta0 <- initializemodel$coefficients[1] initialbeta1 <- initializemodel$coefficients[2] # Generate the Bayesian CLT based parameter estimates needed for inference on odds ratio. fitmod <- stats::optim(c(initialbeta0, initialbeta1), bernoulliloglike, randdata = sampleranddata, histdata = histdata, a0 = a0_val, method = "Nelder-Mead", hessian = TRUE) #Extract model parameters and statistics modparm <- fitmod$par covarmat <- solve(fitmod$hessian) logoddsratio <- modparm[2] odds_ratio <- exp(logoddsratio) lower_oddsratio <- exp(logoddsratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper_oddsratio <- exp(logoddsratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_oddsratio > 1) | (upper_oddsratio < 1)), 1, 0) output <- c(odds_ratio, covarmat[2, 2], reject) #Return the odds ratio, the estimated variance of the log odds ratio, and the trial decision. names(output) <- c("odds_ratio", "log_or_var", "reject") return(output) } #' Simulate a single randomized trial using a Bernoulli outcome but not including any information from #' historical controls (Logistic regression model). #' #' \code{bernoullitrialsimulator()} function only used internally by #' \code{simple_bernoulli_sim()} function to run a single trial simulation involving historical #' control data and a Bernoulli (0/1) outcome. #' #' The simulation of a trial with a Bernoulli outcome without historical control data returns #' an estimate of the odds ratio as well as an estimate of the log odds ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{bernoullitrialsimulatornohist()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param prob1_val prob parameter value for randomized control arm. Used in call to \code{rbinom()}. #' @param odds_ratio_val Desired odds ratio between randomized experimental and control groups. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{bernoullitrialsimulatornohist()} returns a vector of simulation results. The #' first element is an estimated odds ratio, the second element is the estimated #' variance of the log odds ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd bernoullitrialsimulatornohist <- function(sample_size_val, prob1_val, odds_ratio_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is not utilized in the parameter estimation. # No call to optim is necessary since using flat priors and # canonical link (expected and observed information are identical) # --------------------------------------------------------------- # # First, Generate Bernoulli trial data given the user defined trial characteristics. sampleranddata <- genbernoullidata(sample_size = sample_size_val, prob1 = prob1_val, odds_ratio = odds_ratio_val) # Generate the Bayesian CLT based parameter estimates needed for inference on odds ratio. initializemodel <- stats::glm(y ~ treatment, family = stats::binomial(link = "logit"), data = sampleranddata) modparm <- initializemodel$coefficients covarmat <- stats::vcov(initializemodel) logoddsratio <- modparm[2] odds_ratio <- exp(logoddsratio) lower_oddsratio <- exp(logoddsratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper_oddsratio <- exp(logoddsratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_oddsratio > 1) | (upper_oddsratio < 1)), 1, 0) #Return the odds ratio, the estimated variance of the log odds ratio, and the trial decision. output <- c(odds_ratio, covarmat[2, 2], reject) names(output) <- c("odds_ratio", "log_or_var", "reject") return(output) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with Historical Data and #' Bernoulli Outcome (Logistic regression model). #' #' \code{bernoulli_sim()} function only used internally by \code{historic_sim()} #' function to run a set of trial simulations involving historical #' control data and a Bernoulli outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, odds ratios, #' and other user requested study summary statistics like variance of odds #' ratio, bias (on odds ratio scale), and mse (on odds ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{bernoulli_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' a0_val, subj_per_arm, effect_vals, and rand_control_diff. As the number #' of trials increases, the precision of the estimate will increase. Default is #' 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param a0_vals A vector of power prior parameters ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param effect_vals A vector of odds ratios (randomized experimental over control), #' all of which must be positive. #' @param rand_control_diff For Bernoulli outcomes this is a vector of odds ratios #' (randomized controls over historical controls) that represent odds ratios #' between randomized and historical controls. #' @param hist_control_data A dataset of historical data. Default is \code{NULL}. #' Historical datasets must have 3 columns: id, treatment, and y. The value of #' treatment should be 0. The values of y must be 0 or 1. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{bernoulli_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd bernoulli_sim <- function(trial_reps=100, subj_per_arm, a0_vals, effect_vals, rand_control_diff, hist_control_data, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, odds ratio estimate, and if requested # by user: variance of odds ratio, bias, and mse. Using a # Bernoulli oucome and incorporating data from historical controls. # --------------------------------------------------------------- # # Need to take the historical data and generate distributional parameter estimates histdata = hist_control_data hist_model <- stats::glm(y ~ 1, family = stats::binomial(link = "logit"), data = histdata) initialprob1 <- exp(hist_model$coefficients[1])/(1 + exp(hist_model$coefficients[1])) # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. for (diffs in 1:length(rand_control_diff)) { # Need to adjust the randomized control odds given the historical control odds and the odds ratios given in # rand_control_diff, then calculate the event prob for randomized controls. rand_cont_odds <- (initialprob1 / (1 - initialprob1)) * rand_control_diff[diffs] adjprob1 <- rand_cont_odds / (1 + rand_cont_odds) for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_vals, and subj_per_arm, simulate the trial # trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #odds ratio scale and take mean of differences between estimated odds ratios and the true #odds ratio. For mse, calculate the mean of squared differences between the estimated odds ratios #and the true odds ratio. Note that rand_control_diff is set to 1 and a0_val is set to 0. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- bernoullitrialsimulator(sample_size_val = subj_per_arm[sizes], histdata, prob1_val = adjprob1, odds_ratio_val = effect_vals[effvals], a0_val = a0_vals[a0vals], alpha = alpha) } #collect is a matrix of data, odds ratio in 1st column, log odds ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("odds_ratio", "log_or_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 404 through 707 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, objtype= 'historic') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with no Historical Data and #' Bernoulli Outcome (Logistic regression model). #' #' \code{simple_bernoulli_sim()} function only used internally by \code{simple_sim()} #' function to run a set of trial simulations involving no historical #' control data and a Bernoulli outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, odds ratios, #' and other user requested study summary statistics like variance of odds #' ratio, bias (on odds ratio scale), and mse (on odds ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{simple_bernoulli_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' subj_per_arm and effect_vals. As the number of trials increases, the #' precision of the estimate will increase. Default is 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param effect_vals A vector of odds ratios (randomized experimental over control), #' all of which must be positive. #' @param prob1_val prob parameter value for randomized control arm. Used in call to \code{rbinom()}. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether or not an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether or not an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether or not an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{simple_bernoulli_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd simple_bernoulli_sim <- function(trial_reps=100, subj_per_arm, effect_vals, prob1_val, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, odds ratio estimate, and if requested by user: # variance of odds ratio, bias, and mse. Using a Bernoulli oucome # but historical control data is not used. # --------------------------------------------------------------- # #The rand_control_diff and a0_val dimensions will be set to 1, and the value for # rand_control_diff will be 1 and a0_val will be set to 0. All summaries will # be set up to ignore these dimensions for simple (no historical data) simulations. rand_control_diff <- 1 a0_vals <- 0 # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. Note that rand_control_diff is set to 1 and a0_val is set to 0. for (diffs in 1:length(rand_control_diff)) { for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial # trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #odds ratio scale and take mean of differences between estimated odds ratios and the true #odds ratio. For mse, calculate the mean of squared differences between the estimated odds ratios #and the true odds ratio. Note that rand_control_diff is set to 1 and a0_val is set to 0. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- bernoullitrialsimulatornohist(sample_size_val = subj_per_arm[sizes], prob1_val = prob1_val, odds_ratio_val = effect_vals[effvals], alpha = alpha) } #collect is a matrix of data, odds ratio in 1st column, log odds ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("odds_ratio", "log_or_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 830 through 1133 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = 0, effect_vals = effect_vals, rand_control_diff = 1, objtype= 'simple') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/BernoulliCode.R
#' Checks for Errors when Outcome is Bernoulli. #' #' \code{bernoulli_error_checks()} function used only used internally by #' \code{historic_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{historic_sim()}. #' @param hist_control_data See help page for \code{historic_sim()}. #' @param rand_control_diff See help page for \code{historic_sim()}. #' @param alpha See help page for \code{historic_sim()}. #' #' @return \code{bernoulli_error_checks()} returns messages when #' \code{historic_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd bernoulli_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, alpha) { hist_chk <- class(hist_control_data) rcp_chk <- is.null(rand_control_diff) # Need to check that EffectSize is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("historic_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Bernoulli, historic_sim() requires effect_vals to represent Odds Ratios which must be positive numbers") } # Need to check that hist_control_data is a data frame and has the correct columns. if (hist_chk == "data.frame") { colnamevals <- colnames(hist_control_data) colnamechk <- (colnamevals == c("id", "treatment", "y")) if (sum(colnamechk) != 3) { stop("historic_sim() requires hist_control_data to have columns: ID, Treatment, and Y.") } if (sum(colnamechk) == 3) { if (!is.numeric(hist_control_data$y)) { stop("historic_sim() requires hist_control_data$Y to be numeric.") } if (!is.numeric(hist_control_data$treatment)) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } if (is.numeric(hist_control_data$treatment)) { trt_levels <- names(table(hist_control_data$treatment)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$Treatment to be numeric 0/1 data.") } } } } # If not NULL, need to check that rand_control_diff is positive. if (rcp_chk == FALSE) { for (rand_cp in rand_control_diff) { if (!is.numeric(rand_cp)) stop("historic_sim() requires rand_control_diff to be numeric.") if (rand_cp <= 0) stop("historic_sim() requires rand_control_diff to be Odds Ratios, so they must be positive.") } } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("historic_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } } #' Checks for Errors when Outcome is Bernoulli. #' #' \code{bernoulli_error_checks_simple()} function used only used internally by #' \code{simple_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{simple_sim()}. #' @param control_parms See help page for \code{simple_sim()}. #' @param alpha See help page for \code{simple_sim()}. #' #' @return \code{bernoulli_error_checks_simple()} returns messages when #' \code{simple_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd bernoulli_error_checks_simple <- function(effect_vals, control_parms, alpha) { chk_parm_lgth <- length(control_parms) # Need to check that EffectSize is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("simple_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Bernoulli, simple_sim() requires effect_vals to represent Odds Ratios which must be positive numbers") } if (chk_parm_lgth != 1) { stop("simple_sim() requires a single elements in control_parms which is the probability parameter for rbinom() among controls") } if (chk_parm_lgth == 1) { if (!is.numeric(control_parms[1])) stop("simple_sim() requires probability parameter for controls to be numeric.") if (control_parms[1] <= 0) stop("simple_sim() requires probability parameter for controls to be between 0 and 1.") if (control_parms[1] >= 1) stop("simple_sim() requires probability parameter for controls to be between 0 and 1.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("simple_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/BernoulliErrorChecks.R
#' Generating function for Gaussian Data. #' #' \code{gengaussiandata()} function used mainly internally by #' \code{gaussiantrialsimulator()} function to generate data for a two-arm #' clinical trial, experimental and control groups. Can be used to generate #' random trial data. #' #' @param sample_size Number of subjects per arm. #' @param mu1 mean parameter used in call to \code{rnorm()}. #' Used only in control arm. #' @param mean_diff Desired Mean Difference between experimental and control groups. #' @param common_sd sd parameter used in call to \code{rnorm()}. #' Used in both arms. #' #' @return \code{gengaussiandata()} returns a data frame with columns: 'id', 'treatment', #' and 'y'. #' #' @examples #' samplehistdata <- gengaussiandata(sample_size=60, mu1=25, mean_diff=0, common_sd=3) #' samplehistdata #' @export gengaussiandata <- function(sample_size, mu1, mean_diff, common_sd) { # --------------------------------------------------------------- # # The function gengaussiandata simulates a balanced clinical trial # with 'sample_size' subjects per arm using a normal distribution. # 'm'1 is the gaussian location parameter, and 'common_sd' is the # gaussian scale parameter for both arms. 'mean_diff' is the # difference in group means (experimental group minus control group). # # In the code below y1 and mu1 are data for the control goup. # In the code below y2 and mu2 are data for the experimental group. # --------------------------------------------------------------- # # mu1 is the normal distribution mu parameter for the control group. # given mean_diff, normal mean for experimental group is: mu2 <- mu1 + mean_diff # Create outcomes for both groups. y1 <- stats::rnorm(sample_size, mean = mu1, sd = common_sd) y2 <- stats::rnorm(sample_size, mean = mu2, sd = common_sd) #Take all data created above and put into a data frame that contains # the required variables. subjid <- seq(from = 1, to = 2 * sample_size) trt <- c(rep(0, sample_size), rep(1, sample_size)) y <- c(y1, y2) gendata <- data.frame(subjid, trt, y) colnames(gendata) <- c("id", "treatment", "y") return(gendata) } #' Log-likelihood function for two-arm trial with historical data using Gaussian #' distribution. #' #' \code{gaussianloglike()} function used only used internally by #' \code{gaussiantrialsimulator()} function to estimate Gaussian model parameters #' when clinical trial involves experimental and control groups as well as historical #' control data. The Gaussian log-likelihood is calculated by modeling \code{data} #' as a Gaussian random variable. Not to be called directly by user. #' #' @param params Three element vector of Gaussian parameters. Third element is log(sd), #' where sd is a parameter required by dnorm(). The first and second elements #' are the intercept and treatment effect parameter, where the treatment effect is #' a mean difference (experimental group minus control group). The mu parameter required by #' dnorm() is equal to params[1] + params[2]*treatment. It is assumed that the log(sd) #' parameter is the same in both randomized and historical data. It is assumed that #' the mu parameter in the randomized and historical control data is equal to params[1]. #' @param randdata Dataset of randomly generated trial data. Randomized trial datasets #' must have 3 columns: id, treatment, and y. The value of treatment must be 0 (control) #' or 1 (experimental). The values of y must be numeric. #' @param histdata Dataset of historical data. Historical datasets must have 3 columns: id, #' treatment, and y. The value of treatment should be 0. The values of y must be #' numeric. #' @param a0 Power prior parameter: 0 implies historical data is ignored and 1 implies #' all information in historical data is used. #' #' @return \code{gaussianloglike()} returns a value of the loglikelihood function #' given a set of Gaussian parameters, randomly generated trial data, and observed #' historical data. #' #' @examples #' #None #' @keywords internal #' @noRd gaussianloglike <- function(params, randdata, histdata, a0) { # --------------------------------------------------------------- # # This function calculates the Gaussian log-likelihood given # a vector of parameter values, a dataset of randomized trial # data (two arms, no covariates beyond treatment), and a dataset # of historical control data. # The standard deviation parameter is common in both randomized # groups and the historical control group. The mean parameter is # assumed to be the same in both control groups. The mean # parameter for the randomized experimental group is the sum # of the control mean and the treatment effect. The parameters # are beta0, beta1, and logs. logs is the common log standard # deviation in all three groups. It follows that the common # standard deviation is equal to exp(logs). beta0 and beta1 # are regression parameters that are linked to the gaussian mean # via the identity function. # beta0 is the control group mean, and beta 1 is the experimental # group mean minus the control group mean. # --------------------------------------------------------------- # # Get params beta0 <- params[1] beta1 <- params[2] logs <- params[3] # Calculate the mean parameter vector for all randomized observations. # Note that beta0 is simply the control mean and beta1 is the # experimental group mean minus the control group mean. mu_i <- beta0 + beta1 * randdata$treatment # Calculate the log-likelihood values for all randomized observations. ll_R <- stats::dnorm(randdata$y, mean = mu_i, sd = exp(logs), log = TRUE) # Calculate the log-likelihood values for all historical control observations. # Note that it is assumed the mean among randomized and historical controls # is the same. ll_H <- stats::dnorm(histdata$y, mean = beta0, sd = exp(logs), log = TRUE) # Calculate the overall log-likelihood by adding the randomized log-likelihood to the historical control # log-likelihood by a0, where a0 is the power prior parameter. This a0 value is defined by the # user and not estimated via object function optimization. ll <- sum(ll_R) + a0 * sum(ll_H) return(-ll) } #' Simulate a single randomized trial using a Gaussian outcome and information from #' historical controls. #' #' \code{gaussiantrialsimulator()} function only used internally by #' \code{gaussian_sim()} function to run a single trial simulation involving historical #' control data and a Gaussian outcome. #' #' The simulation of a trial with a Gaussian outcome involving historical control data returns #' an estimate of the mean difference as well as an estimate of the mean difference variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{gaussiantrialsimulator()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param histdata Dataset of historical data. Historical datasets must have 3 columns: id, #' treatment, and y. The value of treatment should be 0. The values of y must be #' numeric. #' @param mu1_val Randomized control arm mean parameter used in call to \code{rnorm()}. #' @param mean_diff_val Desired mean difference between randomized experimental and control groups. #' @param common_sd_val Randomized sd parameter used in call to \code{rnorm()}. #' Used in both randomized arms. #' @param a0_val A power prior parameter ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{gaussiantrialsimulator()} returns a vector of simulation results. The #' first element is an estimated mean difference, the second element is the estimated #' variance of the mean difference, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd gaussiantrialsimulator <- function(sample_size_val, histdata, mu1_val, mean_diff_val, common_sd_val, a0_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate Gaussian trial data given the user defined trial characteristics. sampleranddata <- gengaussiandata(sample_size = sample_size_val, mu1 = mu1_val, mean_diff = mean_diff_val, common_sd = common_sd_val) # Generate initial values for your call to optim() initializemodel <- stats::lm(y ~ treatment, data = sampleranddata) initialbeta0 <- initializemodel$coefficients[1] initialbeta1 <- initializemodel$coefficients[2] initiallogs <- log(summary(initializemodel)$sigma) # Generate the Bayesian CLT based parameter estimates needed for inference on hazard ratio. fitmod <- stats::optim(c(initialbeta0, initialbeta1, initiallogs), gaussianloglike, randdata = sampleranddata, histdata = histdata, a0 = a0_val, method = "Nelder-Mead", hessian = TRUE) #Extract model parameters and statistics modparm <- fitmod$par covarmat <- solve(fitmod$hessian) gaussianmeandiff <- modparm[2] lower_gaussianmeandiff <- gaussianmeandiff - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2]) upper_gaussianmeandiff <- gaussianmeandiff + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2]) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_gaussianmeandiff > 0) | (upper_gaussianmeandiff < 0)), 1, 0) output <- c(gaussianmeandiff, covarmat[2, 2], reject) #Return the mean, the estimated variance of the mean difference, and the trial decision. names(output) <- c("mean_diff", "mean_diff_var", "reject") return(output) } #' Simulate a single randomized trial using a Gaussian outcome but not including any information from #' historical controls. #' #' \code{gaussiantrialsimulatornohist()} function only used internally by #' \code{simple_gaussian_sim()} function to estimate Gaussian model parameters #' when clinical trial involves experimental and control groups but no historical control #' data. #' #' The simulation of a trial with a Gaussian outcome involving no historical control data returns #' an estimate of the mean difference as well as an estimate of the mean difference variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{gaussiantrialsimulatornohist()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param mu1_val Randomized control arm mean parameter used in call to \code{rnorm()}. #' @param mean_diff_val Desired mean difference between randomized experimental and control groups. #' @param common_sd_val Randomized sd parameter used in call to \code{rnorm()}. #' Used in both randomized arms. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{gaussiantrialsimulatornohist()} returns a vector of simulation results. The #' first element is an estimated mean difference, the second element is the estimated #' variance of the mean difference, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd gaussiantrialsimulatornohist <- function(sample_size_val, mu1_val, mean_diff_val, common_sd_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is not utilized in the parameter estimation. # No call to optim is necessary since using flat priors and # canonical link (expected and observed information are identical) # --------------------------------------------------------------- # # First, Generate Gaussian trial data given the user defined trial characteristics. sampleranddata <- gengaussiandata(sample_size = sample_size_val, mu1 = mu1_val, mean_diff = mean_diff_val, common_sd = common_sd_val) # Generate the Bayesian CLT based parameter estimates needed for inference on mean difference. X = matrix(c(rep(1,length(sampleranddata$y)),sampleranddata$treatment),ncol=2) Beta_hat = solve(t(X)%*%X)%*%t(X)%*%sampleranddata$y mleVal = X%*%Beta_hat Sigma_hat = sqrt(sum((sampleranddata$y-mleVal)^2))/sqrt(2*sample_size_val) Covarmatinv <- matrix(rep(0,9),ncol=3) Covarmatinv[1:2,1:2] = t(X)%*%X/(Sigma_hat^2) Covarmatinv[1:2,3] = c(0,0) Covarmatinv[3,1:2] = c(0,0) Covarmatinv[3,3] = (Sigma_hat^(-6))*sum((sampleranddata$y-mleVal)^2)-(sample_size_val/(Sigma_hat^4)) Covarmatinv = solve(Covarmatinv) #Extract model parameters and statistics mle <- Beta_hat covarmat <- Covarmatinv gaussianmeandiff <- mle[2] lower_gaussianmeandiff <- gaussianmeandiff - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2]) upper_gaussianmeandiff <- gaussianmeandiff + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2]) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_gaussianmeandiff > 0) | (upper_gaussianmeandiff < 0)), 1, 0) output <- c(gaussianmeandiff, covarmat[2, 2], reject) #Return the mean difference, the estimated variance of the mean difference, and the trial decision. names(output) <- c("mean_diff", "mean_diff_var", "reject") return(output) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with Historical Data and #' Gaussian Outcome. #' #' \code{gaussian_sim()} function only used internally by \code{historic_sim()} #' function to run a set of trial simulations involving historical #' control data and a Gaussian outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, mean difference, #' and other user requested study summary statistics like variance of mean #' difference, bias, and mse. The number of repeated simulations is defined #' by the user. #' #' \code{gaussian_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' a0_val, subj_per_arm, effect_vals, and rand_control_diff. As the number #' of trials increases, the precision of the estimate will increase. Default is #' 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param a0_vals A vector of power prior parameters ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param effect_vals A vector of mean differences (randomized experimental minus control). #' @param rand_control_diff For Gaussian outcomes this is a vector of mean differences #' (randomized controls minus historical controls) that represent differences #' between randomized and historical controls. #' @param hist_control_data A dataset of historical data. Default is \code{NULL}. #' Historical datasets must have 3 columns: id, treatment, and y. The value of #' treatment should be 0. The values of y must be numeric. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{gaussian_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd gaussian_sim <- function(trial_reps=100, subj_per_arm, a0_vals, effect_vals, rand_control_diff, hist_control_data, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, mean difference estimate, and if requested # by user: variance of mean difference, bias, and mse. Using a # Gaussian oucome and incorporating data from historical controls. # --------------------------------------------------------------- # # Need to take the historical data and generate distributional parameter estimates histdata <- hist_control_data initializemodel <- stats::lm(y ~ 1, data = histdata) initialmu1 <- initializemodel$coefficients[1] initialsig <- summary(initializemodel)$sigma # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. for (diffs in 1:length(rand_control_diff)) { # Need to adjust the randomized control mean given the historical control mean and the mean differences given in # rand_control_diff adjmu1 <- initialmu1 + rand_control_diff[diffs] for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_vals, and subj_per_arm, simulate the trial #trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #untransformed scale and take mean of differences between estimated mean differences and the true mean #mean difference. For mse, calculate the mean of squared differences between the estimated mean #difference and the true mean difference. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- gaussiantrialsimulator(sample_size_val = subj_per_arm[sizes], histdata, mu1_val = adjmu1, mean_diff_val = effect_vals[effvals], common_sd_val = initialsig, a0_val = a0_vals[a0vals], alpha = alpha) } #collect is a matrix of data, mean difference in 1st column, mean difference variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("mean_diff", "mean_diff_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # difference estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 2]) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 416 through 719 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, objtype= 'historic') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with no Historical Data and #' Gaussian Outcome. #' #' \code{simple_gaussian_sim()} function only used internally by \code{simple_sim()} #' function to run a set of trial simulations involving no historical #' control data and a Gaussian outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, mean difference, #' and other user requested study summary statistics like variance of mean #' difference, bias, and mse. The number of repeated simulations is defined #' by the user. #' #' \code{simple_gaussian_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' subj_per_arm and effect_vals. As the number of trials increases, the #' precision of the estimate will increase. Default is 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param effect_vals A vector of mean differences (randomized experimental minus #' controls). #' @param mu1_val mean parameter value for randomized control arm. Used in call to #' \code{rnorm()}. #' @param common_sd_val sd parameter value used in both randomized arms. Used in call #' to \code{rnorm()}. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{simple_gaussian_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd simple_gaussian_sim <- function(trial_reps=100, subj_per_arm, effect_vals, mu1_val, common_sd_val, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, mean difference estimate, and if requested # by user: variance of mean difference, bias, and mse. Using a # Gaussian oucome but historical control data is not used. # --------------------------------------------------------------- # #The rand_control_diff and a0_val dimensions will be set to 1, and the value for # rand_control_diff will be 1 and a0_val will be set to 0. All summaries will # be set up to ignore these dimensions for simple (no historical data) simulations. rand_control_diff <- 1 a0_vals <- 0 # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. Note that rand_control_diff is set to 1 and a0_val is set to 0. for (diffs in 1:length(rand_control_diff)) { for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial # trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #untransformed scale and take mean of differences between estimated mean differences and the true mean #mean difference. For mse, calculate the mean of squared differences between the estimated mean #difference and the true mean difference. Note that rand_control_diff is set to 1 and #a0_val is set to 0. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- gaussiantrialsimulatornohist(sample_size_val = subj_per_arm[sizes], mu1_val = mu1_val, mean_diff_val = effect_vals[effvals], common_sd_val = common_sd_val, alpha = alpha) } #collect is a matrix of data, mean difference in 1st column, mean difference variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("mean_diff", "mean_diff_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # difference estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 2]) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 846 through 1149 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = 0, effect_vals = effect_vals, rand_control_diff = 1, objtype= 'simple') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/GaussianCode.R
#' Checks for Errors when Outcome is Gaussian. #' #' \code{gaussian_error_checks()} function used only used internally by #' \code{historic_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{historic_sim()}. #' @param hist_control_data See help page for \code{historic_sim()}. #' @param rand_control_diff See help page for \code{historic_sim()}. #' @param alpha See help page for \code{historic_sim()}. #' #' @return \code{gaussian_error_checks()} returns messages when #' \code{historic_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd gaussian_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, alpha) { hist_chk <- class(hist_control_data) rcp_chk <- is.null(rand_control_diff) # Need to check that EffectSize is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("historic_sim() requires effect_vals to be numeric.") } # Need to check that hist_control_data is a data frame and has the correct columns. if (hist_chk == "data.frame") { colnamevals <- colnames(hist_control_data) colnamechk <- (colnamevals == c("id", "treatment", "y")) if (sum(colnamechk) != 3) { stop("historic_sim() requires hist_control_data to have columns: id, treatment, and y.") } if (sum(colnamechk) == 3) { if (!is.numeric(hist_control_data$y)) { stop("historic_sim() requires hist_control_data$y to be numeric.") } if (!is.numeric(hist_control_data$treatment)) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } if (is.numeric(hist_control_data$treatment)) { trt_levels <- names(table(hist_control_data$treatment)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } } } } # If not NULL, need to check that rand_control_diff is numeric. if (rcp_chk == FALSE) { for (rand_cp in rand_control_diff) { if (!is.numeric(rand_cp)) stop("historic_sim() requires rand_control_diff to be numeric.") } } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("historic_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } } #' Checks for Errors when Outcome is Gaussian. #' #' \code{gaussian_error_checks_simple()} function used only used internally by #' \code{simple_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{simple_sim()}. #' @param control_parms See help page for \code{simple_sim()}. #' @param alpha See help page for \code{simple_sim()}. #' #' @return \code{gaussian_error_checks_simple()} returns messages when #' \code{simple_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd gaussian_error_checks_simple <- function(effect_vals, control_parms, alpha) { chk_parmlgth <- length(control_parms) # Need to check that EffectSize is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("simple_sim() requires effect_vals to be numeric.") } if (chk_parmlgth != 2) { stop("simple_sim() requires two elements in control_parms, first=Gaussian mean parameter for rnorm(), second = Gaussian sd parameter for rnorm()") } if (chk_parmlgth == 2) { if (!is.numeric(control_parms[1])) stop("simple_sim() requires Gaussian mean parameter for controls to be numeric.") if (!is.numeric(control_parms[2])) stop("simple_sim() requires Gaussian sd parameter for controls to be numeric.") if (control_parms[2] <= 0) stop("simple_sim() requires Gaussian sd parameter for controls to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("simple_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/GaussianErrorChecks.R
#' Checks \code{historic_sim()} Function Call for Global Type Errors. #' #' \code{global_error_checks()} function used only used internally by \code{historic_sim()} #' function to check for proper input. Not to be called directly by user. #' #' @param outcome_type See help page for \code{historic_sim()}. #' @param subj_per_arm See help page for \code{historic_sim()}. #' @param a0_vals See help page for \code{historic_sim()}. #' @param hist_control_data See help page for \code{historic_sim()}. #' @param rand_control_diff See help page for \code{historic_sim()}. #' @param get_var See help page for \code{historic_sim()}. #' @param get_bias See help page for \code{historic_sim()}. #' @param get_mse See help page for \code{historic_sim()}. #' #' @return \code{global_error_checks()} returns messages when \code{historic_sim()} function #' inputs are incorrectly specified. Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd global_error_checks <- function(outcome_type, a0_vals, subj_per_arm, hist_control_data, rand_control_diff, get_var, get_bias, get_mse) { if (!(tolower(outcome_type) %in% c("weibull", "lognormal", "pwe", "gaussian", "bernoulli", "poisson"))) { stop("historic_sim only supports the following outcome distributions:\nWeibull, Lognormal,Piecewsie Exponential (PWE), Gaussian, Logistic, and Poisson.\noutcome_type values must be equal to weibull, lognormal, pwe, gaussian, logistic, or poisson") } # a0_val must be numeric and between 0 and 1 inclusively. for (pow_parm in a0_vals) { if (!is.numeric(pow_parm)) stop("historic_sim requires a0_val to be numeric.") if (is.numeric(pow_parm) & (pow_parm < 0 | pow_parm > 1)) stop("historic_sim requires a0_val to be between 0 and 1 inclusively.") } # subj_per_arm must be a list of non-negative values. temp_s <- as.integer(subj_per_arm) for (sam_siz in subj_per_arm) { if (!is.numeric(sam_siz)) stop("historic_sim requires subj_per_arm to be numeric.") if (sam_siz < 1) stop("historic_sim requires at least 1 randomized subject per arm. Negative numbers or zero not allowed.") } sam_siz_chk <- sum(temp_s == subj_per_arm) if (sam_siz_chk != length(subj_per_arm)) stop("historic_sim requires subj_per_arm to be an integer.") # hist_control_data must be a data frame or a list of numeric values. hist_chk <- class(hist_control_data) if (hist_chk != "data.frame") { stop("historic_sim requires hist_control_data to be a data frame.") } # Need to check that rand_control_diff is either NULL or a list of reasonable numbers rcp_chk <- is.null(rand_control_diff) if (rcp_chk == FALSE) { for (rand_cp in rand_control_diff) { if (!is.numeric(rand_cp)) stop("historic_sim requires rand_control_diff to be numeric.") } } # Need to check that get_var is TRUE/FALSE if (get_var != TRUE & get_var != FALSE) { stop("historic_sim requires get_var to be either TRUE or FALSE") } # Need to check that get_bias is TRUE/FALSE if (get_bias != TRUE & get_bias != FALSE) { stop("historic_sim requires get_bias to be either TRUE or FALSE") } # Need to check that get_mse is TRUE/FALSE if (get_mse != TRUE & get_mse != FALSE) { stop("historic_sim requires get_mse to be either TRUE or FALSE") } } #' Checks \code{simple_sim()} Function Call for Global Type Errors. #' #' \code{global_error_checks_simple()} function used only used internally by #' \code{simple_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param outcome_type See help page for \code{simple_sim()}. #' @param subj_per_arm See help page for \code{simple_sim()}. #' @param get_var See help page for \code{simple_sim()}. #' @param get_bias See help page for \code{simple_sim()}. #' @param get_mse See help page for \code{simple_sim()}. #' #' @return \code{global_error_checks_simple()} returns messages when #' \code{simple_sim()} function inputs are incorrectly specified. Not to be called #' directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd global_error_checks_simple <- function(outcome_type, subj_per_arm, get_var, get_bias, get_mse) { if (!(tolower(outcome_type) %in% c("weibull", "lognormal", "pwe", "gaussian", "bernoulli", "poisson"))) { stop("simple_sim only supports the following outcome distributions:\nWeibull, Lognormal,Piecewsie Exponential (PWE), Gaussian, Logistic, and Poisson.\noutcome_type values must be equal to weibull, lognormal, pwe, gaussian, logistic, or poisson") } # subj_per_arm must be a list of non-negative values. temp_s <- as.integer(subj_per_arm) for (sam_siz in subj_per_arm) { if (!is.numeric(sam_siz)) stop("simple_sim requires subj_per_arm to be numeric.") if (sam_siz < 1) stop("simple_sim requires at least 1 randomized subject per arm. Negative numbers or zero not allowed.") } sam_siz_chk <- sum(temp_s == subj_per_arm) if (sam_siz_chk != length(subj_per_arm)) stop("simple_sim requires subj_per_arm to be an integer.") # Need to check that get_var is TRUE/FALSE if (get_var != TRUE & get_var != FALSE) { stop("simple_sim requires get_var to be either TRUE or FALSE") } # Need to check that get_bias is TRUE/FALSE if (get_bias != TRUE & get_bias != FALSE) { stop("simple_sim requires get_bias to be either TRUE or FALSE") } # Need to check that get_mse is TRUE/FALSE if (get_mse != TRUE & get_mse != FALSE) { stop("simple_sim requires get_mse to be either TRUE or FALSE") } } #' Checks \code{print.bayes_ctd_array()} Function Call for Errors. #' #' \code{print_error_checks()} function used only internally by #' \code{print.bayes_ctd_array()} function to check for proper input. Not to be called #' directly by user. #' #' @param bayes_ctd_robj See help page for \code{print()}. #' @param measure, See help page for \code{print()}. #' @param tab_type, See help page for \code{print()}. #' @param subj_per_arm_val See help page for \code{print()}. #' @param a0_val See help page for \code{print()}. #' @param effect_val See help page for \code{print()}. #' @param rand_control_diff_val See help page for \code{print()}. #' #' @return \code{print_error_checks()} returns messages when #' \code{printbayes_ctd_array()} function inputs are incorrectly specified. Not to be called #' directly by user. #' #' @examples #' #None. #' @keywords internal #' @noRd print_error_checks <- function(bayes_ctd_robj, measure, tab_type, subj_per_arm_val, a0_val, effect_val, rand_control_diff_val) { if (!(tolower(measure) %in% c("power", "est", "var", "bias", "mse"))) { stop("print.bayes_ctd_array() requires measure to be equal to power, est, var, bias, mse") } if ((tolower(measure) == "var") & is.null(bayes_ctd_robj$data$var)){ stop("Table of variance cannot be printed or plotted, because variance estimates were not requested in the trial simulation.") } if ((tolower(measure) == "bias") & is.null(bayes_ctd_robj$data$bias)){ stop("Table of bias cannot be printed or plotted, because bias estimates were not requested in the trial simulation.") } if ((tolower(measure) == "mse") & is.null(bayes_ctd_robj$data$mse)){ stop("Table of mse cannot be printed or plotted, because mse estimates were not requested in the trial simulation.") } if (!(toupper(tab_type) %in% c("WX|YZ", "WY|XZ", "WZ|XY", "XY|WZ", "XZ|WY", "YZ|WX", "ZX|WY", "XW|YZ", "YW|XZ", "YX|WZ", "ZW|XY", "ZX|WY", "ZY|WX"))) { stop("print.bayes_ctd_array() requires tab_type to be equal to WX|YZ, WY|XZ, WZ|XY, XY|WZ, XZ|WY, YZ|WX, ZX|WY, XW|YZ, YW|XZ, YX|WZ, ZW|XY, ZX|WY, or ZY|WX") } if (toupper(tab_type) == "WX|YZ") { if (is.null(effect_val) | is.null(rand_control_diff_val)) { stop("print.bayes_ctd_array() requires effect_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "WY|XZ") { if (is.null(a0_val) | is.null(rand_control_diff_val)) { stop("print.bayes_ctd_array() requires a0_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "WZ|XY") { if (is.null(a0_val) | is.null(effect_val)) { stop("print.bayes_ctd_array() requires a0_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "XY|WZ") { if (is.null(subj_per_arm_val) | is.null(rand_control_diff_val)) { stop("print.bayes_ctd_array() requires subj_per_arm_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "XZ|WY") { if (is.null(subj_per_arm_val) | is.null(effect_val)) { stop("print.bayes_ctd_array() requires subj_per_arm_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "YZ|WX") { if (is.null(subj_per_arm_val) | is.null(a0_val)) { stop("print.bayes_ctd_array() requires subj_per_arm_val and a0_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZX|WY") { if (is.null(subj_per_arm_val) | is.null(effect_val)) { stop("print.bayes_ctd_array() requires subj_per_arm_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "XW|YZ") { if (is.null(effect_val) | is.null(rand_control_diff_val)) { stop("print.bayes_ctd_array() requires effect_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "YW|XZ") { if (is.null(a0_val) | is.null(rand_control_diff_val)) { stop("print.bayes_ctd_array() requires a0_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "YX|WZ") { if (is.null(subj_per_arm_val) | is.null(rand_control_diff_val)) { stop("print.bayes_ctd_array() requires subj_per_arm_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZW|XY") { if (is.null(a0_val) | is.null(effect_val)) { stop("print.bayes_ctd_array() requires a0_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZX|WY") { if (is.null(subj_per_arm_val) | is.null(effect_val)) { stop("print.bayes_ctd_array() requires subj_per_arm_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZY|WX") { if (is.null(subj_per_arm_val) | is.null(a0_val)) { stop("print.bayes_ctd_array() requires subj_per_arm_val and a0_val to be non-missing and equal to a value used in your simulation.") } } subj_per_arm_vec <- bayes_ctd_robj$subj_per_arm a0_val_vec <- bayes_ctd_robj$a0_vals effect_val_vec <- bayes_ctd_robj$effect_vals rand_control_diff_vec <- bayes_ctd_robj$rand_control_diff if (!is.null(subj_per_arm_val)) { if (is.na(match(subj_per_arm_val, subj_per_arm_vec))) { text_val <- "print.bayes_ctd_array() requires subj_per_arm_val to be equal to one of the following values: " for (i in 1:length(subj_per_arm_vec)) { text_val <- paste(text_val, subj_per_arm_vec[i], sep = "") if (i != length(subj_per_arm_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } if (!is.null(a0_val)) { if (is.na(match(a0_val, a0_val_vec))) { text_val <- "print.bayes_ctd_array() requires a0_val to be equal to one of the following values: " for (i in 1:length(a0_val_vec)) { text_val <- paste(text_val, a0_val_vec[i], sep = "") if (i != length(a0_val_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } if (!is.null(effect_val)) { if (is.na(match(effect_val, effect_val_vec))) { text_val <- "print.bayes_ctd_array() requires effect_val to be equal to one of the following values: " for (i in 1:length(effect_val_vec)) { text_val <- paste(text_val, effect_val_vec[i], sep = "") if (i != length(effect_val_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } if (!is.null(rand_control_diff_val)) { if (is.na(match(rand_control_diff_val, rand_control_diff_vec))) { text_val <- "print.bayes_ctd_array() requires rand_control_diff_val to be equal to one of the following values: " for (i in 1:length(rand_control_diff_vec)) { text_val <- paste(text_val, rand_control_diff_vec[i], sep = "") if (i != length(rand_control_diff_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } } #' Checks \code{plot.bayes_ctd_array()} Function Call for Errors. #' #' \code{plot_error_checks()} function used only internally by #' \code{plot.bayes_ctd_array()} function to check for proper input. Not to be called #' directly by user. #' #' @param bayes_ctd_robj See help page for \code{plot()}. #' @param measure See help page for \code{plot()}. #' @param tab_type See help page for \code{plot()}. #' @param subj_per_arm_val See help page for \code{plot()}. #' @param a0_val See help page for \code{print()}. #' @param effect_val See help page for \code{plot()}. #' @param rand_control_diff_val See help page for \code{plot()}. #' @param smooth See help page for \code{plot()}. #' @param plot_out See help page for \code{plot()}. #' @param span See help page for \code{plot()}. #' #' @return \code{plot_error_checks()} returns messages when #' \code{plot.bayes_ctd_array()} function inputs are incorrectly specified. Not to be called #' directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd plot_error_checks <- function(bayes_ctd_robj, measure, tab_type, smooth, plot_out, subj_per_arm_val, a0_val, effect_val, rand_control_diff_val, span) { if (!(tolower(measure) %in% c("power", "est", "var", "bias", "mse"))) { stop("plot.bayes_ctd_array() requires measure to be equal to power, est, var, bias, mse") } if (!(toupper(tab_type) %in% c("WX|YZ", "WY|XZ", "WZ|XY", "XY|WZ", "XZ|WY", "YZ|WX", "ZX|WY", "XW|YZ", "YW|XZ", "YX|WZ", "ZW|XY", "ZX|WY", "ZY|WX"))) { stop("plot.bayes_ctd_array() requires tab_type to be equal to WX|YZ, WY|XZ, WZ|XY, XY|WZ, XZ|WY, YZ|WX, ZX|WY, XW|YZ, YW|XZ, YX|WZ, ZW|XY, ZX|WY, or ZY|WX") } if (toupper(tab_type) == "WX|YZ") { if (is.null(effect_val) | is.null(rand_control_diff_val)) { stop("plot.bayes_ctd_array() requires effect_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "WY|XZ") { if (is.null(a0_val) | is.null(rand_control_diff_val)) { stop("plot.bayes_ctd_array() requires a0_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "WZ|XY") { if (is.null(a0_val) | is.null(effect_val)) { stop("plot.bayes_ctd_array() requires a0_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "XY|WZ") { if (is.null(subj_per_arm_val) | is.null(rand_control_diff_val)) { stop("plot.bayes_ctd_array() requires subj_per_arm_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "XZ|WY") { if (is.null(subj_per_arm_val) | is.null(effect_val)) { stop("plot.bayes_ctd_array() requires subj_per_arm_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "YZ|WX") { if (is.null(subj_per_arm_val) | is.null(a0_val)) { stop("plot.bayes_ctd_array() requires subj_per_arm_val and a0_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZX|WY") { if (is.null(subj_per_arm_val) | is.null(effect_val)) { stop("plot.bayes_ctd_array() requires subj_per_arm_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "XW|YZ") { if (is.null(effect_val) | is.null(rand_control_diff_val)) { stop("plot.bayes_ctd_array() requires effect_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "YW|XZ") { if (is.null(a0_val) | is.null(rand_control_diff_val)) { stop("plot.bayes_ctd_array() requires a0_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "YX|WZ") { if (is.null(subj_per_arm_val) | is.null(rand_control_diff_val)) { stop("plot.bayes_ctd_array() requires subj_per_arm_val and rand_control_diff_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZW|XY") { if (is.null(a0_val) | is.null(effect_val)) { stop("plot.bayes_ctd_array() requires a0_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZX|WY") { if (is.null(subj_per_arm_val) | is.null(effect_val)) { stop("plot.bayes_ctd_array() requires subj_per_arm_val and effect_val to be non-missing and equal to a value used in your simulation.") } } if (toupper(tab_type) == "ZY|WX") { if (is.null(subj_per_arm_val) | is.null(a0_val)) { stop("plot.bayes_ctd_array() requires subj_per_arm_val and a0_val to be non-missing and equal to a value used in your simulation.") } } # Need to check that smooth is TRUE/FALSE if (smooth != TRUE & smooth != FALSE) { stop("plot.bayes_ctd_array() requires smooth to be either TRUE or FALSE") } # Need to check that plot_out is TRUE/FALSE if (plot_out != TRUE & plot_out != FALSE) { stop("plot.bayes_ctd_array() requires plot_out to be either TRUE or FALSE") } # Need to make sure span elements are all positive numbers. for (sp in span) { if (!is.numeric(sp)) stop("plot.bayes_ctd_array() requires span to be numeric.") if (sp <= 0) stop("plot.bayes_ctd_array() requires span to be positive") } subj_per_arm_vec <- bayes_ctd_robj$subj_per_arm a0_val_vec <- bayes_ctd_robj$a0_vals effect_val_vec <- bayes_ctd_robj$effect_vals rand_control_diff_vec <- bayes_ctd_robj$rand_control_diff if (!is.null(subj_per_arm_val)) { if (is.na(match(subj_per_arm_val, subj_per_arm_vec))) { text_val <- "plot.bayes_ctd_array() requires subj_per_arm_val to be equal to one of the following values: " for (i in 1:length(subj_per_arm_vec)) { text_val <- paste(text_val, subj_per_arm_vec[i], sep = "") if (i != length(subj_per_arm_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } if (!is.null(a0_val)) { if (is.na(match(a0_val, a0_val_vec))) { text_val <- "plot.bayes_ctd_array() requires a0_val to be equal to one of the following values: " for (i in 1:length(a0_val_vec)) { text_val <- paste(text_val, a0_val_vec[i], sep = "") if (i != length(a0_val_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } if (!is.null(effect_val)) { if (is.na(match(effect_val, effect_val_vec))) { text_val <- "plot.bayes_ctd_array() requires effect_val to be equal to one of the following values: " for (i in 1:length(effect_val_vec)) { text_val <- paste(text_val, effect_val_vec[i], sep = "") if (i != length(effect_val_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } if (!is.null(rand_control_diff_val)) { if (is.na(match(rand_control_diff_val, rand_control_diff_vec))) { text_val <- "plot.bayes_ctd_array() requires rand_control_diff_val to be equal to one of the following values: " for (i in 1:length(rand_control_diff_vec)) { text_val <- paste(text_val, rand_control_diff_vec[i], sep = "") if (i != length(rand_control_diff_vec)) { text_val <- paste(text_val, ", ", sep = "") } } stop(text_val) } } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/GlobalErrorChecks.R
#' Generating function for Lognormal Data. #' #' \code{genlognormaldata()} function used mainly internally by #' \code{lognormaltrialsimulator()} and \code{lognormaltrialsimulatornohist()} functions #' to generate data for a two-arm clinical trial, experimental and control groups. #' Can be used to generate random trial data. #' #' @param sample_size Number of subjects per arm. #' @param mu1 meanlog parameter used in call to \code{rlnorm()}. #' Used only in control arm. #' @param mean_ratio Desired Mean Ratio between experimental and control groups. #' @param common_sd sdlog parameter used in call to \code{rlnorm()}. #' Used in both arms. #' @param censor_value Value at which time-to-event data are right censored. #' #' @return \code{genlognormaldata()} returns a data frame with columns: 'id', 'treatment', #' 'event_time', and 'status'. #' #' @examples #' samplehistdata <- genlognormaldata(sample_size=60, mu1=1.06, mean_ratio=0.6, #' common_sd=1.25, censor_value=3) #' samplehistdata #' @export genlognormaldata <- function(sample_size, mu1, mean_ratio, common_sd, censor_value) { # --------------------------------------------------------------- # # The function genlognormaldata simulates a balanced clinical trial # with 'sample_size' subjects per arm using a lognormal distribution. # 'm1' is the lognormal location parameter, and 'common_sd' is the # lognormal scale parameter for both arms. 'censor_value' is the # value when right censoring occurs. As of 9/5/2016, # genlognormaldata only generates data with right censoring. # Random right censoring is not incorporated. 'mean_ratio is the # ratio of group means (experimental group over control group). # # In the code below time1, mu1, test1, status1, etc. are data # for the control goup. # In the code below time2, mu2, test2, status2, etc. are data # for the experimental group. # --------------------------------------------------------------- # # mu1 is the lognormal distribution mu parameter for the control group. # The lognormal mean for control group is: lnmean1 <- exp(mu1 + 0.5 * common_sd^2) # given user specified mean_ratio, the lognormal mean for experimental # group is: lnmean2 <- mean_ratio * lnmean1 # Now, I need to transform the lognormal mean in the experimental group # to the mu parameter for experimental group. mu2 <- log(lnmean2) - 0.5 * common_sd^2 # Create event times for both groups time1 <- stats::rlnorm(sample_size, meanlog = mu1, sdlog = common_sd) time2 <- stats::rlnorm(sample_size, meanlog = mu2, sdlog = common_sd) # Create variables needed for simulation when censor_value is specified. if (!is.null(censor_value) == TRUE) { test1 <- (time1 > censor_value) #Identify which times need right censoring. test2 <- (time2 > censor_value) status1 <- rep(1, sample_size) #Initialize the Status variable. status2 <- rep(1, sample_size) #For all observations that need to be right censored, set the time # value to the right censor value and set the status value to 0 # (indicating right censoring). Status=1 implies observed event. # Status=0 implies right censored event. time1[test1] <- censor_value time2[test2] <- censor_value status1[test1] <- 0 status2[test2] <- 0 } #Create status variable if censor_value is not specified (in such a case # status = 1 for all observeations.) if (is.null(censor_value) == TRUE) { status1 <- rep(1, sample_size) status2 <- rep(1, sample_size) } #Take all data created above and put into a data frame that contains # the required variables. subjid <- seq(from = 1, to = 2 * sample_size) trt <- c(rep(0, sample_size), rep(1, sample_size)) time <- c(time1, time2) status <- c(status1, status2) gendata <- data.frame(subjid, trt, time, status) colnames(gendata) <- c("id", "treatment", "event_time", "status") return(gendata) } #' Log-likelihood function for two-arm trial with historical data using Lognormal #' distribution. #' #' \code{lognormalloglike()} function only used internally by #' \code{lognormaltrialsimulator()} function to estimate Lognormal model parameters #' when clinical trial involves experimental and control groups as well as historical #' control data. The lognormal log-likelihood is calculated by modeling \code{log(data)} #' as a Gaussian random variable. Not to be called directly by user. #' #' @param params Three element vector of Lognormal parameters. Third element is log(sd), #' where sd is a parameter required by dnorm(). The first and second elements #' are the intercept (beta0) and treatment effect parameter (beta1), where the treatment effect is #' a log mean ratio (experimental group over control group). The mu parameter required by #' dnorm() is equal to params[1] + params[2]*treatment. It is assumed that the log(sd) #' parameter is the same in both randomized and historical data. It is assumed that #' the mu parameter in the randomized and historical control data is equal to params[1]. #' @param randdata Dataset of randomly generated trial data. Randomized trial datasets #' must have 4 columns: id, treatment, event_time, and status. The value of treatment #' must be 0 (control) or 1 (experimental). The values of event_time must be positive. #' The values of status must be 0 (right censored event) or 1 (observed event). #' @param histdata Dataset of historical data. Historical datasets must have 4 columns: #' id, treatment, event_time, and status. The value of treatment should be 0. The #' values of event_time must be positive. The values of status must be 0 (right #' censored event) or 1 (observed event). #' @param a0 Power prior parameter: 0 implies historical data is ignored and 1 implies #' all information in historical data is used. #' #' @return \code{lognormalloglike()} returns a value of the loglikelihood function #' given a set of Lognormal parameters, randomly generated trial data, and observed #' historical data. #' #' @examples #' #None #' @keywords internal #' @noRd lognormalloglike <- function(params, randdata, histdata, a0) { # --------------------------------------------------------------- # # This function calculates the Lognormal log-likelihood given # a vector of parameter values, a dataset of randomized trial # data (two arms, no covariates beyond treatment), and a dataset # of historical control data. # The lognormal scale parameter is common in both randomized # groups and the historical control group. The lognormal location # parameter is assumed to be the same in both control groups. # The location parameter for the randomized experimental group is # a linear function of the control location and the treatment # effect. The parameters are beta0, beta1, and logs. logs is the # log of the common scale parameter. beta0 and beta1 are regression # parameters that are linked to the Lognoraml location parameter, # mu, via the identity link. beta1 is the log mean ratio # (experimental group over control group), while beta0 is the # location parameter for controls. # --------------------------------------------------------------- # # Get params. Note that the scale parameter is on the log scale. # To calculate the lognormal standard deviation value one must use exp(logs). beta0 <- params[1] beta1 <- params[2] logs <- params[3] # Calculate the lognormal mu parameter vector for all randomized observations. mu_i <- beta0 + beta1 * randdata$treatment # Calculate the log-likelihood values for all randomized observations. # Note that I am modeling the lognormal by taking the log of event_time and then # using the Gaussian distribution for the log transformed values. Could have used # lnorm(), but did it this way just because it is what I am used to doing. ll_R <- randdata$status * stats::dnorm(log(randdata$event_time), mean = mu_i, sd = exp(logs), log = TRUE) + (1 - randdata$status) * stats::pnorm(log(randdata$event_time), mean = mu_i, sd = exp(logs), log.p = TRUE, lower.tail = FALSE) # Calculate the loglikelihood values for all historical control observations. # Note that the lognormal mu parameter is equal to beta0. ll_H <- histdata$status * stats::dnorm(log(histdata$event_time), mean = beta0, sd = exp(logs), log = TRUE) + (1 - histdata$status) * stats::pnorm(log(histdata$event_time), mean = beta0, sd = exp(logs), log.p = TRUE, lower.tail = FALSE) # Calculate the overall log likelihood by adding the randomized log-likelihood to the historical control # log-likelihood by a0, where a0 is the power prior parameter. This a0 value is defined by the # user and not estimated via object function optimization. ll <- sum(ll_R) + a0 * sum(ll_H) # Return the sum of all individual elements to the negative log-likelihood return(-ll) } #' Log-likelihood function for two-arm trial with no historical data using Lognormal distribution. #' #' \code{lognormalloglikenohist()} function only used internally by #' \code{lognormaltrialsimulatornohist()} function to estimate Lognormal model parameters #' when clinical trial involves experimental and control groups but no historical control #' data. The lognormal log-likelihood is calculated by modeling \code{log(data)} as #' a Gaussian random variable. Not to be called directly by user. #' #' @param params Three element vector of Lognormal parameters. Third element is log(sd), #' where sd is a parameter required by dnorm(). The first and second elements #' are the intercept (beta0) and treatment effect parameter (beta1), where the treatment effect is #' a log mean ratio (experimental group over control group). The mu parameter required by #' dnorm() is equal to params[1] + params[2]*treatment. It is assumed that #' the mu parameter in the randomized control data is equal to params[1]. #' @param randdata Dataset of randomly generated trial data. Randomized trial datasets #' must have 4 columns: id, treatment, event_time, and status. The value of treatment #' must be 0 (control) or 1 (experimental). The values of event_time must be positive. #' The values of status must be 0 (right censored event) or 1 (observed event). #' #' @return \code{lognormalloglikenohist()} returns a value of the loglikelihood function #' given a set of Lognormal parameters and randomly generated trial data. #' #' @examples #' #None #' @keywords internal #' @noRd lognormalloglikenohist <- function(params, randdata) { # --------------------------------------------------------------- # # This function calculates the Lognormal log-likelihood given # a vector of parameter values, and a dataset of randomized trial # data (two arms, no covariates beyond treatment). Historical # data is not utilized in this log-likelihood function. # The lognormal scale parameter is common in both randomized # groups. The location parameter for the randomized experimental # group is a linear function of the control location and the # treatment effect. The parameters are beta0, beta1, and logs. # logs is the log of the common scale parameter. beta0 and beta1 # are regression parameters that are linked to the Lognoraml # location parameter, mu, via the identity link. beta1 is the # log mean ratio (experimental group over control group), while # beta0 is the location parameter for controls. # --------------------------------------------------------------- # # Get params. Note that the scale parameter is on the log scale. # To calculate the lognormal standard deviation value one must use exp(logs). beta0 <- params[1] beta1 <- params[2] logs <- params[3] # Calculate the lognormal mu parameter vector for all randomized observations. mu_i <- beta0 + beta1 * randdata$treatment # Calculate the log-likelihood values for all randomized observations. # Note that I am modeling the lognormal by taking the log of event_time and then # using the Gaussian distribution for the log transformed values. Could have used # lnorm(), but did it this way just because it is what I am used to doing. ll_R <- randdata$status * stats::dnorm(log(randdata$event_time), mean = mu_i, sd = exp(logs), log = TRUE) + (1 - randdata$status) * stats::pnorm(log(randdata$event_time), mean = mu_i, sd = exp(logs), log.p = TRUE, lower.tail = FALSE) # Return the sum of all individual elements to the negative log-likelihood return(sum(-ll_R)) } #' Simulate a single randomized trial using a Lognormal outcome and information from #' historical controls. #' #' \code{lognormaltrialsimulator()} function only used internally by #' \code{lognormal_sim()} function to run a single trial simulation involving historical #' control data and a Lognormal outcome. #' #' The simulation of a trial with a Lognormal outcome involving historical control data returns #' an estimate of the mean ratio as well as an estimate of the log mean ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{lognormaltrialsimulator()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param histdata Dataset of historical data. Historical datasets must have 4 columns: #' id, treatment, event_time, and status. The value of treatment should be 0. The #' values of event_time must be positive. The values of status must be 0 (right #' censored event) or 1 (observed event). #' @param mu1_val Randomized control arm meanlog parameter used in call to \code{rlnorm()}. #' @param mean_ratio_val Desired mean ratio between randomized experimental and control arms. #' @param common_sd_val Randomized sdlog parameter used in call to \code{rlnorm()}. #' Used in both randomized arms. #' @param censor_value Value at which time-to-event data are right censored. #' @param a0_val A power prior parameter ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{lognormaltrialsimulator()} returns a vector of simulation results. The #' first element is an estimated mean ratio, the second element is the estimated #' variance of the log mean ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd lognormaltrialsimulator <- function(sample_size_val, histdata, mu1_val, mean_ratio_val, common_sd_val, censor_value, a0_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate lognormal trial data given the user defined trial characteristics. sampleranddata <- genlognormaldata(sample_size = sample_size_val, mu1 = mu1_val, mean_ratio = mean_ratio_val, common_sd = common_sd_val, censor_value = censor_value) # Make sure the trial data has at least one not right censored observation. if (sum(sampleranddata$event_time == censor_value) == dim(sampleranddata)[1]) { stop("Simulated trial data must have at least one observation that is not right censored.") } # Generate initial values for your call to optim() initializemodel <- survival::survreg(survival::Surv(event_time, status) ~ treatment, dist = "lognormal", data = sampleranddata) initialbeta0 <- initializemodel$coefficients[1] initialbeta1 <- initializemodel$coefficients[2] initiallogs <- log(initializemodel$scale) # Generate the Bayesian CLT based parameter estimates needed for inference on mean ratio. fitmod <- stats::optim(c(initialbeta0, initialbeta1, initiallogs), lognormalloglike, randdata = sampleranddata, histdata = histdata, a0 = a0_val, method = "Nelder-Mead", hessian = TRUE) #Extract model parameters and statistics modparm <- fitmod$par covarmat <- solve(fitmod$hessian) lognormallogmeanratio <- modparm[2] lognormalmeanratio <- exp(lognormallogmeanratio) lower_lognormalmeanratio <- exp(lognormallogmeanratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper_lognormalmeanratio <- exp(lognormallogmeanratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_lognormalmeanratio > 1) | (upper_lognormalmeanratio < 1)), 1, 0) output <- c(lognormalmeanratio, covarmat[2, 2], reject) #Return the mean ratio, the estimated variance of the log mean ratio, and the trial decision. names(output) <- c("mean_ratio", "log_mean_ratio_var", "reject") return(output) } #' Simulate a single randomized trial using a Lognormal outcome but not including any information from #' historical controls. #' #' \code{lognormaltrialsimulatornohist()} function only used internally by #' \code{simple_lognormal_sim()} function to estimate Lognormal model parameters #' when clinical trial involves experimental and control groups but no historical control #' data. #' #' The simulation of a trial with a Lognormal outcome involving no historical control data returns #' an estimate of the mean ratio as well as an estimate of the log mean ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{lognormaltrialsimulatornohist()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param mu1_val meanlog parameter used in call to \code{rlnorm()}. #' Used only in randomized control arm. #' @param mean_ratio_val Desired mean ratio between experimental and control arms. #' @param common_sd_val sdlog parameter used in call to \code{rlnorm()}. #' Used in both arms. #' @param censor_value Value at which time-to-event data are right censored. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{lognormaltrialsimulatornohist()} returns a vector of simulation results. The #' first element is an estimated mean ratio, the second element is the estimated #' variance of the log mean ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd lognormaltrialsimulatornohist <- function(sample_size_val, mu1_val, mean_ratio_val, common_sd_val, censor_value, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is not utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate lognormal trial data given the user defined trial characteristics. sampleranddata <- genlognormaldata(sample_size = sample_size_val, mu1 = mu1_val, mean_ratio = mean_ratio_val, common_sd = common_sd_val, censor_value = censor_value) # Make sure the trial data has at least one not right censored observation. if (sum(sampleranddata$event_time == censor_value) == dim(sampleranddata)[1]) { stop("Simulated trial data must have at least one observation that is not right censored.") } # Generate the Bayesian CLT based parameter estimates needed for inference on mean ratio. initializemodel <- survival::survreg(survival::Surv(event_time, status) ~ treatment, dist = "lognormal", data = sampleranddata) #Extract model parameters and statistics modparm <- initializemodel$coefficients covarmat <- stats::vcov(initializemodel) lognormallogmeanratio <- modparm[2] lognormalmeanratio <- exp(lognormallogmeanratio) lower_lognormalmeanratio <- exp(lognormallogmeanratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper_lognormalmeanratio <- exp(lognormallogmeanratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_lognormalmeanratio > 1) | (upper_lognormalmeanratio < 1)), 1, 0) output <- c(lognormalmeanratio, covarmat[2, 2], reject) #Return the hazard ratio, the estimated variance of the log hazard ratio, and the trial decision. names(output) <- c("mean_ratio", "log_mean_ratio_var", "reject") return(output) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with Historical Data and #' Lognormal Outcome. #' #' \code{lognormal_sim()} function only used internally by \code{historic_sim()} #' function to run a set of trial simulations involving historical #' control data and a Lognormal outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, mean ratios, #' and other user requested study summary statistics like variance of mean #' ratio, bias (on mean ratio scale), and mse (on mean ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{lognormal_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' a0_val, subj_per_arm, effect_vals, and rand_control_diff. As the number #' of trials increases, the precision of the estimate will increase. Default is #' 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param a0_vals A vector of power prior parameters ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param effect_vals A vector of mean ratios (randomized experimental over control), #' all of which must be positive. #' @param rand_control_diff For Lognormal outcomes this is a vector of mean ratios #' (randomized controls over historical controls) that represent differences #' between randomized and historical controls. #' @param hist_control_data A dataset of historical data. Default is \code{NULL}. #' Historical datasets must have 4 columns: id, treatment, event_time, and #' status. The value of treatment should be 0. The values of event_time must #' be positive. The values of status must be 0 (right censored event) or #' 1 (observed event). #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Default is \code{NULL}, where #' \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{lognormal_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd lognormal_sim <- function(trial_reps=100, subj_per_arm, a0_vals, effect_vals, rand_control_diff, hist_control_data, censor_value, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, mean ratio estimate, and if requested by user: # variance of mean ratio, bias, and mse. Using a Lognormal oucome # and incorporating data from historical controls. # --------------------------------------------------------------- # # Need to take the historical data and generate distributional parameter estimates histdata <- hist_control_data hist_model <- survival::survreg(survival::Surv(event_time, status) ~ 1, dist = "lognormal", data = histdata) initialmu1 <- hist_model$coefficients[1] initialsd1 <- hist_model$scale # Initialize arrays to hold power, var, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. for (diffs in 1:length(rand_control_diff)) { # Need to adjust the randomized control mean given the historical control mean and the mean ratios given in # rand_control_diff. Note, mean ratios in rand_control_diff are ratios of lognormal means # and not mu parameters of lognormal distributions (means of variables on log scale), so # you first need to calculate the lognormal mean for the historical control group. # lognormal mean for historical control group is: lnmean1 <- exp(initialmu1 + 0.5 * initialsd1^2) # given mean_ratio, lognormal for randomized control group is: lnmean2 <- rand_control_diff[diffs] * lnmean1 # Now that we have the randomized control lognormal mean, we need to transform this # back to a lognormal mu parameter: # lognormal mu parameter for randomized control group is: adjmu1 <- log(lnmean2) - 0.5 * initialsd1^2 for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_vals, and subj_per_arm, simulate the trial #trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #mean ratio scale and take the mean of all differences between estimated mean ratios and the #true mean ratio. For mse, calculate the mean of squared differences between the #estimated mean ratios and the true mean ratio value. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- lognormaltrialsimulator(sample_size_val = subj_per_arm[sizes], histdata, mu1_val = adjmu1, mean_ratio_val = effect_vals[effvals], common_sd_val = initialsd1, censor_value = censor_value, a0_val = a0_vals[a0vals], alpha = alpha) } #collect is a matrix of data, mean ratio in 1st column, log mean ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("mean_ratio", "log_mean_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 534 through 837 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, objtype= 'historic') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with no Historical Data and #' Lognormal Outcome. #' #' \code{simple_lognormal_sim()} function only used internally by \code{simple_sim()} #' function to run a set of trial simulations involving no #' historical control data and a Lognormal outcome. User defined simulation #' parameters are used to generate a set of trial scenarios. Each scenario is #' simulated multiple times and then means are taken to calculate estimates #' of power, mean ratios, and other user requested study summary statistics #' like variance of mean ratio, bias (on mean ratio scale), and #' mse (on mean ratio scale). The number of repeated simulations is #' defined by the user. #' #' \code{simple_lognormal_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' subj_per_arm and effect_vals. As the number of trials increases, the #' precision of the estimate will increase. Default is 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param effect_vals A vector of mean ratios (randomized experimental over control), #' all of which must be positive. #' @param mu1_val meanlog parameter value for randomized control arm. Used in call #' to \code{rlnorm()}. #' @param common_sd_val sdlog parameter value used in both randomized arms. Used in call to #' \code{rlnorm()}. #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Default is \code{NULL}, where #' \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{simple_lognormal_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd simple_lognormal_sim <- function(trial_reps, subj_per_arm, effect_vals, mu1_val, common_sd_val, censor_value, alpha, get_var, get_bias, get_mse, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, mean ratio estimate, and if requested by user: # variance of mean ratio, bias, and mse. Using a Lognormal oucome # but historical control data is not used. # --------------------------------------------------------------- # #The rand_control_diff and a0_val dimensions will be set to 1, and the value for # rand_control_diff will be 1 and a0_val will be set to 0. All summaries will # be set up to ignore these dimensions for simple (no historical data) simulations. rand_control_diff <- 1 a0_vals <- 0 # Initialize arrays to hold power, var, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. Note that rand_control_diff is set to 1 and a0_val is set to 0. for (diffs in 1:length(rand_control_diff)) { for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial # trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #mean ratio scale and take the mean of all differences between estimated mean ratios and the #true mean ratio. For mse, calculate the mean of squared differences between the estimated #mean ratios and the true mean ratio value. Note that rand_control_diff is set to 1 and #a0_val is set to 0. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- lognormaltrialsimulatornohist(sample_size_val = subj_per_arm[sizes], mu1_val = mu1_val, mean_ratio_val = effect_vals[effvals], common_sd_val = common_sd_val, censor_value = censor_value, alpha = alpha) } #collect is a matrix of data, mean ratio in 1st column, log mean ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("mean_ratio", "log_mean_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 970 through 1273 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = 0, effect_vals = effect_vals, rand_control_diff = 1, objtype= 'simple') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/LogNormalCode.R
#' Checks for Errors when Outcome is Lognormal. #' #' \code{lognormal_error_checks()} function used only used internally by #' \code{historic_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{historic_sim()}. #' @param hist_control_data See help page for \code{historic_sim()}. #' @param rand_control_diff See help page for \code{historic_sim()}. #' @param censor_value See help page for \code{historic_sim()}. #' @param alpha See help page for \code{historic_sim()}. #' #' @return \code{lognormal_error_checks()} returns messages when #' \code{historic_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd lognormal_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, censor_value, alpha) { hist_chk <- class(hist_control_data) rcp_chk <- is.null(rand_control_diff) # Need to check that EffectSize is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("historic_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Lognormal, historic_sim() requires effect_vals to represent Mean Ratios which must be positive numbers") } # Need to check that hist_control_data is a data frame and has the correct columns. if (hist_chk == "data.frame") { colnamevals <- colnames(hist_control_data) colnamechk <- (colnamevals == c("id", "treatment", "event_time", "status")) if (sum(colnamechk) != 4) { stop("historic_sim() requires hist_control_data to have columns: id, treatment, event_time, and status.") } if (sum(colnamechk) == 4) { if (!is.numeric(hist_control_data$event_time)) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } if (is.numeric(hist_control_data$event_time)) { if (min(hist_control_data$event_time) <= 0) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } } if (!is.numeric(hist_control_data$treatment)) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } if (is.numeric(hist_control_data$treatment)) { trt_levels <- names(table(hist_control_data$treatment)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } } if (!is.numeric(hist_control_data$status)) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } if (is.numeric(hist_control_data$status)) { trt_levels <- names(table(hist_control_data$status)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } } } } # If not NULL, need to check that rand_control_diff is positive. if (rcp_chk == FALSE) { for (rand_cp in rand_control_diff) { if (!is.numeric(rand_cp)) stop("historic_sim() requires rand_control_diff to be numeric.") if (rand_cp <= 0) stop("historic_sim() requires rand_control_diff to be Mean Ratios, so they must be positive.") } } # Need to check that censor_value is NULL or a non-negative number if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("historic_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("historic_sim() requires censor_value to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("historic_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } } #' Checks for Errors when Outcome is Lognormal. #' #' \code{lognormal_error_checks_simple()} function used only used internally by #' \code{simple_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{simple_sim()}. #' @param control_parms See help page for \code{simple_sim()}. #' @param censor_value See help page for \code{simple_sim()}. #' @param alpha See help page for \code{simple_sim()}. #' #' @return \code{lognormal_error_checks_simple()} returns messages when #' \code{simple_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd lognormal_error_checks_simple <- function(effect_vals, control_parms, censor_value, alpha) { chk_parm_lgth <- length(control_parms) # Need to check that Effect_vals is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("simple_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Lognormal, simple_sim() requires effect_vals to represent Mean Ratios which must be positive numbers") } if (chk_parm_lgth != 2) { stop("simple_sim() requires two elements in control_parms, first=Lognormal mu parameter for rlnorm(), second= Lognormal sd parameter for rlnorm()") } if (chk_parm_lgth == 2) { if (!is.numeric(control_parms[1])) stop("simple_sim() requires Lognormal mu parameter for controls to be numeric.") if (!is.numeric(control_parms[2])) stop("simple_sim() requires Lognormal sd parameter for controls to be numeric.") if (control_parms[2] <= 0) stop("simple_sim() requires Lognormal sd parameter for controls to be positive.") } # Need to check that censor_value is NULL or a non-negative number if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("simple_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("simple_sim() requires censor_value to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("simple_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/LogNormalErrorChecks.R
#' Generating function for Piece-wise Exponential Data. #' #' \code{genpwedata()} function used mainly internally by #' \code{pwetrialsimulator()} function to generate data for a two-arm #' clinical trial, experimental and control groups. Can be used to generate #' random trial data. #' #' @param sample_size Number of subjects per arm. #' @param lambda_vec Set of lambdas passed to \code{eha::rpch()} through the #' levels parameter. Used only in control arm. #' @param hazard_ratio Desired Hazard Ratio between experimental and control groups. #' @param time_vec Set of cutpoints passed to \code{eha::rpch()} through the #' cuts parameter. #' @param censor_value Value at which time-to-event data are right censored. #' #' @return \code{genpwedata()} returns a data frame with columns: 'id', 'treatment', #' 'event_time', 'status', and 'indicator'. #' #' @examples #' nvalHC <- 60 #' time.vec <- c(0.3,0.9,1.5,2.1,2.4) #' lambdaHC.vec <- c(0.19,0.35,0.56,0.47,0.38,0.34) #' censor.value <- 3 #' #' SampleHistData <- genpwedata(nvalHC, lambdaHC.vec, 1.0, time.vec, censor.value) #' SampleHistData #' @export genpwedata <- function(sample_size, lambda_vec, hazard_ratio, time_vec, censor_value) { # --------------------------------------------------------------- # # The function genpwedata simulates a balanced clinical trial with # 'sample_size' subjects per arm using a piecewise exponential # distribution. 'lambda_vec' is the vector of exponential hazard # rates for each interval. 'time_vec' identifies the time # boundaries of each interval. 'hazard_ratio' defines the # relationship between group hazards in each interval. At present # a constant hazard ratio is used. 'censor_value' is the value when # right censoring occurs. As of 4/11/2018, genpwedata only # generates data with right censoring. Random right censoring # is not incorporated. # # In the code below time1, lambda_vec, test1, status1, etc. are # data for the control goup. # In the code below time2, lambda_vec2, test2, status2, etc. are # data for the experimental group. # --------------------------------------------------------------- # # The user specified interval hazard vector, lambda_vec, and the # user specified vector of time cut points, are used to # generate random event times from a piecewise exponential. # Before I generate the event times for the experimental group # I need to generate the hazards for the experimental group. # For both control and experimental groups, each interval can # have its own hazard; however, in every interval the hazard_ratio # is equal to the user specified hazard ratio. lambdavec2 <- hazard_ratio * lambda_vec # Create event times for both groups time1 <- eha::rpch(n = sample_size, cuts = time_vec, levels = lambda_vec) time2 <- eha::rpch(n = sample_size, cuts = time_vec, levels = lambdavec2) # Create variables needed for simulation. if (!is.null(censor_value) == TRUE) { test1 <- (time1 > censor_value) #Identify which times need right censoring. test2 <- (time2 > censor_value) status1 <- rep(1, sample_size) #Initialize the Status variable. status2 <- rep(1, sample_size) #For all observations that need to be right censored, set the time # value to the right censor value and set the status value to 0 # (indicating right censoring). Status=1 implies observed event. # Status=0 implies right censored event. time1[test1] <- censor_value time2[test2] <- censor_value status1[test1] <- 0 status2[test2] <- 0 # Need to add explaination of indicator1 & indicator2. indicator1 <- rep(2, sample_size) indicator2 <- rep(3, sample_size) } #Create status variable if censor_value is not specified (in such a case # status = 1 for all observeations.) if (is.null(censor_value) == TRUE) { status1 <- rep(1, sample_size) status2 <- rep(1, sample_size) # Need to add explaination of indicator1 & indicator2. indicator1 <- rep(2, sample_size) indicator2 <- rep(3, sample_size) } #Take all data created above and put into a data frame that contains # the required variables. subjid <- seq(from = 1, to = 2 * sample_size) trt <- c(rep(0, sample_size), rep(1, sample_size)) event_time <- c(time1, time2) status <- c(status1, status2) indicator <- c(indicator1, indicator2) gendata <- data.frame(subjid, trt, event_time, status, indicator) colnames(gendata) <- c("id", "treatment", "event_time", "status", "indicator") return(gendata) } #' Log-likelihood function for two-arm trial with historical data using Piece-wise #' Exponential (pwe) distribution. #' #' \code{pwe_loglike()} function used only used internally by #' \code{pwetrialsimulator()} function to estimate pwe model parameters #' when clinical trial involves experimental and control groups as well as historical #' control data. The pwe log-likelihood is calculated by using \code{eha::dpch()}. #' pwe_loglike() should not be called directly by user. #' #' @param params A vector of p + 1 parameters. The last element is #' the log hazard ratio. The first p elements are the estimated log hazards #' within each section created by \code{time_vec}. If \code{time_vec} has #' m elements, then p = m + 1. #' @param time_vec Vector of cut points used to divide time-scale into sections #' within which hazard is constant. #' @param randdata Dataset of randomly generated trial data. #' @param hist_data Dataset of historical data. #' @param a0 Power prior parameter: 0 implies historical data is ignored and 1 implies #' all information in historical data is used. #' #' @return \code{pwe_loglike()} returns a value of the loglikelihood function #' given a set of pwe parameters, randomly generated trial data, and observed #' historical data. #' #' @examples #' #None #' @keywords internal #' @noRd pwe_loglike <- function(params, time_vec, randdata, hist_data, a0) { # --------------------------------------------------------------- # # This function calculates the piecewise exponential # log-likelihood given a vector of parameter values, a vector # of time cutpoints to define intervals, a dataset of randomized # trial data (two arms, no covariates beyond treatment), and a # dataset of historical control data. # The hazards within each interval is assumed to be the same in # both control groups. # For each interval the hazard in the experimental group is equal # to the hazard ratio times the control hazard for that interval. # The parameter vector is of length p+1, implying p time # intervals and one parameter for the hazard ratio. The # parameters are on the log scale, so the first p parameters # are log hazards for the time intervals and the last parameter # is the log hazard ratio. # --------------------------------------------------------------- # # Extract the vector of hazards for control group from the parameter vector. # Note the parameters are on the log scale. params_c_i <- exp(params[-length(params)]) # Extract the vector of hazards for the experimental group from the parameter vector. params_e_i <- exp(params[-length(params)] + params[length(params)]) # Calculate the log-likelihood values for all randomized observations. ll_R <- (randdata$status == 1 & randdata$treatment == 0) * eha::dpch(randdata$event_time, cuts = time_vec, levels = params_c_i, log = TRUE) + (randdata$status == 0 & randdata$treatment == 0) * eha::ppch(randdata$event_time, cuts = time_vec, levels = params_c_i, lower.tail = FALSE, log.p = TRUE) + (randdata$status == 1 & randdata$treatment == 1) * eha::dpch(randdata$event_time, cuts = time_vec, levels = params_e_i, log = TRUE) + (randdata$status == 0 & randdata$treatment == 1) * eha::ppch(randdata$event_time, cuts = time_vec, levels = params_e_i, lower.tail = FALSE, log.p = TRUE) # Calculate the loglikelihood values for all historical control observations. ll_H <- (hist_data$status == 1) * eha::dpch(hist_data$event_time, cuts = time_vec, levels = params_c_i, log = TRUE) + (hist_data$status == 0) * eha::ppch(hist_data$event_time, cuts = time_vec, levels = params_c_i, lower.tail = FALSE, log.p = TRUE) # Calculate the overall log likelihood by adding the randomized log-likelihood to the historical control # log-likelihood by a0, where a0 is the power prior parameter. This a0 value is defined by the # user and not estimated via object function optimization. ll <- sum(ll_R) + a0 * sum(ll_H) # Return the sum of all individual elements to the negative log-likelihood return(-ll) } #' Simulate a single randomized trial using a piece-wise exponential outcome and information from #' historical controls. #' #' \code{pwetrialsimulator()} function only used internally by #' \code{pwe_sim()} function to run a single trial simulation involving historical #' control data and a piece-wise exponential outcome. #' #' The simulation of a trial with a piece-wise exponential outcome involving historical control data returns #' an estimate of the hazard ratio as well as an estimate of the log hazard ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{pwetrialsimulator()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param hist_data Dataset of historical data. Historical datasets must have 5 columns: #' id, treatment, event_time, status, and indicator. The value of treatment should be 0. The #' values of event_time must be positive. The values of status must be 0 (right #' censored event) or 1 (observed event). The value of indicator must be 2. #' @param lambda_vec_val Set of lambdas for the randomized control arm that will be #' passed to \code{eha::rpch()} through the levels parameter. #' @param time_vec_val Set of cutpoints for the simulated trial data that will be #' passed to \code{eha::rpch()} through the cuts parameter. #' @param hazard_ratio_val Desired Hazard Ratio between randomized experimental and control groups. #' @param censor_value Value at which time-to-event data are right censored. #' @param a0_val A power prior parameter ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{pwetrialsimulator()} returns a vector of simulation results. The #' first element is an estimated hazard ratio, the second element is the estimated #' variance of the log hazard ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd pwetrialsimulator <- function(sample_size_val, hist_data, lambda_vec_val, time_vec_val, hazard_ratio_val, censor_value, a0_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate pwe trial data given the user defined trial characteristics. sampleranddata <- genpwedata(sample_size = sample_size_val, lambda_vec = lambda_vec_val, hazard_ratio = hazard_ratio_val, time_vec = time_vec_val, censor_value = censor_value) if (sum(sampleranddata$event_time == censor_value) == dim(sampleranddata)[1]) { stop("Simulated trial data must have at least one observation that is not right censored.") } # I have a problem to solve, what if I have an interval that has no events? # To solve this problem, I check to see if each time interval has enough events among # controls and experimental group. # Using the variable 'indicator', which is equal to 2 for controls and 3 for # experimental group, I create a table of indicator value by interval that identifies the # number of events that have occurred in each interval by 'indicator' combination. # If each cell of this table does not contain at least 2 events, then I reduce the number # of intervals by one, reconstruct the table and reassess. The process stops if # all table cells contain at least 2 events or the number of intervals equals two. # Note that historical controls and randomized controls both need to have 'indicator' # set to 2, so both control groups will be combined into the same row of the assessment # table. If the historical controls have a different value for 'indicator' then # the assessment table will have three rows and the number of intervals will be # heavily influenced by the historical data. # Regardless of the number of rows in the assessment table, each cell in the all_trts # by interval_test table needs to have at least 2 events. # First, get a list of event times for all observed events. all_events <- c(hist_data$event_time[hist_data$status == 1], sampleranddata$event_time[sampleranddata$status == 1]) # Next, get a list of the indicator values for all observed events. all_trts <- c(hist_data$indicator[hist_data$status == 1], sampleranddata$indicator[sampleranddata$status == 1]) # Set the flag used to indicator when an acceptable set of time intervals are identified. flag1 <- 0 # First check the user defined intervals for sufficient number of events in each interval # Note, findInterval uses time_vec_val to divide the real line into p + 1 intervals, # where p is equal to the number of elements in time_vec_val. The return value of # findInterval() is 0,1,2,3,etc., where 0 is the interval 0 to the first element of # time_vec_val, 1 is the interval between the first and second elements of time_vec_val, # etc. interval_test <- findInterval(all_events, time_vec_val) test_table <- table(all_trts, interval_test) for (m in 1:dim(test_table)[1]) { for (n in 1:dim(test_table)[2]) { if (test_table[m, n] < 2 & flag1 == 0) flag1 <- 1 } } # If user defined set of time cutoffs are sufficient use them. if (flag1 == 0) new_breaks <- time_vec_val #If user defined intervals do not create an assessment table with at least 5 events, then # start with a set of cutpoints equal in number to the length of the user defined set, but # spaced so that the number of events in each interval are about the same. if (flag1 == 1){ new_breaks <- NULL splits <- length(time_vec_val) + 1 #Ensures the number of initial new breaks with equal length(time_vec_val) repeat { #For present number of cutpoints, identify cutpoints with equal proportions of # events within time intervals created by cutpoints. temp_breaks <- stats::quantile(all_events, prob = seq(from = 1/splits, to = 1 - 1/splits, by = 1/splits)) #For all events, find the interval number (interval 1, interval 2, etc.) that # contains the event. interval_test <- findInterval(all_events, temp_breaks) # Create a table of group source (historical controls, randomized controls, or # or experimental group) by interval counts. test_table <- table(all_trts, interval_test) # If each cell in test_table contains at least 5 events, then cut point # selection is used to estimate hazard ratio. for (m in 1:dim(test_table)[1]) { for (n in 1:dim(test_table)[2]) { if (test_table[m, n] < 2 & flag1 == 1) flag1 <- 0 } } # If we only have two intervals, stop. Note: splits equals the number of intervals not number of cutpoints. if (flag1 == 1 | splits == 2) { break } else { splits <- splits - 1 flag1 <- 1 } } new_breaks <- as.vector(temp_breaks) } new_breaks2 <- c(0, new_breaks, censor_value) # The values in new_breaks create length(new_breaks)+1 time intervals. Each must have a # modeled hazard parameter. Also the last parameter passed to the model fitting routine # will be the log hazard ratio. # Generate initial values for your call to optim() chk_model <- eha::pchreg(survival::Surv(event_time, status) ~ treatment, data = sampleranddata, cuts = new_breaks2) rc_hazards <- c(chk_model$hazards) rand_hr <- exp(chk_model$coefficients) init.parms <- as.vector(c(log(rc_hazards), log(rand_hr))) # Generate the Bayesian CLT based parameter estimates needed for inference on hazard ratio. fitmod <- stats::optim(par = init.parms, fn = pwe_loglike, time_vec = new_breaks, randdata = sampleranddata, hist_data = hist_data, a0 = a0_val, method = "Nelder-Mead", hessian = TRUE) #Extract model parameters and statistics hr_loc <- length(init.parms) covar_mat <- solve(fitmod$hessian) hazard_ratio <- exp(fitmod$par[hr_loc]) lower_pwe_hazard_ratio <- exp(fitmod$par[hr_loc] - stats::qnorm(1 - alpha/2) * sqrt(covar_mat[hr_loc, hr_loc])) upper_pwe_hazard_ratio <- exp(fitmod$par[hr_loc] + stats::qnorm(1 - alpha/2) * sqrt(covar_mat[hr_loc, hr_loc])) # Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_pwe_hazard_ratio > 1) | (upper_pwe_hazard_ratio < 1)), 1, 0) output <- c(hazard_ratio, covar_mat[hr_loc, hr_loc], reject) # Return the mean ratio, the estimated variance of the log mean ratio, and the trial decision. names(output) <- c("pwe_hazard_ratio", "log_hr_var", "reject") return(output) } #' Simulate a single randomized trial using a piece-wise exponential outcome but not including any #' information from historical controls. #' #' \code{pwetrialsimulatornohist()} function only used internally by #' \code{simple_pwe_sim()} function to estimate piece-wise exponential model parameters #' when clinical trial involves experimental and control groups but no historical control #' data. #' #' The simulation of a trial with a piece-wise exponential outcome involving no historical control #' data returns an estimate of the hazard ratio as well as an estimate of the log hazard ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{pwetrialsimulatornohist()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param lambda_vec_val Set of lambdas for the randomized control arm that will be #' passed to \code{eha::rpch()} through the levels parameter. #' @param time_vec_val Set of cutpoints for the simulated trial data that will be #' passed to \code{eha::rpch()} through the cuts parameter. #' @param hazard_ratio_val Desired Hazard Ratio between randomized experimental and control groups. #' @param censor_value Value at which time-to-event data are right censored. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{pwetrialsimulatornohist()} returns a vector of simulation results. The #' first element is an estimated hazard ratio, the second element is the estimated #' variance of the log hazard ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd pwetrialsimulatornohist <- function(sample_size_val, lambda_vec_val, time_vec_val, hazard_ratio_val, censor_value, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where no # historical data is utilized in the parameter estimation. # Only randomized data is used in parameter estimation. # --------------------------------------------------------------- # # Generate pwe trial data sampleranddata <- genpwedata(sample_size = sample_size_val, lambda_vec = lambda_vec_val, hazard_ratio = hazard_ratio_val, time_vec = time_vec_val, censor_value = censor_value) if (sum(sampleranddata$event_time == censor_value) == dim(sampleranddata)[1]) { stop("Simulated trial data must have at least one observation that is not right censored.") } # I have a problem to solve, what if I have an interval that has no events? # To solve this problem, I check to see if each time interval has enough events among # controls and experimental group. # Using the variable 'indicator', which is equal to 2 for controls and 3 for # experimental group, I create a table of indicator value by interval that identifies the # number of events that have occurred in each interval by 'indicator' combination. # If each cell of this table does not contain at least 2 events, then I reduce the number # of intervals by one, reconstruct the table and reassess. The process stops if # all table cells contain at least 2 events or the number of intervals equals two. # Note that historical controls and randomized controls both need to have 'indicator' # set to 2, so both control groups will be combined into the same row of the assessment # table. If the historical controls have a different value for 'indicator' then # the assessment table will have three rows and the number of intervals will be # heavily influenced by the historical data. # Regardless of the number of rows in the assessment table, each cell in the all_trts # by interval_test table needs to have at least 2 events. # First, get a list of event times for all observed events. all_events <- c(sampleranddata$event_time[sampleranddata$status == 1]) # Next, get a list of the indicator values for all observed events. all_trts <- c(sampleranddata$indicator[sampleranddata$status == 1]) # Set the flag used to indicator when an acceptable set of time intervals are identified. flag1 <- 0 #First check the user defined intervals for sufficient number of events in each interval # Note, findInterval uses time_vec_val to divide the real line into p + 1 intervals, # where p is equal to the number of elements in time_vec_val. The return value of # findInterval() is 0,1,2,3,etc., where 0 is the interval 0 to the first element of # time_vec_val, 1 is the interval between the first and second elements of time_vec_val, # etc. interval_test <- findInterval(all_events, time_vec_val) test_table <- table(all_trts, interval_test) for (m in 1:dim(test_table)[1]) { for (n in 1:dim(test_table)[2]) { if (test_table[m, n] < 2 & flag1 == 0) flag1 <- 1 } } # If user defined set of time cutoffs are sufficient use them. if (flag1 == 0) new_breaks <- time_vec_val # If user defined intervals do not create an assessment table with at least 5 events, then # start with a set of cutpoints equal in number to the length of the user defined set, but # spaced so that the number of events in each interval are about the same. if (flag1 == 1){ new_breaks <- NULL splits <- length(time_vec_val) + 1 #Ensures the number of initial new breaks with equal length(time_vec_val) repeat { # For present number of cutpoints, identify cutpoints with equal proportions of # events within time intervals created by cutpoints. temp_breaks <- stats::quantile(all_events, prob = seq(from = 1/splits, to = 1 - 1/splits, by = 1/splits)) # For all events, find the interval number (interval 1, interval 2, etc.) that # contains the event. interval_test <- findInterval(all_events, temp_breaks) # Create a table of group source (historical controls, randomized controls, or # or experimental group) by interval counts. test_table <- table(all_trts, interval_test) # If each cell in test_table contains at least 5 events, then cut point # selection is used to estimate hazard ratio. for (m in 1:dim(test_table)[1]) { for (n in 1:dim(test_table)[2]) { if (test_table[m, n] < 2 & flag1 == 1) flag1 <- 0 } } # If we only have two intervals, stop. Note: splits equals the number of intervals not number of cutpoints. if (flag1 == 1 | splits == 2) { break } else { splits <- splits - 1 flag1 <- 1 } } new_breaks <- as.vector(temp_breaks) } new_breaks2 <- c(0, new_breaks, censor_value) # The values in new_breaks create length(new_breaks)+1 time intervals. Each must have a # modeled hazard parameter. Also the last parameter passed to the model fitting routine # will be the log hazard ratio. # Generate initial values for your call to optim() chk_model <- eha::pchreg(survival::Surv(event_time, status) ~ treatment, data = sampleranddata, cuts = new_breaks2) # Extract model parameters and statistics rc_hazards <- c(chk_model$hazards) rand_hr <- exp(chk_model$coefficients) hazard_ratio <- exp(chk_model$coefficients) lower_pwe_hazard_ratio <- exp(chk_model$coefficients - stats::qnorm(1 - alpha/2) * sqrt(chk_model$var)) upper_pwe_hazard_ratio <- exp(chk_model$coefficients + stats::qnorm(1 - alpha/2) * sqrt(chk_model$var)) # Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_pwe_hazard_ratio > 1) | (upper_pwe_hazard_ratio < 1)), 1, 0) output <- c(hazard_ratio, chk_model$var, reject) # Return the hazard ratio, the estimated variance of the log hazard ratio, and the trial decision. names(output) <- c("pwe_hazard_ratio", "log_hr_var", "reject") return(output) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with Historical Data and #' Piece-wise Exponential Outcome. #' #' \code{pwe_sim()} function only used internally by \code{historic_sim()} #' function to run a set of trial simulations involving historical #' control data and a piece-wise exponential outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, hazard ratios, #' and other user requested study summary statistics like variance of hazard #' ratio, bias (on hazard ratio scale), and mse (on hazard ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{pwe_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' a0_val, subj_per_arm, effect_vals, and rand_control_diff. As the number #' of trials increases, the precision of the estimate will increase. Default is #' 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param a0_vals A vector of power prior parameters ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param effect_vals A vector of hazard ratios (randomized experimental over control), #' all of which must be positive. #' @param rand_control_diff For piece-wise exponential outcomes this is a vector of hazard ratios #' (randomized controls over historical controls) that represent differences #' between randomized and historical controls. #' @param hist_control_data A dataset of historical data. Default is \code{NULL}. #' Historical datasets must have 4 columns: id, treatment, event_time, status, and #' indicator. The value of treatment should be 0. The values of event_time must #' be positive. The values of status must be 0 (right censored event) or #' 1 (observed event). The value of indicator must be 2. #' @param time_vec_val A vector of time values which are used to create time periods #' within which the exponential hazard is constant. Only used for piecewise #' exponential models. Default is \code{NULL}. #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Default is \code{NULL}, where #' \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{pwe_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd pwe_sim <- function(trial_reps=100, subj_per_arm, a0_vals, effect_vals, rand_control_diff, hist_control_data, time_vec_val, censor_value, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, hazard ratio estimate, and if requested by user: # variance of hazard ratio, bias, and mse. Using a piece-wise # exponential oucome and incorporating data from historical controls. # --------------------------------------------------------------- # time_vec_val2 <- c(0, time_vec_val, censor_value) # Need to take the historical data and generate distributional parameter estimates hist_data <- hist_control_data chk_model <- eha::pchreg(survival::Surv(event_time, status) ~ 1, data = hist_data, cuts = time_vec_val2) hc_hazards <- c(chk_model$hazards) # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. for (diffs in 1:length(rand_control_diff)) { # Need to adjust the randomized control lambda parameters given the historical control lambda parameters and the # hazard ratios given in rand_control_diff adj_lambda <- rand_control_diff[diffs] * hc_hazards for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial #trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #hazard ratio scale and take the mean of all differences between estimated hazard ratios and the #true hazard ratio. For mse, calculate the mean of squared differences between the #estimated hazard ratios and the true hazard ratio value. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- pwetrialsimulator(sample_size_val = subj_per_arm[sizes], hist_data = hist_data, lambda_vec_val = adj_lambda, time_vec_val = time_vec_val, hazard_ratio_val = effect_vals[effvals], censor_value = censor_value, a0_val = a0_vals[a0vals], alpha = alpha) } #collect is a matrix of data, hazard ratio in 1st column, log hazard ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("hazard_ratio", "log_hazard_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and hazard # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 637 through 940 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, objtype= 'historic') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with no Historical Data and #' Piece-wise Exponential Outcome. #' #' \code{simple_pwe_sim()} function only used internally by \code{simple_sim()} #' function to run a set of trial simulations involving no historical #' control data and a piece-wise exponential outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, hazard ratios, #' and other user requested study summary statistics like variance of hazard #' ratio, bias (on hazard ratio scale), and mse (on hazard ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{simple_pwe_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' a0_val, subj_per_arm, effect_vals, and rand_control_diff. As the number #' of trials increases, the precision of the estimate will increase. Default is #' 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param effect_vals A vector of hazard ratios (randomized experimental over control), #' all of which must be positive. #' @param time_vec_val Set of cutpoints for the simulated trial data that will be #' passed to \code{eha::rpch()} through the cuts parameter. #' @param rc_hazards Set of lambdas for the randomized control arm that will be #' passed to \code{eha::rpch()} through the levels parameter. #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Default is \code{NULL}, where #' \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{simple_pwe_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd simple_pwe_sim <- function(trial_reps=100, subj_per_arm, effect_vals, time_vec_val, rc_hazards, censor_value, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, hazard ratio estimate, and if requested by user: # variance of hazard ratio, bias, and mse. Using a Weibull oucome # but historical control data is not used. # --------------------------------------------------------------- # #The rand_control_diff and a0_val dimensions will be set to 1, and the value for # rand_control_diff will be 1 and a0_val will be set to 0. All summaries will # be set up to ignore these dimensions for simple (no historical data) simulations. rand_control_diff <- 1 a0_vals <- 0 # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. Note that rand_control_diff is set to 1 and a0_val is set to 0. for (diffs in 1:length(rand_control_diff)) { for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial # trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #hazard ratio scale and take the mean of all differences between estimated hazard ratios and the #true hazard ratio. For mse, calculate the mean of squared differences between the estimated #hazard ratios and the true hazard ratio value. Note that rand_control_diff is set to 1 and #a0_val is set to 0. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal in both arms collect[k, ] <- pwetrialsimulatornohist(sample_size_val = subj_per_arm[sizes], lambda_vec_val = rc_hazards, time_vec_val = time_vec_val, hazard_ratio_val = effect_vals[effvals], censor_value = censor_value, alpha = alpha) } #collect is a matrix of data, hazard ratio in 1st column, log hazard ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("hazard_ratio", "log_hazard_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and hazard # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 1073 through 1376 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = 0, effect_vals = effect_vals, rand_control_diff = 1, objtype= 'simple') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/PWECode.R
#' Checks for Errors when Outcome is Piece-wise Exponential. #' #' \code{pwe_error_checks()} function used only used internally by #' \code{historic_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{historic_sim()}. #' @param hist_control_data See help page for \code{historic_sim()}. #' @param rand_control_diff See help page for \code{historic_sim()}. #' @param time_vec See help page for \code{historic_sim()}. #' @param censor_value See help page for \code{historic_sim()}. #' @param alpha See help page for \code{historic_sim()}. #' #' @return \code{pwe_error_checks()} returns messages when #' \code{historic_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd pwe_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, time_vec, censor_value, alpha) { hist_chk <- class(hist_control_data) rcp_chk <- is.null(rand_control_diff) tv_chk <- is.null(time_vec) # Need to check that Effect_vals is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("historic_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For pwe, historic_sim() requires effect_vals to represent Hazard Ratios which must be positive numbers") } # Need to check that hist_control_data is a data frame and has the correct columns. if (hist_chk == "data.frame") { colnamevals <- colnames(hist_control_data) colnamechk <- (colnamevals == c("id", "treatment", "event_time", "status", "indicator")) if (sum(colnamechk) != 5) { stop("historic_sim() requires hist_control_data to have columns: id, treatment, event_time, status, and indicator.") } if (sum(colnamechk) == 5) { if (!is.numeric(hist_control_data$event_time)) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } if (is.numeric(hist_control_data$event_time)) { if (min(hist_control_data$event_time) <= 0) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } } if (!is.numeric(hist_control_data$treatment)) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } if (is.numeric(hist_control_data$treatment)) { trt_levels <- names(table(hist_control_data$treatment)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } } if (!is.numeric(hist_control_data$status)) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } if (is.numeric(hist_control_data$status)) { trt_levels <- names(table(hist_control_data$status)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } } if (!is.numeric(hist_control_data$indicator)) { stop("historic_sim() requires hist_control_data$indicator to be a vector of 2s.") } if (2*dim(hist_control_data)[1] != sum(hist_control_data$indicator)) { stop("historic_sim() requires hist_control_data$indicator to be a vector of 2s.") } } } # If not NULL, need to check that rand_control_diff is positive. if (rcp_chk == FALSE) { for (Rand_cp in rand_control_diff) { if (!is.numeric(Rand_cp)) stop("historic_sim() requires rand_control_diff to be numeric.") if (Rand_cp <= 0) stop("historic_sim() requires rand_control_diff to be Hazard Ratios, so they must be positive.") } } if (tv_chk == TRUE) { stop("historic_sim() requires at least one value in time_vec for a pwe model.") } if (tv_chk == FALSE) { for (tvcp in time_vec) { if (!is.numeric(tvcp)) stop("historic_sim() requires time_vec to be numeric.") if (tvcp <= 0) stop("historic_sim() requires time_vec to be positive.") } } # Need to check that censor_value is NULL or a non-negative number if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("historic_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("historic_sim() requires censor_value to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("historic_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } } #' Checks for Errors when Outcome is Piece-wise Exponential. #' #' \code{pwe_error_checks_simple()} function used only used internally by #' \code{simple_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{simple_sim()}. #' @param time_vec See help page for \code{simple_sim()}. #' @param control_parms See help page for \code{simple_sim()}. #' @param censor_value See help page for \code{simple_sim()}. #' @param alpha See help page for \code{simple_sim()}. #' #' @return \code{pwe_error_checks_simple()} returns messages when #' \code{simple_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd pwe_error_checks_simple <- function(effect_vals, time_vec, control_parms, censor_value, alpha) { tv_chk <- is.null(time_vec) tv_len <- length(time_vec) rv_chk <- is.null(control_parms) rv_len <- length(control_parms) # Need to check that Effect_vals is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("simple_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For pwe, simple_sim() requires effect_sizes to represent Hazard Ratios which must be positive numbers") } if (tv_chk == TRUE) { stop("simple_sim() requires at least one value in time_vec for a pwe model.") } if (tv_chk == FALSE) { for (tvcp in time_vec) { if (!is.numeric(tvcp)) stop("simple_sim() requires time_vec to be numeric.") if (tvcp <= 0) stop("simple_sim() requires time_vec to be positive.") } } if (rv_chk == TRUE) { stop("simple_sim() requires at least two value in control_parms for a pwe model.") } if (rv_chk == FALSE) { if (length(control_parms) < 2) { stop("simple_sim() requires at least two value in control_parms for a pwe model.") } if (rv_len != (tv_len + 1)) { stop("simple_sim() requires control_parms to have one more element than time_vec") } for (rvcp in control_parms) { if (!is.numeric(rvcp)) stop("simple_sim() requires control_parms to be numeric.") if (rvcp <= 0) stop("simple_sim() requires control_parms to be positive.") } } # Need to check that censor_value is NULL or a non-negative number if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("simple_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("simple_sim() requires censor_value to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("simple_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/PWEErrorChecks.R
#' Generating function for Poisson Data. #' #' \code{genpoissondata()} function mainly used internally by #' \code{poissontrialsimulator()} function to generate data for a two-arm #' clinical trial, experimental and control groups. Can be used to generate #' random trial data. #' #' @param sample_size Number of subjects per arm. #' @param mu1 lambda parameter used in call to \code{rpois()}. #' Used only in control arm. #' @param mean_ratio Desired Mean Ratio between experimental and control groups. #' #' @return \code{genpoissondata()} returns a data frame with columns: 'id', 'treatment', #' and 'y'. #' #' @examples #' samplehistdata <- genpoissondata(sample_size=60, mu1=1, mean_ratio=1.0) #' samplehistdata #' @export genpoissondata <- function(sample_size, mu1, mean_ratio) { # --------------------------------------------------------------- # # The function genpoissondata simulates a balanced clinical trial # with 'sample_size' subjects per arm using a Poisson distribution. # 'm1' is the Poisson lambda parameter, which equals the mean. # 'mean_ratio is the ratio of group means (experimental group over # control group). # # In the code below y1 and mu1 are data for the control goup. # In the code below y2 and mu2 are data for the experimental group. # --------------------------------------------------------------- # # mu1 is the Poisson distribution lambda parameter for the control # group (ie the Poisson mean). Given mean_ratio, I need to # calculate the Poisson mean for experimental group. mu2 <- mu1 * mean_ratio # Create outcomes for both groups. y1 <- stats::rpois(sample_size, lambda = mu1) y2 <- stats::rpois(sample_size, lambda = mu2) #Take all data created above and put into a data frame that contains # the required variables. subjid <- seq(from = 1, to = 2 * sample_size) trt <- c(rep(0, sample_size), rep(1, sample_size)) y <- c(y1, y2) gendata <- data.frame(subjid, trt, y) colnames(gendata) <- c("id", "treatment", "y") return(gendata) } #' Log-likelihood function for two-arm trial with historical data using Poisson #' distribution. #' #' \code{poissonloglike()} function only used internally by #' \code{poissontrialsimulator()} function to estimate Poisson model parameters #' when clinical trial involves experimental and control groups as well as historical #' control data. The Poisson log-likelihood is calculated by modeling \code{data} #' as a Poisson random variable. Not to be called directly by user. #' #' @param params Two element vector of Poisson parameters. The first and second elements #' are the intercept (beta0) and treatment effect parameter (beta1), where the treatment effect is #' a log mean ratio (experimental group over control group). The lambda parameter required by #' dpois() is equal to exp(params[1] + params[2]*treatment). It is assumed that the params[1] #' parameter is the same in both randomized and historical data. It is assumed that #' the lambda parameter in the randomized and historical control data is equal to exp(params[1]). #' @param randdata Dataset of randomly generated trial data. Randomized trial datasets #' must have 3 columns: id, treatment, and y. The value of treatment must be 0 (control) #' or 1 (experimental). The values of y must be non negative. #' @param histdata Dataset of historical data. Historical datasets must have 3 columns: id, #' treatment, and y. The value of treatment should be 0. The values of y must be #' non negative. #' @param a0 Power prior parameter: 0 implies historical data is ignored and 1 implies #' all information in historical data is used. #' #' @return \code{poissonloglike()} returns a value of the loglikelihood function #' given a set of Poisson parameters, randomly generated trial data, and observed #' historical data. #' #' @examples #' #None #' @keywords internal #' @noRd poissonloglike <- function(params, randdata, histdata, a0) { # --------------------------------------------------------------- # # This function calculates the Poisson log-likelihood given # a vector of parameter values, a dataset of randomized trial # data (two arms, no covariates beyond treatment), and a dataset # of historical control data. # The Poisson mean parameter, lambda, is assumed to be the same # in both control groups. # The log mean parameter for the randomized experimental group is # a linear function of the log control mean and the treatment # effect, log mean ratio. The parameters are beta0, and beta1. # beta0 and beta1 are regression parameters that are linked to # Poisson mean parameter, lambda, via the exponential link. # beta1 is the log mean ratio (experimental group over control # group), while beta0 is the log mean parameter for controls. # --------------------------------------------------------------- # # Get params beta0 <- params[1] beta1 <- params[2] # Calculate the mean parameter vector for all randomized observations on log scale. pred_i <- beta0 + beta1 * randdata$treatment # Calculate the log-likelihood values for all randomized observations. ll_R <- stats::dpois(randdata$y, lambda = exp(pred_i), log = TRUE) # Calculate the loglikelihood values for all historical control observations. # Note that mean for historical controls is assumed to equal mean of randomized controls ll_H <- stats::dpois(histdata$y, lambda = exp(beta0), log = TRUE) # Calculate the overall log likelihood by adding the randomized log-likelihood to the historical control # log-likelihood by a0, where a0 is the power prior parameter. This a0 value is defined by the # user and not estimated via object function optimization. ll <- sum(ll_R) + a0 * sum(ll_H) # Return the sum of all individual elements to the negative log-likelihood return(-ll) } #' Simulate a single randomized trial using a Gaussian outcome and information from #' historical controls. #' #' \code{poissontrialsimulator()} function only used internally by #' \code{poisson_sim()} function to run a single trial simulation involving historical #' control data and a Poisson outcome. #' #' The simulation of a trial with a Poisson outcome involving historical control data returns #' an estimate of the mean ratio as well as an estimate of the log mean ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{poissontrialsimulator()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param histdata Dataset of historical data. Historical datasets must have 3 columns: id, #' treatment, and y. The value of treatment should be 0. The values of y must be #' non negative. #' @param mu1_val Mean parameter value for randomized control arm. Used in call to \code{rpois()}. #' @param mean_ratio_val Desired mean ratio between randomized experimental and control groups. #' @param a0_val A power prior parameter ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{poissontrialsimulator()} returns a vector of simulation results. The #' first element is an estimated mean ratio, the second element is the estimated #' variance of the log mean ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd poissontrialsimulator <- function(sample_size_val, histdata, mu1_val, mean_ratio_val, a0_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate Poisson trial data given the user defined trial characteristics. sampleranddata <- genpoissondata(sample_size = sample_size_val, mu1 = mu1_val, mean_ratio = mean_ratio_val) # Generate initial values for your call to optim() initializemodel <- stats::glm(y ~ treatment, family = stats::poisson(link = "log"), data = sampleranddata) initialbeta0 <- initializemodel$coefficients[1] initialbeta1 <- initializemodel$coefficients[2] # Generate the Bayesian CLT based parameter estimates needed for inference on mean ratio. fitmod <- stats::optim(c(initialbeta0, initialbeta1), poissonloglike, randdata = sampleranddata, histdata = histdata, a0 = a0_val, method = "Nelder-Mead", hessian = TRUE) #Extract model parameters and statistics modparm <- fitmod$par covarmat <- solve(fitmod$hessian) poissonlogmeanratio <- modparm[2] poissonmeanratio <- exp(poissonlogmeanratio) lower95_poissonmeanratio <- exp(poissonlogmeanratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper95_poissonmeanratio <- exp(poissonlogmeanratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower95_poissonmeanratio > 1) | (upper95_poissonmeanratio < 1)), 1, 0) output <- c(poissonmeanratio, covarmat[2, 2], reject) #Return the mean ratio, the estimated variance of the log mean ratio, and the trial decision. names(output) <- c("mean_ratio_mr", "log_mean_ratio_var", "reject") return(output) } #' Simulate a single randomized trial using a Poisson outcome but not including any information from #' historical controls. #' #' \code{poissontrialsimulatornohist()} function only used internally by #' \code{simple_poisson_sim()} function to estimate Poisson model parameters #' when clinical trial involves experimental and control groups but no historical control #' data. #' #' The simulation of a trial with a Poisson outcome involving no historical control data returns #' an estimate of the mean ratio as well as an estimate of the log mean ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{poissontrialsimulatornohist()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param mu1_val Mean parameter value for randomized control arm. Used in call to \code{rpois()}. #' @param mean_ratio_val Desired mean ratio between randomized experimental and control groups. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{poissontrialsimulatornohist} returns a vector of simulation results. The #' first element is an estimated mean ratio, the second element is the estimated #' variance of the log mean ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd poissontrialsimulatornohist <- function(sample_size_val, mu1_val, mean_ratio_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is not utilized in the parameter estimation. # No call to optim is necessary since using flat priors and # canonical link (expected and observed information are identical) # --------------------------------------------------------------- # # First, Generate Poisson trial data given the user defined trial characteristics. sampleranddata <- genpoissondata(sample_size = sample_size_val, mu1 = mu1_val, mean_ratio = mean_ratio_val) # Generate the Bayesian CLT based parameter estimates needed for inference on mean ratio. initializemodel <- stats::glm(y ~ treatment, family = stats::poisson(link = "log"), data = sampleranddata) #Extract model parameters and statistics modparm <- initializemodel$coefficients covarmat <- stats::vcov(initializemodel) poissonlogmeanratio <- modparm[2] poissonmeanratio <- exp(poissonlogmeanratio) lower95_poissonmeanratio <- exp(poissonlogmeanratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper95_poissonmeanratio <- exp(poissonlogmeanratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower95_poissonmeanratio > 1) | (upper95_poissonmeanratio < 1)), 1, 0) output <- c(poissonmeanratio, covarmat[2, 2], reject) #Return the mean ratio, the estimated variance of the log mean ratio, and the trial decision. names(output) <- c("mean_ratio_mr", "log_mean_ratio_var", "reject") return(output) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with Historical Data and #' Poisson Outcome. #' #' \code{poisson_sim()} function only used internally by \code{historic_sim()} #' function to run a set of trial simulations involving historical #' control data and a Poisson outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, mean ratios, #' and other user requested study summary statistics like variance of mean #' ratio, bias (on mean ratio scale), and mse (on mean ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{poisson_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' a0_val, subj_per_arm, effect_vals, and rand_control_diff. As the number #' of trials increases, the precision of the estimate will increase. Default is #' 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param a0_vals A vector of power prior parameters ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param effect_vals A vector of mean ratios (randomized experimental over control), #' all of which must be positive. #' @param rand_control_diff For Poisson outcomes this is a vector of mean ratios #' (randomized controls over historical controls) that represent ratios #' between randomized and historical controls. #' @param hist_control_data A dataset of historical data. Default is \code{NULL}. #' Historical datasets must have 3 columns: id, treatment, and y. The value of #' treatment should be 0. The values of y must be non negative. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{poisson_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd poisson_sim <- function(trial_reps, subj_per_arm, a0_vals, effect_vals, rand_control_diff, hist_control_data, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, mean ratio estimate, and if requested # by user: variance of mean ratio, bias, and mse. Using a Poisson # oucome and incorporating data from historical controls. # --------------------------------------------------------------- # # Need to take the historical data and generate distributional parameter estimates histdata <- hist_control_data hist_model <- stats::glm(y ~ 1, family = stats::poisson(link = "log"), data = histdata) initialmu1 <- exp(hist_model$coefficients[1]) # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. for (diffs in 1:length(rand_control_diff)) { # Need to adjust the randomized control mean given the historical control mean and the mean ratios given in # rand_control_diff adjmu1 <- initialmu1 * rand_control_diff[diffs] for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial #trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #mean ratio scale and take mean of differences between estimated mean ratios and the true mean #ratio. For mse, calculate the mean of squared differences between the estimated mean #ratios and the true mean ratio. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- poissontrialsimulator(sample_size_val = subj_per_arm[sizes], histdata, mu1_val = adjmu1, mean_ratio_val = effect_vals[effvals], a0_val = a0_vals[a0vals], alpha = alpha) } #collect is a matrix of data, mean ratio in 1st column, log mean ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("mean_ratio", "log_mean_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 397 through 700 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, objtype= 'historic') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with no Historical Data and #' Poisson Outcome. #' #' \code{simple_poisson_sim()} function only used internally by \code{simple_sim()} #' function to run a set of trial simulations involving no historical #' control data and a Poisson outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, mean ratios, #' and other user requested study summary statistics like variance of mean #' ratio, bias (on mean ratio scale), and mse (on mean ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{simple_poisson_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' subj_per_arm and effect_vals. As the number of trials increases, the #' precision of the estimate will increase. Default is 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param effect_vals A vector of mean ratios (randomized experimental over control), #' all of which must be positive. #' @param mu1_val lambda parameter value for randomized control arm. Used in call to \code{rpois()}. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{simple_poisson_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd simple_poisson_sim <- function(trial_reps=100, subj_per_arm, effect_vals, mu1_val, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, mean ratio estimate, and if requested by user: # variance of mean ratio, bias, and mse. Using a Lognormal oucome # but historical control data is not used. # --------------------------------------------------------------- # #The rand_control_diff and a0_val dimensions will be set to 1, and the value for # rand_control_diff will be 1 and a0_val will be set to 0. All summaries will # be set up to ignore these dimensions for simple (no historical data) simulations. rand_control_diff <- 1 a0_vals <- 0 # Initialize arrays to hold power, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. Note that rand_control_diff is set to 1 and a0_val is set to 0. for (diffs in 1:length(rand_control_diff)) { for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial # trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #mean ratio scale and take mean of differences between estimated mean ratios and the true mean ratio. #For mse, calculate the mean of squared differences between the estimated mean ratios and the true #mean ratio. Note that rand_control_diff is set to 1 and a0_val is set to 0. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- poissontrialsimulatornohist(sample_size_val = subj_per_arm[sizes], mu1_val = mu1_val, mean_ratio_val = effect_vals[effvals], alpha = alpha) } #collect is a matrix of data, mean ratio in 1st column, log mean ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("mean_ratio", "log_mean_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and mean # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 823 through 1126 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = 0, effect_vals = effect_vals, rand_control_diff = 1, objtype= 'simple') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/PoissonCode.R
#' Checks for Errors when Outcome is Poisson. #' #' \code{poisson_error_checks()} function used only used internally by #' \code{historic_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{historic_sim()}. #' @param hist_control_data See help page for \code{historic_sim()}. #' @param rand_control_diff See help page for \code{historic_sim()}. #' @param alpha See help page for \code{historic_sim()}. #' #' @return \code{poisson_error_checks()} returns messages when #' \code{historic_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd poisson_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, alpha) { hist_chk <- class(hist_control_data) rcp_chk <- is.null(rand_control_diff) # Need to check that EffectSize is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("historic_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Poisson, historic_sim() requires effect_vals to represent Mean Ratios which must be positive numbers") } # Need to check that hist_control_data is a data frame and has the correct columns. if (hist_chk == "data.frame") { colnamevals <- colnames(hist_control_data) colnamechk <- (colnamevals == c("id", "treatment", "y")) if (sum(colnamechk) != 3) { stop("historic_sim() requires hist_control_data to have columns: id, treatment, and y.") } if (sum(colnamechk) == 3) { if (!is.numeric(hist_control_data$y)) { stop("historic_sim() requires hist_control_data$y to be numeric.") } if (!is.numeric(hist_control_data$treatment)) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } if (is.numeric(hist_control_data$treatment)) { trt_levels <- names(table(hist_control_data$treatment)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } } } } # If not NULL, need to check that rand_control_diff is positive. if (rcp_chk == FALSE) { for (rand_cp in rand_control_diff) { if (!is.numeric(rand_cp)) stop("historic_sim() requires rand_control_diff to be numeric.") if (rand_cp <= 0) stop("historic_sim() requires rand_control_diff to be Mean Ratios, so they must be positive.") } } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("historic_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } } #' Checks for Errors when Outcome is Poisson. #' #' \code{poisson_error_checks_simple()} function used only used internally by #' \code{simple_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{simple_sim()}. #' @param control_parms See help page for \code{simple_sim()}. #' @param alpha See help page for \code{simple_sim()}. #' #' @return \code{poisson_error_checks_simple()} returns messages when #' \code{simple_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd poisson_error_checks_simple <- function(effect_vals, control_parms, alpha) { chk_parm_lgth <- length(control_parms) # Need to check that EffectSize is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("simple_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Poisson, simple_sim() requires effect_vals to represent Mean Ratios which must be positive numbers") } if (chk_parm_lgth != 1) { stop("simple_sim() requires a single elements in control_parms which is the lambda parameter, mean, for rpois()") } if (chk_parm_lgth == 1) { if (!is.numeric(control_parms[1])) stop("simple_sim() requires Poisson Lambda parameter for controls to be numeric.") if (control_parms[1] <= 0) stop("simple_sim() requires Poisson Lambda parameter for controls to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("simple_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/PoissonErrorChecks.R
#' Generating function for Weibull Data. #' #' \code{genweibulldata()} function used mainly internally by #' \code{weibulltrialsimulator()} and \code{weibulltrialsimulatornohist()} functions #' to generate data for a two-arm clinical trial, experimental and control groups. #' Can be used to generate random trial data. #' #' @param sample_size Number of subjects per arm. #' @param scale1 Scale parameter used in call to \code{rweibull()}. #' Used only in control arm. #' @param hazard_ratio Desired Hazard Ratio between experimental and control groups. #' @param common_shape Shape parameter used in call to \code{rweibull()}. #' Used in both arms. #' @param censor_value Value at which time-to-event data are right censored. #' #' @return \code{genweibulldata()} returns a data frame with columns: 'id', 'treatment', #' 'event_time', and 'status'. #' #' @examples #' SampleHistData <- genweibulldata(sample_size=60, scale1=2.82487, #' hazard_ratio=0.6, common_shape=3, #' censor_value=3) #' SampleHistData #' @export genweibulldata <- function(sample_size, scale1, hazard_ratio, common_shape, censor_value) { # --------------------------------------------------------------- # # The function genweibulldata simulates a balanced clinical trial # with 'sample_size' subjects per arm using a weibull distribution. # 'scale1' is the weibull scale parameter, and 'common_shape' is the # weibull common shape parameter for both arms, where scale and # shape parameters are defined according to the rweibull() function # in R. 'censor_value' is the value when right censoring occurs. As # of 9/5/2016, genweibulldata only generates data with right # censoring. Random right censoring is not incorporated. # 'hazard_ratio is the ratio of group hazards (experimental group # over control group). # # In the code below time1, scale1, test1, status1, etc. are data # for the control goup. # In the code below time2, scale2, test2, status2, etc. are data # for the experimental group. # --------------------------------------------------------------- # #Define experimental group scale parameter given control group # scale parameter, commom shape parameter in both groups, and # the user specified hazard ratio. scale2 <- exp(log(scale1) - (1/common_shape) * log(hazard_ratio)) # Create event times for both groups time1 <- stats::rweibull(sample_size, shape = common_shape, scale = scale1) time2 <- stats::rweibull(sample_size, shape = common_shape, scale = scale2) # Create variables needed for simulation, if censor_value is specified. if (!is.null(censor_value) == TRUE) { test1 <- (time1 > censor_value) #Identify which times need right censoring. test2 <- (time2 > censor_value) status1 <- rep(1, sample_size) #Initialize the Status variable. status2 <- rep(1, sample_size) #For all observations that need to be right censored, set the time # value to the right censor value and set the status value to 0 # (indicating right censoring). Status=1 implies observed event. # Status=0 implies right censored event. time1[test1] <- censor_value time2[test2] <- censor_value status1[test1] <- 0 status2[test2] <- 0 } #Create status variable if censor_value is not specified (in such a case # status = 1 for all observeations.) if (is.null(censor_value) == TRUE) { status1 <- rep(1, sample_size) status2 <- rep(1, sample_size) } #Take all data created above and put into a data frame that contains # the required variables. subjid <- seq(from = 1, to = 2 * sample_size) trt <- c(rep(0, sample_size), rep(1, sample_size)) time <- c(time1, time2) status <- c(status1, status2) gendata <- data.frame(subjid, trt, time, status) colnames(gendata) <- c("id", "treatment", "event_time", "status") return(gendata) } #' Log-likelihood function for two-arm trial with historical data using Weibull distribution. #' #' \code{weibullloglike()} function only used internally by #' \code{weibulltrialsimulator()} function to estimate Weibull model parameters #' when clinical trial involves experimental and control groups as well as historical #' control data. #' #' The Weibull log-likelihood is calculated by using \code{dweibull()}. The following #' derivation was used to reparametrize the model parameters so that \code{dweibull()} #' could be used in the log-likelihood function and still estimate the hazard ratio as a #' parameter. #' #' If we let \eqn{scale = exp(-beta0/shape - beta1*treatment/shape)}, then that for the control #' group: \eqn{scale0 = exp(-beta0/shape)}. Similarly, for the experimental group #' \eqn{scale1 = exp(-beta0/shape - beta1/shape)}. #' #' Now for the Weibull distribution \deqn{hazard(t) = (shape)*(scale^(-shape))*(t^(shape-1))} #' From this equation, we can derive the Weibull hazard ratio, HR, (experimental over control) as a #' function of \eqn{scale0}, \eqn{scale1}, and the shape parameter \eqn{HR = (scale0/scale1)^shape}. #' #' Substituting for \eqn{scale0} and eqn{scale1} using functions of \eqn{beta0}, \eqn{beta1}, and #' \eqn{shape}, we can express the hazard ratio in terms of \eqn{beta0} and \eqn{beta1}. When #' we do this we have \deqn{HR = (exp(-beta0/shape)/exp(-beta0/shape - beta1/shape))^shape} #' After reducing terms we have a simply formula for the hazard ratio, #' \eqn{HR = (exp(beta1/shape))^shape}, which reduces further to \eqn{exp(beta1)}. #' #' Therefore, \eqn{beta1} is the log hazard ratio of experimental over control. Similarly #' \eqn{log(scale0) = -beta0/shape} so the nuisance parameter \eqn{beta0} is equal to #' \eqn{(-shape)log(scale0)}. #' #' \code{weibullloglike()} should not be called directly by user. #' #' @param params Three element vector of Weibull parameters. The third element is #' the shape parameter used in \code{dweibull()}. The first and second elements #' are the intercept (beta0), and treatment effect (beta1), parameters as defined in #' details section. The beta1 parameter is the log hazard ratio. #' @param randdata Dataset of randomly generated trial data. Randomized trial datasets #' must have 4 columns: id, treatment, event_time, and status. The value of treatment #' must be 0 (control) or 1 (experimental). The values of event_time must be positive. #' The values of status must be 0 (right censored event) or 1 (observed event). #' @param histdata Dataset of historical control data. Historical datasets must have 4 columns: #' id, treatment, event_time, and status. The value of treatment should be 0. The #' values of event_time must be positive. The values of status must be 0 (right #' censored event) or 1 (observed event). #' @param a0 Power prior parameter where 0 implies historical control data is ignored and 1 implies #' all information in historical control data is used. A value between 0 and 1 partially includes #' the historical control data. #' #' @return \code{weibullloglike()} returns a value of the loglikelihood function #' given a set of Weibull parameters, randomly generated trial data, and observed #' historical control data. #' #' @examples #' #None #' @keywords internal #' @noRd weibullloglike <- function(params, randdata, histdata, a0) { # --------------------------------------------------------------- # # This function calculates the Weibull log-likelihood given # a vector of parameter values, a dataset of randomized trial # data (two arms, no covariates beyond treatment), and a dataset # of historical control data. # The weibull shape parameter is common in both randomized groups # and the historical control group. The scale parameter is # assumed to be the same in both control groups. The scale # parameter for the randomized experimental group is a function # of the control scale and the treatment effect. The parameters # are beta0, beta1, and v. v is the common shape parameter. # beta0 and beta1 are regression parameters that are linked to # the Weibull scale parameter via the exp() function. # beta1 is the log hazard ratio (experimental group over control # group), while beta0 = -v*log(scale0). # Note, scale0 is the scale parameter for controls. # --------------------------------------------------------------- # # Get params beta0 <- params[1] beta1 <- params[2] v <- params[3] # Calculate the scale parameter vector for all randomized observations. b_i <- exp((-1 * beta0/v) + (-1 * beta1/v) * randdata$treatment) # Calculate the log-likelihood values for all randomized observations. ll_r <- randdata$status * stats::dweibull(randdata$event_time, shape = v, scale = b_i, log = TRUE) + (1 - randdata$status) * stats::pweibull(randdata$event_time, shape = v, scale = b_i, log.p = TRUE, lower.tail = FALSE) # Calculate the scale parameter vector for all historical controls. All values in this vector are the same. # Note that bh_i is the same as the randomized control scale parameter for randomized observations. bh_i <- exp(-1 * beta0/v) # Calculate the log-likelihood values for all historical control observations. ll_h <- histdata$status * stats::dweibull(histdata$event_time, shape = v, scale = bh_i, log = TRUE) + (1 - histdata$status) * stats::pweibull(histdata$event_time, shape = v, scale = bh_i, log.p = TRUE, lower.tail = FALSE) # Calculate the overall log-likelihood by adding the randomized log-likelihood to the historical control # log-likelihood by a0, where a0 is the power prior parameter. This a0 value is defined by the # user and not estimated via object function optimization. ll <- sum(ll_r) + a0 * sum(ll_h) # Return the sum of all individual elements to the negative log-likelihood return(-ll) } #' Log-likelihood function for two-arm trial with no historical data using Weibull distribution. #' #' \code{weibullloglikenohist()} function only used internally by #' \code{weibulltrialsimulatornohist()} function to estimate Weibull model parameters #' when clinical trial involves experimental and control groups but no historical control #' data. #' #' The Weibull log-likelihood is calculated by using \code{dweibull()}. The following #' derivation was used to reparametrize the model parameters so that \code{dweibull()} #' could be used in the log-likelihood function and still estimate the hazard ratio as a #' parameter. #' #' If we let \eqn{scale = exp(-beta0/shape - beta1*treatment/shape)}, then that for the control #' group: \eqn{scale0 = exp(-beta0/shape)}. Similarly, for the experimental group #' \eqn{scale1 = exp(-beta0/shape - beta1/shape)}. #' #' Now for the Weibull distribution \deqn{hazard(t) = (shape)*(scale^(-shape))*(t^(shape-1))} #' From this equation, we can derive the Weibull hazard ratio, HR, (experimental over control) as a #' function of \eqn{scale0}, \eqn{scale1}, and the shape parameter \eqn{HR = (scale0/scale1)^shape}. #' #' Substituting for \eqn{scale0} and eqn{scale1} using functions of \eqn{beta0}, \eqn{beta1}, and #' \eqn{shape}, we can express the hazard ratio in terms of \eqn{beta0} and \eqn{beta1}. When #' we do this we have \deqn{HR = (exp(-beta0/shape)/exp(-beta0/shape - beta1/shape))^shape} #' After reducing terms we have a simply formula for the hazard ratio, #' \eqn{HR = (exp(beta1/shape))^shape}, which reduces further to \eqn{exp(beta1)}. #' #' Therefore, \eqn{beta1} is the log hazard ratio of experimental over control. Similarly #' \eqn{log(scale0) = -beta0/shape} so the nuisance parameter \eqn{beta0} is equal to #' \eqn{(-shape)log(scale0)}. #' #' \code{weibullloglike()} should not be called directly by user. #' #' @param params Three element vector of Weibull parameters. The third element is #' the shape parameter used in \code{dweibull()}. The first and second elements #' are the intercept (beta0), and treatment effect (beta1), parameters as defined in #' details section. The beta1 parameter is the log hazard ratio. #' @param randdata Dataset of randomly generated trial data. Randomized trial datasets #' must have 4 columns: id, treatment, event_time, and status. The value of treatment #' must be 0 (control) or 1 (experimental). The values of event_time must be positive. #' The values of status must be 0 (right censored event) or 1 (observed event). #' #' @return \code{weibullloglikenohist()} returns a value of the loglikelihood function #' given a set of Weibull parameters and randomly generated trial data. #' #' @examples #' #None #' @keywords internal #' @noRd weibullloglikenohist <- function(params, randdata) { # --------------------------------------------------------------- # # This function calculates the Weibull log-likelihood given # a vector of parameter values, and a dataset of randomized trial # data (two arms, no covariates beyond treatment). Historical # data is not utilized in this log-likelihood function. # The weibull shape parameter is common in both randomized groups. # The scale parameter for the randomized experimental group is a # function of the control scale and the treatment effect. # The parameters are beta0, beta1, and v. v is the common shape # parameter. beta0 and beta1 are regression parameters that are # linked to the Weibull scale parameter via the exp() function. # beta1 is the log hazard ratio (experimental group over control # group), while beta0 = -v*log(scale0). # Note, scale0 is the scale parameter for controls. # --------------------------------------------------------------- # # Get params beta0 <- params[1] beta1 <- params[2] v <- params[3] # Calculate the scale parameter vector for all randomized observations. b_i <- exp((-1 * beta0/v) + (-1 * beta1/v) * randdata$treatment) # Calculate the log-likelihood values for all randomized observations. ll_r <- randdata$status * stats::dweibull(randdata$event_time, shape = v, scale = b_i, log = TRUE) + (1 - randdata$status) * stats::pweibull(randdata$event_time, shape = v, scale = b_i, log.p = TRUE, lower.tail = FALSE) # Return the sum of all individual elements to the negative log-likelihood return(sum(-ll_r)) } #' Simulate a single randomized trial using a Weibull outcome and information from #' historical controls. #' #' \code{weibulltrialsimulator()} function only used internally by #' \code{weibull_sim()} function to run a single trial simulation involving historical #' control data and a Weibull outcome. #' #' The simulation of a trial with a Weibull outcome involving historical control data returns #' an estimate of the hazard ratio as well as an estimate of the log hazard ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{weibulltrialsimulator()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param histdata Dataset of historical data. Historical datasets must have 4 columns: #' id, treatment, event_time, and status. The value of treatment should be 0. The #' values of event_time must be positive. The values of status must be 0 (right #' censored event) or 1 (observed event). #' @param scale1_val Randomized control arm scale parameter used in call to \code{rweibull()}. #' @param hazard_ratio_val Desired hazard ratio between randomized experimental and control arms. #' @param common_shape_val Randomized shape parameter used in call to \code{rweibull()}. #' Used in both randomized arms. #' @param censor_value Value at which time-to-event data are right censored. #' @param a0_val A power prior parameter ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{weibulltrialsimulator()} returns a vector of simulation results. The #' first element is an estimated hazard ratio, the second element is the estimated #' variance of the log hazard ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd weibulltrialsimulator <- function(sample_size_val, histdata, scale1_val, hazard_ratio_val, common_shape_val, censor_value, a0_val, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate weibull trial data given the user defined trial characteristics. sampleranddata <- genweibulldata(sample_size = sample_size_val, scale1 = scale1_val, hazard_ratio = hazard_ratio_val, common_shape = common_shape_val, censor_value = censor_value) # Make sure the trial data has at least one not right censored observation. if (sum(sampleranddata$event_time == censor_value) == dim(sampleranddata)[1]) { stop("Simulated trial data must have at least one observation that is not right censored.") } # Generate initial values for your call to optim() initializemodel <- survival::survreg(survival::Surv(event_time, status) ~ treatment, dist = "weibull", data = sampleranddata) initialbeta0 <- -1 * initializemodel$coefficients[1]/initializemodel$scale initialbeta1 <- -1 * initializemodel$coefficients[2]/initializemodel$scale initialv <- 1/initializemodel$scale # Generate the Bayesian CLT based parameter estimates needed for inference on hazard ratio. fitmod <- stats::optim(c(initialbeta0, initialbeta1, initialv), weibullloglike, randdata = sampleranddata, histdata = histdata, a0 = a0_val, method = "Nelder-Mead", hessian = TRUE) #Extract model parameters and statistics modparm <- fitmod$par covarmat <- solve(fitmod$hessian) weibullloghazard_ratio <- modparm[2] weibullhazard_ratio <- exp(weibullloghazard_ratio) lower_weibullhazard_ratio <- exp(weibullloghazard_ratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper_weibullhazard_ratio <- exp(weibullloghazard_ratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_weibullhazard_ratio > 1) | (upper_weibullhazard_ratio < 1)), 1, 0) output <- c(weibullhazard_ratio, covarmat[2, 2], reject) #Return the hazard ratio, the estimated variance of the log hazard ratio, and the trial decision. names(output) <- c("hazard_ratio", "loghazard_ratio_var", "reject") return(output) } #' Simulate a single randomized trial using a Weibull outcome but not including any information from #' historical controls. #' #' \code{weibulltrialsimulatornohist()} function only used internally by #' \code{simple_weibull_sim()} function to run a single trial simulation involving #' a Weibull outcome but no historical control data. #' #' The simulation of a trial with a Weibull outcome involving no historical control data returns #' an estimate of the hazard ratio as well as an estimate of the log hazard ratio variance. #' Finally the simulation returns an indication of whether or not the simulated trial led to #' a rejection of the null hypothesis (1) or not (0). #' #' \code{weibulltrialsimulatornohist()} should not be called directly by user. #' #' @param sample_size_val Number of subjects per arm. #' @param scale1_val Scale parameter used in call to \code{rweibull()}. #' Used only in randomized control arm. #' @param hazard_ratio_val Desired hazard ratio between experimental and control arms. #' @param common_shape_val Shape parameter used in call to \code{rweibull()}. #' Used in both randomized arms. #' @param censor_value Value at which time-to-event data are right censored. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' #' @return \code{weibulltrialsimulatornohist()} returns a vector of simulation results. The #' first element is an estimated hazard ratio, the second element is the estimated #' variance of the log hazard ratio, and the third element is a 0/1 variable indicator #' whether or not the trial rejected the null hypothesis (1) or failed to reject #' the null hypothesis (0). #' #' @examples #' #None #' @keywords internal #' @noRd weibulltrialsimulatornohist <- function(sample_size_val, scale1_val, hazard_ratio_val, common_shape_val, censor_value, alpha) { # --------------------------------------------------------------- # # This function simulates a two-arm Bayesian trial where # historical data is not utilized in the parameter estimation. # --------------------------------------------------------------- # # First, Generate weibull trial data given the user defined trial characteristics. sampleranddata <- genweibulldata(sample_size = sample_size_val, scale1 = scale1_val, hazard_ratio = hazard_ratio_val, common_shape = common_shape_val, censor_value = censor_value) # Make sure the trial data has at least one not right censored observation. if (sum(sampleranddata$event_time == censor_value) == dim(sampleranddata)[1]) { stop("Simulated trial data must have at least one observation that is not right censored.") } #Unlike Bernoulli, Poisson, Gaussian, and Lognormal, I cannot use survreg #directly, because survreg does not use a parameterization where the hazard #ratio is a model parameter. # Generate initial values for your call to optim() initializemodel <- survival::survreg(survival::Surv(event_time, status) ~ treatment, dist = "weibull", data = sampleranddata) initialbeta0 <- -1 * initializemodel$coefficients[1]/initializemodel$scale initialbeta1 <- -1 * initializemodel$coefficients[2]/initializemodel$scale initialv <- 1/initializemodel$scale # Generate the Bayesian CLT based parameter estimates needed for inference on hazard ratio. fitmod <- stats::optim(c(initialbeta0, initialbeta1, initialv), weibullloglikenohist, randdata = sampleranddata, method = "Nelder-Mead", hessian = TRUE) #Extract model parameters and statistics modparm <- fitmod$par covarmat <- solve(fitmod$hessian) weibullloghazard_ratio <- modparm[2] weibullhazard_ratio <- exp(weibullloghazard_ratio) lower_weibullhazard_ratio <- exp(weibullloghazard_ratio - stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) upper_weibullhazard_ratio <- exp(weibullloghazard_ratio + stats::qnorm(1 - alpha/2) * sqrt(covarmat[2, 2])) #Make a decision about the simulated trial, reject or fail to reject null hypothesis. reject <- ifelse(((lower_weibullhazard_ratio > 1) | (upper_weibullhazard_ratio < 1)), 1, 0) output <- c(weibullhazard_ratio, covarmat[2, 2], reject) #Return the hazard ratio, the estimated variance of the log hazard ratio, and the trial decision. names(output) <- c("hazard_ratio", "loghazard_ratio_var", "reject") return(output) } #' Repeated Two Arm Bayesian Clinical Trial Simulation with Historical Data and #' Weibull Outcome. #' #' \code{weibull_sim()} function only used internally by \code{historic_sim()} #' function to run a set of trial simulations involving historical #' control data and a Weibull outcome. User defined simulation parameters are #' used to generate a set of trial scenarios. Each scenario is simulated multiple #' times and then means are taken to calculate estimates of power, hazard ratios, #' and other user requested study summary statistics like variance of hazard #' ratio, bias (on hazard ratio scale), and mse (on hazard ratio scale). #' The number of repeated simulations is defined by the user. #' #' \code{weibull_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' a0_val, subj_per_arm, effect_vals, and rand_control_diff. As the number #' of trials increases, the precision of the estimate will increase. Default is #' 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param a0_vals A vector of power prior parameters ranging from 0 to 1, where 0 #' implies no information from historical data should be used, 1 implies all of #' the information from historical data should be used. A value between 0 and 1 #' implies that a proportion of the information from historical data will be used. #' @param effect_vals A vector of hazard ratios between randomized arms (randomized #' experimental over control), all of which must be positive. #' @param rand_control_diff A vector of hazard ratios (randomized controls over #' historical controls) representing differences between historical and randomized #' controls. #' @param hist_control_data A dataset of historical data. Default is \code{NULL}. #' Historical datasets must have 4 columns: id, treatment, event_time, and #' status. The value of treatment should be 0. The values of event_time must #' be positive. The values of status must be 0 (right censored event) or #' 1 (observed event). #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Default is \code{NULL}, where #' \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{weibull_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd weibull_sim <- function(trial_reps=100, subj_per_arm, a0_vals, effect_vals, rand_control_diff, hist_control_data, censor_value, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, hazard ratio estimate, and if requested by user: # variance of hazard ratio, bias , and mse. Using a Weibull oucome # and incorporating data from historical controls. # --------------------------------------------------------------- # # Need to take the historical data and generate distributional parameter estimates histdata = hist_control_data hist_model <- survival::survreg(survival::Surv(event_time, status) ~ 1, dist = "weibull", data = histdata) bparm_histc <- exp(hist_model$coefficients) aparm_histc <- 1/hist_model$scale # Initialize arrays to hold power, var, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. for (diffs in 1:length(rand_control_diff)) { # Need to adjust the randomized control scale parameter given the historical control scale parameters and the hazard # ratios given in rand_control_diff bparm_randc <- exp(log(bparm_histc) - (1/aparm_histc) * log(rand_control_diff[diffs])) for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_vals, and subj_per_arm, simulate the trial #trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #hazard ratio scale and take the mean of all differences between estimated hazard ratios and the #hazard ratio. For mse, calculate the mean of squared differences between the #estimated hazard ratios and the true hazard ratio value. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal to both arms collect[k, ] <- weibulltrialsimulator(sample_size_val = subj_per_arm[sizes], histdata, scale1_val = bparm_randc, hazard_ratio_val = effect_vals[effvals], common_shape_val = aparm_histc, censor_value = censor_value, a0_val = a0_vals[a0vals], alpha = alpha) } #collect is a matrix of data, hazard ratio in 1st column, log hazard ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("hazard_ratio", "log_hazard_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and hazard # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 576 through 879 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = a0_vals, effect_vals = effect_vals, rand_control_diff = rand_control_diff, objtype = 'historic') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) } #' Two Arm Bayesian Clinical Trial Simulation with no Historical Data and #' Weibull Outcome. #' #' \code{simple_weibull_sim()} function only used internally by #' \code{simple_sim()} function to run a set of trial simulations involving no #' historical control data and a Weibull outcome. User defined simulation #' parameters are used to generate a set of trial scenarios. Each scenario is #' simulated multiple times and then means are taken to calculate estimates #' of power, hazard ratios, and other user requested study summary statistics #' like variance of hazard ratio, bias (on hazard ratio scale), and #' mse (on hazard ratio scale). The number of repeated simulations is #' defined by the user. #' #' \code{simple_weibull_sim()} should not be called directly by user. #' #' @param trial_reps Number of trials to replicate within each combination of #' subj_per_arm and effect_vals. As the number of trials increases, the #' precision of the estimate will increase. Default is 100. #' @param subj_per_arm A vector of sample sizes, all of which must be positive #' integers. #' @param effect_vals A vector of hazard ratios (randomized experimental over control), #' all of which must be positive. #' @param scale1_value scale parameter value for randomized controls. Used in call #' to \code{rweibull()}. #' @param common_shape_value shape parameter value assumed common in both arms. #' Used in call to \code{rweibull()}. #' @param censor_value A single value at which right censoring occurs when #' simulating randomized subject outcomes. Default is \code{NULL}, where #' \code{NULL} implies no right censoring. #' @param alpha A number ranging between 0 and 1 that defines the acceptable Type 1 #' error rate. Default is 0.05. #' @param get_var A TRUE/FALSE indicator of whether an array of variance #' estimates will be returned. Default is \code{FALSE}. #' @param get_bias A TRUE/FALSE indicator of whether an array of bias #' estimates will be returned. Default is \code{FALSE}. #' @param get_mse A TRUE/FALSE indicator of whether an array of MSE #' estimates will be returned. Default is \code{FALSE}. #' @param quietly A TRUE/FALSE indicator of whether notes are printed #' to output about simulation progress as the simulation runs. If #' running interactively in RStudio or running in the R console, #' \code{quietly} can be set to FALSE. If running in a Notebook or #' knitr document, \code{quietly} needs to be set to TRUE. Otherwise #' each note will be printed on a separate line and it will take up #' a lot of output space. Default is \code{TRUE}. #' #' @return \code{simple_weibull_sim()} returns an S3 object of class bayes_ctd_array. #' #' @examples #' #None #' @keywords internal #' @noRd simple_weibull_sim <- function(trial_reps=100, subj_per_arm, effect_vals, scale1_value, common_shape_value, censor_value, alpha=0.05, get_var=FALSE, get_bias=FALSE, get_mse=FALSE, quietly=TRUE) { # --------------------------------------------------------------- # # For a set of user specified scenarios (defined by combinations # of user specified parameters), simulate "trial_reps" trials # and estimate power, hazard ratio estimate, and if requested by user: # variance of hazard ratio, bias, and mse. Using a Weibull oucome # but historical control data is not used. # --------------------------------------------------------------- # #The rand_control_diff and a0_val dimensions will be set to 1, and the value for # rand_control_diff will be 1 and a0_val will be set to 0. All summaries will # be set up to ignore these dimensions for simple (no historical data) simulations. rand_control_diff <- 1 a0_vals <- 0 # Initialize arrays to hold power, var, mse, and bias estimate results as requested. len_val <- length(rand_control_diff) * length(effect_vals) * length(a0_vals) * length(subj_per_arm) power_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) est_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) if (get_mse == TRUE) { mse_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_bias == TRUE) { bias_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } if (get_var == TRUE) { var_results <- array(rep(0, len_val), c(length(subj_per_arm), length(a0_vals), length(effect_vals), length(rand_control_diff))) } # Cycle through the passed values in rand_control_diff, effect_vals, a0_val, and subj_per_arm to generate the # requested trial characteristics. Note that rand_control_diff is set to 1 and a0_val is set to 0. for (diffs in 1:length(rand_control_diff)) { for (effvals in 1:length(effect_vals)) { for (a0vals in 1:length(a0_vals)) { for (sizes in 1:length(subj_per_arm)) { if (!quietly){ cat("\r", c(subj_per_arm[sizes], a0_vals[a0vals], effect_vals[effvals], rand_control_diff[diffs])) } # For each combination of rand_control_diff, effect_vals, a0_val, and subj_per_arm, simulate the trial # trial_reps times and then calculate the mean reject rate to estimate power. For bias, work on the #hazard ratio scale and take the mean of all differences between estimated hazard ratios and the #true hazard ratio. For mse, calculate the mean of squared differences between the estimated #hazard ratios and the true hazard ratio value. Note that rand_control_diff is set to 1 and #a0_val is set to 0. collect <- matrix(rep(0, 3 * trial_reps), ncol = 3) for (k in 1:trial_reps) { # sample_size_val will be equal in both arms collect[k, ] <- weibulltrialsimulatornohist(sample_size_val = subj_per_arm[sizes], scale1_val = scale1_value, hazard_ratio_val = effect_vals[effvals], common_shape_val = common_shape_value, censor_value = censor_value, alpha = alpha) } #collect is a matrix of data, hazard ratio in 1st column, log hazard ratio variance # in second column, and a vector of 0/1s in third column indicating whether or # not trial represented by row led to a rejection of null hypothesis (1) or not (0). # Note that collect gets rewritten for each scenario. colnames(collect) <- c("hazard_ratio", "log_hazard_ratio_var", "reject") #Start calculating means for each scenarios and placing the means in the proper # array. Every simulation will contain an array of power results and hazard # ratio estimates. power_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 3]) est_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1]) if (get_bias == TRUE) { bias_results[sizes, a0vals, effvals, diffs] <- mean(collect[, 1] - effect_vals[effvals]) } if (get_var == TRUE) { var_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1]*sqrt(collect[, 2]))^2) } if (get_mse == TRUE) { mse_results[sizes, a0vals, effvals, diffs] <- mean((collect[, 1] - effect_vals[effvals])^2) } if (!quietly){ cat("\r", " ") } } } } } cat("\n") #Lines 1011 through 1314 simply apply names to the dimensions of array created by the # simulation depending on values get_bias, get_var, and get_mse. if (get_bias == FALSE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results) names(output) <- c("power", "est") } if (get_bias == FALSE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, mse_results) names(output) <- c("power", "est", "mse") } if (get_bias == TRUE & get_var == FALSE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results) names(output) <- c("power", "est", "bias") } if (get_bias == TRUE & get_var == FALSE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, bias_results, mse_results) names(output) <- c("power", "est", "bias", "mse") } if (get_bias == FALSE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results) names(output) <- c("power", "est", "var") } if (get_bias == FALSE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, mse_results) names(output) <- c("power", "est", "var", "mse") } if (get_bias == TRUE & get_var == TRUE & get_mse == FALSE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results) names(output) <- c("power", "est", "var", "bias") } if (get_bias == TRUE & get_var == TRUE & get_mse == TRUE) { if (length(subj_per_arm) == 1) { dimnames(power_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(power_results)[[1]] <- as.character(subj_per_arm) } dimnames(power_results)[[2]] <- as.character(a0_vals) dimnames(power_results)[[3]] <- as.character(effect_vals) dimnames(power_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(est_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(est_results)[[1]] <- as.character(subj_per_arm) } dimnames(est_results)[[2]] <- as.character(a0_vals) dimnames(est_results)[[3]] <- as.character(effect_vals) dimnames(est_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(bias_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(bias_results)[[1]] <- as.character(subj_per_arm) } dimnames(bias_results)[[2]] <- as.character(a0_vals) dimnames(bias_results)[[3]] <- as.character(effect_vals) dimnames(bias_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(var_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(var_results)[[1]] <- as.character(subj_per_arm) } dimnames(var_results)[[2]] <- as.character(a0_vals) dimnames(var_results)[[3]] <- as.character(effect_vals) dimnames(var_results)[[4]] <- as.character(rand_control_diff) if (length(subj_per_arm) == 1) { dimnames(mse_results)[[1]] <- list(as.character(subj_per_arm)) } if (length(subj_per_arm) > 1) { dimnames(mse_results)[[1]] <- as.character(subj_per_arm) } dimnames(mse_results)[[2]] <- as.character(a0_vals) dimnames(mse_results)[[3]] <- as.character(effect_vals) dimnames(mse_results)[[4]] <- as.character(rand_control_diff) output <- list(power_results, est_results, var_results, bias_results, mse_results) names(output) <- c("power", "est", "var", "bias", "mse") } #Create an list of results and apply the bayes_ctd_array class to the list, then # return the output object. class_out <- list(data = output, subj_per_arm = subj_per_arm, a0_vals = 0, effect_vals = effect_vals, rand_control_diff = 1, objtype = 'simple') class(class_out) <- append("bayes_ctd_array", class(class_out)) return(class_out) }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/WeibullCode.R
#' Checks for Errors when Outcome is Weibull. #' #' \code{weibull_error_checks()} function used only used internally by #' \code{historic_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{historic_sim()}. #' @param hist_control_data See help page for \code{historic_sim()}. #' @param rand_control_diff See help page for \code{historic_sim()}. #' @param censor_value See help page for \code{historic_sim()}. #' @param alpha See help page for \code{historic_sim()}. #' #' @return \code{weibull_error_checks()} returns messages when #' \code{historic_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd weibull_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, censor_value, alpha) { hist_chk <- class(hist_control_data) rcp_chk <- is.null(rand_control_diff) # Need to check that Effect_vals is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("historic_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Weibull, historic_sim() requires effect_vals to represent Hazard Ratios which must be positive numbers") } # Need to check that hist_control_data is a data frame and has the correct columns. if (hist_chk == "data.frame") { colnamevals <- colnames(hist_control_data) colnamechk <- (colnamevals == c("id", "treatment", "event_time", "status")) if (sum(colnamechk) != 4) { stop("historic_sim() requires hist_control_data to have columns: id, treatment, event_time, and status.") } if (sum(colnamechk) == 4) { if (!is.numeric(hist_control_data$event_time)) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } if (is.numeric(hist_control_data$event_time)) { if (min(hist_control_data$event_time) <= 0) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } } if (!is.numeric(hist_control_data$treatment)) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } if (is.numeric(hist_control_data$treatment)) { trt_levels <- names(table(hist_control_data$treatment)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } } if (!is.numeric(hist_control_data$status)) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } if (is.numeric(hist_control_data$status)) { trt_levels <- names(table(hist_control_data$status)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } } } } # If not NULL, need to check that rand_control_diff is positive. if (rcp_chk == FALSE) { for (rand_cp in rand_control_diff) { if (!is.numeric(rand_cp)) stop("historic_sim() requires rand_control_diff to be numeric.") if (rand_cp <= 0) stop("historic_sim() requires rand_control_diff to be Hazard Ratios, so they must be positive.") } } # Need to check that censor_value is NULL or a non-negative number if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("historic_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("historic_sim() requires censor_value to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("historic_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } } #' Checks for Errors when Outcome is Weibull. #' #' \code{weibull_error_checks_simple()} function used only used internally by #' \code{simple_sim()} function to check for proper input. Not to be called #' directly by user. #' #' @param effect_vals See help page for \code{simple_sim()}. #' @param control_parms See help page for \code{simple_sim()}. #' @param censor_value See help page for \code{simple_sim()}. #' @param alpha See help page for \code{simple_sim()}. #' #' @return \code{weibull_error_checks_simple()} returns messages when #' \code{simple_sim()} function inputs are incorrectly specified. #' Not to be called directly by user. #' #' @examples #' #None #' @keywords internal #' @noRd weibull_error_checks_simple <- function(effect_vals, control_parms, censor_value, alpha) { chk_parm_lgth <- length(control_parms) # Need to check that effect_vals is a list of positive numbers for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("simple_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For Weibull, simple_sim() requires effect_vals to represent Hazard Ratios which must be positive numbers") } if (chk_parm_lgth != 2) { stop("simple_sim() requires two elements in control_parms, first=Weibull scale parameter for rweibull(), second= Weibull shape parameter for rweibull()") } if (chk_parm_lgth == 2) { if (!is.numeric(control_parms[1])) stop("simple_sim() requires Weibull scale parameter for controls to be numeric.") if (!is.numeric(control_parms[2])) stop("simple_sim() requires Weibull shape parameter for controls to be numeric.") if (control_parms[1] <= 0) stop("simple_sim() requires Weibull scale parameter for controls to be positive.") if (control_parms[2] <= 0) stop("simple_sim() requires Weibull shape parameter for controls to be positive.") } # Need to check that censor_value is NULL or a non-negative number if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("simple_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("simple_sim() requires censor_value to be positive.") } # Need to check that alpha ranges between 0 and 1 if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("simple_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } }
/scratch/gouwar.j/cran-all/cranData/BayesCTDesign/R/WeibullErrorChecks.R
#' @title B1 Artificial Dataset #' @description A \code{2}-dimensional dataset from Wiroonsri and Preedasawakul (2024) generated from \code{1} Gaussian and \code{1} Uniform distributions labeled as \code{1-2}. #' @format A data frame with 5500 data points and 3 variables #' \describe{ #' \item{\code{x}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{y}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{label}}{Categorical labels 1,2} #'} #' @references {N. Wiroonsri, O. Preedasawakul, A Bayesian cluster validity index, arXiv:2402.02162, 2024} #' @author {Nathakhun Wiroonsri and Onthada Preedasawakul} #' @seealso {\link{B2_data}, \link{B3_data}, \link{B_WP.IDX}, \link{B_Wvalid}, \link{B_XB.IDX}} "B1_data"
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B1_data.R
#' @title B2 Artificial Dataset #' @description A \code{2}-dimensional dataset from Wiroonsri and Preedasawakul (2024) generated from \code{5} different Gaussian distributions labeled as \code{1-5}. #' @format A data frame with 850 data points and 3 variables #' \describe{ #' \item{\code{x}}{Numeric values generated from Gaussian distributions} #' \item{\code{y}}{Numeric values generated from Gaussian distributions} #' \item{\code{label}}{Categorical labels 1,2,3,4,5} #'} #' @references {N. Wiroonsri, O. Preedasawakul, A Bayesian cluster validity index, arXiv:2402.02162, 2024} #' @author {Nathakhun Wiroonsri and Onthada Preedasawakul} #' @seealso {\link{B1_data}, \link{B3_data}, \link{B_WP.IDX}, \link{B_Wvalid}, \link{B_XB.IDX}} "B2_data"
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B2_data.R
#' @title B3 Artificial Dataset #' @description A \code{2}-dimensional dataset from Wiroonsri and Preedasawakul (2024) generated from \code{5} different Gaussian distributions labeled as \code{1-5}. #' @format A data frame with 2300 data points and 3 variables #' \describe{ #' \item{\code{x}}{Numeric values generated from Gaussian distributions} #' \item{\code{y}}{Numeric values generated from Gaussian distributions} #' \item{\code{label}}{Categorical labels 1,2,3,4,5} #'} #' @references {N. Wiroonsri, O. Preedasawakul, A Bayesian cluster validity index, arXiv:2402.02162, 2024} #' @author {Nathakhun Wiroonsri and Onthada Preedasawakul} #' @seealso {\link{B2_data}, \link{B4_data}, \link{B_WP.IDX}, \link{B_Wvalid}, \link{B_XB.IDX}} "B3_data"
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B3_data.R
#' @title B4 Artificial Dataset #' @description A \code{2}-dimensional dataset from Wiroonsri and Preedasawakul (2024) generated from \code{6} different Gaussian distributions labeled as \code{1-6}. #' @format A data frame with 740 data points and 3 variables #' \describe{ #' \item{\code{x}}{Numeric values generated from Gaussian distributions} #' \item{\code{y}}{Numeric values generated from Gaussian distributions} #' \item{\code{label}}{Categorical labels 1,2,3,4,5,6} #'} #' @references {N. Wiroonsri, O. Preedasawakul, A Bayesian cluster validity index, arXiv:2402.02162, 2024} #' @author {Nathakhun Wiroonsri and Onthada Preedasawakul} #' @seealso {\link{B3_data}, \link{B5_data}, \link{B_WP.IDX}, \link{B_Wvalid}, \link{B_XB.IDX}} "B4_data"
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B4_data.R
#' @title B5 Artificial Dataset #' @description A \code{2}-dimensional dataset from Wiroonsri and Preedasawakul (2024) generated from \code{7} different Gaussian and \code{2} Uniform distributions labeled as \code{1-9}. #' @format A data frame with 1820 data points and 3 variables #' \describe{ #' \item{\code{x}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{y}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{label}}{Categorical labels 1,2,3,4,5,6,7,8,9} #'} #' @references {N. Wiroonsri, O. Preedasawakul, A Bayesian cluster validity index, arXiv:2402.02162, 2024} #' @author {Nathakhun Wiroonsri and Onthada Preedasawakul} #' @seealso {\link{B4_data}, \link{B6_data}, \link{B_WP.IDX}, \link{B_Wvalid}, \link{B_XB.IDX}} "B5_data"
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B5_data.R
#' @title B6 Artificial Dataset #' @description A \code{2}-dimensional dataset from Wiroonsri and Preedasawakul (2024) generated from \code{3} different Gaussian and \code{2} Uniform distributions labeled as \code{1-5}. #' @format A data frame with 1000 data points and 3 variables #' \describe{ #' \item{\code{x}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{y}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{label}}{Categorical labels 1,2,3,4,5} #'} #' @references {N. Wiroonsri, O. Preedasawakul, A Bayesian cluster validity index, arXiv:2402.02162, 2024} #' @author {Nathakhun Wiroonsri and Onthada Preedasawakul} #' @seealso {\link{B5_data}, \link{B7_data}, \link{B_WP.IDX}, \link{B_Wvalid}, \link{B_XB.IDX}} "B6_data"
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B6_data.R
#' @title B7 Artificial Dataset #' @description A \code{2}-dimensional dataset from Wiroonsri and Preedasawakul (2024) generated from \code{3} different Gaussian and \code{2} Uniform distributions labeled as \code{1-5}. #' @format A data frame with 800 data points and 3 variables #' \describe{ #' \item{\code{x}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{y}}{Numeric values generated from Gaussian and Uniform distributions} #' \item{\code{label}}{Categorical labels 1,2,3,4,5} #'} #' @references {N. Wiroonsri, O. Preedasawakul, A Bayesian cluster validity index, arXiv:2402.02162, 2024} #' @author {Nathakhun Wiroonsri and Onthada Preedasawakul} #' @seealso {\link{B6_data}, \link{B1_data}, \link{B_WP.IDX}, \link{B_Wvalid}, \link{B_XB.IDX}} "B7_data"
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B7_data.R
B_CCV.IDX <- function(x, kmax, indexlist = "all", method = 'FCM', fzm = 2, iter = 100, nstart = 20, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(indexlist %in% c("all","CCVP", "CCVS"))) stop("Argument 'indexlist' is not in 'all', 'CCVP', 'CCVS'") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector ccvp = vector() ccvs = vector() distance =dist(x,diag = TRUE,upper= TRUE) # FOR CCVP CCVS distc = as.vector(as.matrix(distance)) # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } uut = m%*%t(m) vnew = as.vector(1-(uut/max(uut))) if(sum(indexlist %in% c("all","CCVP"))>=1){ ccvp[k-kmin+1] = cor(distc-mean(distc),vnew-mean(vnew),method = "pearson") #NW } if(sum(indexlist %in% c("all","CCVS"))>=1){ ccvs[k-kmin+1] = cor(distc,vnew,method = "spearman") #NW } } # END CCVP CCVS index # Bayesian part if(any(indexlist %in% "all")){ indexlist = c("CCVP","CCVS") } CCV.list = list() for (idx in seq(length(indexlist))) { CVI.dframe = data.frame("C" = kmin:kmax,"Index" = get(tolower(indexlist[idx]))) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k",paste0(indexlist[idx])) list.re = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) assign(paste0(indexlist[idx],"_list"),list.re) CCV.list[[paste0(indexlist[idx])]] = get(paste0(indexlist[idx],"_list")) } if (sum(indexlist %in% "all")>=1){ return(CCV.list) } else { return(CCV.list[indexlist]) } }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_CCV.IDX.R
B_CH.IDX <- function(x, kmax, method = 'kmeans', nstart = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans","hclust_complete","hclust_average","hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average', 'hclust_single'") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(startsWith(method,"hclust_")){ H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part dm = dim(x) ch = vector() for(k in kmin:kmax){ xnew = matrix(0,dm[1],dm[2]) centroid = matrix(0,k,dm[2]) if(method == "kmeans"){ K.model = kmeans(x,k,nstart =nstart) cluss = K.model$cluster centroid = K.model$centers xnew = centroid[cluss,] } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) for (j in 1:k){ if (is.null(nrow(x[cluss==j,])) | sum(nrow(x[cluss==j,]))==1){ centroid[j,] = as.numeric(x[cluss==j,]) } else { centroid[j,] = colMeans(x[cluss==j,]) } } xnew = centroid[cluss,] } # End check algorithm if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") d.cen = rowSums((x - xnew)^2) num = sapply(1:k, function(i) { ck = x[cluss == i, ] cen.k = centroid[i, ] n.clust_k = nrow(ck) n.clust_k * sum((cen.k - colMeans(x))^2) }) num = as.numeric(num) dem = sapply(1:k, function(i) sum(d.cen[cluss == i])) ch[k-kmin+1] = ((nrow(x) - k) / (k-1)) * (sum(num[!is.na(num)]) / sum(dem)) } # Baye's part CVI.dframe = data.frame("C" = kmin:kmax,"Index" = ch) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","CH") CH.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(CH.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_CH.IDX.R
B_CSL.IDX <- function(x, kmax, method = 'kmeans', nstart = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans","hclust_complete","hclust_average","hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average', 'hclust_single'") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(startsWith(method,"hclust_")){ H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part dm = dim(x) csl = rep(0,kmax-kmin+1) for(k in kmin:kmax){ centroid = matrix(0,k,dm[2]) if(method == "kmeans"){ K.model = kmeans(x,k,nstart =nstart) cluss = K.model$cluster centroid = K.model$centers for(j in 1:k){ dd = as.matrix(dist(x[cluss==j,])) csl[k-kmin+1] = csl[k-kmin+1] + sum(apply(dd,2,max))/sum(cluss==j) } } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) for (j in 1:k){ if (is.null(nrow(x[cluss==j,])) | sum(nrow(x[cluss==j,]))==1){ centroid[j,] = as.numeric(x[cluss==j,]) } else { centroid[j,] = colMeans(x[cluss==j,]) } dd = as.matrix(dist(x[cluss==j,])) csl[k-kmin+1] = csl[k-kmin+1] + sum(apply(dd,2,max))/sum(cluss==j) } } if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") dd2 = as.matrix(dist(centroid)) dd2 = matrix(dd2[dd2 > 0],k-1,k) csl[k-kmin+1] = csl[k-kmin+1]/sum(apply(dd2,2,min)) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = csl) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","CSL") CSL.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(CSL.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_CSL.IDX.R
B_DB.IDX <- function(x, kmax, method = 'kmeans', indexlist = 'all', #c(,"all","DB","DBs") p = 2, q = 2, nstart = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans","hclust_complete","hclust_average","hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average', 'hclust_single'") if(!any(indexlist %in% c("all","DB","DBs"))) stop("Argument 'indexlist' should be 'all', 'DB', 'DBs'") if(!is.numeric(p)) stop("Argument 'p' must be numeric") if(!is.numeric(q)) stop("Argument 'q' must be numeric") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(startsWith(method,"hclust_")){ H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part dm = dim(x) db = vector() dbs = vector() for(k in kmin:kmax){ xnew = matrix(0,dm[1],dm[2]) centroid = matrix(0,k,dm[2]) if(method == "kmeans"){ K.model = kmeans(x,k,nstart =nstart) cluss = K.model$cluster centroid = K.model$centers xnew = centroid[cluss,] } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) for (j in 1:k){ if (is.null(nrow(x[cluss==j,])) | sum(nrow(x[cluss==j,]))==1){ centroid[j,] = as.numeric(x[cluss==j,]) } else { centroid[j,] = colMeans(x[cluss==j,]) } } xnew = centroid[cluss,] } # End check algorithm if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") # Si,q S = vector() #length = k sizecluss = as.vector(table(cluss)) for(i in 1:k){ C = sizecluss[i] if(C>1){ cenI = xnew[cluss ==i,] S[i] = (sum(sqrt(rowSums((x[cluss==i,]-cenI)^2))^q)/C)^(1/q) }else{ S[i] = 0 } } m = as.matrix(dist(centroid,method="minkowski",p=p)) R = matrix(0,k,k) r = vector() rs = vector() wcdd = vector() for (i in 1:k){ C = sizecluss[i] r[i] = max((S[i] + S[-i])/m[i,][m[i,]!=0]) rs[i] = max(S[i] + S[-i])/min(m[i,][m[i,]!=0]) # for SF index wcdd[i] = sum(dist(rbind(centroid[i,],x[cluss==i,]))[1:C])/C } db[k-kmin+1] = mean(r) dbs[k-kmin+1] = mean(rs) } if(any(indexlist %in% "all")){ indexlist = c("DB","DBs") } DB.list = list() for (idx in seq(length(indexlist))) { CVI.dframe = data.frame("C" = kmin:kmax,"Index" = get(tolower(indexlist[idx]))) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k",paste0(indexlist[idx])) list.re = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) assign(paste0(indexlist[idx],"_list"),list.re) DB.list[[paste0(indexlist[idx])]] = get(paste0(indexlist[idx],"_list")) } if (sum(indexlist == "all")==1){ return(DB.list) } else { return(DB.list[indexlist]) } }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_DB.IDX.R
B_DI.IDX <- function(x, kmax, method = 'kmeans', nstart = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans","hclust_complete","hclust_average","hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average', 'hclust_single'") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(startsWith(method,"hclust_")){ H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part di = vector() for(k in kmin:kmax){ if(method == "kmeans"){ K.model = kmeans(x,k,nstart =nstart) cluss = K.model$cluster } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) } # End check algorithm if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") size = table(cluss) dunn.dem = 0 dunn.num = 1e10 for (i in 1:(k-1)){ dunn.dem = max(dunn.dem,max(dist(x[cluss==i,]))) for(j in (i+1):k){ dunn.num = min(dunn.num,min(as.matrix(dist(rbind(x[cluss==i,],x[cluss==j,])))[(size[i]+size[j]):(size[i]+1),1:size[i]])) } } dunn.dem = max(dunn.dem,max(dist(x[cluss==k,]))) di[k-kmin+1] = dunn.num / dunn.dem } # Bayesian CVI.dframe = data.frame("C" = kmin:kmax,"Index" = di) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","DI") DI.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(DI.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_DI.IDX.R
B_GC.IDX <- function(x, kmax, indexlist = "all", method = 'FCM', fzm = 2, iter = 100, nstart = 20, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(indexlist %in% c("all", "GC1", "GC2", "GC3", "GC4"))) stop("Argument 'indexlist' is not in 'all', 'GC1', 'GC2', 'GC3', 'GC4'") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector gc1 = vector() gc2 = vector() gc3 = vector() gc4 = vector() distance =dist(x,diag = TRUE,upper= TRUE) dd = as.matrix(distance) dd[lower.tri(dd)] = 0 diag(dd) = 0 # For checking IDX Check_GC1 = sum(indexlist %in% c("all","GC1"))>=1 Check_GC2 = sum(indexlist %in% c("all","GC2"))>=1 Check_GC3 = sum(indexlist %in% c("all","GC3"))>=1 Check_GC4 = sum(indexlist %in% c("all","GC4"))>=1 # Start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # Defined variable n = nrow(x) mt = t(m) NI = colSums(m) nws = floor(sum(NI*(NI-1)/2)) # GC1: sum product if(Check_GC1){ PD1 = m%*%mt G1 = sum(PD1*dd) Gmax1 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD1[lower.tri(PD1)],decreasing = T)[1:nws]) Gmin1 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD1[lower.tri(PD1)],decreasing = F)[1:nws]) gc1[k-kmin+1] = (G1-Gmin1)/(Gmax1-Gmin1) } if(sum(indexlist %in% c("all","GC2","GC3","GC4"))>=1){ PD2 = matrix(rep(0,n^2),n,n) PD3 = matrix(rep(0,n^2),n,n) PD4 = matrix(rep(0,n^2),n,n) for (s in 1:n){ #GC2: sum-min if(Check_GC2){ PD2[s,] = colSums(pmin(mt,m[s,])) } # GC3: max-product if(Check_GC3){ PD3[s,] = apply(m[s,]*mt,2,max) } # GC4: max-min if(Check_GC4){ PD4[s,] = apply(pmin(mt,m[s,]),2,max) } } # end loop s if(Check_GC2){ G2 = sum(PD2*dd) Gmax2 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD2[lower.tri(PD2)],decreasing = T)[1:nws]) Gmin2 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD2[lower.tri(PD2)],decreasing = F)[1:nws]) gc2[k-kmin+1] = (G2-Gmin2)/(Gmax2-Gmin2) } if(Check_GC3){ G3 = sum(PD3*dd) Gmax3 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD3[lower.tri(PD3)],decreasing = T)[1:nws]) Gmin3 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD3[lower.tri(PD3)],decreasing = F)[1:nws]) gc3[k-kmin+1] = (G3-Gmin3)/(Gmax3-Gmin3) } if(Check_GC4){ G4 = sum(PD4*dd) Gmax4 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD4[lower.tri(PD4)],decreasing = T)[1:nws]) Gmin4 = sum(sort(dd,decreasing = T)[1:nws]*sort(PD4[lower.tri(PD4)],decreasing = F)[1:nws]) gc4[k-kmin+1] = (G4-Gmin4)/(Gmax4-Gmin4) } }# END GC index }#end k loop if(any(indexlist %in% "all")){ indexlist = paste0("GC",seq(4)) } GC.list = list() for (idx in seq(length(indexlist))) { CVI.dframe = data.frame("C" = kmin:kmax,"Index" = get(tolower(indexlist[idx]))) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k",paste0(indexlist[idx])) list.re = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) assign(paste0(indexlist[idx],"_list"),list.re) GC.list[[paste0(indexlist[idx])]] = get(paste0(indexlist[idx],"_list")) } if (sum(indexlist == "all")==1){ return(GC.list) } else { return(GC.list[indexlist]) } }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_GC.IDX.R
B_HF.IDX <- function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector hf = vector() # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # Defined variable d3 = vector() d5 = vector() n = nrow(x) for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) d5[j] = (m[,j])^fzm%*%rowSums((x-center)^2) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) s=s+1 } } adp = (1/(k*(k-1)))*sum(d3) hf[k-kmin+1] = (sum(d5) + 2*adp)/ ((n/2*k)* (min(d3) + median(d3))) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = hf) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","HF") HF.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(HF.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_HF.IDX.R
B_KPBM.IDX <- function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector kpbm = vector() # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # Defined variables d3 = vector() d8 = vector() d9 = vector() n = nrow(x) for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) d8[j] = (m[,j])%*%sqrt(rowSums((x-center)^2)) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) d9[s]= sqrt(d3[s]) #NW s=s+1 } } kpbm[k-kmin+1] = ((1/k)*(max(d9)/sum(d8)))^2 } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = kpbm) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","KPBM") KPBM.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(KPBM.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_KPBM.IDX.R
B_KWON.IDX <- function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector kwon = vector() # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } d1= vector() d2 = rowSums((c-matrix(colMeans(x),k,ncol(x),byrow=T))^2) #NW d3 = vector() n = nrow(x) for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) #NW d1[j] = (m[,j])^2%*%rowSums((x-center)^2) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) s=s+1 } } kwon[k-kmin+1] = (sum(d1)+ mean(d2))/min(d3) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = kwon) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","KWON") KWON.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(KWON.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_KWON.IDX.R
B_KWON2.IDX <- function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector kwon2 = vector() # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # Defined variable d2 = rowSums((c-matrix(colMeans(x),k,ncol(x),byrow=T))^2) d3 = vector() d4 = vector() n = nrow(x) w1 = (n-k+1)/n w2 = (k/(k-1))^sqrt(2) w3 = (n*k)/(n-k+1)^2 for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) d4[j] = ((m[,j])^(2^sqrt(fzm/2))%*%rowSums((x-center)^2)) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) s=s+1 } } kwon2[k-kmin+1] = w1*((w2*sum(d4)) + (sum(d2)/max(d2)) + w3 ) / (min(d3) + 1/k + 1/(k^(fzm - 1))) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = kwon2) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","KWON2") KWON2.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(KWON2.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_KWON2.IDX.R
B_PB.IDX <- function(x, kmax, method = 'kmeans', corr = 'pearson', nstart = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans","hclust_complete","hclust_average","hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average', 'hclust_single'") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(!any(corr == c("pearson","kendall","spearman"))) stop("Argument 'corr' should be one of 'pearson', 'kendall', 'spearman'") if(startsWith(method,"hclust_")){ H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part d = as.vector(dist(x)) dm = dim(x) pb = vector() for(k in kmin:kmax){ xnew = matrix(0,dm[1],dm[2]) centroid = matrix(0,k,dm[2]) if(method == "kmeans"){ K.model = kmeans(x,k,nstart =nstart) cluss = K.model$cluster centroid = K.model$centers xnew = centroid[cluss,] } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) for (j in 1:k){ if (is.null(nrow(x[cluss==j,])) | sum(nrow(x[cluss==j,]))==1){ centroid[j,] = as.numeric(x[cluss==j,]) } else { centroid[j,] = colMeans(x[cluss==j,]) } } xnew = centroid[cluss,] } # End check algorithm if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") d3 = as.vector(dist(xnew)) d3[d3>0] = 1 pb[k-kmin+1] = cor(d,d3,method=corr) } # Bayesian CVI.dframe = data.frame("C" = kmin:kmax,"Index" = pb) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","PB") PB.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(PB.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_PB.IDX.R
B_PBM.IDX <- function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector pbm = vector() # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # Defined variable d3 = vector() n = nrow(x) d7 = sqrt(rowSums((x-matrix(colMeans(x),n,ncol(x),byrow=T))^2)) #NW d8 = vector() d9 = vector() for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) d8[j] = (m[,j])%*%sqrt(rowSums((x-center)^2)) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) d9[s]= sqrt(d3[s]) #NW s=s+1 } } pbm[k-kmin+1] = ((1/k)*(sum(d7)*max(d9)/sum(d8)))^2 } #end loop if for indexes based on compactness and seperated CVI.dframe = data.frame("C" = kmin:kmax,"Index" = pbm) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","PBM") S_PBM.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(S_PBM.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_PBM.IDX.R
B_SF.IDX <- function(x, kmax, method = 'kmeans', nstart = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans","hclust_complete","hclust_average","hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average', 'hclust_single'") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(startsWith(method,"hclust_")){ H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha sf = vector() #vector defined for(k in kmin:kmax){ centroid = matrix(0,k,dim(x)[2]) if(method == "kmeans"){ K.model = kmeans(x,k,nstart =nstart) cluss = K.model$cluster centroid = K.model$centers } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) for (j in 1:k){ if (is.null(nrow(x[cluss==j,])) | sum(nrow(x[cluss==j,]))==1){ centroid[j,] = as.numeric(x[cluss==j,]) } else { centroid[j,] = colMeans(x[cluss==j,]) } } } # End check algorithm if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") sizecluss = as.vector(table(cluss)) wcdd = vector() for (i in 1:k){ wcdd[i] = sum(dist(rbind(centroid[i,],x[cluss==i,]))[1:sizecluss[i]])/sizecluss[i] } # SF index bcd = sum(dist(rbind(colMeans(x),centroid))[1:k]*sizecluss)/(dim(x)[1]*k) wcd = sum(wcdd) sf[k-kmin+1] = 1-1/exp(bcd+wcd) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = sf) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","SF") SF.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(SF.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_SF.IDX.R
B_STRPBM.IDX <- function(x, kmax, method = 'kmeans', indexlist = 'all', #c(,"all","STR","PBM") nstart = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans","hclust_complete","hclust_average","hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average', 'hclust_single'") if(!any(indexlist %in% c("all","STR","PBM"))) stop("Argument 'indexlist' should be 'all', 'STR', 'PBM'") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(startsWith(method,"hclust_")){ H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part dm = dim(x) str = rep(0,kmax-kmin+1) pbm = rep(0,kmax-kmin+1) EK = rep(0,kmax-kmin+2) DK = rep(0,kmax-kmin+3) md = rep(0,kmax-kmin+3) if (kmin == 2){ lb = 2 } else { lb = kmin-1 } for(k in lb:(kmax+1)){ xnew = matrix(0,dm[1],dm[2]) centroid = matrix(0,k,dm[2]) if(method == "kmeans"){ K.model = kmeans(x,k,nstart =nstart) cluss = K.model$cluster centroid = K.model$centers xnew = centroid[cluss,] } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) for (j in 1:k){ if (is.null(nrow(x[cluss==j,])) | sum(nrow(x[cluss==j,]))==1){ centroid[j,] = as.numeric(x[cluss==j,]) } else { centroid[j,] = colMeans(x[cluss==j,]) } } xnew = centroid[cluss,] } # End check algorithm if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") EK[k-kmin+2] = sum(sqrt(rowSums((x - xnew)^2))) ddd = dist(centroid) md[k-kmin+2] = max(ddd) DK[k-kmin+2] = max(ddd)/min(ddd) } E0 = sum(sqrt(rowSums((x-colMeans(x))^2))) if (kmin == 2){ EK[1] = E0 } EKK = E0/EK str = (EKK[2:(length(EKK)-1)]-EKK[1:(length(EKK)-2)])*(DK[3:(length(DK))]-DK[2:(length(DK)-1)]) pbm = EKK[2:(length(EKK)-1)]*md[2:(length(EKK)-1)]/(kmin:kmax) # Bayesian part if(any(indexlist %in% "all")){ indexlist = c("STR","PBM") } STR.list = list() for (idx in seq(length(indexlist))) { CVI.dframe = data.frame("C" = kmin:kmax,"Index" = get(tolower(indexlist[idx]))) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k",paste0(indexlist[idx])) list.re = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) assign(paste0(indexlist[idx],"_list"),list.re) STR.list[[paste0(indexlist[idx])]] = get(paste0(indexlist[idx],"_list")) } if (sum(indexlist == "all")==1){ return(STR.list) } else { return(STR.list[indexlist]) } }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_STRPBM.IDX.R
B_TANG.IDX <- function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector tang = vector() # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # Define variable d1= vector() d3 = vector() n = nrow(x) for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) #NW d1[j] = (m[,j])^2%*%rowSums((x-center)^2) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) s=s+1 } } adp = (1/(k*(k-1)))*sum(d3) tang[k-kmin+1] = (sum(d1) + 2*adp)/ (min(d3) + 1/k) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = tang) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","TANG") TANG.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(TANG.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_TANG.IDX.R
B_WL.IDX <- function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # Defined vector wl = vector() # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose=FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # Defined variables d1= vector() d3 = vector() d6 = vector() n = nrow(x) for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) #NW d1[j] = (m[,j])^2%*%rowSums((x-center)^2) d6[j] = sum((m[,j])) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) s=s+1 } } wl[k-kmin+1] = sum(d1/d6) / (min(d3) + median(d3)) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = wl) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","WL") WL.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(WL.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_WL.IDX.R
B_WP.IDX <- function(x, kmax, corr = 'pearson', method = "FCM",fzm = 2,gamma = (fzm^2*7)/4, sampling = 1, iter = 100, nstart = 20, NCstart = TRUE, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(!any(corr == c("pearson","kendall","spearman"))) stop("Argument 'corr' should be one of 'pearson', 'kendall', 'spearman'") if(!is.logical(NCstart)) stop("Argument 'NCstart' must be logical") if(!is.numeric(gamma)) stop("Argument 'gamma' must be numeric or leave blank for default value") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(sampling)) stop("Argument 'sampling' must be numeric") if(!(sampling > 0 & sampling <= 1)) stop("'sampling' must be greater than 0 and less than or equal to 1") if(sampling == 1){ x = x }else { sample = sample(1:(nrow(x)),ceiling(nrow(x)*sampling),replace = FALSE) x = x[sample,] } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index crr = vector() WPI = vector() WPCI2 = vector() WPCI3 = vector() # Distance part distance = dist(x,diag = TRUE,upper= TRUE) # FOR WP idx (single distance) distx = as.vector(distance) # Algorithm method if(method == "EM"){ if(NCstart & (kmin<=2)){ dtom = sqrt(rowSums((x-colMeans(x))^2)) crr[1] = sd(dtom)/(max(dtom)-min(dtom)) } else{ EM.model <- Mclust(x,G=kmin-1,verbose = FALSE) xnew = ((EM.model$z^gamma)/rowSums(EM.model$z^gamma))%*%t(EM.model$parameters$mean) crr[1]= cor(distx,as.vector(dist(xnew)),method=corr) } EM.model <- Mclust(x,G = kmax+1,verbose = FALSE) xnew = ((EM.model$z^gamma)/rowSums(EM.model$z^gamma))%*%t(EM.model$parameters$mean) crr[kmax-kmin+3]= cor(distx,as.vector(dist(xnew)),method=corr) }else if(method == "FCM"){ if(NCstart & kmin<=2){ dtom = sqrt(rowSums((x-colMeans(x))^2)) crr[1] = sd(dtom)/(max(dtom)-min(dtom)) }else{ wd = Inf for (nr in 1:nstart){ minFCM.model = cmeans(x,kmax+1,iter,verbose=FALSE,method="cmeans",m=fzm) if (minFCM.model$withinerror < wd){ wd = minFCM.model$withinerror minFCM.model2 =minFCM.model } } xnew = ((minFCM.model2$membership^gamma)/rowSums(minFCM.model2$membership^gamma))%*%minFCM.model2$center crr[1]= cor(distx,as.vector(dist(xnew)),method=corr) } # crr kmax + 1 wd = Inf for (nr in 1:nstart){ maxFCM.model = cmeans(x,kmax+1,iter,verbose=FALSE,method="cmeans",m=fzm) if (maxFCM.model$withinerror < wd){ wd = maxFCM.model$withinerror maxFCM.model2 = maxFCM.model } } xnew = ((maxFCM.model2$membership^gamma)/rowSums(maxFCM.model2$membership^gamma))%*%maxFCM.model2$center crr[kmax-kmin+3]= cor(distx,as.vector(dist(xnew)),method=corr) } # END if first process defined # start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose = FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf # cm.out = list() for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } xnew = ((m^gamma)/rowSums(m^gamma))%*%c crr[k-kmin+2]= cor(distx,as.vector(dist(xnew)),method=corr) } K = length(crr) WPI = ((crr[2:(K-1)]-crr[1:(K-2)])/(1-crr[1:(K-2)]))/pmax(0,(crr[3:K]-crr[2:(K-1)])/(1-crr[2:(K-1)])) WPCI2 = (crr[2:(K-1)]-crr[1:(K-2)])/(1-crr[1:(K-2)])-(crr[3:K]-crr[2:(K-1)])/(1-crr[2:(K-1)]) WPCI3 = WPI if(sum(is.finite(WPI))==0){ WPCI3[WPI==Inf] = WPCI2[WPI==Inf] WPCI3[WPI==-Inf] = pmin(0,WPCI2[WPI==-Inf]) }else{ if (max(WPI)<Inf){ if (min(WPI) == -Inf){ WPCI3[WPI==-Inf] = min(WPI[is.finite(WPI)]) } } if (max(WPI)==Inf){ WPCI3[WPI==Inf] = max(WPI[is.finite(WPI)])+WPCI2[WPI==Inf] WPCI3[WPI<Inf] = WPI[WPI<Inf] + WPCI2[WPI<Inf] #added if (min(WPI) == -Inf){ WPCI3[WPI==-Inf] = min(WPI[is.finite(WPI)])+WPCI2[WPI==-Inf] } } } # Baye's part CVI.dframe = data.frame("C" = kmin:kmax,"Index" = WPCI3) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","WP") WP.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(WP.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_WP.IDX.R
B_Wvalid <- function(x, kmax, method='kmeans', corr='pearson', nstart=100, sampling = 1, NCstart = TRUE, alpha = "default", mult.alpha = 1/2) { if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("kmeans", "hclust_complete", "hclust_average", "hclust_single"))) stop("Argument 'method' should be one of 'kmeans', 'hclust_complete', 'hclust_average' or 'hclust_single'") if(!any(corr == c("pearson","kendall","spearman"))) stop("Argument 'corr' should be one of 'pearson', 'kendall', 'spearman'") if(method == "kmeans"){ if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") } if(!is.numeric(sampling)) stop("Argument 'sampling' must be numeric") if(!(sampling > 0 & sampling <= 1)) stop("'sampling' must be greater than 0 and less than or equal to 1") if(sampling == 1){ x = x }else { sample = sample(1:(nrow(x)),ceiling(nrow(x)*sampling),replace = FALSE) x = x[sample,] } if(!is.logical(NCstart)) stop("Argument 'NCstart' must be logical") if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part dm=dim(x) d = as.vector(dist(x)) crr = rep(0,kmax-kmin+2) if (NCstart) { dtom = sqrt(rowSums((x-colMeans(x))^2)) crr[1] = sd(dtom)/(max(dtom)-min(dtom)) } if(startsWith(method,"hclust_")){ # Check hierarchical method H.model = hclust(dist(x),method = sub("hclust_", "", method)) } if (kmin == 2){ lb = 2 } else { lb = kmin-1 } for (k in lb:(kmax+1)){ xnew = matrix(0,dm[1],dm[2]) centroid = matrix(0,k,dm[2]) if (method == 'kmeans'){ K.model=kmeans(x,k,nstart =nstart) cluss = K.model$cluster xnew = K.model$centers[cluss,] } else if(startsWith(method,"hclust_")){ cluss = cutree(H.model,k) for (j in 1:k){ if (is.null(nrow(x[cluss==j,])) | sum(nrow(x[cluss==j,]))==1){ centroid[j,] = as.numeric(x[cluss==j,]) } else { centroid[j,] = colMeans(x[cluss==j,]) } } xnew = centroid[cluss,] } if(!all(seq(k) %in% unique(cluss))) warning("Some clusters are empty.") d2 = as.vector(dist(xnew)) crr[k-kmin+2]= cor(d,d2,method=corr) } K = length(crr) NWI = ((crr[2:(K-1)]-crr[1:(K-2)])/(1-crr[1:(K-2)]))/pmax(0,(crr[3:K]-crr[2:(K-1)])/(1-crr[2:(K-1)])) NWI2 = (crr[2:(K-1)]-crr[1:(K-2)])/(1-crr[1:(K-2)])-(crr[3:K]-crr[2:(K-1)])/(1-crr[2:(K-1)]) NWI3 = NWI if (max(NWI)<Inf){ if (min(NWI) == -Inf){ NWI3[NWI==-Inf] = min(NWI[is.finite(NWI)]) } } if (max(NWI)==Inf){ NWI3[NWI==Inf] = max(NWI[is.finite(NWI)])+NWI2[NWI==Inf] NWI3[NWI<Inf] = NWI[NWI<Inf] + NWI2[NWI<Inf] if (min(NWI) == -Inf){ NWI3[NWI==-Inf] = min(NWI[is.finite(NWI)])+NWI2[NWI==-Inf] } } # Bayesian CVI.dframe = data.frame("C" = kmin:kmax,"Index" = NWI3) minGI = min(CVI.dframe[,"Index"]) # The largest value of the GI indicates the optimal number of cluster rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","NCI") WI.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(WI.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_Wvalid.R
B_XB.IDX <-function(x, kmax, method = "FCM", fzm = 2, nstart = 20, iter = 100, alpha = "default", mult.alpha = 1/2){ if(missing(x)) stop("Missing input argument. A numeric data frame or matrix is required") if(missing(kmax)) stop("Missing input argument. A maximum number of clusters is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(kmax > nrow(x)) stop("The maximum number of clusters for consideration should be less than or equal to the number of data points in dataset.") if(!any(method == c("FCM","EM"))) stop("Argument 'method' should be one of 'FCM','EM' ") if(method == "FCM"){ if(fzm <= 1) stop("Argument 'fcm' should be the number greater than 1",call. = FALSE) if(!is.numeric(nstart)) stop("Argument 'nstart' must be numeric") if(!is.numeric(iter)) stop("Argument 'iter' must be numeric") } if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") n = nrow(x) kmin = 2 #fix value if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } if(length(kmin:kmax) != length(alpha)) # check stop("The length of kmin to kmax must be equal to the length of alpha") adj.alpha = alpha*(n)^mult.alpha # index part # Defined vector xb = vector() # Start k loop for(k in kmin:kmax){ if(method == "EM"){ # EM Algorithm EM.model <- Mclust(x,G=k,verbose = FALSE) assign("m",EM.model$z) assign("c",t(EM.model$parameters$mean)) }else if(method == "FCM"){ # FCM Algorithm wd = Inf for (nr in 1:nstart){ FCM.model = cmeans(x,k,iter,verbose=FALSE,method="cmeans",m=fzm) if (FCM.model$withinerror < wd){ wd = FCM.model$withinerror FCM.model2 =FCM.model } } assign("m",FCM.model2$membership) assign("c",FCM.model2$centers) } # defined variable for index d1= vector() d3 = vector() n = nrow(x) for (j in 1:k){ center = matrix(c[j,],n,ncol(x),byrow = T) #NW d1[j] = (m[,j])^2%*%rowSums((x-center)^2) } s=1 for(i in 1:(k-1)){ for(j in (i+1):k){ d3[s]=sum((c[i,]-c[j,])^2) s=s+1 } } xb[k-kmin+1] = (sum(d1))/(n*min(d3)) } CVI.dframe = data.frame("C" = kmin:kmax,"Index" = xb) maxGI = max(CVI.dframe[,"Index"]) # The smallest value of the GI indicates the optimal number of cluster rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) colnames(CVI.dframe) = c("k","XB") XB.result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe) return(XB.result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/B_XB.IDX.R
BayesCVIs <- function(CVI, n, kmax, opt.pt, alpha = "default", mult.alpha = 1/2){ if(missing(CVI)) stop("Missing input argument. A numeric result from cluster validity index is required") if(missing(n)) stop("Missing input argument. A numeric data point value is required") if(!is.numeric(n)) stop("Argument 'n' must be numeric") if(missing(kmax)) stop("A maximum number of clusters from cluster validity index is required") if(!is.numeric(kmax)) stop("Argument 'kmax' must be numeric") if(!opt.pt %in% c("min","max")) stop("Argument 'opt.pt' should be one of 'min', 'max'") if(!is.numeric(mult.alpha)) stop("Argument 'mult.alpha' must be numeric") kmin = 2 if(any(alpha %in% "default")){ alpha = rep(1,length(kmin:kmax)) } adj.alpha = alpha*(n)^mult.alpha if(length(kmin:kmax) != length(adj.alpha)) stop("The length of kmin to kmax must be equal to the length of alpha") # create new dataframe for index CVI.dframe = data.frame("C" = kmin:kmax,"Index" = CVI) # Bayesian CVI if(opt.pt == "max"){ minGI = min(CVI.dframe[,"Index"]) rk = (CVI.dframe[,"Index"] - minGI)/sum(CVI.dframe[,"Index"] - minGI) } else { maxGI = max(CVI.dframe[,"Index"]) rk = (maxGI - CVI.dframe[,"Index"])/sum(maxGI - CVI.dframe[,"Index"]) } nrk = n*rk ex = (adj.alpha + nrk) / (sum(adj.alpha)+ n) var = ((adj.alpha+nrk)*(sum(adj.alpha)+n - adj.alpha - nrk))/((sum(adj.alpha)+n)^2*(sum(adj.alpha)+n+1)) BCVI = data.frame("k" = kmin:kmax,"BCVI" = ex) VarBCVI = data.frame("k" = kmin:kmax,"Var" = var) result = list("BCVI" = BCVI,"VAR" = VarBCVI,"Index" = CVI.dframe,"opt.pt" = opt.pt) return(result) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/BayesCVIs.R
utils::globalVariables(c("k", "BCVI", "VAR"))
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/globals.R
plot_BCVI <- function(B.result, mult.err.bar = 2){ if(sum(names(B.result) %in% c("BCVI","VAR","Index","opt.pt")) <=2) stop("Bad input, 'B.result' is not a result from a function in the package.") if(sum(names(B.result) %in% c("BCVI","VAR","Index","opt.pt")) ==4){ opt.pt = B.result[["opt.pt"]] } else if((any(colnames(B.result[["Index"]][2]) %in% c("WP","PBM","KPBM","CCVP","CCVS","CH","DI","PB","NCI","STR")))){ opt.pt = "max" } else{ opt.pt = "min" } if(!is.numeric(mult.err.bar)) stop("Argument 'mult.err.bar' must be numeric") # BCVI plot pp.BCVI = ggplot(B.result[["BCVI"]], aes(k, BCVI))+ geom_point(size = 2)+ geom_point(data = B.result[["BCVI"]][which.max(B.result[["BCVI"]][,2]),],colour = "red")+ geom_line()+ theme_minimal() pp = data.frame(B.result[["BCVI"]],"VAR" = mult.err.bar*sqrt(B.result[["VAR"]][,2])) pp.VAR = ggplot(pp, aes(k, BCVI)) + geom_line() + geom_errorbar(aes(ymin = BCVI-VAR, ymax = BCVI+VAR,width = 0.2)) + geom_errorbar(data = pp[which.max(pp[,"BCVI"]),],aes(ymin = BCVI-VAR, ymax = BCVI+VAR,width = 0.2), colour = "red",size=1)+ geom_point(size = 1)+ geom_text(aes(label= round(BCVI,4)), colour="black", size =3,hjust=-0.3)+ theme_minimal() pp.Index = ggplot(B.result[["Index"]], aes_string(x = colnames(B.result[["Index"]])[1],y =colnames(B.result[["Index"]])[2]))+ geom_point(size = 2)+ geom_point(data = if(opt.pt=="max"){ B.result[["Index"]][which.max(B.result[["Index"]][,2]),] }else{ B.result[["Index"]][which.min(B.result[["Index"]][,2]),] },colour = 'red')+ geom_line()+ theme_minimal() result = list("plot_BCVI" = pp.BCVI,"error_bar_plot" = pp.VAR,"plot_index" = pp.Index) }
/scratch/gouwar.j/cran-all/cranData/BayesCVI/R/plot_BCVI.R
#' @title Calculates the posterior probability of hypotheses for multiple #' studies #' #' @description The function takes multiple effect sizes and a their standard #' errors and calculates the posterior probability for each hypothesis (H<: the #' effect size is less than 0, H0: the effect size is zero, or H>: the effect #' size is greater than zero). #' #' @details This function calls \code{pph()} once for each study to be combined, #' where the posterior probabilities for one study are used as the priors for #' the next study. One exeption is that values for \code{se0} are ignored as #' they are calculated automatically. #' #' @inheritParams pph #' #' @param ... Options to be passed to \code{pph()}. #' #' @return Object of class \code{EV} which contains a matrix of posterior #' probabilities for each updated step and other calculated values. #' #' @export #' @examples #' x <- ev.combo(beta = c(0.0126, 5.0052, 1.2976, 0.0005), #' se.beta = c(0.050, 2.581, 2.054, 0.003) ) #' x #' plot(x) ev.combo <- function(beta, se.beta, beta0 = 0, ci = 99, H0 = c(0, 0), scale = FALSE, H.priors = rep(1/3, 3), se.mult = 1, adjust = FALSE, epsilon = 1e-6, adj.factor = 0.0001, ... ) { if(length(beta) != length(se.beta)) { stop("beta and se.beta must be the same length.") } if(length(H.priors) != 3 || sum(H.priors) != 1 ) { stop("H.priors must have 3 values that sum to one.") } n.studies <- length(beta) se0 <- numeric(n.studies) post.b <- numeric(n.studies) post.se <- numeric(n.studies) # pphs with uniform priors res.uni <- matrix(NA, nrow = n.studies, ncol = 3) colnames(res.uni) <- c("H<", "H0", "H>") # running total pphs res <- matrix(NA, nrow = n.studies + 1, ncol = 3) res[1,] <- H.priors colnames(res) <- c("H<", "H0", "H>") for (i in 1:n.studies) { # uniform priors tmp.uni <- pph(beta = beta[i], se.beta = se.beta[i], beta0 = beta0, ci = ci, H0 = H0, H.priors = rep(1/3, 3), se.mult = se.mult, adjust = adjust, epsilon = epsilon, adj.factor = adj.factor, scale=scale) # running total tmp <- pph(beta = beta[i], se.beta = se.beta[i], beta0 = beta0, ci = ci, H0 = H0, H.priors = res[i,], se.mult = se.mult, adjust = adjust, epsilon = epsilon, adj.factor = adj.factor, scale=scale) se0[i] <- tmp$se0 post.b[i] <- tmp$post.b post.se[i] <- tmp$post.se res.uni[i, ] <- tmp.uni$pphs res[i+1,] <- tmp$pphs } if (scale) { # standardise beta <- beta/se.beta se.beta <- se.beta/se.beta } return( structure(list(N=n.studies, beta = beta, se.beta = se.beta, beta0 = beta0, ci = ci, se0 = se0, post.b = post.b, post.se = post.se, H.priors = H.priors, pph.uniform = res.uni, pphs = res), class = "EV") ) }
/scratch/gouwar.j/cran-all/cranData/BayesCombo/R/ev.combo.R
#' @title Forest plot #' #' @description Plots the effect sizes and standard errors for a set of studies #' as a standard forest plot. Also shown are the priors for each study. #' #' @details This function plots results from the \code{ev.combo()} function. The #' results may be hard to visualise if the effect sizes differ greatly, and it #' may be preferable to standardise the effect sizes by setting \code{scale = #' TRUE} in the \code{ev.combo()} function. #' #' @param x An object of the class \code{EV}. #' #' @param range A numeric vector of length two that sets the range of the #' x-axis. Values are passed to \code{xlim}. Sensible default values are used #' when \code{range = NULL}. #' #' @param xlab,ylab Text for the x and y axes labels. #' #' @param labels Names for studies to be plotted on the y-axis. If \code{NULL}, #' then numbers are used. #' #' @param ... Other options passed to \code{plot()}. #' #' @return A forest plot. #' #' @seealso \code{\link{ev.combo}} #' #' @export #' #' @examples #' x <- ev.combo( beta = c(0.0126, 5.0052, 1.2976, 0.0005), #' se.beta = c(0.050, 2.581, 2.054, 0.003) ) #' forestplot(x) #' forestplot <- function(x, range=NULL, xlab="Effect size", ylab="Study", ..., labels=NULL) { if (!inherits(x, "EV")){ stop("Input must be a 'EV' object from the ev.combo() function.") } # multiplier for confidence intervals ci <- (x$ci / 100) ci <- ci + (1 - ci) / 2 multiplier <- qnorm(ci) # calclate x-axis range if (is.null(range)){ xlim <- c(min(x$beta0 - x$se0 * multiplier), max(x$beta0 + x$se0 * multiplier)) } else { xlim <- c(range[1], range[2]) } # setup plot old.par <- par(no.readonly = TRUE) par(las=1) plot(c(1:x$N) ~ x$beta, type="n", yaxt="n", xlab = xlab, ylab = ylab, xlim = xlim, ...) if (is.null(labels)) { axis(2, at=1:x$N) } else { axis(2, at=1:x$N, labels=labels) } # priors segments(rep(x$beta0, x$N) - x$se0 * multiplier, 1:x$N, rep(x$beta0, x$N) + x$se0 * multiplier, 1:x$N, lwd=6, col="darkgrey") # data arrows(x$beta - x$se.beta * multiplier, 1:x$N, x$beta + x$se.beta * multiplier, 1:x$N, code=3, angle=90, length=0.05) points(c(1:x$N) ~ x$beta, pch=18, cex=1.2) on.exit(par(old.par)) }
/scratch/gouwar.j/cran-all/cranData/BayesCombo/R/forestplot.R
#' @title Plot of posterior probabilities for each hypothesis #' #' @description Shows how the posterior probabilities evolve as each study is #' added to the analysis. #' #' @details Each line in the graph is a hypothesis and the lines start at the #' prior hypothesis probabilities (usually 1/3). #' #' @param x An object of the class \code{EV} created by the \code{ev.combo()} #' function. #' #' @param leg.loc Location of the legend; default is top left. See the #' \code{legend()} help pages for all the options. #' #' @param lty An vector of integers that specifies the line types. See the #' \code{matplot()} function for details. #' #' @param ... Other options passed to \code{matplot()}. #' #' @return Plot of posterior probabilities for each hypothesis. #' #' @seealso \code{\link{ev.combo}} #' #' @export #' #' @examples #' x <- ev.combo(beta = c(0.0126, 5.0052, 1.2976, 0.0005), #' se.beta = c(0.050, 2.581, 2.054, 0.003) ) #' plot(x) plot.EV <- function(x, leg.loc="topleft", lty=1, ...) { if (!inherits(x, "EV") ) { stop("Input must be a 'EV' object from the ev.combo() function.") } matplot(x$pphs, type="l", col=c("royalblue","darkgrey","firebrick"), lty=lty, lwd=c(1,3,1), ylim = c(0, 1), xaxt = "n", ...) axis(1, at = 1:(x$N+1), labels = 0:(x$N)) legend(leg.loc, legend = c("H<", "H0", "H>"), fill = c("royalblue","darkgrey","firebrick")) }
/scratch/gouwar.j/cran-all/cranData/BayesCombo/R/plot.EV.R
#' @title Plot of prior, likelihood, and posterior distributions #' #' @description Plots the prior, likelihood, and posterior distribution from a #' single study. #' #' @details Plots the prior, likelihood (data), and posterior distribution #' calculated from the \code{pph()} function for a single study. #' #' @param x A \code{PPH} object created by the \code{pph()} function. #' #' @param range A numeric vector of length two that sets the range of the #' x-axis. Values are passed to \code{xlim}. Sensible default values are used #' when \code{range = NULL}. #' #' @param n An integer that specifies the number of x-values to use when #' plotting the distributions. #' #' @param leg.loc Location of the legend; default is top left. See the #' \code{legend()} help pages for all the options. If \code{leg.loc = NULL} the #' legend is not plotted. #' #' @param xlab,ylab Text for the x and y axes labels. #' #' @param ... Other options passed to \code{plot()}. #' #' @return Plot of distributions. #' #' @seealso \code{\link{pph}} #' #' @export #' #' @examples #' x <- pph(beta = 5.005, se.beta = 2.05) #' plot(x) plot.PPH <- function(x, range=NULL, n=200, leg.loc="topleft", xlab="Effect size", ylab="", ...) { if (!inherits(x, "PPH") ) { stop("Input must be a 'PPH' object from the pph() function.") } if (is.null(range)){ xvals <- seq(x$beta0 - 3*x$se0, x$beta0 + 3*x$se0, length.out = n) } else { xvals <- seq(range[1], range[2], length.out = n) } lik <- dnorm(xvals, x$beta, x$se.beta) prior <- dnorm(xvals, x$beta0, x$se0) post <- dnorm(xvals, x$post.b, x$post.se) plot(prior ~ xvals, col="darkgrey", lwd=3, type="l", ylim=c(0, max(c(lik, prior, post))), xlim=c(min(xvals), max(xvals)), xlab = xlab, ylab = ylab, ...) lines(lik ~ xvals, lty=2) lines(post ~ xvals) if (!is.null(leg.loc)){ legend(leg.loc, legend=c("Prior", "Data", "Posterior"), lwd=c(3, 1, 1), lty=c(1, 2, 1), col=c("darkgrey", "black", "black")) } }
/scratch/gouwar.j/cran-all/cranData/BayesCombo/R/plot.PPH.R
#' @title Calculates the posterior probability of hypotheses for one study #' #' @description The function takes a single effect size and its standard error #' and calculates the posterior probability of each hypothesis (H<: the effect #' size is less than 0, H0: the effect size is zero, or H>: the effect size is #' greater than zero). #' #' @details Effect sizes could be a mean difference between groups, regression #' slope, odds ratio, or other values provided by statistical models. The #' standard errors represent the uncertainty in the effect size and are provided #' by most statistical software. #' #' Two types of priors need to be specified. The first is the prior for the #' effect size, which is given by a mean (usually zero) and standard error, #' which can be specified by the user or calculated automatically. Second, prior #' probabilities for each hypothesis need to be provided, and an equal #' probability of 1/3 is used by default. #' #' The null hypothesis (usually effect size = 0) can be specified as either a #' point null or as a range. A point null tests if the effect size is #' \emph{exactly} zero while the range null tests if the effect size close #' enough to zero for practical purposes. 'Close enough' is defined by the user #' as a range on either size of zero. #' #' To combine multiple effect sizes use the \code{ev.combo} function. #' #' @param beta Effect size. #' #' @param se.beta Standard error for the effect. #' #' @param beta0 A prior value for the effect size. Default is zero. #' #' @param se0 A prior standard error for the effect size. Default is \code{NULL} #' and is calculated automatically. #' #' @param ci Is used to calculate the prior standard error if \code{se0 = #' NULL}. The default value of 99 calculates the prior standard error so that #' the 99% confidence intervals of the prior distribution are aligned with the #' largest (furthest from zero) confidence interval of the data distribution. #' #' @param se.mult Standard error multiplier used to increase or decrease the #' prior SE and used in conjunction with \code{ci} when \code{se0 = NULL}. #' #' #' @param H0 A vector of length two that defines the null hypothesis. If the #' values are identical (e.g. \code{H0 = c(0,0)}) a point null is used, #' otherwise the null is defined as the range between the lower and upper value. #' #' @param H.priors Prior hypothesis probabilities; default is an equal #' probability of 1/3, and they are specified in the following order: #' \code{H<0}, \code{H=0}, \code{H>0}. #' #' @param scale Logical. Whether to scale the effect size by its standard #' error. Standardising has no effect on the calculations but standardised #' effect sizes may be easier to compare in a forest plot. #' #' @param adjust Logical. Whether to adjust very small posterior hypothesis #' probabilities. Adjusting prevents a single study from having too much #' influence on the results when combining multiple studies. For example, if the #' probability for a hypothesis from one study is zero, then additional studies #' cannot alter this probability (multiplying anything by zero is still zero). #' #' @param epsilon A small value that a posterior hypothesis probability must #' fall below before an adjustment is made. Ignored if \code{adjust = FALSE}. #' #' @param adj.factor A small number added to each posterior hypothesis #' probability if \code{adjust = TRUE} and one of the posterior hypothesis #' probabilities is less than \code{epsilon}. The PPHs are then re-scaled to sum #' to one. #' #' @return Object of class \code{pph} which contains the posterior hypothesis #' probabilities and other calculated values. #' #' @seealso \code{\link{plot.PPH}}, \code{\link{ev.combo}} #' @export #' @examples #' # library(labstats) # need to install from CRAN #' # plot(time.immob ~ dose, data=fluoxetine) #' # summary(lm(time.immob ~ dose, data=fluoxetine)) #' x <- pph(beta=-0.25200, se.beta=0.09913) # dose effect from above output #' x pph <- function(beta, se.beta, beta0 = 0, se0 = NULL, ci = 99, se.mult = 1, H0 = c(0,0), H.priors = rep(1/3, 3), scale = FALSE, adjust = FALSE, epsilon = 1e-6, adj.factor = 0.0001) { if (beta0 < H0[1] | beta0 > H0[2] ) { stop("beta0 must lie between the lower and upper bounds of H0.") } if (length(H0) != 2) { stop("H0 must have two values. Use c(0,0) for a point null at zero.") } if (any(se.beta <= 0)){ stop("se.beta must be greater than zero.") } if (scale) { # standardise beta <- beta/se.beta se.beta <- se.beta/se.beta } if (ci <= 0 | ci >= 100 ) { stop("ci must lie between zero and one.") } if (is.null(se0)){ # calculate if not given se0 <- prior.se(beta, se.beta, ci) * se.mult } post.b <- calc.post.beta(beta, se.beta, beta0, se0) post.se <- calc.post.se(se.beta, se0) # BFs lt <- pnorm(H0[1], post.b, post.se) / pnorm(H0[1], beta0, se.beta) gt <- pnorm(H0[2], post.b, post.se, lower.tail = FALSE) / pnorm(H0[2], beta0, se.beta, lower.tail = FALSE) if (H0[1] == H0[2]){ # point null null <- dnorm(beta0, post.b, post.se) / dnorm(H0[1], beta0, se0) } else { # range null null <- (pnorm(H0[2], post.b, post.se) - pnorm(H0[1], post.b, post.se)) / (pnorm(H0[2], beta0, se.beta) - pnorm(H0[1], beta0, se.beta)) } bfs <-c("H<" = lt, "H0" = null, "H>" = gt) # PPHs pphs <- (bfs * H.priors) / sum(bfs * H.priors) names(pphs) <- c("H<", "H0", "H>") if (adjust & any(pphs < epsilon)){ adj <- pphs + adj.factor pphs <- adj/sum(adj) } return( structure(list(beta = beta, se.beta = se.beta, beta0 = beta0, ci = ci, se0 = se0, post.b = post.b, post.se = post.se, H.priors = H.priors, BFs = bfs, pphs = pphs), class = "PPH") ) }
/scratch/gouwar.j/cran-all/cranData/BayesCombo/R/pph.R
#' @title Print and summary methods for PPH and EV objects #' #' @description Print and summary methods for PPH and EV objects. #' #' @param x A \code{PPH} or \code{EV} object. #' @param digits Number of digits to show. #' #' @return A list of posterior hypothesis probabilities and other calculated #' values. #' @method summary PPH # summarise one study summary.PPH <- function(x, digits=4){ return(round(x$pphs, digits)) } #' @rdname summary.PPH #' @method print PPH print.PPH <- function(x, digits=4){ return(list("post.b"=round(x$post.b, digits), "post.se"=round(x$post.se, digits), "BFs"=round(x$BFs, digits), "pphs"=round(x$pphs, digits))) } # summarise multiple studies #' @rdname summary.PPH #' @method summary EV summary.EV <- function(x, digits=4){ return(round(x$pphs, digits)) } #' @rdname summary.PPH #' @method print EV print.EV <- function(x, digits=4){ return(list("post.b"=round(x$post.b, digits), "post.se"=round(x$post.se, digits), "pphs"=round(x$pphs, digits))) }
/scratch/gouwar.j/cran-all/cranData/BayesCombo/R/summary.R
#' @title Utility functions #' #' @description Not called directly by user. #' #' @param beta Effect size. #' @param se.beta Standard error of the effect. #' @param beta0 Prior for the effect size. #' @param se0 Prior standard error. #' @param ci A numeric value that is used to calculate the prior standard error. #' # posterior mean (standard Bayesian updating for normal conjugate prior) calc.post.beta <- function(beta, se.beta, beta0, se0){ ((beta/se.beta^2) + (beta0/se0^2)) / ((1/se.beta^2) + (1/se0^2)) } #' @rdname calc.post.beta # Posterior variance calc.post.se <- function(se.beta, se0){ sqrt(1 / ((1/se.beta^2) + (1/se0^2)) ) } #' @rdname calc.post.beta # Prior variance prior.se <- function(beta, se.beta, ci) { if (!is.numeric(beta)) stop("beta is not numeric") if (!is.numeric(se.beta)) stop("se.beta is not numeric") # multiplier for confidence intervals ci <- (ci / 100) ci <- ci + (1 - ci) / 2 multiplier <- qnorm(ci) data <- matrix(NA, ncol = 2, nrow = length(beta)) # get min/max data[, 1:2] <- beta + c(-se.beta, se.beta) * multiplier bounds <- abs(data) se0 <- apply(bounds, 1, max) se0 <- ( (se0 / multiplier)) return(se0) }
/scratch/gouwar.j/cran-all/cranData/BayesCombo/R/utils.R
## ---- echo = FALSE, include=FALSE---------------------------------------- library(knitr) opts_chunk$set(fig.align='center') ## ----setup, echo = FALSE, warning= FALSE, message=FALSE------------------ library(BayesCombo) ## ---- echo=FALSE, out.width='90%', fig.cap='Five steps to get from a prior to a posterior probability of a hypothesis. The effect size is the parameter $\\theta$, and `H<`, `H0`, and `H>` represent the three hypotheses of negative, zero, and positive effects.'---- knitr::include_graphics("procedure.pdf") ## ---- fig.height=4, fig.width=4, fig.cap='Effect of fluoxetine (Prozac) on rats in the Forced Swim Test. Data are from Lazic [4]'---- library(labstats) par(las=1) plot(time.immob ~ dose, data=fluoxetine, col="royalblue", ylab="Time immobile (s)", ylim=c(0, 250), xlim=c(0, 250), xlab="Dose of fluoxetine (mg/L in drinking water)") abline(lm(time.immob ~ dose, data=fluoxetine), col="royalblue") # add reg. line ## ------------------------------------------------------------------------ summary(lm(time.immob ~ dose, data=fluoxetine))$coef ## ---- echo=FALSE, fig.height=6.5, fig.width=3, fig.cap='Prior, Likelihood (data), and posterior distributions for an experiment. Bayes factors for the three hypotheses are calculated as the ratio of posterior to prior areas or heights.'---- # x-values for plotting xx <- seq(-5,5, length.out = 401) # observed data (beta=0.75, se=1)... aka likelihood obs <- dnorm(xx, 0.75, 1) # prior distribution (se is for a 99% CI) up <- dnorm(xx, 0, 1.29) # posterior (standard Bayesian updating for normal conjugate prior) post.b <- ((0.75/1^2) + (0/1.29^2)) / ((1/1^2) + (1/1.29^2)) post.se <- sqrt(1/((1/1^2) + (1/1.29^2))) # posterior distribution post <- dnorm(xx, post.b, post.se) par(mfrow=c(3,1), mar=c(4,3,1,2), las=0) # prior plot(up ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Prior", side=4, line=1) polygon(c(xx[1:201],0), c(up[1:201],0), border="darkgrey", col="lightgrey", lwd=1.5) polygon(c(xx[201:400],0), c(up[201:400],0), border="royalblue", col="#348ABD", lwd=1.5) points(up[201] ~ xx[201], pch=16) text(x=-1, y=0.1, labels = "a", cex=1.25) text(x=0, y=0.35, labels = "b", cex=1.25) text(x=1, y=0.1, labels = "c", cex=1.25) # likelihood plot(obs ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Likelihood", side=4, line=1) # posterior plot(post ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Posterior", side=4, line=1) polygon(c(xx[1:201],0), c(post[1:201],0), border="darkgrey", col="lightgrey") polygon(c(xx[201:400],0), c(post[201:400],0), border="royalblue", col="#348ABD") points(post[201] ~ xx[201], pch=16) text(x=-1+0.47, y=0.1, labels = "d", cex=1.25) text(x=0, y=0.48, labels = "e", cex=1.25) text(x=1, y=0.1, labels = "f", cex=1.25) mtext("Effect size", side=1, line=2.5) ## ------------------------------------------------------------------------ x <- pph(beta = -0.252, se.beta = 0.099) summary(x) ## ---- fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data.'---- par(las=1) plot(x, leg.loc = "topright", xlab="Effect size (slope of regression line)") ## ---- fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data. Same as Fig. 4 but with a wider prior.'---- x2 <- pph(beta = -0.252, se.beta = 0.099, se.mult = 2) summary(x2) par(las=1) plot(x2, leg.loc = "topright", xlab="Effect size (slope of regression line)") ## ---- fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data. Same as Fig. 4 but with alternative options specified.'---- x3 <- pph(beta = -0.252, se.beta = 0.099, beta0=0, se0=1.2, H0 = c(-0.05, 0.05), H.priors=c(0.495, 0.495, 0.01)) summary(x3) par(las=1) plot(x3, leg.loc = "topright", xlab="Effect size (slope of regression line)") ## ------------------------------------------------------------------------ x4 <- ev.combo(beta = c(2.3, 1.2, 0.2, 0.44), se.beta = c(1.03, 0.75, 0.16, 0.28)) ## ----fig.height=4, fig.width=4, fig.cap='Forest plot showing effect sizes for four hypothetical clinical studies. Positive effect sizes indicate an improvement and grey lines are the priors.'---- par(las=1) forestplot(x4) abline(v=0, lty=2) ## ----summaryPPH---------------------------------------------------------- summary(x4) ## ----out.width='50%', fig.height=5, fig.width=5, fig.cap='Accumulation of support for the `H>` hypothesis as studies are added. PPH = Posterior Probability of a Hypothesis.'---- par(las=1) plot(x4, ylab="PPH", xlab="Study") ## ----out.width='90%', fig.height=5, fig.width=8, fig.cap='Posterior Probabilities for each hypothesis for four studies. Each graph shows the same information and only groups the hypothesis and studies differently.'---- par(mfrow=c(1,2)) dotchart(x4$pph.uniform, xlim=c(0,1), xlab="PPH", pch=21, bg="grey") dotchart(t(x4$pph.uniform), xlim=c(0,1), xlab="PPH", pch=21, bg="grey")
/scratch/gouwar.j/cran-all/cranData/BayesCombo/inst/doc/BayesCombo_vignette.R
--- title: "BayesCombo: A Quick Guide" author: "Bruno Contrino & Stanley E. Lazic" date: "25 Jan 2017" output: rmarkdown::html_vignette: toc: true number_sections: FALSE vignette: > %\VignetteIndexEntry{BayesCombo} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo = FALSE, include=FALSE} library(knitr) opts_chunk$set(fig.align='center') ``` ```{r setup, echo = FALSE, warning= FALSE, message=FALSE} library(BayesCombo) ``` # Introduction Scientists often evaluate theories or draw conclusions by informally combining results from several experiments. The experiments and the measured outcomes are usually diverse &#8211; making a meta-analyses inappropriate &#8211; and scientists therefore typically use the number of significant p-values to support their conclusion. P-values, however, are a poor way of integrating results, and since statistical power is often low, "conflicting results" are common. Informal methods of evaluating a series of experiments makes inefficient use of the data and can lead to incorrect conclusions and poor decisions. Here we show how to combine diverse evidence across experiments using Bayes factors [1,2], based on a method developed by Kuiper et al. [3]. The procedure is outlined in Figure 1 and consists of the following five steps: 1. Before seeing the data, specify the prior probability of three hypotheses: that the effect is less than zero, greater than zero, and exactly zero. An equal probability of 1/3 is usually appropriate for these exhaustive and mutually exclusive hypotheses. These probabilities will be updated after observing the data. (It is also possible to have a range of values around zero instead of a point value of exactly zero, and the null hypothesis could be a value other than zero; we will ignore these details for now.) 1. Specify a prior distribution for the effect size (ES). The ES depends on the research question and could be a difference between means, the slope of a regression line, or an odds ratio. The `BayesCombo` package calculates a sensible default prior if none is specified. 1. Calculate the effect size and standard error (SE) from an experiment, which can be obtained from output of a standard statistical analysis. 1. Calculate the Bayes factor (BF) for each hypothesis, which represents the evidence for a hypothesis after seeing the data, relative to the probability of a hypothesis before seeing the data. The BFs are calculated by the `BayesCombo` package as a ratio of posterior to prior distributions over a defined range of parameter values. 1. Update the prior probability for each hypothesis with the Bayes factors to give the posterior probability for each hypothesis. For the next experiment, use these updated probabilities to replace those defined in Step 1 and go through steps 2--5 again. Repeat for all experiments that you want to include. Let's work through an example. # Posterior probability for a single experiment ```{r, echo=FALSE, out.width='90%', fig.cap='Five steps to get from a prior to a posterior probability of a hypothesis. The effect size is the parameter $\\theta$, and `H<`, `H0`, and `H>` represent the three hypotheses of negative, zero, and positive effects.'} knitr::include_graphics("procedure.pdf") ``` ## Step 1: Specify priors for hypotheses We have an experiment where 20 rats were randomised to one of four doses of the antidepressant fluoxetine, given in the drinking water. The time that the rats spent immobile in the Forced Swim Test (FST) was recorded. The FST is a standard behavioural test of "depression" in rodents. First, we specify the prior probability of three hypotheses: that fluoxetine increases (`H>`), decreases (`H<`), or has no effect (`H0`) on immobility time. These three hypotheses are exhaustive (include all possible outcomes) and mutually exclusive (only one can be true). Although fluoxetine is known to decrease immobility time, we will specify an equality probability of 1/3 for each hypothesis to illustrate the approach. ## Step 2: Specify a prior for the effect size Next, we need to specify a prior for the effect size (we define the effect size in the Step 3). For now we will use the default prior, which is calculated from the data. It is a normal prior, centred at zero, with the width calculated such that the 99% confidence interval (CI) of the prior matches the 99% CI of the data distribution. The results can be sensitive to the choice of prior, especially if the width is large relative to the data. The default prior is suitable for most situations where you have no prior information to include, and the results are insensitive to small changes near the default value (see below). ## Step 3: Calculate effect size and standard error The data for this example are in the `labstats` package (available on CRAN) and plotted in Figure 2. To calculate the effect size (and the prior in the previous step) we need to define the analysis. Here, dose is treated as a continuous variable (see reference [5]) and so a linear regression quantifies the relationship between fluoxetine and immobility time. No effect corresponds to a flat line (slope = 0) in Figure 2. ```{r, fig.height=4, fig.width=4, fig.cap='Effect of fluoxetine (Prozac) on rats in the Forced Swim Test. Data are from Lazic [4]'} library(labstats) par(las=1) plot(time.immob ~ dose, data=fluoxetine, col="royalblue", ylab="Time immobile (s)", ylim=c(0, 250), xlim=c(0, 250), xlab="Dose of fluoxetine (mg/L in drinking water)") abline(lm(time.immob ~ dose, data=fluoxetine), col="royalblue") # add reg. line ``` The code below calculates the effect size and standard error. These are the required inputs to calculate the posterior probabilities and are returned from `lm()`, `glm()`, and related functions (e.g. from ANOVAs, t-tests, or regressions with Gaussian, Poisson, or binomial outcomes). ```{r} summary(lm(time.immob ~ dose, data=fluoxetine))$coef ``` From the above output we see that the estimated slope is -0.252, with a standard error of 0.099, and a p-value of 0.020. We now have all the information to calculate the probability that fluoxetine increases, decreases, or has no effect on immobility time.[^1] [^1]: A potential source of confusion: We use normal or Gaussian distributions to represent likelihoods and priors, and normal distributions are defined by a mean and standard deviation. A standard error reflects the uncertainty (or precision) of an estimate, which we get from the output of a standard statistical analysis. Thus, we can say that "the estimated slope is -0.252 with a __standard error__ of 0.099". We can also say that we will represent our uncertainty in the slope as a "normal distribution with a mean of -0.252 a __standard deviation__ of 0.099". Here we are saying that a standard error and standard deviation are the same value, which is not usually true. We can do this because we are using the output of one analysis as the input into another one. Later in the code you will see the likelihood defined as `beta = -0.252` and `se.beta = 0.099`. Similarly, the prior for the effect size is defined as `beta0` and `se0`. But both `se.beta` and `se0` are the standard deviations of normal distributions (e.g. as in Fig. 4). This confusion in terminology arises because we are taking the output from a frequentist analysis and using it as input into a Bayesian analysis. To keep things simple, we have used `se` in the code when referring to this quantity. ## Step 4: Calculate Bayes factors Bayes factors are used as an intermediate step in calculating the posterior probabilities of each hypothesis. The functions in the `BayesCombo` package calculate these automatically, but we take a brief digression from the fluoxetine example to illustrate how they are calculated to provide some insight into the method. Figure 3 shows a standard Bayesian updating of a prior distribution to a posterior distribution based on the data (likelihood). The prior in the top panel is normal with a mean of zero and standard deviation of 1.29. The middle panel shows the data (likelihood) distribution, which has a mean of 0.75 and standard deviation of 1. The bottom panel shows the posterior, which is shifted to positive values relative to the prior and reflects the influence of the data. The prior and likelihood correspond to steps 2 and 3 in Figure 1. The BFs for the three hypotheses are then calculated as the ratio of posterior to prior areas or heights of the distributions: $$ BF_{H<0} = \dfrac{\mathrm{area~of~d}}{\mathrm{area~of~a}} $$ $$ BF_{H=0} = \dfrac{\mathrm{height~of~point~e}}{\mathrm{height~of~point~b}} $$ $$ BF_{H>0} = \dfrac{\mathrm{area~of~f}}{\mathrm{area~of~c}} $$ For example, 50% of the prior distribution is above 0 (region c), as is 72% of the posterior (region f). The interpretation is that the data have increased the plausibility of hypothesis H> from 50% to 72%. The ratio of these values is the Bayes factor and is equal to 0.72/0.5 = 1.4. Thus, we can say that H> is 1.4 times more likely. More generally, a BF > 1 means that the data support a hypothesis, whereas a BF < 1 means that data do not support a hypothesis. ```{r, echo=FALSE, fig.height=6.5, fig.width=3, fig.cap='Prior, Likelihood (data), and posterior distributions for an experiment. Bayes factors for the three hypotheses are calculated as the ratio of posterior to prior areas or heights.'} # x-values for plotting xx <- seq(-5,5, length.out = 401) # observed data (beta=0.75, se=1)... aka likelihood obs <- dnorm(xx, 0.75, 1) # prior distribution (se is for a 99% CI) up <- dnorm(xx, 0, 1.29) # posterior (standard Bayesian updating for normal conjugate prior) post.b <- ((0.75/1^2) + (0/1.29^2)) / ((1/1^2) + (1/1.29^2)) post.se <- sqrt(1/((1/1^2) + (1/1.29^2))) # posterior distribution post <- dnorm(xx, post.b, post.se) par(mfrow=c(3,1), mar=c(4,3,1,2), las=0) # prior plot(up ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Prior", side=4, line=1) polygon(c(xx[1:201],0), c(up[1:201],0), border="darkgrey", col="lightgrey", lwd=1.5) polygon(c(xx[201:400],0), c(up[201:400],0), border="royalblue", col="#348ABD", lwd=1.5) points(up[201] ~ xx[201], pch=16) text(x=-1, y=0.1, labels = "a", cex=1.25) text(x=0, y=0.35, labels = "b", cex=1.25) text(x=1, y=0.1, labels = "c", cex=1.25) # likelihood plot(obs ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Likelihood", side=4, line=1) # posterior plot(post ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Posterior", side=4, line=1) polygon(c(xx[1:201],0), c(post[1:201],0), border="darkgrey", col="lightgrey") polygon(c(xx[201:400],0), c(post[201:400],0), border="royalblue", col="#348ABD") points(post[201] ~ xx[201], pch=16) text(x=-1+0.47, y=0.1, labels = "d", cex=1.25) text(x=0, y=0.48, labels = "e", cex=1.25) text(x=1, y=0.1, labels = "f", cex=1.25) mtext("Effect size", side=1, line=2.5) ``` ## Step 5: Use the BFs to update the prior probability of each hypothesis The final step is to update the prior probability for each hypothesis with the BFs to get the posterior probability for each hypothesis. The equation below shows the calculation for the hypothesis that the effect is greater than zero (H>), and other probabilities are calculated in the same way, just substituting other BFs in the numerator. $Pr()$ are the prior probabilities for each hypothesis, and they cancel out from the equation when they are all equal (e.g. if they are all 1/3). $$ P(H>) = \dfrac{Pr(H>)BF_{H>}}{Pr(H<)BF_{H<} + Pr(H0)BF_{H0} + Pr(H>)BF_{H>}}$$ All of the above steps can be conveniently calculated using the `pph()` function (Posterior Probability of a Hypothesis). Returning to the fluoxetine example, we can calculate the probability that the slope is negative, positive, or zero. Below, we specify the slope (`beta = -0.252`) and its standard error (`se.beta = 0.099`) that we obtained previously from the output of the `lm()` function. The default settings are used for all other options. The output below shows that the probability of a negative slope (`H<`) is 0.9120, a positive slope (`H>`) is 0.0106, and a zero slope (`H0`, corresponding to no effect) is 0.0774. Unlike a p-value, which is the probability of the data given a hypothesis, these probabilities have a direct and intuitive interpretation as the probability of a hypothesis given the data. ```{r} x <- pph(beta = -0.252, se.beta = 0.099) summary(x) ``` Plotting the output of the `pph()` function returns the likelihood, prior, and posterior distributions (Fig. 4). The mean of the likelihood (data distribution; dotted line) is centred on -0.252 and the standard error (0.099) determines the width of this distribution. The prior (thick grey line) was automatically calculated and we can see how it encompasses the likelihood distribution and is centred at zero. The posterior distribution (thin black line) represents the combination of prior and likelihood. The BFs and posterior probabilities of the three hypotheses are then calculated from these prior and posterior distributions (analogous to the distributions in Fig. 3). ```{r, fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data.'} par(las=1) plot(x, leg.loc = "topright", xlab="Effect size (slope of regression line)") ``` The above default prior may be more informative than desired (note how the posterior is pulled towards the prior in Fig. 4) and the easiest way to decrease the influence of the prior is to make it wider by specifying a multiplier. The code below doubles the previous standard error (`se.mult = 2`), and the posterior is now much closer to the data distribution (Fig. 5). However, the posterior hypothesis probabilities are similar to the previous analysis; rounded to two decimal places, the probability that the slope is negative is still 0.91. ```{r, fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data. Same as Fig. 4 but with a wider prior.'} x2 <- pph(beta = -0.252, se.beta = 0.099, se.mult = 2) summary(x2) par(las=1) plot(x2, leg.loc = "topright", xlab="Effect size (slope of regression line)") ``` A final example illustrates other options. The prior for the slope is directly specified as having a mean of 0 (`beta0 = 0`) and standard error of 1.2 (`se0 = 1.2`). In the previous analyses H0 was defined as exactly equal to 0, but here we define H0 as a range of values close to zero using `H0 = c(-0.05, 0.05)`. Finally, the priors on the hypotheses are also given as an argument to `H.priors`. The values indicate that the prior probability of the slope being negative, zero, and positive are 0.495, 0.495, 0.01, respectively. The interpretation is that we expect that fluoxetine either decreases immobility time or has no effect, but it is unlikely to increase immobility time. ```{r, fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data. Same as Fig. 4 but with alternative options specified.'} x3 <- pph(beta = -0.252, se.beta = 0.099, beta0=0, se0=1.2, H0 = c(-0.05, 0.05), H.priors=c(0.495, 0.495, 0.01)) summary(x3) par(las=1) plot(x3, leg.loc = "topright", xlab="Effect size (slope of regression line)") ``` With these options, the probability that fluoxetine decreases immobility time is now 0.98, and the distributions are shown in Figure 6. # Posterior probability for multiple experiments We can use the above procedure to sequentially combine results from multiple experiments, where the posterior probabilities for hypotheses from one experiment are used as the prior probabilities for the next experiment. It is the analysts responsibility to ensure that the experiments are testing the same overall hypothesis or theory. In addition, the direction of the effects should be aligned; for example, if a positive effect size in one experiment is interpreted as supporting a theory, but a negative effect size in another experiment also supports the theory, then the negative effect should be multiplied by -1 to change its sign. The `ev.combo()` function combines results and only requires effect sizes (`beta`) and standard errors (`se.beta`) from two or more experiments as input. The default prior mean (`beta0 = 0`) is suitable for most analyses, as is the equal prior hypothesis probabilities (`H.priors = c(1/3, 1/3, 1/3)`) for each hypothesis. In the example below, assume we have four clinical trials where positive effect sizes indicate a beneficial effect of a treatment. ```{r} x4 <- ev.combo(beta = c(2.3, 1.2, 0.2, 0.44), se.beta = c(1.03, 0.75, 0.16, 0.28)) ``` The `forestplot()` function makes a graph resembling a traditional forest plot (Fig. 7), with the observed effect sizes and their 99% CI (black lines). The automatically calculated priors for the effect sizes are also plotted (grey lines). All four experiments have positive effect sizes but only the first experiment is significant at the usual 0.05 level, and a simple "vote counting" suggests that the treatment is ineffective, despite the three non-significant studies being in the predicted direction. ```{r fig.height=4, fig.width=4, fig.cap='Forest plot showing effect sizes for four hypothetical clinical studies. Positive effect sizes indicate an improvement and grey lines are the priors.'} par(las=1) forestplot(x4) abline(v=0, lty=2) ``` The results summary below shows how the support for the three hypotheses changes as each experiment is added. The first line in the output contains the prior hypothesis probability of 1/3 or 33%. When the first experiment is included (second row) the probability that the effect size is greater than zero (`H>`) increases to 85%. As more experiments are included, the probability increases further to 98%, and the null has only 1.7% support. ```{r summaryPPH} summary(x4) ``` It is easier to see how these probabilities change as experiments are added with a graph (Fig. 8). ```{r out.width='50%', fig.height=5, fig.width=5, fig.cap='Accumulation of support for the `H>` hypothesis as studies are added. PPH = Posterior Probability of a Hypothesis.'} par(las=1) plot(x4, ylab="PPH", xlab="Study") ``` In addition to seeing how the probabilities of hypotheses change as experiments are added, we can also plot the evidence for each experiment. This is equivalent to analysing each experiment separately with the `pph()` function, and the results are shown in Fig. 9. Both graphs plot the same data; the left graph group the studies by hypothesis, while the right graph groups the hypotheses by study. It is easy to see in the left graph that the `H>` hypothesis has the most support (above 0.5) for all four experiments. ```{r out.width='90%', fig.height=5, fig.width=8, fig.cap='Posterior Probabilities for each hypothesis for four studies. Each graph shows the same information and only groups the hypothesis and studies differently.'} par(mfrow=c(1,2)) dotchart(x4$pph.uniform, xlim=c(0,1), xlab="PPH", pch=21, bg="grey") dotchart(t(x4$pph.uniform), xlim=c(0,1), xlab="PPH", pch=21, bg="grey") ``` # References 1. Wagenmakers E-J, Lodewyckx T, Kuriyal H, Grasman R (2010). Bayesian hypothesis testing for psychologists: A tutorial on the Savage-Dickey method. _Cognitive Psychology_ 60: 158-189. 1. Wetzels R, Grasman RP, Wagenmakers E-J (2010). An encompassing prior generalization of the Savage-Dickey density ratio. _Computational Statistics and Data Analysis_ 54: 2094-2102. 1. Kuiper RM, Buskens V, Raub W, Hoijtink H (2012). Combining statistical evidence from several studies: A method using Bayesian updating and an example from research on trust problems in social and economic exchange. _Sociological Methods and Research_ 42(1): 60-81. 1. Lazic SE (2008). Why we should use simpler models if the data allow this: relevance for ANOVA designs in experimental biology. _BMC Physiology_ 8:16. 1. Lazic SE (2016). _Experimental Design for Laboratory Biologists: Maximising Information and Improving Reproducibility_. Cambridge University Press: Cambridge, UK
/scratch/gouwar.j/cran-all/cranData/BayesCombo/inst/doc/BayesCombo_vignette.Rmd
--- title: "BayesCombo: A Quick Guide" author: "Bruno Contrino & Stanley E. Lazic" date: "25 Jan 2017" output: rmarkdown::html_vignette: toc: true number_sections: FALSE vignette: > %\VignetteIndexEntry{BayesCombo} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo = FALSE, include=FALSE} library(knitr) opts_chunk$set(fig.align='center') ``` ```{r setup, echo = FALSE, warning= FALSE, message=FALSE} library(BayesCombo) ``` # Introduction Scientists often evaluate theories or draw conclusions by informally combining results from several experiments. The experiments and the measured outcomes are usually diverse &#8211; making a meta-analyses inappropriate &#8211; and scientists therefore typically use the number of significant p-values to support their conclusion. P-values, however, are a poor way of integrating results, and since statistical power is often low, "conflicting results" are common. Informal methods of evaluating a series of experiments makes inefficient use of the data and can lead to incorrect conclusions and poor decisions. Here we show how to combine diverse evidence across experiments using Bayes factors [1,2], based on a method developed by Kuiper et al. [3]. The procedure is outlined in Figure 1 and consists of the following five steps: 1. Before seeing the data, specify the prior probability of three hypotheses: that the effect is less than zero, greater than zero, and exactly zero. An equal probability of 1/3 is usually appropriate for these exhaustive and mutually exclusive hypotheses. These probabilities will be updated after observing the data. (It is also possible to have a range of values around zero instead of a point value of exactly zero, and the null hypothesis could be a value other than zero; we will ignore these details for now.) 1. Specify a prior distribution for the effect size (ES). The ES depends on the research question and could be a difference between means, the slope of a regression line, or an odds ratio. The `BayesCombo` package calculates a sensible default prior if none is specified. 1. Calculate the effect size and standard error (SE) from an experiment, which can be obtained from output of a standard statistical analysis. 1. Calculate the Bayes factor (BF) for each hypothesis, which represents the evidence for a hypothesis after seeing the data, relative to the probability of a hypothesis before seeing the data. The BFs are calculated by the `BayesCombo` package as a ratio of posterior to prior distributions over a defined range of parameter values. 1. Update the prior probability for each hypothesis with the Bayes factors to give the posterior probability for each hypothesis. For the next experiment, use these updated probabilities to replace those defined in Step 1 and go through steps 2--5 again. Repeat for all experiments that you want to include. Let's work through an example. # Posterior probability for a single experiment ```{r, echo=FALSE, out.width='90%', fig.cap='Five steps to get from a prior to a posterior probability of a hypothesis. The effect size is the parameter $\\theta$, and `H<`, `H0`, and `H>` represent the three hypotheses of negative, zero, and positive effects.'} knitr::include_graphics("procedure.pdf") ``` ## Step 1: Specify priors for hypotheses We have an experiment where 20 rats were randomised to one of four doses of the antidepressant fluoxetine, given in the drinking water. The time that the rats spent immobile in the Forced Swim Test (FST) was recorded. The FST is a standard behavioural test of "depression" in rodents. First, we specify the prior probability of three hypotheses: that fluoxetine increases (`H>`), decreases (`H<`), or has no effect (`H0`) on immobility time. These three hypotheses are exhaustive (include all possible outcomes) and mutually exclusive (only one can be true). Although fluoxetine is known to decrease immobility time, we will specify an equality probability of 1/3 for each hypothesis to illustrate the approach. ## Step 2: Specify a prior for the effect size Next, we need to specify a prior for the effect size (we define the effect size in the Step 3). For now we will use the default prior, which is calculated from the data. It is a normal prior, centred at zero, with the width calculated such that the 99% confidence interval (CI) of the prior matches the 99% CI of the data distribution. The results can be sensitive to the choice of prior, especially if the width is large relative to the data. The default prior is suitable for most situations where you have no prior information to include, and the results are insensitive to small changes near the default value (see below). ## Step 3: Calculate effect size and standard error The data for this example are in the `labstats` package (available on CRAN) and plotted in Figure 2. To calculate the effect size (and the prior in the previous step) we need to define the analysis. Here, dose is treated as a continuous variable (see reference [5]) and so a linear regression quantifies the relationship between fluoxetine and immobility time. No effect corresponds to a flat line (slope = 0) in Figure 2. ```{r, fig.height=4, fig.width=4, fig.cap='Effect of fluoxetine (Prozac) on rats in the Forced Swim Test. Data are from Lazic [4]'} library(labstats) par(las=1) plot(time.immob ~ dose, data=fluoxetine, col="royalblue", ylab="Time immobile (s)", ylim=c(0, 250), xlim=c(0, 250), xlab="Dose of fluoxetine (mg/L in drinking water)") abline(lm(time.immob ~ dose, data=fluoxetine), col="royalblue") # add reg. line ``` The code below calculates the effect size and standard error. These are the required inputs to calculate the posterior probabilities and are returned from `lm()`, `glm()`, and related functions (e.g. from ANOVAs, t-tests, or regressions with Gaussian, Poisson, or binomial outcomes). ```{r} summary(lm(time.immob ~ dose, data=fluoxetine))$coef ``` From the above output we see that the estimated slope is -0.252, with a standard error of 0.099, and a p-value of 0.020. We now have all the information to calculate the probability that fluoxetine increases, decreases, or has no effect on immobility time.[^1] [^1]: A potential source of confusion: We use normal or Gaussian distributions to represent likelihoods and priors, and normal distributions are defined by a mean and standard deviation. A standard error reflects the uncertainty (or precision) of an estimate, which we get from the output of a standard statistical analysis. Thus, we can say that "the estimated slope is -0.252 with a __standard error__ of 0.099". We can also say that we will represent our uncertainty in the slope as a "normal distribution with a mean of -0.252 a __standard deviation__ of 0.099". Here we are saying that a standard error and standard deviation are the same value, which is not usually true. We can do this because we are using the output of one analysis as the input into another one. Later in the code you will see the likelihood defined as `beta = -0.252` and `se.beta = 0.099`. Similarly, the prior for the effect size is defined as `beta0` and `se0`. But both `se.beta` and `se0` are the standard deviations of normal distributions (e.g. as in Fig. 4). This confusion in terminology arises because we are taking the output from a frequentist analysis and using it as input into a Bayesian analysis. To keep things simple, we have used `se` in the code when referring to this quantity. ## Step 4: Calculate Bayes factors Bayes factors are used as an intermediate step in calculating the posterior probabilities of each hypothesis. The functions in the `BayesCombo` package calculate these automatically, but we take a brief digression from the fluoxetine example to illustrate how they are calculated to provide some insight into the method. Figure 3 shows a standard Bayesian updating of a prior distribution to a posterior distribution based on the data (likelihood). The prior in the top panel is normal with a mean of zero and standard deviation of 1.29. The middle panel shows the data (likelihood) distribution, which has a mean of 0.75 and standard deviation of 1. The bottom panel shows the posterior, which is shifted to positive values relative to the prior and reflects the influence of the data. The prior and likelihood correspond to steps 2 and 3 in Figure 1. The BFs for the three hypotheses are then calculated as the ratio of posterior to prior areas or heights of the distributions: $$ BF_{H<0} = \dfrac{\mathrm{area~of~d}}{\mathrm{area~of~a}} $$ $$ BF_{H=0} = \dfrac{\mathrm{height~of~point~e}}{\mathrm{height~of~point~b}} $$ $$ BF_{H>0} = \dfrac{\mathrm{area~of~f}}{\mathrm{area~of~c}} $$ For example, 50% of the prior distribution is above 0 (region c), as is 72% of the posterior (region f). The interpretation is that the data have increased the plausibility of hypothesis H> from 50% to 72%. The ratio of these values is the Bayes factor and is equal to 0.72/0.5 = 1.4. Thus, we can say that H> is 1.4 times more likely. More generally, a BF > 1 means that the data support a hypothesis, whereas a BF < 1 means that data do not support a hypothesis. ```{r, echo=FALSE, fig.height=6.5, fig.width=3, fig.cap='Prior, Likelihood (data), and posterior distributions for an experiment. Bayes factors for the three hypotheses are calculated as the ratio of posterior to prior areas or heights.'} # x-values for plotting xx <- seq(-5,5, length.out = 401) # observed data (beta=0.75, se=1)... aka likelihood obs <- dnorm(xx, 0.75, 1) # prior distribution (se is for a 99% CI) up <- dnorm(xx, 0, 1.29) # posterior (standard Bayesian updating for normal conjugate prior) post.b <- ((0.75/1^2) + (0/1.29^2)) / ((1/1^2) + (1/1.29^2)) post.se <- sqrt(1/((1/1^2) + (1/1.29^2))) # posterior distribution post <- dnorm(xx, post.b, post.se) par(mfrow=c(3,1), mar=c(4,3,1,2), las=0) # prior plot(up ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Prior", side=4, line=1) polygon(c(xx[1:201],0), c(up[1:201],0), border="darkgrey", col="lightgrey", lwd=1.5) polygon(c(xx[201:400],0), c(up[201:400],0), border="royalblue", col="#348ABD", lwd=1.5) points(up[201] ~ xx[201], pch=16) text(x=-1, y=0.1, labels = "a", cex=1.25) text(x=0, y=0.35, labels = "b", cex=1.25) text(x=1, y=0.1, labels = "c", cex=1.25) # likelihood plot(obs ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Likelihood", side=4, line=1) # posterior plot(post ~ xx, type="l", ylim=c(0, 0.5), xlab="", yaxt="n") mtext("Posterior", side=4, line=1) polygon(c(xx[1:201],0), c(post[1:201],0), border="darkgrey", col="lightgrey") polygon(c(xx[201:400],0), c(post[201:400],0), border="royalblue", col="#348ABD") points(post[201] ~ xx[201], pch=16) text(x=-1+0.47, y=0.1, labels = "d", cex=1.25) text(x=0, y=0.48, labels = "e", cex=1.25) text(x=1, y=0.1, labels = "f", cex=1.25) mtext("Effect size", side=1, line=2.5) ``` ## Step 5: Use the BFs to update the prior probability of each hypothesis The final step is to update the prior probability for each hypothesis with the BFs to get the posterior probability for each hypothesis. The equation below shows the calculation for the hypothesis that the effect is greater than zero (H>), and other probabilities are calculated in the same way, just substituting other BFs in the numerator. $Pr()$ are the prior probabilities for each hypothesis, and they cancel out from the equation when they are all equal (e.g. if they are all 1/3). $$ P(H>) = \dfrac{Pr(H>)BF_{H>}}{Pr(H<)BF_{H<} + Pr(H0)BF_{H0} + Pr(H>)BF_{H>}}$$ All of the above steps can be conveniently calculated using the `pph()` function (Posterior Probability of a Hypothesis). Returning to the fluoxetine example, we can calculate the probability that the slope is negative, positive, or zero. Below, we specify the slope (`beta = -0.252`) and its standard error (`se.beta = 0.099`) that we obtained previously from the output of the `lm()` function. The default settings are used for all other options. The output below shows that the probability of a negative slope (`H<`) is 0.9120, a positive slope (`H>`) is 0.0106, and a zero slope (`H0`, corresponding to no effect) is 0.0774. Unlike a p-value, which is the probability of the data given a hypothesis, these probabilities have a direct and intuitive interpretation as the probability of a hypothesis given the data. ```{r} x <- pph(beta = -0.252, se.beta = 0.099) summary(x) ``` Plotting the output of the `pph()` function returns the likelihood, prior, and posterior distributions (Fig. 4). The mean of the likelihood (data distribution; dotted line) is centred on -0.252 and the standard error (0.099) determines the width of this distribution. The prior (thick grey line) was automatically calculated and we can see how it encompasses the likelihood distribution and is centred at zero. The posterior distribution (thin black line) represents the combination of prior and likelihood. The BFs and posterior probabilities of the three hypotheses are then calculated from these prior and posterior distributions (analogous to the distributions in Fig. 3). ```{r, fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data.'} par(las=1) plot(x, leg.loc = "topright", xlab="Effect size (slope of regression line)") ``` The above default prior may be more informative than desired (note how the posterior is pulled towards the prior in Fig. 4) and the easiest way to decrease the influence of the prior is to make it wider by specifying a multiplier. The code below doubles the previous standard error (`se.mult = 2`), and the posterior is now much closer to the data distribution (Fig. 5). However, the posterior hypothesis probabilities are similar to the previous analysis; rounded to two decimal places, the probability that the slope is negative is still 0.91. ```{r, fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data. Same as Fig. 4 but with a wider prior.'} x2 <- pph(beta = -0.252, se.beta = 0.099, se.mult = 2) summary(x2) par(las=1) plot(x2, leg.loc = "topright", xlab="Effect size (slope of regression line)") ``` A final example illustrates other options. The prior for the slope is directly specified as having a mean of 0 (`beta0 = 0`) and standard error of 1.2 (`se0 = 1.2`). In the previous analyses H0 was defined as exactly equal to 0, but here we define H0 as a range of values close to zero using `H0 = c(-0.05, 0.05)`. Finally, the priors on the hypotheses are also given as an argument to `H.priors`. The values indicate that the prior probability of the slope being negative, zero, and positive are 0.495, 0.495, 0.01, respectively. The interpretation is that we expect that fluoxetine either decreases immobility time or has no effect, but it is unlikely to increase immobility time. ```{r, fig.height=4.5, fig.width=4.5, fig.cap='Prior, likelihood (data), and posterior distributions for the fluoxetine data. Same as Fig. 4 but with alternative options specified.'} x3 <- pph(beta = -0.252, se.beta = 0.099, beta0=0, se0=1.2, H0 = c(-0.05, 0.05), H.priors=c(0.495, 0.495, 0.01)) summary(x3) par(las=1) plot(x3, leg.loc = "topright", xlab="Effect size (slope of regression line)") ``` With these options, the probability that fluoxetine decreases immobility time is now 0.98, and the distributions are shown in Figure 6. # Posterior probability for multiple experiments We can use the above procedure to sequentially combine results from multiple experiments, where the posterior probabilities for hypotheses from one experiment are used as the prior probabilities for the next experiment. It is the analysts responsibility to ensure that the experiments are testing the same overall hypothesis or theory. In addition, the direction of the effects should be aligned; for example, if a positive effect size in one experiment is interpreted as supporting a theory, but a negative effect size in another experiment also supports the theory, then the negative effect should be multiplied by -1 to change its sign. The `ev.combo()` function combines results and only requires effect sizes (`beta`) and standard errors (`se.beta`) from two or more experiments as input. The default prior mean (`beta0 = 0`) is suitable for most analyses, as is the equal prior hypothesis probabilities (`H.priors = c(1/3, 1/3, 1/3)`) for each hypothesis. In the example below, assume we have four clinical trials where positive effect sizes indicate a beneficial effect of a treatment. ```{r} x4 <- ev.combo(beta = c(2.3, 1.2, 0.2, 0.44), se.beta = c(1.03, 0.75, 0.16, 0.28)) ``` The `forestplot()` function makes a graph resembling a traditional forest plot (Fig. 7), with the observed effect sizes and their 99% CI (black lines). The automatically calculated priors for the effect sizes are also plotted (grey lines). All four experiments have positive effect sizes but only the first experiment is significant at the usual 0.05 level, and a simple "vote counting" suggests that the treatment is ineffective, despite the three non-significant studies being in the predicted direction. ```{r fig.height=4, fig.width=4, fig.cap='Forest plot showing effect sizes for four hypothetical clinical studies. Positive effect sizes indicate an improvement and grey lines are the priors.'} par(las=1) forestplot(x4) abline(v=0, lty=2) ``` The results summary below shows how the support for the three hypotheses changes as each experiment is added. The first line in the output contains the prior hypothesis probability of 1/3 or 33%. When the first experiment is included (second row) the probability that the effect size is greater than zero (`H>`) increases to 85%. As more experiments are included, the probability increases further to 98%, and the null has only 1.7% support. ```{r summaryPPH} summary(x4) ``` It is easier to see how these probabilities change as experiments are added with a graph (Fig. 8). ```{r out.width='50%', fig.height=5, fig.width=5, fig.cap='Accumulation of support for the `H>` hypothesis as studies are added. PPH = Posterior Probability of a Hypothesis.'} par(las=1) plot(x4, ylab="PPH", xlab="Study") ``` In addition to seeing how the probabilities of hypotheses change as experiments are added, we can also plot the evidence for each experiment. This is equivalent to analysing each experiment separately with the `pph()` function, and the results are shown in Fig. 9. Both graphs plot the same data; the left graph group the studies by hypothesis, while the right graph groups the hypotheses by study. It is easy to see in the left graph that the `H>` hypothesis has the most support (above 0.5) for all four experiments. ```{r out.width='90%', fig.height=5, fig.width=8, fig.cap='Posterior Probabilities for each hypothesis for four studies. Each graph shows the same information and only groups the hypothesis and studies differently.'} par(mfrow=c(1,2)) dotchart(x4$pph.uniform, xlim=c(0,1), xlab="PPH", pch=21, bg="grey") dotchart(t(x4$pph.uniform), xlim=c(0,1), xlab="PPH", pch=21, bg="grey") ``` # References 1. Wagenmakers E-J, Lodewyckx T, Kuriyal H, Grasman R (2010). Bayesian hypothesis testing for psychologists: A tutorial on the Savage-Dickey method. _Cognitive Psychology_ 60: 158-189. 1. Wetzels R, Grasman RP, Wagenmakers E-J (2010). An encompassing prior generalization of the Savage-Dickey density ratio. _Computational Statistics and Data Analysis_ 54: 2094-2102. 1. Kuiper RM, Buskens V, Raub W, Hoijtink H (2012). Combining statistical evidence from several studies: A method using Bayesian updating and an example from research on trust problems in social and economic exchange. _Sociological Methods and Research_ 42(1): 60-81. 1. Lazic SE (2008). Why we should use simpler models if the data allow this: relevance for ANOVA designs in experimental biology. _BMC Physiology_ 8:16. 1. Lazic SE (2016). _Experimental Design for Laboratory Biologists: Maximising Information and Improving Reproducibility_. Cambridge University Press: Cambridge, UK
/scratch/gouwar.j/cran-all/cranData/BayesCombo/vignettes/BayesCombo_vignette.Rmd
BC <- function(Y, X = NULL, model = 'null', covlist = NULL, condition = NULL, its = 100, ...) { if (!is.matrix(Y)) { stop("Y must be a matrix") } if (!(is.null(X) | is.matrix(X))) { stop("X must be a matrix or null") } n <- nrow(Y) nsp <- ncol(Y) Xname <- colnames(X) if (model %in% c('null', 'environment', 'community', 'full')) { if (model == 'null') { X <- matrix(1, n, 1) updateR <- F covlist <- NULL } else if (model == 'environment') { X <- cbind(rep(1, n), X) updateR <- F } else if (model == 'community') { X <- matrix(1, n, 1) updateR <- T covlist <- NULL } else if (model == 'full') { X <- cbind(rep(1, n), X) updateR <- T } } else { stop ("model must be one of: 'null', 'environment', 'community' or 'full'") } k <- ncol(X) # matrix column names if (is.matrix(X) & is.null(Xname)) { colnames(X) <- paste("cov", 0:(k-1), sep = "") } colnames(X)[1] <- "intercept" if(is.null(colnames(Y))) { colnames(Y) <- paste("sp", 1:ncol(Y), sep = "") } # covariate list if (is.null(covlist)) { # if null, add them all for (i in 1:nsp) { covlist[i] <- list(1:k) } } else { if (!is.list(covlist)) { stop("covlist must be a list or null") } # otherwise add the intercept to the list covlist <- lapply(covlist, function(x) c(1, x+1) ) } if (max(unlist(lapply(covlist, length))) > k) { stop ("too many elements in covlist") } if (max(unlist(lapply(covlist, max))) > k) { stop ("covlist index out of range of covariates") } if (!is.null(condition)) { if(!is.matrix(condition)){ stop("condition must be a matrix or null") } if (is.null(colnames(condition))){ colnames(condition) <- paste("cond", 1:ncol(condition), sep = ".") } # add them to X and adjust the covariate list ind <- (ncol(X)+1):(ncol(X) + ncol(condition)) X <- cbind(X, condition) covlist <- lapply(covlist, function(x) c(x, ind)) } # initialise mu at species prevalence mu <- qnorm(rowMeans(t(Y))) mu <- matrix(rep(mu, n), n, nsp, byrow = TRUE) # initialise z - just on the right side of 0 trunc <- find_trunc(mu, t(Y)) e <- matrix(0, n, nsp) e <- ifelse(trunc[, , 1] == -Inf, trunc[, , 2] - 1, trunc[, , 1] + 1) e <- sample_e(e, trunc, diag(nsp)) z <- mu + e # initialise R W <- cov(e) if (!updateR) W <- diag(nsp) R <- cov2cor(W) reslis <- BCfit(Y, X, covlist, R, z, mu, updateR, its, ...) res <- NULL res$trace <- list(R = reslis$R, B = reslis$B, z = reslis$z) res$call <- list(model = model, Y = Y, X = X, covlist = covlist, its = its, start = reslis$burn + 1, thin = reslis$thin) res$other <- list(mu = reslis$mu) class(res) <- "bayescomm" res }
/scratch/gouwar.j/cran-all/cranData/BayesComm/R/BC.R
BCfit <- function(y, X, covlist, R, z, mu, updateR, iters, thin = 1, burn = 0, priW = c(nrow(z) + 2 * ncol(z), 2 * ncol(z)), verbose = 0) { spnames <- colnames(y) y <- t(y) # NOTE: y is transposed relative to the input! nsp <- dim(y)[1] # number of species n <- dim(y)[2] # number of sites iR <- solve(R) # Inverse correlation matrix e <- z - mu # component of z that can't be explained by mu nsamp <- (iters - burn) %/% thin # Dave asks: Should mu be in the output as well? It wasn't before, but that # may have been an oversight. # Nick: It's not needed since it's just X %*% B, we could # store it for convenience but I doubt it's worth the memory used output <- list( R = array(NA, dim = c(nsamp, ((nsp * nsp - nsp) / 2))), B = NULL, z = array(NA, dim = c(nsamp, n, nsp)), burn = burn, thin = thin ) for (i in 1:nsp) { temp <- matrix(NA, nsamp, length(covlist[[i]])) colnames(temp) <- colnames(X)[covlist[[i]]] output$B[[spnames[i]]] <- temp } rm(temp) nam <- rep(NA, n * n) for (i in 1:nsp) { for (j in 1:nsp) { nam[(i - 1) * nsp + j] <- paste(spnames[i], "_", spnames[j], sep="") } } colnames(output$R) <- nam[which(upper.tri(diag(nsp)))] dimnames(output$z)[[3]] <- spnames # start sampler rec <- 0 # counter for record number after burn-in and thinning start <- Sys.time() for (iter in 1:iters) { # get truncation values and sample z trunc <- find_trunc(mu, y) e <- sample_e(e, trunc, iR) z <- mu + e # sample mu and calculate e mulis<- sample_mu(z, X, covlist) mu <- mulis[[1]] e <- z - mu # sample R if (updateR) { R <- sample_R(z - mu, priW) iR <- chol2inv(chol(R)) } if(verbose == 2){ message(iter) } if(verbose > 0 & iter == burn){ message("burn-in complete") } # record parameters if (iter %% thin == 0 & iter > burn) { if(verbose == 1){ message(iter) } rec <- rec + 1 output$R[rec, ] <- R[upper.tri(R)] output$z[rec, , ] <- z for (i in 1:nsp) { output$B[[i]][rec, ] <- mulis[[2]][[i]] } } } # sampler output }
/scratch/gouwar.j/cran-all/cranData/BayesComm/R/BCfit.R
DIC <- function (BC) { # make this a Z <- BC$trace$z Y <- BC$call$Y # calculate D_hat zhat <- apply(Z, c(2, 3), mean) # posterior mean of z p <- pnorm(zhat, log.p = TRUE) ind <- which(!Y) p[ind] <- log(-expm1(p[ind])) Dhat <- -2 * sum(p) # calculate D_bar p <- pnorm(Z, log.p = TRUE) for(j in 1:ncol(Y)) { ind <- which(!Y[, j]) p[, ind, j] <- log(-expm1(p[, ind, j])) } Dbar <- mean(-2 * apply(p, 1, sum)) # return DIC 2 * sum(Dbar) - Dhat }
/scratch/gouwar.j/cran-all/cranData/BayesComm/R/DIC.R