code
stringlengths 1
13.8M
|
---|
apexGameValue<-function(S,n,apexPlayer){
paramCheckResult=getEmptyParamCheckResult()
stopOnInvalidCoalitionS(paramCheckResult,S, n=n)
stopOnInvalidNumberOfPlayers(paramCheckResult,n)
stopOnInvalidNumber(paramCheckResult,apexPlayer)
logicapexGameValue(S,n,apexPlayer)
}
apexGameVector<-function(n,apexPlayer){
bitMatrix = createBitMatrix(n)[,1:n];
A<-c()
i<-1
end<-((2^n)-1)
while(i<=end){
currCoal<-which(bitMatrix[i,]&1)
A[i] = apexGameValue(S=currCoal,n=n,apexPlayer=apexPlayer)
i<-i+1
}
return(A)
}
logicapexGameValue<-function(S,n,apexPlayer){
S<-sort(S)
retVal<-0
if((apexPlayer %in% S) && (length(S) > 1)){
return (1)
}
N<-c(1:n)
setWithoutApex<-N[-(which(N == apexPlayer))]
if(identical(as.numeric(S), as.numeric(setWithoutApex))){
return (1)
}
return(retVal)
}
apexGame<-function(n,apexPlayer){
v = apexGameVector(n=n,apexPlayer=apexPlayer)
retapexGame=list(n=n,apexPlayer=apexPlayer,v=v)
return(retapexGame)
}
|
pmax0 <- function(x){(x + abs(x))/2}
apply_bfun <- function(bfun, p, fun = c("bfun", "b1fun")){
k <- attr(bfun, "k")
n <- length(p)
if(inherits(bfun, "slp.basis")){
pp <- matrix(, n, k + 1)
pp[,1] <- 1; pp[,2] <- p
if(k > 1){for(j in 2:k){pp[,j + 1] <- pp[,j]*p}}
if(fun == "bfun"){out <- tcrossprod(pp, t(bfun$a))}
else{out <- cbind(0, tcrossprod(pp[,1:k, drop = FALSE], t(bfun$a1[-1,-1, drop = FALSE])))}
if(!attr(bfun, "intB")){out <- out[,-1, drop = FALSE]}
}
else{
out <- matrix(,n,k)
if(fun == "bfun"){for(j in 1:k){out[,j] <- bfun[[j]](p)}}
else{for(j in 1:k){out[,j] <- bfun[[j]](p, deriv = 1)}}
}
out
}
p.bisec <- function(theta, y,X, bfun, n.it = 20){
n <- length(y); k <- ncol(theta)
bp <- attr(bfun, "bp")
p <- attr(bfun, "p")
Xtheta <- tcrossprod(X, t(theta))
eta <- tcrossprod(Xtheta,bp[512,, drop = FALSE])
m <- as.integer(512 + sign(y - eta)*256)
for(i in 3:10){
eta <- .rowSums(Xtheta*bp[m,, drop = FALSE], n, k)
m <- m + as.integer(sign(y - eta)*(2^(10 - i)))
}
m <- p[m]
for(i in 11:n.it){
bp <- apply_bfun(bfun, m, "bfun")
delta.m <- y - .rowSums(Xtheta*bp, n,k)
m <- m + sign(delta.m)/2^i
}
m <- c(m)
out.l <- which(m == 1/2^n.it)
out.r <- which(m == 1 - 1/2^n.it)
m[out.l] <- 0; m[out.r] <- 1
attr(m, "out") <- c(out.l, out.r)
attr(m, "out.r") <- out.r
m
}
p.bisec.internal <- function(theta, y,X,bp){
n <- length(y); k <- ncol(theta)
Xtheta <- tcrossprod(X, t(theta))
eta <- tcrossprod(Xtheta,bp[512,, drop = FALSE])
m <- as.integer(512 + sign(y - eta)*256)
for(i in 3:10){
eta <- .rowSums(Xtheta*bp[m,, drop = FALSE], n, k)
m <- m + as.integer(sign(y - eta)*(2^(10 - i)))
}
out.l <- which(m == 1)
out.r <- which(m == 1023)
attr(m, "out") <- c(out.l, out.r)
attr(m, "out.r") <- out.r
m
}
make.bfun <- function(p,x){
n <- length(x)
x1 <- x[1:(n-1)]
x2 <- x[2:n]
if(all(x1 < x2) | all(x1 > x2)){method <- "hyman"}
else{method <- "fmm"}
splinefun(p,x, method = method)
}
num.fun <- function(dx,fx, op = c("int", "der")){
n <- length(dx) + 1
k <- ncol(fx)
fL <- fx[1:(n-1),, drop = FALSE]
fR <- fx[2:n,, drop = FALSE]
if(op == "int"){out <- apply(rbind(0, 0.5*dx*(fL + fR)),2,cumsum)}
else{
out <- (fR - fL)/dx
out <- rbind(out[1,],out)
}
out
}
extract.p <- function(model,p, cov = FALSE){
theta <- model$coefficients
v <- model$covar
q <- nrow(theta)
k <- ncol(theta)
bfun <- attr(model$mf, "bfun")
pred.p <- apply_bfun(bfun, p, "bfun")
beta <- c(pred.p%*%t(theta))
cov.beta <- matrix(NA,q,q)
for(j1 in 1:q){
w1 <- seq.int(j1,q*k,q)
for(j2 in j1:q){
w2 <- seq.int(j2,q*k,q)
cc <- v[w1,w2, drop = FALSE]
cov.beta[j1,j2] <- cov.beta[j2,j1] <- pred.p%*%cc%*%t(pred.p)
}
}
se <- sqrt(diag(cov.beta))
z <- beta/se
out <- cbind(beta, se, z, 2*pnorm(-abs(z)))
colnames(out) <- c("Estimate", "std.err", "z value", "p(>|z|))")
rownames(out) <- colnames(cov.beta) <- rownames(cov.beta) <- rownames(theta)
if(cov){list(coef = out, cov = cov.beta)}
else{list(coef = out)}
}
pred.beta <- function(model, p, se = FALSE){
if(se){
Beta <- NULL
SE <- NULL
for(j in p){
b <- extract.p(model,j)$coef
Beta <- rbind(Beta, b[,1])
SE <- rbind(SE, b[,2])
}
out <- list()
for(j in 1:ncol(Beta)){
low <- Beta[,j] - 1.96*SE[,j]
up <- Beta[,j] + 1.96*SE[,j]
out[[j]] <- data.frame(p = p, beta = Beta[,j], se = SE[,j], low = low, up = up)
}
names(out) <- rownames(model$coefficients)
return(out)
}
else{
theta <- model$coefficients
beta <- apply_bfun(attr(model$mf, "bfun"), p, "bfun")%*%t(theta)
out <- list()
for(j in 1:nrow(theta)){out[[j]] <- data.frame(p = p, beta = beta[,j])}
names(out) <- rownames(theta)
return(out)
}
}
iqr.waldtest <- function(obj){
bfun <- attr(obj$mf, "bfun")
ax <- attr(obj$mf, "assign")
ap <- attr(bfun, "assign")
theta <- obj$coefficients
q <- nrow(theta)
k <- ncol(theta)
s <- obj$s
cc <- obj$covar
ind.x <- rep(ax,k)
ind.p <- sort(rep.int(ap,q))
K <- tapply(rowSums(s), ax, sum)
Q <- tapply(colSums(s), ap, sum)
testx <- testp <- NULL
if(q > 1){
for(i in unique(ax)){
theta0 <- c(theta[which(ax == i),])
w <- which(ind.x == i)
c0 <- cc[w,w, drop = FALSE]
theta0 <- theta0[theta0 != 0]
w <- which(rowSums(c0) != 0)
c0 <- c0[w,w, drop = FALSE]
if(length(theta0) == 0){tx <- NA}
else{tx <- t(theta0)%*%chol2inv(chol(c0))%*%t(t(theta0))}
testx <- c(testx, tx)
}
testx <- cbind(testx, df = K, pchisq(testx, df = K, lower.tail = FALSE))
colnames(testx) <- c("chi-square", "df", "P(> chi)")
nx <- attr(attr(obj$mf, "terms"), "term.labels")
if(attr(attr(obj$mf, "terms"), "intercept") == 1){nx <- c("(Intercept)", nx)}
rownames(testx) <- nx
}
if(k > 1){
for(i in unique(ap)){
theta0 <- c(theta[,which(ap == i)])
w <- which(ind.p == i)
c0 <- cc[w,w, drop = FALSE]
theta0 <- theta0[theta0 != 0]
w <- which(rowSums(c0) != 0)
c0 <- c0[w,w, drop = FALSE]
if(length(theta0) == 0){tp <- NA}
else{tp <- t(theta0)%*%chol2inv(chol(c0))%*%t(t(theta0))}
testp <- c(testp, tp)
}
testp <- cbind(testp, df = Q, pchisq(testp, df = Q, lower.tail = FALSE))
colnames(testp) <- c("chi-square", "df", "P(> chi)")
np <- attr(bfun, "term.labels")
if(any(ap == 0)){np <- c("(Intercept)", np)}
rownames(testp) <- np
}
list(test.x = testx, test.p = testp)
}
test.fit <- function (object, ...){UseMethod("test.fit")}
check.out <- function(theta, S, covar){
blockdiag <- function(A, d, type = 1){
h <- nrow(A); g <- d/h
if(type == 1){
out <- diag(1,d)
for(j in 1:g){ind <- (j*h - h + 1):(j*h); out[ind,ind] <- A}
}
else{
out <- matrix(0,d,d)
for(i1 in 1:h){
for(i2 in 1:h){
ind1 <- (i1*g - g + 1):(i1*g)
ind2 <- (i2*g - g + 1):(i2*g)
out[ind1, ind2] <- diag(A[i1,i2],g)
}
}
out <- t(out)
}
out
}
mydiag <- function(x){
if(length(x) > 1){return(diag(x))}
else{matrix(x,1,1)}
}
th <- cbind(c(theta))
q <- nrow(theta)
k <- ncol(theta)
g <- q*k
aX <- S$X; ay <- S$y; aB <- S$B
cX <- aX$const; cB <- aB$const
A <- blockdiag(mydiag(1/aX$S), g)
th <- A%*%th
covar <- A%*%covar%*%t(A)
if(aX$intercept){
A <- diag(1,q); A[cX,] <- -aX$M; A[cX, cX] <- 1
A <- blockdiag(A,g)
th <- A%*%th
covar <- A%*%covar%*%t(A)
}
A <- blockdiag(mydiag(1/aB$S),g,2)
th <- A%*%th
covar <- A%*%covar%*%t(A)
if(aB$intercept){
A <- diag(1,k); A[,cB] <- -aB$M; A[cB, cB] <- 1
A <- blockdiag(A,g,2)
th <- A%*%th
covar <- A%*%covar%*%t(A)
}
A <- blockdiag(aX$rot,g)
th <- A%*%th
covar <- A%*%covar%*%t(A)
A <- blockdiag(t(aB$rot),g,2)
th <- A%*%th
covar <- A%*%covar%*%t(A)
A <- blockdiag(mydiag(1/aX$s),g)
th <- A%*%th
covar <- A%*%covar%*%t(A)
if(aX$intercept){
A <- diag(1,q); A[cX,] <- -aX$m/aX$s[cX]; A[cX, cX] <- 1
A <- blockdiag(A,g)
th <- A%*%th
covar <- A%*%covar%*%t(A)
}
A <- blockdiag(mydiag(1/aB$s),g,2)
th <- A%*%th
covar <- A%*%covar%*%t(A)
if(aB$intercept){
A <- diag(1,k); A[,cB] <- -aB$m/aB$s[cB]; A[cB, cB] <- 1
A <- blockdiag(A,g,2)
th <- A%*%th
covar <- A%*%covar%*%t(A)
}
v <- (ay$M - ay$m)/10
th <- th*v
covar <- covar*(v^2)
theta <- matrix(th,q,k)
theta[cX,cB] <- theta[cX,cB] + ay$m/aB$s[cB]/aX$s[cX]
list(theta = theta, covar = covar)
}
safesolve <- function(A,B, lambda){
if(any(eigen(A)$values <= 0)){stop("A is not definite positive")}
n <- nrow(A)
lambda <- seq(lambda,0,length = 20)
for(i in 1:length(lambda)){
X <- A - lambda[i]*B
inv <- try(chol2inv(chol(X)), silent = TRUE)
if(!inherits(inv, "try-error")){break}
}
list(X = X, inv = inv, lambda = lambda[i], warn = (i > 1))
}
maxind <- function(A){
w <- which.max(A)
n <- nrow(A)
m <- ncol(A)
row <- w %% n
if(row == 0){row <- n}
col <- floor(w/n) + (row < n)
c(row, col)
}
|
draw_posterior.dfmodel <- function(object, FUN = NULL, mc.cores = NULL, ...){
only_one_model <- FALSE
if ("data" %in% names(object)) {
object <- list(object)
only_one_model <- TRUE
}
cat("Estimating models...\n")
if (is.null(mc.cores)) {
object <- lapply(object, .posterior_dfmodel, use = FUN)
} else {
object <- parallel::mclapply(object, .posterior_dfmodel, use = FUN,
mc.cores = mc.cores, mc.preschedule = FALSE)
}
if (only_one_model) {
object <- object[[1]]
} else {
class(object) <- append("bvarlist", class(object))
}
return(object)
}
.posterior_dfmodel <- function(object, use) {
if (is.null(use)) {
object <- try(dfmpost(object))
} else {
object <- try(use(object))
}
if (inherits(object, "try-error")) {
object <- c(object, list(coefficients = NULL))
}
return(object)
}
|
GSAtool <- function(parameters_set, out_set, pp_names, steps = 100, save=FALSE, dir=NULL){
data_Bstat <- Bstat(out_set)
CM <- Cond_Moments(parameters_set, out_set , pp_names, steps = steps)
SOBOL_indices <- SOBOL(data_var = data_Bstat[,3], CM_mean = CM$CM_mean, CM_var = CM$CM_var, pp_names = pp_names)
AMA_indices <- AMA(data_Bstat , CM, pp_names, steps = steps)
if (save==TRUE){
(save_results(SOBOL = SOBOL_indices[[1]], amae = AMA_indices$AMAE, amav = AMA_indices$AMAV,
amar = AMA_indices$AMAR, amak = AMA_indices$AMAK, dir=dir))
}
GSA <- list(SOBOL_indices, AMA_indices)
return(GSA)
}
|
genera_strippr <- function(tree, tax_frame){
if (!inherits(tree, "phylo")){
stop("tree must be of class 'phylo'")
}
if (! is.data.frame(tax_frame)){
tax_frame <- as.data.frame(tax_frame)
}
if (ncol(tax_frame) == 2){
names(tax_frame) <- c("taxon", "age")
} else if (ncol(tax_frame) == 1) {
names(tax_frame) <- "taxon"
}
else {
stop("Taxon frame must be a dataframe containing, at minimum, a column labeled taxon, which contains the total set of taxa both on the tree and to be added.")
}
total_set <- unname(unlist(lapply(tax_frame["taxon"], as.character)))
(absent <- unlist(total_set[which(!total_set %in% tree$tip.label)]))
return(absent)
}
|
mergeVote <- function(x, vote, Office="House", vote.x,
check.x=TRUE){
nameOfx <- deparse(substitute(x))
nameOfVote <- deparse(substitute(vote))
nx <- nrow(x)
nv <- nrow(vote)
nmx <- names(x)
nmv <- names(vote)
votey <- grep('vote', nmv, value=TRUE)
if(length(votey)<1)
stop('No vote column found in the vote data.frame = ',
deparse(substitute(vote)))
if(missing(vote.x)){
vote.x <- grep('vote', names(x), value=TRUE)
if(length(vote.x)<1)vote.x <- votey
}
if(!(vote.x %in% names(x)))
x[, vote.x] <- rep('notEligible', nx)
if(!('Office' %in% nmv))
vote <- cbind(vote, Office=Office)
lnmx <- tolower(nmx)
lnmv <- tolower(nmv)
surnmx <- nmx[grep('surname', lnmx)]
surnmv <- nmv[grep('surname', lnmv)]
givenx <- nmx[grep('givenname', lnmx)]
givenv <- nmv[grep('givenname', lnmv)]
stx <- nmx[grep('state', lnmx)]
stv <- nmv[grep('state', lnmv)]
distx <- nmx[grep('district', lnmx)]
distv <- nmv[grep('district', lnmv)]
keyx <- paste(x$Office, x[[surnmx]], sep=":")
keyv <- paste(vote$Office, vote[[surnmv]], sep=":")
keyx2 <- paste(keyx, x[[givenx]], sep=":")
keyv2 <- paste(keyv, vote[[givenv]], sep=':')
keyx. <- paste(x$Office, x[[stx]], x[[distx]], sep=":")
keyv. <- paste(vote$Office, vote[[stv]], vote[[distv]], sep=":")
vote.notFound <- integer(0)
voteFound <- rep(0, nv)
for(iv in 1:nv){
jv <- which(keyx == keyv[iv])
if(length(jv)<1){
jv <- which(keyx. == keyv.[iv])
if(length(jv)!=1)
vote.notFound <- c(vote.notFound, iv)
}
if(length(jv)>1){
jv <- which(keyx2 == keyv2[iv])
if(length(jv)!=1)
jv <- which(keyx.==keyv.[iv])
if(length(jv)!=1){
vote.notFound <- c(vote.notFound, iv)
}
}
if(length(jv)==1) {
x[jv, vote.x] <- as.character(vote[iv, votey])
voteFound[iv] <- jv
}
}
if(check.x){
Votex <- which(x[, vote.x] != 'notEligible')
oops <- which(!(Votex %in% voteFound))
if(length(oops)>0){
print(x[oops,])
stop('People found voting in x = ', nameOfx[1],
'\n not found in the data.frame vote = ',
nameOfVote[1],
'\n look for and fix the error(s) printed above.')
}
}
x[, vote.x] <- factor(x[, vote.x])
if((no <- length(vote.notFound))>0){
cat(no, 'rows of vote not found:\n')
print(vote[vote.notFound,] )
stop('Unable to find vote in x')
}
x
}
|
densratio.appe <-
function(xtrain, xtest, method="uLSIF", sigma=NULL, lambda=NULL, kernel_num=NULL, fold=5, stabilize=TRUE, qstb=0.025) {
xtrain = as.matrix(xtrain)
xtest = as.matrix(xtest)
if (is.null(kernel_num)) kernel_num = 100
if (is.null(sigma)) {
center = matrix(xtest[sample(1:nrow(xtest), kernel_num),], kernel_num, ncol(xtest))
sigma = as.array(quantile((dist(center))))
sigma = unique(sigma[ sigma>0.001 ])
}
if (is.null(lambda)) lambda = "auto"
if (method == "uLSIF" || method == "KLIEP") {
wgt = densratio(xtrain, xtest, method, sigma, lambda, kernel_num, fold, verbose=FALSE)$compute_density_ratio(xtest)
} else {
stop("\n\nmethod should be either in ('uLSIF', 'KLIEP').\n\n")
}
if (stabilize) {
vl = quantile(wgt, qstb)
wgt[ wgt < vl ] = vl
vl = quantile(wgt, 1-qstb)
wgt[ wgt > vl ] = vl
}
return(wgt)
}
|
plot_gbm <- function(object=stop("no 'object' argument"),
smooth = c(0, 0, 0, 1),
col = c(1, 2, 3, 4),
ylim = "auto",
legend.x = NULL,
legend.y = NULL,
legend.cex = .8,
grid.col = NA,
n.trees = NA,
col.n.trees ="darkgray",
...)
{
check.classname(object, "object", c("gbm", "GBMFit"))
obj <- object
if((!is.numeric(smooth) && !is.logical(smooth)) ||
any(smooth != 0 & smooth != 1))
stop0("smooth should be a four-element vector specifying if train, ",
"test, CV, and OOB curves are smoothed, e.g. smooth=c(0,0,0,1)")
smooth <- rep_len(smooth, 4)
col <- rep_len(col, 4)
col[is.na(col)] <- 0
check.integer.scalar(n.trees, min=1, max=n.trees,
na.ok=TRUE, logical.ok=FALSE)
n.alltrees = gbm.n.trees(obj)
train.error <- gbm.train.error(obj)
valid.error <- gbm.valid.error(obj)
cv.error <- gbm.cv.error(obj)
final.max <- max(train.error[length(train.error)],
valid.error[length(valid.error)],
cv.error [length(cv.error)],
na.rm=TRUE)
if(any1(col)) {
par <- par("mar", "mgp")
on.exit(par(mar=par$mar, mgp=par$mgp))
init.gbm.plot(obj, ylim, final.max, par$mar, ...)
if(is.specified(grid.col[1]))
grid(col=grid.col[1], lty=3)
if(is.specified(n.trees))
vertical.line(n.trees, col.n.trees, 1, 0)
}
leg.text <- leg.col <- leg.lty <- leg.vert <- leg.imin <- NULL
voffset <- 0
y <- maybe.smooth(train.error, "train", smooth[1], n.alltrees)
imin <- which.min1(y)
imins <- c(imin, 0, 0, 0)
names(imins) <- c("train", "test", "CV", "OOB")
train.fraction <- gbm.train.fraction(obj)
if(is.specified(col[1])) {
lines(y, col=col[1])
leg.text <- c(leg.text,
if(train.fraction == 1) "train"
else sprint("train (frac %g)", train.fraction))
leg.col <- c(leg.col, col[1])
leg.lty <- c(leg.lty, 1)
leg.vert <- c(leg.vert, FALSE)
leg.imin <- imin
}
if(train.fraction != 1) {
y <- maybe.smooth(valid.error, "test", smooth[2], n.alltrees)
imin <- imins[2] <- which.min1(y)
if(is.specified(col[2])) {
if(imin)
vertical.line(imin, col[2], 3, voffset)
voffset <- voffset + 1
lines(y, col=col[2])
leg.text <- c(leg.text,
if(!imin) "test not plotted"
else sprint("test (frac %g)", 1-train.fraction))
leg.col <- c(leg.col, col[2])
leg.lty <- c(leg.lty, 1)
leg.vert <- c(leg.vert, FALSE)
leg.imin <- c(leg.imin, imin)
}
}
if(!is.null(cv.error)) {
y <- maybe.smooth(cv.error, "CV", smooth[3], n.alltrees)
imin <- imins[3] <- which.min1(y)
if(is.specified(col[3])) {
if(imin)
vertical.line(imin, col[3], 3, voffset)
voffset <- voffset + 1
lines(y, col=col[3])
leg.text <- c(leg.text,
if(!imin) "CV not plotted"
else sprint("CV (%g fold)", gbm.cv.folds(obj)))
leg.col <- c(leg.col, col[3])
leg.lty <- c(leg.lty, 1)
leg.vert <- c(leg.vert, FALSE)
leg.imin <- c(leg.imin, imin)
}
}
bag.fraction <- gbm.bag.fraction(obj)
if(bag.fraction != 1) {
oobag.improve <- gbm.oobag.improve(obj)
y <- maybe.smooth(-cumsum(oobag.improve), "OOB", smooth[4], n.alltrees)
imin <- imins[4] <- which.min1(y)
if(is.specified(col[4])) {
if(imin)
draw.oob.curve(y, imin, voffset, col[4], smooth, train.error)
voffset <- voffset + 1
leg.text <- c(leg.text,
if(!imin) "OOB not plotted"
else "OOB (rescaled)")
leg.col <- c(leg.col, col[4])
leg.lty <- c(leg.lty, 2)
leg.vert <- c(leg.vert, FALSE)
leg.imin <- c(leg.imin, imin)
}
}
if(is.specified(n.trees)) {
leg.text <- c(leg.text, "predict n.trees")
leg.col <- c(leg.col, col.n.trees)
leg.lty <- c(leg.lty, 1)
leg.vert <- c(leg.vert, TRUE)
leg.imin <- c(leg.imin, n.trees)
}
if(any1(col)) {
box()
gbm.legend(legend.x, legend.y, legend.cex,
leg.text, leg.col, leg.lty, leg.vert, leg.imin)
gbm.top.labels(leg.imin, leg.text, leg.col)
}
invisible(imins)
}
init.gbm.plot <- function(obj, ylim, final.max, mar, ...)
{
xlim <- dota("xlim", ...)
n.alltrees <- gbm.n.trees(obj)
if(!is.specified(xlim))
xlim <- c(0, n.alltrees)
xlim <- fix.lim(xlim)
ylim <- get.gbm.ylim(obj, xlim, ylim, final.max)
ylab <- get.gbm.ylab(obj)
main <- dota("main", ...)
nlines.needed.for.main <- if(is.specified(main)) nlines(main) + .5 else 0
par(mar=c(mar[1], mar[2], max(mar[3], nlines.needed.for.main + 1), mar[4]))
par(mgp=c(1.5, .4, 0))
train.error <- gbm.train.error(obj)
call.plot(graphics::plot, force.x=1:n.alltrees, force.y=train.error,
force.type="n", force.main="", force.xlim=xlim, def.ylim=ylim,
def.xlab="Number of Trees", def.ylab=ylab, ...)
if(is.specified(main))
mtext(main, side=3, line=1.3, cex=par("cex"))
}
get.gbm.ylim <- function(obj, xlim, ylim, final.max)
{
train.error <- gbm.train.error(obj)
valid.error <- gbm.valid.error(obj)
cv.error <- gbm.cv.error(obj)
if(is.character(ylim) && substr(ylim[1], 1, 1) == "a") {
imin <- max(1, min(1, xlim[1]))
imax <- min(length(train.error), max(length(train.error), xlim[2]))
cv.error <- gbm.cv.error(obj)
ylim <- range(train.error[imin:imax],
valid.error[imin:imax],
cv.error [imin:imax], na.rm=TRUE)
ylim[2] <- ylim[1] + 2 * (final.max - ylim[1])
i <- floor(xlim[1] + .25 * (xlim[2] - xlim[1]))
if(i >= 1 && i <= length(train.error[imin:imax]))
ylim[2] <- max(ylim[2], train.error[i])
} else if(!is.specified(ylim))
ylim <- range(train.error, valid.error, cv.error, na.rm=TRUE)
fix.lim(ylim)
}
get.gbm.ylab <- function(obj)
{
dist <- gbm.short.distribution.name(obj)
if(dist =="pa")
switch(obj$distribution$metric,
conc="Fraction of Concordant Pairs",
ndcg="Normalized Discounted Cumulative Gain",
map ="Mean Average Precision",
mrr ="Mean Reciprocal Rank",
stop0("unrecognized pairwise metric: ",
obj$distribution$metric))
else
switch(dist,
ga="Squared Error Loss",
la="Absolute Loss",
td="t-distribution deviance",
be="Bernoulli Deviance",
hu="Huberized Hinge Loss",
mu="Multinomial Deviance",
ad="Adaboost Exponential Bound",
ex="Exponential Loss",
po="Poisson Deviance",
co="Cox Partial Deviance",
qu="Quantile Loss",
stop0("unrecognized distribution name: ",
obj$distribution.name))
}
vertical.line <- function(x, col=1, lty=1, voffset=0)
{
if(is.specified(col)) {
usr <- par("usr")
range <- usr[4] - usr[3]
lwd <- 1
if(lty == 3) {
lwd <- min(1.5, 2 * par("cex"))
voffset <- 0.008 * voffset * range
} else
voffset <- 0
lines(x=c(x, x), y=c(usr[3], usr[4]) - voffset, col=col, lty=lty, lwd=lwd)
lines(x=c(x, x), y=c(usr[3], usr[3] + .02 * range), col=col, lty=1)
}
}
maybe.smooth <- function(y, yname, must.smooth, n.alltrees)
{
if(any(!is.finite(y))) {
warning0("plot_gbm: cannot plot ", yname,
" curve (it has some non-finite values)")
return(NA)
}
if(must.smooth) {
x <- 1:n.alltrees
if(n.alltrees < 10)
y <- lowess(x, y)$y
else
y <- loess(y~x,
na.action=na.omit,
enp.target=min(max(4, n.alltrees/10), 50))$fitted
}
y
}
which.min1 <- function(x)
{
if(all(is.na(x)))
return(0)
which.min(x)
}
draw.oob.curve <- function(y, imin, voffset, col, smooth, train.error)
{
stopifnot(!is.na(imin))
vertical.line(imin, col, 3, voffset)
usr <- par("usr")
y <- y - min(y)
y <- y / max(y)
e <- train.error
n <- length(e)
y <- e[n] + (e[max(1, 0.1 * n)] - e[n]) * y
lines(1:n, y, col=col, lty=2)
}
gbm.legend <- function(legend.x, legend.y, legend.cex,
leg.text, leg.col, leg.lty, leg.vert, leg.imin)
{
xjust <- 0
usr <- par("usr")
if(is.null(legend.y))
legend.y <- usr[3] + .65 * (usr[4] - usr[3])
if(is.null(legend.x)) {
xjust <- 1
imin <- c(usr[2],
leg.imin[which(leg.imin > usr[1] + .7 * (usr[2]-usr[1]))])
legend.x <- min(imin) - .05 * (usr[2] - usr[1])
legend.y <- usr[4] - .05 * (usr[4] - usr[3])
}
if(is.specified(legend.x))
elegend(x=legend.x, y=legend.y,
legend=leg.text, col=leg.col, lty=leg.lty,
vert=leg.vert,
bg="white", cex=legend.cex, xjust=xjust, yjust=xjust)
}
gbm.top.labels <- function(leg.imin, leg.text, leg.col)
{
stopifnot(substring(leg.text[1], 1, 5) == "train")
leg.col[1] <- 0
leg.col[leg.col == "darkgray"] <- lighten("darkgray", -0.1)
usr <- par("usr")
x <- TeachingDemos::spread.labs(leg.imin,
mindiff=par("cex") * max(strwidth(paste0(leg.imin, " "))),
min=usr[1], max=usr[2])
margin <- .05 * (usr[2] - usr[1])
ok <- (x > usr[1] - margin) & (x < usr[2] + margin) & (leg.imin != 0)
if(any(ok))
text(x=x[ok],
y=usr[4] + .4 * strheight("X"),
labels=leg.imin[ok], col=leg.col[ok],
adj=c(.5, 0),
xpd=NA)
}
|
calc_dig <- function(num, build = FALSE) {
lengths <- stringr::str_length(num)
if (max(lengths) != 18 | min(lengths) != 18) {
stop("Lawsuit IDs without check digits should have 18 numerical digits.")
}
NNNNNNN <- substr(num, 1L, 7L)
AAAA <- substr(num, 8L, 11L)
JTR <- substr(num, 12L, 14L)
OOOO <- substr(num, 15L, 18L)
n1 <- sprintf("%02d", as.numeric(NNNNNNN) %% 97)
n2 <- sprintf("%02d", as.numeric(sprintf("%s%s%s", n1, AAAA, JTR)) %% 97)
n3 <- sprintf("%02d", 98 - ((as.numeric(sprintf("%s%s", n2, OOOO)) * 100) %% 97))
dig <- n3
if (build) {
return(sprintf("%s%s%s", substr(num, 1, 7), dig, substr(num, 8, 18)))
}
return(dig)
}
check_dig <- function(num) {
num <- stringr::str_replace_all(num, "[.-]", "")
if (stringr::str_length(num) != 20) {
warning("Complete docket numbers should have 20 numerical digits.")
return(FALSE)
}
num_no_dig <- stringr::str_c(substr(num, 1L, 7L), substr(num, 10L, 20L))
num_with_dig <- calc_dig(num_no_dig, build = TRUE)
return(identical(num_with_dig, num))
}
check_dig_vet <- function(num) {
purrr::map_lgl(num, abjutils::check_dig)
}
verify_cnj <- function(cnj) {
nprocesso2 <- dplyr::if_else(is.na(cnj), "", clean_cnj(cnj))
resp <- dplyr::case_when(
nprocesso2 == "" ~ "vazio ou NA",
stringr::str_length(clean_cnj(cnj)) > 20 ~ "> 20 digitos",
!check_dig_vet(stringr::str_pad(dplyr::if_else(stringr::str_length(nprocesso2) > 20, stringr::str_sub(nprocesso2, end = 20), nprocesso2), 20, "left", "0")) ~ "dv invalido ou nao-cnj",
T ~ "valido"
)
return(resp)
}
extract_parts <- function(id, parts = "") {
parts <- unique(parts)
if (any(parts == "")) {
parts <- c("N", "D", "A", "J", "T", "O")
}
if (any(!(parts %in% c("N", "D", "A", "J", "T", "O")))) {
stop("Invalid parts")
}
id <- id %>%
clean_id() %>%
purrr::modify_if(~ stringr::str_length(.x) == 18, calc_dig, build = TRUE) %>%
unlist()
get_parts <- function(id, parts) {
out <- c()
for (part in parts) {
range <- switch(part,
"N" = list(1, 7),
"D" = list(8, 9),
"A" = list(10, 13),
"J" = list(14, 14),
"T" = list(15, 16),
"O" = list(17, 20)
)
out <- c(out, purrr::set_names(
stringr::str_sub(id, range[[1]], range[[2]]), part
))
}
return(out)
}
purrr::map(id, get_parts, parts)
}
clean_id <- function(id) {
stringr::str_replace_all(id, pattern = "[\\-\\.]", replacement = "")
}
build_id <- function(id) {
build <- function(id) {
stringr::str_c(
id[1], "-", id[2], ".", id[3], ".",
id[4], ".", id[5], ".", id[6]
)
}
purrr::map_chr(extract_parts(id), build)
}
separate_cnj <- function(data, col, ...) {
tidyr::separate(
data, {{ col }},
into = c("N", "D", "A", "J", "T", "O"), sep = "[\\-\\.]", ...
)
}
pattern_cnj <- function() {
stringr::str_glue(
"[0-9]{{3,7}}-?",
"[0-9]{{2}}\\.?",
"[0-9]{{4}}\\.?",
"[0-9]{{1}}\\.?",
"[0-9]{{2}}\\.?",
"[0-9]{{4}}"
) %>% as.character()
}
clean_cnj <- function(x) {
stringr::str_replace_all(x, "[^0-9]", "")
}
|
na.locf0 <- function(object, fromLast = FALSE, maxgap = Inf, coredata = NULL) {
if(is.null(coredata)) coredata <- inherits(object, "ts") || inherits(object, "zoo") || inherits(object, "its") || inherits(object, "irts")
if(coredata) {
x <- object
object <- if (fromLast) rev(coredata(object)) else coredata(object)
} else {
if(fromLast) object <- rev(object)
}
ok <- which(!is.na(object))
if(is.na(object[1L])) ok <- c(1L, ok)
gaps <- diff(c(ok, length(object) + 1L))
object <- if(any(gaps > maxgap)) {
.fill_short_gaps(object, rep(object[ok], gaps), maxgap = maxgap)
} else {
rep(object[ok], gaps)
}
if (fromLast) object <- rev(object)
if(coredata) {
x[] <- object
return(x)
} else {
return(object)
}
}
na.locf <- function(object, na.rm = TRUE, ...)
UseMethod("na.locf")
na.locf.default <- function(object, na.rm = TRUE, fromLast, rev, maxgap = Inf, rule = 2, ...) {
L <- list(...)
if ("x" %in% names(L) || "xout" %in% names(L)) {
if (!missing(fromLast)) {
stop("fromLast not supported if x or xout is specified")
}
return(na.approx(object, na.rm = na.rm,
maxgap = maxgap, method = "constant", rule = rule, ...))
}
if (!missing(rev)) {
warning("na.locf.default: rev= deprecated. Use fromLast= instead.")
if (missing(fromLast)) fromLast <- rev
} else if (missing(fromLast)) fromLast <- FALSE
rev <- base::rev
object[] <- if (length(dim(object)) == 0)
na.locf0(object, fromLast = fromLast, maxgap = maxgap)
else
apply(object, length(dim(object)), na.locf0, fromLast = fromLast, maxgap = maxgap)
if (na.rm) na.trim(object, is.na = "all") else object
}
na.locf.data.frame <- function(object, na.rm = TRUE, fromLast = FALSE, maxgap = Inf, ...)
{
object[] <- lapply(object, na.locf0, fromLast = fromLast, maxgap = maxgap)
if (na.rm) na.omit(object) else object
}
na.contiguous.data.frame <-
na.contiguous.zoo <- function(object, ...)
{
if (length(dim(object)) == 2)
good <- apply(!is.na(object), 1, all)
else good <- !is.na(object)
if (!sum(good))
stop("all times contain an NA")
tt <- cumsum(!good)
ln <- sapply(0:max(tt), function(i) sum(tt == i))
seg <- (seq_along(ln)[ln == max(ln)])[1] - 1
keep <- (tt == seg)
st <- min(which(keep))
if (!good[st])
st <- st + 1
en <- max(which(keep))
omit <- integer(0)
n <- NROW(object)
if (st > 1)
omit <- c(omit, 1:(st - 1))
if (en < n)
omit <- c(omit, (en + 1):n)
cl <- class(object)
if (length(omit)) {
object <- if (length(dim(object)))
object[st:en, ]
else object[st:en]
attr(omit, "class") <- "omit"
attr(object, "na.action") <- omit
if (!is.null(cl))
class(object) <- cl
}
object
}
na.contiguous.list <- function(object, ...)
lapply(object, na.contiguous)
|
cumsum_mu_synch <- function(motor_unit_1, motor_unit_2, order = 1,
binwidth = 0.001, get_data = T, plot = F) {
recurrence_intervals2 <- function(motor_unit_1, motor_unit_2, order) {
if (!is.vector(motor_unit_1) || !is.vector(motor_unit_2)) {
stop("'motor_unit_1' and 'motor_unit_2' must be vectors.")
}
if (length(motor_unit_1) <= 1 || length(motor_unit_2) <= 1) {
stop ("'motor_unit_1' and 'motor_unit_2' must be vectors of length > 1.")
}
if (is.unsorted(motor_unit_1, strictly = T)
|| is.unsorted(motor_unit_2, strictly = T)) {
stop ("'motor_unit_1' and 'motor_unit_2' must be strictly increasing.")
}
if (!is.numeric(order) || order%%1 != 0) {
stop("Order must be whole number.")
}
if (length(motor_unit_1) < length(motor_unit_2)) {
ref.name <- deparse(substitute(motor_unit_1, env = parent.frame()))
event.name <- deparse(substitute(motor_unit_2, env = parent.frame()))
ref.MU <- motor_unit_1
event.MU <- motor_unit_2
ref.MU.ISI <- diff(motor_unit_1)
event.MU.ISI <- diff(motor_unit_2)
mean.ref.ISI <- round(mean(ref.MU.ISI), digits = 3)
mean.event.ISI <- round(mean(event.MU.ISI), digits = 3)
} else {
ref.name <- deparse(substitute(motor_unit_2, env = parent.frame()))
event.name <- deparse(substitute(motor_unit_1, env = parent.frame()))
ref.MU <- motor_unit_2
event.MU <- motor_unit_1
ref.MU.ISI <- diff(motor_unit_2)
event.MU.ISI <- diff(motor_unit_1)
mean.ref.ISI <- round(mean(ref.MU.ISI), digits = 3)
mean.event.ISI <- round(mean(event.MU.ISI), digits = 3)
}
MU.names <- list(Reference_Unit = ref.name,
Number_of_Reference_Discharges = length(ref.MU),
Reference_ISI = ref.MU.ISI,
Mean_Reference_ISI = mean.ref.ISI,
Event_Unit = event.name,
Number_of_Event_Discharges = length(event.MU),
Event_ISI = event.MU.ISI,
Mean_Event_ISI = mean.event.ISI,
Duration = max(ref.MU, event.MU) - min(ref.MU, event.MU))
lags <- vector('list', order)
for (i in 1:length(ref.MU)) {
pre_diff <- rev(event.MU[event.MU < ref.MU[i]])
pre_diff <- pre_diff[1:order]
pre_diff <- pre_diff - (ref.MU[i])
post_diff <- event.MU[event.MU >= ref.MU[i]]
post_diff <- post_diff[1:order]
post_diff <- post_diff - (ref.MU[i])
for (j in 1:order) {
y <- c(pre_diff[j], post_diff[j])
lags[[j]] <- append(lags[[j]], y)
}
}
lags <- lapply(lags, Filter, f = Negate(is.na))
names(lags) <- paste(1:order)
lags <- append(MU.names, lags)
return(lags)
}
recurrence.data <- recurrence_intervals2(motor_unit_1,
motor_unit_2,
order)
mean.reference.ISI <- recurrence.data$Mean_Reference_ISI
frequency.data <- unlist(recurrence.data[paste(1:order)])
frequency.data <- frequency.data[frequency.data >= -mean.reference.ISI &
frequency.data <= mean.reference.ISI]
frequency.data <- as.vector(frequency.data)
frequency.data <- motoRneuron::bin(frequency.data, binwidth = binwidth)
baseline.mean <- frequency.data[frequency.data$Bin <= ((min(frequency.data$Bin))
+ 0.060) | frequency.data$Bin >=
(max(frequency.data$Bin) - 0.060), ]
baseline.mean <- mean(as.numeric(unlist(baseline.mean["Freq"])))
baseline.sd <- frequency.data[frequency.data$Bin <= ((min(frequency.data$Bin))
+ 0.060) | frequency.data$Bin >=
(max(frequency.data$Bin) - 0.060), ]
baseline.sd <- sd(as.numeric(unlist(baseline.sd["Freq"])))
cumsum <- data.frame(Bin = frequency.data$Bin, Cumsum = cumsum(
as.numeric(frequency.data$Freq) - baseline.mean))
cumsum <- cumsum[cumsum$Bin >= ((min(frequency.data$Bin)) + 0.060) &
cumsum$Bin <= (max(frequency.data$Bin) - 0.060),]
ninety.percent <- min(cumsum$Cumsum) + ((max(cumsum$Cumsum) - min(cumsum$Cumsum)) * 0.9)
ten.percent <- min(cumsum$Cumsum) + ((max(cumsum$Cumsum) - min(cumsum$Cumsum)) * 0.1)
bounds <- vector()
bounds[1] <- cumsum[(which(abs(cumsum$Cumsum - ten.percent)
== min(abs(cumsum$Cumsum - ten.percent)))), 1]
bounds[2] <- cumsum[(which(abs(cumsum$Cumsum - ninety.percent)
== min(abs(cumsum$Cumsum - ninety.percent)))), 1]
if(bounds[1] > bounds[2]) {
old.lower <- bounds[1]
bounds[1] <- bounds[2]
bounds[2] <- old.lower
rm(old.lower)
}
peak <- frequency.data[frequency.data$Bin >= bounds[1] &
frequency.data$Bin <= bounds[2],]
peak <- as.numeric(unlist(peak["Freq"]))
peak.mean <- mean(peak)
peak.zscore <- (peak.mean - baseline.mean) / baseline.sd
if(peak.zscore < 1.96) {
bounds[1] <- -0.005
bounds[2] <- 0.005
peak <- frequency.data[frequency.data$Bin >= bounds[1] &
frequency.data$Bin <= bounds[2],]
peak <- as.numeric(unlist(peak["Freq"]))
peak.mean <- mean(peak)
peak.zscore <- (peak.mean - baseline.mean) / baseline.sd
}
total.peak <- sum(peak)
extra.peak <- sum((peak - baseline.mean)[which((peak - baseline.mean) > 0)])
total.count <- sum(as.numeric(unlist(frequency.data$Freq)))
q <- as.numeric(vector())
for (m in 1:length(peak)) {
if (peak[m] <= baseline.mean) {
q <- c(q, peak[m])
} else {next}
}
expected.peak <- baseline.mean *
(length(which(peak > baseline.mean))) +
sum(q)
Cumsum.Synch <- list()
if (get_data) {
Cumsum.Synch[["Data"]] <- recurrence.data
}
if (plot) {
show(plot_bins(frequency.data))
}
Cumsum.Synch[["Indices"]] <- list(CIS = extra.peak / recurrence.data$Duration,
kprime = (total.peak / expected.peak),
kminus1 = (extra.peak / expected.peak),
E = (extra.peak
/ recurrence.data$Number_of_Reference_Discharges),
S = (extra.peak
/ (recurrence.data$Number_of_Reference_Discharges
+ recurrence.data$Number_of_Event_Discharges)),
SI = (extra.peak / (total.count / 2)),
Peak.duration = bounds[2] - bounds[1],
Peak.center = median(c(bounds[2], bounds[1])))
return(Cumsum.Synch)
}
|
context("Tricky Examples")
test_that("B <- rep(2:4,9)", {
B <- rep(2:4, 9)
golden <-
structure(
c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L),
.Dim = c(3L,
3L),
.Dimnames = structure(list(B = c("2", "3", "4"), c("T1",
"T2", "T3")), .Names = c("B", "draw")),
class = "table"
)
draw <- block_ra(blocks = B, prob_each = rep(1 / 3, 3))
expect_identical(table(B, draw),
golden)
draw <-
block_ra(blocks = B,
prob_each = c(.33, .33, .33) / sum(c(.33, .33, .33)))
expect_identical(table(B, draw),
golden)
expect_error(table(B, block_ra(
blocks = B, prob_each = c(.33, .33, .33)
)))
})
test_that("ABAD", {
B <- c("A", "B", "A", "D")
draw <-
block_ra(blocks = B,
prob_each = c(.33, .33, .33) / sum(c(.33, .33, .33)))
expect_true(all(table(B, draw) %in% 0:2))
})
test_that("ABD", {
B <- c("A", "B", "D")
draw <-
block_ra(blocks = B,
prob_each = c(.33, .33, .33) / sum(c(.33, .33, .33)))
expect_true(all(table(B, draw) %in% 0:1))
B <- c(B, B)
draw <-
block_ra(blocks = B,
prob_each = c(.43, .33, .33) / sum(c(.43, .33, .33)))
expect_true(all(table(B, draw) %in% 0:2))
})
test_that("B=12121", {
B <- c(1, 2, 1, 2, 1)
draw <-
block_ra(blocks = B,
prob_each = c(.33, .33, .33) / sum(c(.33, .33, .33)))
expect_equivalent(as.numeric(table(B, draw)[1, ]),
c(1, 1, 1))
})
test_that("Complete N=16", {
expect_equivalent(as.numeric(table(complete_ra(16))),
c(8, 8))
})
test_that("Complete N=16 p=.25", {
expect_equivalent(as.numeric(table(complete_ra(16, prob = .25))),
c(12, 4))
})
test_that("Complete 16 ABCD", {
draw <-
complete_ra(
16,
prob_each = rep(.25, 4),
conditions = c("T00", "T01", "T10", "T11")
)
expect_true(all(table(draw) == 4))
})
test_that("B=AABB", {
B <- c("A", "A", "B", "B")
expect_true(all(table(B, block_ra(blocks = B)) == 1))
})
test_that("B=1122 ABC", {
B <- c(1, 1, 2, 2)
draw <- block_ra(blocks = B, prob_each = c(.21, .29, .5))
expect_true(all(table(B, draw) %in% 0:1))
})
test_that("B=111222", {
B <- c(1, 1, 1, 2, 2, 2)
draw <- block_ra(blocks = B, prob = .5)
t <- table(B, draw)
expect_equivalent(as.numeric(sort(t[1, ])), 1:2)
expect_equivalent(as.numeric(sort(t[1, ])), 1:2)
})
test_that("B=1112222", {
B <- c(1, 1, 1, 2, 2, 2, 2)
draw <- block_ra(blocks = B, prob = .5)
t <- table(B, draw)
expect_equivalent(as.numeric(sort(t[1, ])), 1:2)
expect_equivalent(as.numeric(t[2, ]), c(2, 2))
})
test_that("B=111222222", {
B <- c(1, 1, 1, 2, 2, 2, 2, 2, 2)
draw <- block_ra(blocks = B, prob_each = c(1 / 3, 1 / 3, 1 / 3))
golden <-
structure(
c(1L, 2L, 1L, 2L, 1L, 2L),
.Dim = 2:3,
.Dimnames = structure(list(
B = c("1", "2"), draw = c("T1", "T2", "T3")
), .Names = c("B",
"draw")),
class = "table"
)
expect_identical(table(B, draw),
golden)
})
test_that("B=111222222344 ABCD", {
B <- c(1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 4, 4)
draw <- block_ra(
blocks = B,
prob_each = c(1 / 6, 1 / 6, 1 / 6, 1 / 2),
conditions = c("A", "B", "C", "D")
)
expect_true(all(table(B, draw)[2, ] >= 1))
})
test_that("balancing with block_prob_each", {
blocks <- rep(c("A", "B", "C"), times = c(51, 103, 207))
block_prob_each <- rbind(c(.3, .6, .1),
c(.2, .7, .1),
c(.1, .8, .1))
draw <- block_ra(blocks, block_prob_each = block_prob_each)
golden <-
structure(
c(15L, 21L, 20L, 31L, 72L, 165L, 5L, 10L, 22L),
.Dim = c(3L,
3L),
.Dimnames = structure(list(
blocks = c("A", "B", "C"),
draw = c("T1",
"T2", "T3")
), .Names = c("blocks", "draw")),
class = "table"
)
expect_true(all (table(blocks, draw) - golden %in% -1:1))
})
test_that("vsample advances rng", {
s1 <- .Random.seed
complete_ra(5)
s2 <- .Random.seed
expect_true(!identical(s1, s2))
})
|
expected <- eval(parse(text="structure(c(1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2), .Dim = 3:4, .Dimnames = list(c(\"Case_1\", \"Case_2\", \"Case_3\"), NULL))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(1:12, .Dim = 3:4, .Dimnames = list(c(\"Case_1\", \"Case_2\", \"Case_3\"), NULL)), 5)"));
do.call(`%%`, argv);
}, o=expected);
|
ps_ouss = function(freq, power_o, sigma, rho, lambda, power_e, epsilon, time_step, series_size){
if(missing(freq)){ stop("Missing freq"); }
if(missing(time_step)){ stop("Missing time_step"); }
if(missing(rho)){
if(missing(lambda)){ stop("Missing rho or lambda"); }
rho = exp(-lambda*time_step);
}else{
lambda = -log(rho)/time_step;
}
N = series_size;
T = time_step*(N-1);
if(missing(sigma)){
if(missing(power_o)){ stop("Missing power_o or sigma"); }
sigma = power_o_to_sigma(power_o, lambda, time_step);
}
if(missing(power_e)){
if(missing(epsilon)){ stop("Missing power_e or epsilon"); }
power_e = time_step * epsilon^2;
}
r = rho*exp(complex(real=0,imaginary=-2*pi*freq*time_step));
q = rho*exp(complex(real=0,imaginary=+2*pi*freq*time_step));
return(power_e + (T/N^2) * sigma^2 * (Re(N * (1/(1-r) + q/(1-q))) - 2*Re(r*(1-r^N)/(1-r)^2)));
}
|
library(nomisr)
context("nomis_content_type")
test_that("nomis_content_type return expected format", {
skip_on_cran()
expect_error(nomis_content_type())
content <- nomis_content_type("sources")
expect_true(nrow(content) == 16)
expect_length(content, 6)
expect_type(content, "list")
expect_true(tibble::is_tibble(content))
content_id <- nomis_content_type("sources", "jsa")
expect_true(nrow(content_id) == 1)
expect_length(content_id, 4)
expect_type(content_id, "list")
expect_true(tibble::is_tibble(content_id))
})
|
yuen1<-function(x,y=NULL,tr=.2,alpha=.05, ...){
if(is.null(y)){
if(is.matrix(x) || is.data.frame(x)){
y=x[,2]
x=x[,1]
}
if(is.list(x)){
y=x[[2]]
x=x[[1]]
}
}
if(tr==.5)stop("Using tr=.5 is not allowed; use a method designed for medians")
if(tr>.25)print("Warning: with tr>.25 type I error control might be poor")
x<-x[!is.na(x)]
y<-y[!is.na(y)]
h1<-length(x)-2*floor(tr*length(x))
h2<-length(y)-2*floor(tr*length(y))
q1<-(length(x)-1)*winvar(x,tr)/(h1*(h1-1))
q2<-(length(y)-1)*winvar(y,tr)/(h2*(h2-1))
df<-(q1+q2)^2/((q1^2/(h1-1))+(q2^2/(h2-1)))
crit<-qt(1-alpha/2,df)
dif<-mean(x,tr)-mean(y,tr)
low<-dif-crit*sqrt(q1+q2)
up<-dif+crit*sqrt(q1+q2)
test<-abs(dif/sqrt(q1+q2))
yuen<-2*(1-pt(test,df))
list(n1=length(x),n2=length(y),est.1=mean(x,tr),est.2=mean(y,tr),ci=c(low,up),p.value=yuen,dif=dif,se=sqrt(q1+q2),teststat=test,alpha = alpha, crit=crit,df=df)
}
|
test_that("flsgen_terrain", {
terrain <- rflsgen::flsgen_terrain(200, 200)
testthat::expect_s4_class(terrain, class = "RasterLayer")
})
|
isSemidefinite <- function( m, ... )
UseMethod( "isSemidefinite" )
isSemidefinite.default <- function( m, ... ) {
stop( "there is currently no default method available" )
}
isSemidefinite.matrix <- function( m, positive = TRUE,
tol = 100 * .Machine$double.eps,
method = ifelse( nrow( m ) < 13, "det", "eigen" ), ... ) {
if( !is.matrix( m ) ) {
stop( "argument 'm' must be a matrix" )
} else {
if( nrow( m ) != ncol( m ) ) {
stop( "argument 'm' or each of its elements must be a _quadratic_ matrix" )
} else if( !isSymmetric( unname( m ), tol = 1000 * tol ) ) {
stop( "argument 'm' must be a symmetric matrix" )
}
m <- ( m + t(m) ) / 2
n <- nrow( m )
if( !positive ) {
m <- -m
}
if( n >= 12 && method == "det" ) {
warning( "using method 'det' can take a very long time",
" for matrices with more than 12 rows and columns;",
" it is suggested to use method 'eigen' for larger matrices",
immediate. = TRUE )
}
if( method == "det" ) {
for( i in 1:n ) {
comb <- combn( n, i )
for( j in 1:ncol( comb ) ) {
mat <- m[ comb[ , j ], comb[ , j ], drop = FALSE ]
if( rcond( mat ) >= tol ) {
princMin <- det( mat )
} else {
princMin <- 0
}
if( princMin < -tol ) {
return( FALSE )
}
}
}
return( TRUE )
} else if( method == "eigen" ) {
ev <- eigen( m, only.values = TRUE )$values
if( is.complex( ev ) ) {
stop( "complex (non-real) eigenvalues,",
" which could be caused by a non-symmetric matrix" )
}
if( all( ev > -tol ) ) {
return( TRUE )
} else {
if( rcond( m ) >= tol || n == 1 ) {
return( FALSE )
} else {
k <- max( 1, min( sum( abs( ev ) <= tol ), n - 1 ) )
comb <- combn( n, n-k )
for( j in 1:ncol( comb ) ) {
mm <- m[ comb[ , j ], comb[ , j ], drop = FALSE ]
if( !semidefiniteness( mm, tol = tol, method = method ) ) {
return( FALSE )
}
}
return( TRUE )
}
}
} else {
stop( "argument 'method' must be either 'det' or 'eigen'" )
}
}
stop( "internal error: please inform the maintainer",
" of the 'miscTools' package",
" (preferably with a reproducible example)" )
}
isSemidefinite.list <- function( m, ... ) {
if( !is.list( m ) ) {
stop( "argument 'm' must be a matrix or a list of matrices" )
} else if( !all( sapply( m, is.matrix ) ) ) {
stop( "all components of the list specified by argument 'm'",
" must be matrices" )
}
result <- logical( length( m ) )
for( t in 1:length( m ) ) {
result[ t ] <- isSemidefinite( m[[ t ]], ... )
}
return( result )
}
semidefiniteness <- function( m, ... ) {
result <- isSemidefinite( m = m, ... )
return( result )
}
|
source("helper-diversitree.R")
context("QuaSSE (split)")
test_that("quasse-split", {
lambda <- function(x) sigmoid.x(x, 0.1, 0.2, 0, 2.5)
mu <- function(x) constant.x(x, 0.03)
char <- make.brownian.with.drift(0, 0.025)
load("phy.Rdata")
pars <- c(.1, .2, 0, 2.5, .03, 0, .01)
pars.s <- rep(pars, 2)
sd <- 1/200
control.C.1 <- list(dt.max=1/200)
control.C.2 <- c(control.C.1, tips.combined=TRUE)
control.M.1 <- list(method="mol")
control.R.1 <- list(dt.max=1/200, method="fftR")
if (check.fftC(FALSE)) {
lik.s <- make.quasse.split(phy, phy$tip.state, sd, sigmoid.x,
constant.x, "nd5", Inf, control.C.1)
lik.q <- make.quasse(phy, phy$tip.state, sd, sigmoid.x, constant.x,
control.C.1)
ll.q <- lik.q(pars)
expect_that(ll.q, equals(-62.06409424693976))
pars.s <- rep(pars, 2)
names(pars.s) <- argnames(lik.s)
expect_that(lik.s(pars.s), equals(ll.q))
set.seed(1)
pars2 <- pars + runif(length(pars), 0, .05)
pars2.s <- rep(pars2, 2)
ll.q <- lik.q(pars2)
expect_that(ll.q, equals(-55.67237675384200))
expect_that(lik.s(pars2.s), equals(ll.q))
pars3.s <- pars + runif(length(pars.s), 0, .05)
expect_that(lik.s(pars3.s), equals(-54.47383577050427))
}
})
|
bs4DashNavbar <- function(..., title = NULL, titleWidth = NULL, disable = FALSE,
.list = NULL, leftUi = NULL, rightUi = NULL, skin = "light", status = "white",
border = TRUE, compact = FALSE, sidebarIcon = shiny::icon("bars"),
controlbarIcon = shiny::icon("th"), fixed = FALSE) {
items <- c(list(...), .list)
if (skin == "dark" && is.null(status)) status <- "gray-dark"
if (!is.null(leftUi)) {
if (inherits(leftUi, "shiny.tag.list")) {
lapply(leftUi, function(item) {
tagAssert(item, type = "li", class = "dropdown")
})
} else {
tagAssert(leftUi, type = "li", class = "dropdown")
}
}
if (!is.null(rightUi)) {
if (inherits(rightUi, "shiny.tag.list")) {
lapply(rightUi, function(item) {
tagAssert(item, type = "li", class = "dropdown")
})
} else {
tagAssert(rightUi, type = "li", class = "dropdown")
}
}
headerTag <- shiny::tags$nav(
style = if (disable) "display: none;",
`data-fixed` = tolower(fixed),
class = paste0(
"main-header navbar navbar-expand", if (!is.null(status)) paste0(" navbar-", status),
" navbar-", skin, if (!border) " border-bottom-0" else NULL,
if (compact) " text-sm" else NULL
),
shiny::tags$ul(
class = "navbar-nav",
shiny::tags$li(
class = "nav-item",
shiny::tags$a(
class = "nav-link",
`data-widget` = "pushmenu",
href = "
sidebarIcon
)
),
leftUi
),
items,
shiny::tags$ul(
class = "navbar-nav ml-auto navbar-right",
rightUi,
shiny::tags$li(
class = "nav-item",
shiny::tags$a(
id = "controlbar-toggle",
class = "nav-link",
`data-widget` = "control-sidebar",
href = "
controlbarIcon
)
)
)
)
list(headerTag, title)
}
bs4DashBrand <- function(title, color = NULL, href = NULL, image = NULL, opacity = .8) {
if (!is.null(color)) validateStatusPlus(color)
shiny::tags$a(
class = if (!is.null(color)) paste0("brand-link bg-", color) else "brand-link",
href = if (!is.null(href)) href else "
target = if (!is.null(href)) "_blank",
if (!is.null(image)) {
shiny::tags$img(
src = image,
class = "brand-image img-circle elevation-3",
style = paste0("opacity: ", opacity)
)
},
shiny::tags$span(class = "brand-text font-weight-light", title)
)
}
bs4DropdownMenu <- function(..., type = c("messages", "notifications", "tasks"),
badgeStatus = "primary", icon = NULL, headerText = NULL,
.list = NULL, href = NULL) {
type <- match.arg(type)
if (!is.null(badgeStatus)) validateStatus(badgeStatus)
items <- c(list(...), .list)
if (is.null(icon)) {
icon <- switch(
type,
messages = shiny::icon("comments"),
notifications = shiny::icon("bell"),
tasks = shiny::icon("tasks")
)
}
numItems <- length(items)
if (is.null(badgeStatus)) {
badge <- NULL
} else {
badge <- shiny::span(class = paste0("badge badge-", badgeStatus, " navbar-badge"), numItems)
}
if (is.null(headerText)) {
headerText <- paste("You have", numItems, type)
}
shiny::tags$li(
class = "nav-item dropdown",
shiny::tags$a(
class = "nav-link",
`data-toggle` = "dropdown",
href = "
`aria-expanded` = "false",
icon,
badge
),
shiny::tags$div(
class = sprintf("dropdown-menu dropdown-menu-lg"),
shiny::tags$span(
class = "dropdown-item dropdown-header",
headerText
),
shiny::tags$div(class = "dropdown-divider"),
items,
if (!is.null(href)) {
shiny::tags$a(
class = "dropdown-item dropdown-footer",
href = href,
target = "_blank",
"More"
)
}
)
)
}
messageItem <- function(from, message, icon = shiny::icon("user"), time = NULL,
href = NULL, image = NULL, color = "secondary", inputId = NULL) {
tagAssert(icon, type = "i")
if (is.null(href)) href <- "
if (!is.null(color)) validateStatusPlus(color)
itemCl <- "dropdown-item"
if (!is.null(inputId)) itemCl <- paste0(itemCl, " action-button")
shiny::tagList(
shiny::a(
class = itemCl,
id = inputId,
href = if (is.null(inputId)) {
"
} else {
href
},
target = if (is.null(inputId)) {
if (!is.null(href)) "_blank"
},
shiny::div(
class = "media",
if (!is.null(image)) {
shiny::img(
src = image,
alt = "User Avatar",
class = "img-size-50 mr-3 img-circle"
)
},
shiny::tags$div(
class = "media-body",
shiny::tags$h3(
class = "dropdown-item-title",
from,
if (!is.null(icon)) {
shiny::tags$span(
class = paste0("float-right text-sm text-", color),
icon
)
}
),
shiny::tags$p(class = "text-sm", message),
if (!is.null(time)) {
shiny::tags$p(
class = "text-sm text-muted",
shiny::tags$i(class = "far fa-clock mr-1"),
time
)
}
)
)
),
shiny::tags$div(class = "dropdown-divider")
)
}
notificationItem <- function(text, icon = shiny::icon("exclamation-triangle"),
status = "success", href = NULL, inputId = NULL) {
tagAssert(icon, type = "i")
if (is.null(href)) href <- "
if (!is.null(status)) validateStatusPlus(status)
itemCl <- "dropdown-item"
if (!is.null(inputId)) itemCl <- paste0(itemCl, " action-button")
if (!is.null(status)) {
icon <- shiny::tagAppendAttributes(icon, class = paste0("text-", status))
}
shiny::tagList(
shiny::tags$a(
class = itemCl,
`disabled` = if (is.null(inputId)) NA else NULL,
href = if (is.null(inputId)) {
"
} else {
href
},
target = if (is.null(inputId)) {
if (!is.null(href)) "_blank"
},
id = inputId,
shiny::tagAppendAttributes(icon, class = "mr-2"),
text
),
shiny::tags$div(class = "dropdown-divider")
)
}
taskItem <- function(text, value = 0, color = "info", href = NULL, inputId = NULL) {
validateStatusPlus(color)
if (is.null(href)) href <- "
itemCl <- "dropdown-item"
if (!is.null(inputId)) itemCl <- paste0(itemCl, " action-button")
shiny::tagList(
shiny::tags$a(
class = itemCl,
href = if (is.null(inputId)) {
"
} else {
href
},
target = if (is.null(inputId)) {
if (!is.null(href)) "_blank"
},
id = inputId,
shiny::h5(
shiny::tags$small(text),
shiny::tags$small(class = "float-right", paste0(value, "%"))
),
progressBar(
value = value,
animated = TRUE,
striped = TRUE,
size = "xs",
status = color
)
),
shiny::tags$div(class = "dropdown-divider")
)
}
bs4UserMenu <- function(..., name = NULL, image = NULL, title = NULL,
subtitle = NULL, footer = NULL, status = NULL) {
if (!is.null(status)) validateStatusPlus(status)
if (!is.null(title)) {
line_1 <- paste0(name, " - ", title)
} else {
line_1 <- name
}
if (!is.null(subtitle)) {
user_text <- shiny::tags$p(line_1, shiny::tags$small(subtitle))
user_header_height <- NULL
} else {
user_text <- shiny::tags$p(line_1)
user_header_height <- shiny::tags$script(shiny::HTML('$(".user-header").css("height", "145px")'))
}
shiny::tagList(
shiny::tags$head(
shiny::tags$script(
"$(function() {
$('.dashboard-user').on('click', function(e){
e.stopPropagation();
});
});
"
)
),
shiny::tags$a(
href = "
class = "nav-link dropdown-toggle",
`data-toggle` = "dropdown",
`aria-expanded` = "false",
shiny::tags$img(
src = image,
class = "user-image img-circle elevation-2",
alt = "User Image"
),
shiny::tags$span(class = "d-none d-md-inline", name)
),
shiny::tags$ul(
class = "dropdown-menu dropdown-menu-lg dropdown-menu-right dashboard-user",
shiny::tags$li(
class = paste0("user-header", if (!is.null(status)) paste0(" bg-", status)),
shiny::tags$img(
src = image,
class = "img-circle elevation-2",
alt = "User Image"
),
shiny::tags$p(title, shiny::tags$small(subtitle))
),
if (length(list(...)) > 0) shiny::tags$li(class = "user-body", shiny::fluidRow(...)),
if (!is.null(footer)) shiny::tags$li(class = "user-footer", footer)
)
)
}
dashboardUserItem <- function(item, width) {
item <- shiny::div(
class = paste0("col-", width, " text-center"),
item
)
}
userOutput <- function(id, tag = shiny::tags$li) {
shiny::uiOutput(outputId = id, container = tag, class = "nav-item dropdown user-menu")
}
renderUser <- function(expr, env = parent.frame(), quoted = FALSE, outputArgs = list()) {
if (!quoted) {
expr <- substitute(expr)
quoted <- TRUE
}
shiny::renderUI(expr, env = env, quoted = quoted, outputArgs = outputArgs)
}
globalVariables("func")
|
utils::globalVariables(c("xval", "yval", "type", "batch1.size", "batch2.size",
"N1.max", "N2.max", "theta1", "obs1", "obs2", "obs", "N.max",
"batch.size"))
Type2.fixed_design = function(theta, test.type, side = "right", theta0, N, N1, N2,
Type1 = 0.005, sigma = 1, sigma1 = 1, sigma2 = 1){
if((test.type!="oneProp") & (test.type!="oneZ") & (test.type!="oneT") &
(test.type!="twoZ") & (test.type!="twoT")){
return(print("Unknown 'test type'. Has to be one of 'oneProp', 'oneZ', 'oneT', 'twoZ' or 'twoT'."))
}
if(test.type=="oneProp"){
if(missing(theta0)) theta0 = 0.5
if(side=="right"){
c.alpha = qbinom(p = Type1, size = N, prob = theta0, lower.tail = F)
return(pbinom(q = c.alpha, size = N, prob = theta))
}else if(side=="left"){
c.alpha = qbinom(p = Type1, size = N, prob = theta0)
return(pbinom(q = c.alpha-1, size = N, prob = theta, lower.tail = F))
}
}else if(test.type=="oneZ"){
if(missing(theta0)) theta0 = 0
if(side=="right"){
z.alpha = qnorm(p = Type1, lower.tail = F)
return(pnorm(q = theta0 + (z.alpha*sigma)/sqrt(N), mean = theta, sd = sigma/sqrt(N)))
}else if(side=="left"){
z.alpha = qnorm(p = Type1, lower.tail = F)
return(pnorm(q = theta0 - (z.alpha*sigma)/sqrt(N), mean = theta, sd = sigma/sqrt(N),
lower.tail = F))
}
}else if(test.type=="oneT"){
if(missing(theta0)) theta0 = 0
if(side=="right"){
t.alpha = qt(p = Type1, df = N-1, lower.tail = F)
return(pt(q = t.alpha, df = N-1, ncp = sqrt(N)*(theta - theta0)))
}else if(side=="left"){
t.alpha = qt(p = Type1, df = N-1, lower.tail = F)
return(pt(q = -t.alpha, df = N-1, ncp = sqrt(N)*(theta - theta0),
lower.tail = F))
}
}else if(test.type=="twoZ"){
if(missing(theta0)) theta0 = 0
if(side=="right"){
z.alpha = qnorm(p = Type1, lower.tail = F)
sigmaD = sqrt((sigma1^2)/N1 + (sigma2^2)/N2)
return(pnorm(q = theta0 + z.alpha*sigmaD, mean = theta, sd = sigmaD))
}else if(side=="left"){
z.alpha = qnorm(p = Type1, lower.tail = F)
sigmaD = sqrt((sigma1^2)/N1 + (sigma2^2)/N2)
return(pnorm(q = theta0 - z.alpha*sigmaD, mean = theta, sd = sigmaD,
lower.tail = F))
}
}else if(test.type=="twoT"){
if(missing(theta0)) theta0 = 0
if(side=="right"){
t.alpha = qt(p = Type1, df = N1 + N2 - 2, lower.tail = F)
return(pt(q = t.alpha, df = N1 + N2 - 2,
ncp = (theta - theta0)/sqrt(1/N1 + 1/N2)))
}else if(side=="left"){
t.alpha = qt(p = Type1, df = N1 + N2 - 2, lower.tail = F)
return(pt(q = -t.alpha, df = N1 + N2 - 2,
ncp = (theta - theta0)/sqrt(1/N1 + 1/N2), lower.tail = F))
}
}
}
fixed_design.alt = function(test.type, side = "right", theta0, N, N1, N2,
Type1 = 0.005, Type2 = .2, sigma = 1, sigma1 = 1, sigma2 = 1){
if((test.type!="oneProp") & (test.type!="oneZ") & (test.type!="oneT") &
(test.type!="twoZ") & (test.type!="twoT")){
return(print("Unknown 'test type'. Has to be one of 'oneProp', 'oneZ', 'oneT', 'twoZ' or 'twoT'."))
}
if(test.type=="oneProp"){
if(missing(theta0)) theta0 = 0.5
if(side=="right"){
c.alpha = qbinom(p = Type1, size = N, prob = theta0, lower.tail = F)
solve.out = uniroot(interval = c(theta0, 1),
f = function(x){
pbinom(q = c.alpha, size = N, prob = x) - Type2
})
return(solve.out$root)
}else if(side=="left"){
c.alpha = qbinom(p = Type1, size = N, prob = theta0)
solve.out = uniroot(interval = c(0, theta0),
f = function(x){
pbinom(q = c.alpha-1, size = N, prob = x,
lower.tail = F) - Type2
})
return(solve.out$root)
}
}else if(test.type=="oneZ"){
if(missing(theta0)==T) theta0 = 0
z.alpha = qnorm(p = Type1, lower.tail = F)
if(side=="right"){
return(theta0 - ((qnorm(p = Type2) - z.alpha)*sigma)/sqrt(N))
}else if(side=="left"){
return(theta0 - ((qnorm(p = 1-Type2) + z.alpha)*sigma)/sqrt(N))
}
}else if(test.type=="oneT"){
if(missing(theta0)==T) theta0 = 0
t.alpha = qt(p = Type1, df = N-1, lower.tail = F)
if(side=="right"){
solve.out = uniroot(interval = c(theta0, .Machine$integer.max),
f = function(x){
pt(q = t.alpha, df = N-1, ncp = sqrt(N)*(x - theta0)) -
Type2
})
return(solve.out$root)
}else if(side=="left"){
solve.out = uniroot(interval = c(-.Machine$integer.max, theta0),
f = function(x){
pt(q = -t.alpha, df = N-1, ncp = sqrt(N)*(x - theta0),
lower.tail = F) - Type2
})
return(solve.out$root)
}
}else if(test.type=="twoZ"){
if(missing(theta0)==T) theta0 = 0
z.alpha = qnorm(p = Type1, lower.tail = F)
sigmaD = sqrt((sigma1^2)/N1 + (sigma2^2)/N2)
if(side=="right"){
return(theta0 - (qnorm(p = Type2) - z.alpha)*sigmaD)
}else if(side=="left"){
return(theta0 - (qnorm(p = 1-Type2) + z.alpha)*sigmaD)
}
}else if(test.type=="twoT"){
if(missing(theta0)==T) theta0 = 0
t.alpha = qt(p = Type1, df = N1 + N2 - 2, lower.tail = F)
if(side=="right"){
solve.out = uniroot(interval = c(theta0, .Machine$integer.max),
f = function(x){
pt(q = t.alpha, df = N1 + N2 - 2,
ncp = (x - theta0)/sqrt(1/N1 + 1/N2)) - Type2
})
return(solve.out$root)
}else if(side=="left"){
solve.out = uniroot(interval = c(-.Machine$integer.max, theta0),
f = function(x){
pt(q = -t.alpha, df = N1 + N2 - 2,
ncp = (x - theta0)/sqrt(1/N1 + 1/N2),
lower.tail = F) - Type2
})
return(solve.out$root)
}
}
}
UMPBT.alt = function(test.type, side = "right", theta0, N, N1, N2,
Type1 = 0.005, sigma = 1, sigma1 = 1, sigma2 = 1,
obs, sd.obs, obs1, obs2, pooled.sd){
if((test.type!="oneProp") & (test.type!="oneZ") & (test.type!="oneT") &
(test.type!="twoZ") & (test.type!="twoT")){
return(print("Unknown 'test type'. Has to be one of 'oneProp', 'oneZ', 'oneT', 'twoZ' or 'twoT'."))
}
if(test.type=="oneProp"){
if(missing(theta0)) theta0 = 0.5
if(side=="right"){
c.alpha = qbinom(p = Type1, size = N, prob = theta0, lower.tail = F)
solve.delta.outer =
nleqslv::nleqslv(x = 3,
fn = function(delta){
out.optimize.UMPBTobjective =
optimize(interval = c(theta0, 1),
f = function(p){
(log(delta) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
out.optimize.UMPBTobjective$objective - c.alpha
})
out.optimize.UMPBTobjective.outer =
optimize(interval = c(theta0, 1),
f = function(p){
(log(solve.delta.outer$x) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
solve.delta.inner =
nleqslv::nleqslv(x = 3,
fn = function(delta){
out.optimize.UMPBTobjective =
optimize(interval = c(theta0, 1),
f = function(p){
(log(delta) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
out.optimize.UMPBTobjective$objective - (c.alpha - 1)
})
out.optimize.UMPBTobjective.inner =
optimize(interval = c(theta0, 1),
f = function(p){
(log(solve.delta.inner$x) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
mix.prob = (Type1 - pbinom(q = c.alpha, size = N, prob = theta0, lower.tail = F))/
dbinom(x = c.alpha, size = N, prob = theta0)
return(list("theta" = c(out.optimize.UMPBTobjective.inner$minimum,
out.optimize.UMPBTobjective.outer$minimum),
"mix.prob" = c(mix.prob, 1-mix.prob)))
}else if(side=="left"){
c.alpha = qbinom(p = Type1, size = N, prob = theta0)
solve.delta.outer =
nleqslv::nleqslv(x = 3,
fn = function(delta){
out.optimize.UMPBTobjective =
optimize(interval = c(0, theta0), maximum = T,
f = function(p){
(log(delta) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
out.optimize.UMPBTobjective$objective - c.alpha
})
out.optimize.UMPBTobjective.outer =
optimize(interval = c(0, theta0), maximum = T,
f = function(p){
(log(solve.delta.outer$x) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
solve.delta.inner =
nleqslv::nleqslv(x = 3,
fn = function(delta){
out.optimize.UMPBTobjective =
optimize(interval = c(0, theta0), maximum = T,
f = function(p){
(log(delta) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
out.optimize.UMPBTobjective$objective - (c.alpha + 1)
})
out.optimize.UMPBTobjective.inner =
optimize(interval = c(0, theta0), maximum = T,
f = function(p){
(log(solve.delta.inner$x) - N*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
mix.prob = (Type1 - pbinom(q = c.alpha-1, size = N, prob = theta0))/
dbinom(x = c.alpha, size = N, prob = theta0)
return(list("theta" = c(out.optimize.UMPBTobjective.inner$maximum,
out.optimize.UMPBTobjective.outer$maximum),
"mix.prob" = c(mix.prob, 1-mix.prob)))
}
}else if(test.type=="oneZ"){
if(missing(theta0)==T) theta0 = 0
z.alpha = qnorm(p = Type1, lower.tail = F)
if(side=="right"){
return(theta0 + (z.alpha*sigma)/sqrt(N))
}else if(side=="left"){
return(theta0 - (z.alpha*sigma)/sqrt(N))
}
}else if(test.type=="oneT"){
if(missing(theta0)) theta0 = 0
if(missing(sd.obs)){
if(missing(obs)){
return("Need to provide either 'sd.obs' or 'obs'.")
}else{
sd.obs = sd(obs)
}
}else{
if(!missing(obs)){
sd.fromdata = sd(obs)
if(round(sd.fromdata, 5)!=sd.obs){
sd.obs = sd.fromdata
print(paste("'sd.obs' that is provided doesn't match with the sd (divisor (n-1)) calculated from 'obs'. Working with sd.obs = ", round(sd.fromdata, 5), "calculated from the data provided."))
}
}
}
t.alpha = qt(p = Type1, df = N-1, lower.tail = F)
if(side=="right"){
return(theta0 + (t.alpha*sd.obs)/sqrt(N))
}else if(side=="left"){
return(theta0 - (t.alpha*sd.obs)/sqrt(N))
}
}else if(test.type=="twoZ"){
if(missing(theta0)) theta0 = 0
z.alpha = qnorm(p = Type1, lower.tail = F)
if(side=="right"){
return(theta0 + z.alpha*sqrt((sigma1^2)/N1 + (sigma2^2)/N2))
}else if(side=="left"){
return(theta0 - z.alpha*sqrt((sigma1^2)/N1 + (sigma2^2)/N2))
}
}else if(test.type=="twoT"){
if(missing(theta0)) theta0 = 0
if(missing(pooled.sd)){
if(any(c(missing(obs1), missing(obs2)))){
return("Need to provide either 'pooled.sd' or both 'obs1' and 'obs2.")
}else{
pooled.sd = sqrt(((length(obs1)-1)*var(obs1) + (length(obs2)-1)*var(obs2))/
(length(obs1) + length(obs2) - 2))
}
}else{
if((!missing(obs1))&&(!missing(obs2))){
pooled.sd.fromdata = sqrt(((length(obs1)-1)*var(obs1) + (length(obs2)-1)*var(obs2))/
(length(obs1) + length(obs2) - 2))
if(round(pooled.sd.fromdata, 5)!=pooled.sd){
pooled.sd = pooled.sd.fromdata
print(paste("'pooled.sd' that is provided doesn't match with the pooled sd (divisor (n1 + n2 - 1)) calculated from 'obs1' and 'obs2'. Working with pooled.sd = ", round(pooled.sd.fromdata, 5), "calculated from the data provided."))
}
}
}
t.alpha = qt(p = Type1, df = N1 + N2 - 2, lower.tail = F)
if(side=="right"){
return(theta0 + t.alpha*pooled.sd*sqrt(1/N1 + 1/N2))
}else if(side=="left"){
return(theta0 - t.alpha*pooled.sd*sqrt(1/N1 + 1/N2))
}
}
}
design.MSPRT_oneProp = function(side = 'right', theta0 = 0.5, theta1 = T,
Type1.target =.005, Type2.target = .2,
N.max, batch.size,
nReplicate = 1e+6, verbose = T, seed = 1){
if(side!='both'){
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a one-sample proportion test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a one-sample proportion test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch.size = c(0, cumsum(batch.size))
if(is.logical(theta1)&&(theta1==F)){
UMPBT = UMPBT.alt(test.type = 'oneProp', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target)
if(verbose==T){
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(UMPBT$theta[1], 3), " & ",
round(UMPBT$theta[2], 3), " with respective probabilities ",
round(UMPBT$mix.prob[1], 3), " & ", 1 - round(UMPBT$mix.prob[1], 3), sep = ''))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum0_n = LR0_n = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N0.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rbinom(length(not.reached.decisionH0.AR),
batch.size[n+1]-batch.size[n], theta0)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n[not.reached.decisionH0.AR] =
UMPBT$mix.prob[1]*(((1 - UMPBT$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$theta[1])))^cumsum0_n[not.reached.decisionH0.AR] +
(1 - UMPBT$mix.prob[2])*(((1 - UMPBT$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$theta[2])))^cumsum0_n[not.reached.decisionH0.AR]
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN0 = mean(N0.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"N0" = list('H0' = N0.AR), "EN" = EN0,
"UMPBT" = UMPBT, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneProp', 'side' = side, 'theta0' = theta0,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = fixed_design.alt(test.type = 'oneProp', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, Type2 = Type2.target)
UMPBT = UMPBT.alt(test.type = 'oneProp', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(UMPBT$theta[1], 3), " & ",
round(UMPBT$theta[2], 3), " with respective probabilities ",
round(UMPBT$mix.prob[1], 3), " & ", 1 - round(UMPBT$mix.prob[1], 3), sep = ''))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum0_n = cumsum1_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N0.AR = N1.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rbinom(length(not.reached.decisionH0.AR),
batch.size[n+1]-batch.size[n], theta0)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n[not.reached.decisionH0.AR] =
UMPBT$mix.prob[1]*(((1 - UMPBT$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$theta[1])))^cumsum0_n[not.reached.decisionH0.AR] +
(1 - UMPBT$mix.prob[2])*(((1 - UMPBT$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$theta[2])))^cumsum0_n[not.reached.decisionH0.AR]
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rbinom(length(not.reached.decisionH1.AR),
batch.size[n+1]-batch.size[n], theta1)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n[not.reached.decisionH1.AR] =
UMPBT$mix.prob[1]*(((1 - UMPBT$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$theta[1])))^cumsum1_n[not.reached.decisionH1.AR] +
(1 - UMPBT$mix.prob[2])*(((1 - UMPBT$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$theta[2])))^cumsum1_n[not.reached.decisionH1.AR]
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN0 = mean(N0.AR)
EN1 = mean(N1.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print(paste("Expected sample size at the alternative: ", round(EN1, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = actual.type2.error.AR,
"N0" = list('H0' = N0.AR, 'H1' = N1.AR), "EN" = c(EN0, EN1),
"UMPBT" = UMPBT, "theta1" = theta1,
"Type2.fixed.design" = Type2.fixed_design(theta = theta1, test.type = 'oneProp', side = side,
theta0 = theta0, N = N.max, Type1 = Type1.target),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneProp', 'side' = side, 'theta0' = theta0,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else{
UMPBT = UMPBT.alt(test.type = 'oneProp', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(UMPBT$theta[1], 3), " & ",
round(UMPBT$theta[2], 3), " with respective probabilities ",
round(UMPBT$mix.prob[1], 3), " & ", 1 - round(UMPBT$mix.prob[1], 3), sep = ''))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum0_n = cumsum1_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N0.AR = N1.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rbinom(length(not.reached.decisionH0.AR),
batch.size[n+1]-batch.size[n], theta0)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n[not.reached.decisionH0.AR] =
UMPBT$mix.prob[1]*(((1 - UMPBT$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$theta[1])))^cumsum0_n[not.reached.decisionH0.AR] +
(1 - UMPBT$mix.prob[2])*(((1 - UMPBT$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$theta[2])))^cumsum0_n[not.reached.decisionH0.AR]
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rbinom(length(not.reached.decisionH1.AR),
batch.size[n+1]-batch.size[n], theta1)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n[not.reached.decisionH1.AR] =
UMPBT$mix.prob[1]*(((1 - UMPBT$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$theta[1])))^cumsum1_n[not.reached.decisionH1.AR] +
(1 - UMPBT$mix.prob[2])*(((1 - UMPBT$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$theta[2])))^cumsum1_n[not.reached.decisionH1.AR]
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN0 = mean(N0.AR)
EN1 = mean(N1.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print(paste("Expected sample size at the alternative: ", round(EN1, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = actual.type2.error.AR,
"N0" = list('H0' = N0.AR, 'H1' = N1.AR), "EN" = c(EN0, EN1),
"UMPBT" = UMPBT, "theta1" = theta1,
"Type2.fixed.design" = Type2.fixed_design(theta = theta1, test.type = 'oneProp', side = side,
theta0 = theta0, N = N.max, Type1 = Type1.target),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneProp', 'side' = side, 'theta0' = theta0,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}
}else if(side=='both'){
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a one-sample proportion test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a one-sample proportion test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch.size = c(0, cumsum(batch.size))
if(is.logical(theta1)&&(theta1==F)){
UMPBT = list('right' = UMPBT.alt(test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max, Type1 = Type1.target/2),
'left' = UMPBT.alt(test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max, Type1 = Type1.target/2))
if(verbose==T){
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(UMPBT$right$theta[1], 3), " & ",
round(UMPBT$right$theta[2], 3), " with respective probabilities ",
round(UMPBT$right$mix.prob[1], 3), " & ", 1 - round(UMPBT$right$mix.prob[1], 3),
sep = ""))
print(paste(' On the left: ', round(UMPBT$left$theta[1], 3), " & ",
round(UMPBT$left$theta[2], 3), " with respective probabilities ",
round(UMPBT$left$mix.prob[1], 3), " & ", 1 - round(UMPBT$left$mix.prob[1], 3),
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum0_n = LR0_n.r = LR0_n.l = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rbinom(length(not.reached.decisionH0.AR),
batch.size[n+1]-batch.size[n], theta0)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n.r[not.reached.decisionH0.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum0_n[not.reached.decisionH0.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum0_n[not.reached.decisionH0.AR.r]
LR0_n.l[not.reached.decisionH0.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum0_n[not.reached.decisionH0.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum0_n[not.reached.decisionH0.AR.l]
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN0 = mean(N0.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
'N' = list('H0' = N0.AR), 'EN' = EN0, "UMPBT" = UMPBT,
"Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneProp', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = list('right' = fixed_design.alt(test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, Type2 = Type2.target),
'left' = fixed_design.alt(test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, Type2 = Type2.target))
UMPBT = list('right' = UMPBT.alt(test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max, Type1 = Type1.target/2),
'left' = UMPBT.alt(test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max, Type1 = Type1.target/2))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(UMPBT$right$theta[1], 3), " & ",
round(UMPBT$right$theta[2], 3), " with respective probabilities ",
round(UMPBT$right$mix.prob[1], 3), " & ", 1 - round(UMPBT$right$mix.prob[1], 3),
sep = ""))
print(paste(' On the left: ', round(UMPBT$left$theta[1], 3), " & ",
round(UMPBT$left$theta[2], 3), " with respective probabilities ",
round(UMPBT$left$mix.prob[1], 3), " & ", 1 - round(UMPBT$left$mix.prob[1], 3),
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum0_n = cumsum1r_n = cumsum1l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = N1r.AR = N1r.AR.r = N1r.AR.l =
N1l.AR = N1l.AR.r = N1l.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rbinom(length(not.reached.decisionH0.AR),
batch.size[n+1]-batch.size[n], theta0)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n.r[not.reached.decisionH0.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum0_n[not.reached.decisionH0.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum0_n[not.reached.decisionH0.AR.r]
LR0_n.l[not.reached.decisionH0.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum0_n[not.reached.decisionH0.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum0_n[not.reached.decisionH0.AR.l]
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
sum1r_n = rbinom(length(not.reached.decisionH1r.AR),
batch.size[n+1]-batch.size[n], theta1$right)
cumsum1r_n[not.reached.decisionH1r.AR] =
cumsum1r_n[not.reached.decisionH1r.AR] + sum1r_n
LR1r_n.r[not.reached.decisionH1r.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum1r_n[not.reached.decisionH1r.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum1r_n[not.reached.decisionH1r.AR.r]
LR1r_n.l[not.reached.decisionH1r.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum1r_n[not.reached.decisionH1r.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum1r_n[not.reached.decisionH1r.AR.l]
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N1r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N1r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
sum1l_n = rbinom(length(not.reached.decisionH1l.AR),
batch.size[n+1]-batch.size[n], theta1$left)
cumsum1l_n[not.reached.decisionH1l.AR] =
cumsum1l_n[not.reached.decisionH1l.AR] + sum1l_n
LR1l_n.r[not.reached.decisionH1l.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum1l_n[not.reached.decisionH1l.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum1l_n[not.reached.decisionH1l.AR.r]
LR1l_n.l[not.reached.decisionH1l.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum1l_n[not.reached.decisionH1l.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum1l_n[not.reached.decisionH1l.AR.l]
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N1l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N1l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N1r.AR[accepted.by.both1r] = pmax(N1r.AR.r[accepted.by.both1r],
N1r.AR.l[accepted.by.both1r])
N1r.AR[onlyrejected.by.right1r] = N1r.AR.r[onlyrejected.by.right1r]
N1r.AR[onlyrejected.by.left1r] = N1r.AR.l[onlyrejected.by.left1r]
N1r.AR[rejected.by.both1r] = pmin(N1r.AR.r[rejected.by.both1r],
N1r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N1l.AR[accepted.by.both1l] = pmax(N1l.AR.r[accepted.by.both1l],
N1l.AR.l[accepted.by.both1l])
N1l.AR[onlyrejected.by.right1l] = N1l.AR.r[onlyrejected.by.right1l]
N1l.AR[onlyrejected.by.left1l] = N1l.AR.l[onlyrejected.by.left1l]
N1l.AR[rejected.by.both1l] = pmin(N1l.AR.r[rejected.by.both1l],
N1l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN0 = mean(N0.AR)
EN1r = mean(N1r.AR)
EN1l = mean(N1l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: ", round(EN1r, 2)))
print(paste(" On the left: ", round(EN1l, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = N0.AR, 'right' = N1r.AR, 'left' = N1l.AR),
'EN' = c(EN0, EN1r, EN1l), "UMPBT" = UMPBT,
"theta1" = theta1,
"Type2.fixed.design" = c(Type2.fixed_design(theta = theta1$right, test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max, Type1 = Type1.target/2),
Type2.fixed_design(theta = theta1$left, test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max, Type1 = Type1.target/2)),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneProp', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else{
UMPBT = list('right' = UMPBT.alt(test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max, Type1 = Type1.target/2),
'left' = UMPBT.alt(test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max, Type1 = Type1.target/2))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(UMPBT$right$theta[1], 3), " & ",
round(UMPBT$right$theta[2], 3), " with respective probabilities ",
round(UMPBT$right$mix.prob[1], 3), " & ", 1 - round(UMPBT$right$mix.prob[1], 3),
sep = ""))
print(paste(' On the left: ', round(UMPBT$left$theta[1], 3), " & ",
round(UMPBT$left$theta[2], 3), " with respective probabilities ",
round(UMPBT$left$mix.prob[1], 3), " & ", 1 - round(UMPBT$left$mix.prob[1], 3),
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum0_n = cumsum1r_n = cumsum1l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = N1r.AR = N1r.AR.r = N1r.AR.l =
N1l.AR = N1l.AR.r = N1l.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rbinom(length(not.reached.decisionH0.AR),
batch.size[n+1]-batch.size[n], theta0)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n.r[not.reached.decisionH0.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum0_n[not.reached.decisionH0.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum0_n[not.reached.decisionH0.AR.r]
LR0_n.l[not.reached.decisionH0.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum0_n[not.reached.decisionH0.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum0_n[not.reached.decisionH0.AR.l]
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
sum1r_n = rbinom(length(not.reached.decisionH1r.AR),
batch.size[n+1]-batch.size[n], theta1$right)
cumsum1r_n[not.reached.decisionH1r.AR] =
cumsum1r_n[not.reached.decisionH1r.AR] + sum1r_n
LR1r_n.r[not.reached.decisionH1r.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum1r_n[not.reached.decisionH1r.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum1r_n[not.reached.decisionH1r.AR.r]
LR1r_n.l[not.reached.decisionH1r.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum1r_n[not.reached.decisionH1r.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum1r_n[not.reached.decisionH1r.AR.l]
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N1r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N1r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
sum1l_n = rbinom(length(not.reached.decisionH1l.AR),
batch.size[n+1]-batch.size[n], theta1$left)
cumsum1l_n[not.reached.decisionH1l.AR] =
cumsum1l_n[not.reached.decisionH1l.AR] + sum1l_n
LR1l_n.r[not.reached.decisionH1l.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum1l_n[not.reached.decisionH1l.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum1l_n[not.reached.decisionH1l.AR.r]
LR1l_n.l[not.reached.decisionH1l.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum1l_n[not.reached.decisionH1l.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum1l_n[not.reached.decisionH1l.AR.l]
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N1l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N1l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N1r.AR[accepted.by.both1r] = pmax(N1r.AR.r[accepted.by.both1r],
N1r.AR.l[accepted.by.both1r])
N1r.AR[onlyrejected.by.right1r] = N1r.AR.r[onlyrejected.by.right1r]
N1r.AR[onlyrejected.by.left1r] = N1r.AR.l[onlyrejected.by.left1r]
N1r.AR[rejected.by.both1r] = pmin(N1r.AR.r[rejected.by.both1r],
N1r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N1l.AR[accepted.by.both1l] = pmax(N1l.AR.r[accepted.by.both1l],
N1l.AR.l[accepted.by.both1l])
N1l.AR[onlyrejected.by.right1l] = N1l.AR.r[onlyrejected.by.right1l]
N1l.AR[onlyrejected.by.left1l] = N1l.AR.l[onlyrejected.by.left1l]
N1l.AR[rejected.by.both1l] = pmin(N1l.AR.r[rejected.by.both1l],
N1l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN0 = mean(N0.AR)
EN1r = mean(N1r.AR)
EN1l = mean(N1l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: ", round(EN1r, 2)))
print(paste(" On the left: ", round(EN1l, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = N0.AR, 'right' = N1r.AR, 'left' = N1l.AR),
'EN' = c(EN0, EN1r, EN1l), "UMPBT" = UMPBT, "theta1" = theta1,
"Type2.fixed.design" = c(Type2.fixed_design(theta = theta1$right, test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max, Type1 = Type1.target/2),
Type2.fixed_design(theta = theta1$left, test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max, Type1 = Type1.target/2)),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneProp', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}
}
}
design.MSPRT_oneZ = function(side = 'right', theta0 = 0, theta1 = T,
Type1.target =.005, Type2.target = .2,
N.max, batch.size, sigma = 1,
nReplicate = 1e+6, verbose = T, seed = 1){
if(side!='both'){
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a one-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a one-sample z test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
}
batch.size = c(0, cumsum(batch.size))
if(is.logical(theta1)&&(theta1==F)){
theta.UMPBT = UMPBT.alt(test.type = 'oneZ', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, sigma = sigma)
if(verbose==T){
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum0_n = LR0_n = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N0.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rnorm(length(not.reached.decisionH0.AR),
(batch.size[n+1]-batch.size[n])*theta0,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n[not.reached.decisionH0.AR] =
exp((cumsum0_n[not.reached.decisionH0.AR]*(theta.UMPBT - theta0) -
((batch.size[n+1]*((theta.UMPBT^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN0 = mean(N0.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("=========================================================================")
cat('\n')
}
return(list("TypeI.attained" = actual.type1.error.AR,
"N" = list('H0' = N0.AR), "EN" = EN0,
"theta.UMPBT" = theta.UMPBT, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneZ', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = fixed_design.alt(test.type = 'oneZ', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, Type2 = Type2.target,
sigma = sigma)
theta.UMPBT = UMPBT.alt(test.type = 'oneZ', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, sigma = sigma)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum0_n = cumsum1_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N0.AR = N1.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rnorm(length(not.reached.decisionH0.AR),
(batch.size[n+1]-batch.size[n])*theta0,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n[not.reached.decisionH0.AR] =
exp((cumsum0_n[not.reached.decisionH0.AR]*(theta.UMPBT - theta0) -
((batch.size[n+1]*((theta.UMPBT^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rnorm(length(not.reached.decisionH1.AR),
(batch.size[n+1]-batch.size[n])*theta1,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n[not.reached.decisionH1.AR] =
exp((cumsum1_n[not.reached.decisionH1.AR]*(theta.UMPBT - theta0) -
((batch.size[n+1]*((theta.UMPBT^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN0 = mean(N0.AR)
EN1 = mean(N1.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print(paste("Expected sample size at the alternative: ", round(EN1, 2)))
print("=========================================================================")
cat('\n')
}
return(list("TypeI.attained" = actual.type1.error.AR,
"TypeII.attained" = actual.type2.error.AR,
"N" = list('H0' = N0.AR, 'H1' = N1.AR), "EN" = c(EN0, EN1),
"theta.UMPBT" = theta.UMPBT, "theta1" = theta1,
"Type2.fixed.design" = Type2.fixed_design(theta = theta1, test.type = 'oneZ', side = side,
theta0 = theta0, sigma = sigma,
N = N.max, Type1 = Type1.target),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneZ', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else{
theta.UMPBT = UMPBT.alt(test.type = 'oneZ', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, sigma = sigma)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum0_n = cumsum1_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N0.AR = N1.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rnorm(length(not.reached.decisionH0.AR),
(batch.size[n+1]-batch.size[n])*theta0,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n[not.reached.decisionH0.AR] =
exp((cumsum0_n[not.reached.decisionH0.AR]*(theta.UMPBT - theta0) -
((batch.size[n+1]*((theta.UMPBT^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rnorm(length(not.reached.decisionH1.AR),
(batch.size[n+1]-batch.size[n])*theta1,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n[not.reached.decisionH1.AR] =
exp((cumsum1_n[not.reached.decisionH1.AR]*(theta.UMPBT - theta0) -
((batch.size[n+1]*((theta.UMPBT^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN0 = mean(N0.AR)
EN1 = mean(N1.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print(paste("Expected sample size at the alternative: ", round(EN1, 2)))
print("=========================================================================")
cat('\n')
}
return(list("TypeI.attained" = actual.type1.error.AR,
"TypeII.attained" = actual.type2.error.AR,
"N" = list('H0' = N0.AR, 'H1' = N1.AR), "EN" = c(EN0, EN1),
"theta.UMPBT" = theta.UMPBT, "theta1" = theta1,
"Type2.fixed.design" = Type2.fixed_design(theta = theta1, test.type = 'oneZ', side = side,
theta0 = theta0, sigma = sigma,
N = N.max, Type1 = Type1.target),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneZ', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}
}else{
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a one-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a one-sample z test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
}
batch.size = c(0, cumsum(batch.size))
if(is.logical(theta1)&&(theta1==F)){
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'oneZ', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma),
'left' = UMPBT.alt(test.type = 'oneZ', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma))
if(verbose==T){
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum0_n = LR0_n.r = LR0_n.l = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rnorm(length(not.reached.decisionH0.AR),
(batch.size[n+1]-batch.size[n])*theta0,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n.r[not.reached.decisionH0.AR.r] =
exp((cumsum0_n[not.reached.decisionH0.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR0_n.l[not.reached.decisionH0.AR.l] =
exp((cumsum0_n[not.reached.decisionH0.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN0 = mean(N0.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
'N' = list('H0' = N0.AR),
'EN' = EN0, "theta.UMPBT" = theta.UMPBT, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneZ', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = list('right' = fixed_design.alt(test.type = 'oneZ', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, Type2 = Type2.target,
sigma = sigma),
'left' = fixed_design.alt(test.type = 'oneZ', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, Type2 = Type2.target,
sigma = sigma))
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'oneZ', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma),
'left' = UMPBT.alt(test.type = 'oneZ', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum0_n = cumsum1r_n = cumsum1l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = N1r.AR = N1r.AR.r = N1r.AR.l =
N1l.AR = N1l.AR.r = N1l.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rnorm(length(not.reached.decisionH0.AR),
(batch.size[n+1]-batch.size[n])*theta0,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n.r[not.reached.decisionH0.AR.r] =
exp((cumsum0_n[not.reached.decisionH0.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR0_n.l[not.reached.decisionH0.AR.l] =
exp((cumsum0_n[not.reached.decisionH0.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
sum1r_n = rnorm(length(not.reached.decisionH1r.AR),
(batch.size[n+1]-batch.size[n])*theta1$right,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1r_n[not.reached.decisionH1r.AR] =
cumsum1r_n[not.reached.decisionH1r.AR] + sum1r_n
LR1r_n.r[not.reached.decisionH1r.AR.r] =
exp((cumsum1r_n[not.reached.decisionH1r.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR1r_n.l[not.reached.decisionH1r.AR.l] =
exp((cumsum1r_n[not.reached.decisionH1r.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N1r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N1r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
sum1l_n = rnorm(length(not.reached.decisionH1l.AR),
(batch.size[n+1]-batch.size[n])*theta1$left,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1l_n[not.reached.decisionH1l.AR] =
cumsum1l_n[not.reached.decisionH1l.AR] + sum1l_n
LR1l_n.r[not.reached.decisionH1l.AR.r] =
exp((cumsum1l_n[not.reached.decisionH1l.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR1l_n.l[not.reached.decisionH1l.AR.l] =
exp((cumsum1l_n[not.reached.decisionH1l.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N1l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N1l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N1r.AR[accepted.by.both1r] = pmax(N1r.AR.r[accepted.by.both1r],
N1r.AR.l[accepted.by.both1r])
N1r.AR[onlyrejected.by.right1r] = N1r.AR.r[onlyrejected.by.right1r]
N1r.AR[onlyrejected.by.left1r] = N1r.AR.l[onlyrejected.by.left1r]
N1r.AR[rejected.by.both1r] = pmin(N1r.AR.r[rejected.by.both1r],
N1r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N1l.AR[accepted.by.both1l] = pmax(N1l.AR.r[accepted.by.both1l],
N1l.AR.l[accepted.by.both1l])
N1l.AR[onlyrejected.by.right1l] = N1l.AR.r[onlyrejected.by.right1l]
N1l.AR[onlyrejected.by.left1l] = N1l.AR.l[onlyrejected.by.left1l]
N1l.AR[rejected.by.both1l] = pmin(N1l.AR.r[rejected.by.both1l],
N1l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN0 = mean(N0.AR)
EN1r = mean(N1r.AR)
EN1l = mean(N1l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: ", round(EN1r, 2)))
print(paste(" On the left: ", round(EN1l, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = N0.AR, 'right' = N1r.AR, 'left' = N1l.AR),
'EN' = c(EN0, EN1r, EN1l), "theta.UMPBT" = theta.UMPBT, "theta1" = theta1,
"Type2.fixed.design" = c(Type2.fixed_design(theta = theta1$right, test.type = 'oneZ', side = 'right',
theta0 = theta0, sigma = sigma,
N = N.max, Type1 = Type1.target/2),
Type2.fixed_design(theta = theta1$left, test.type = 'oneZ', side = 'left',
theta0 = theta0, sigma = sigma,
N = N.max, Type1 = Type1.target/2)),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneZ', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else{
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'oneZ', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma),
'left' = UMPBT.alt(test.type = 'oneZ', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum0_n = cumsum1r_n = cumsum1l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = N1r.AR = N1r.AR.r = N1r.AR.l =
N1l.AR = N1l.AR.r = N1l.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum0_n = rnorm(length(not.reached.decisionH0.AR),
(batch.size[n+1]-batch.size[n])*theta0,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + sum0_n
LR0_n.r[not.reached.decisionH0.AR.r] =
exp((cumsum0_n[not.reached.decisionH0.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR0_n.l[not.reached.decisionH0.AR.l] =
exp((cumsum0_n[not.reached.decisionH0.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
sum1r_n = rnorm(length(not.reached.decisionH1r.AR),
(batch.size[n+1]-batch.size[n])*theta1$right,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1r_n[not.reached.decisionH1r.AR] =
cumsum1r_n[not.reached.decisionH1r.AR] + sum1r_n
LR1r_n.r[not.reached.decisionH1r.AR.r] =
exp((cumsum1r_n[not.reached.decisionH1r.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR1r_n.l[not.reached.decisionH1r.AR.l] =
exp((cumsum1r_n[not.reached.decisionH1r.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N1r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N1r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
sum1l_n = rnorm(length(not.reached.decisionH1l.AR),
(batch.size[n+1]-batch.size[n])*theta1$left,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1l_n[not.reached.decisionH1l.AR] =
cumsum1l_n[not.reached.decisionH1l.AR] + sum1l_n
LR1l_n.r[not.reached.decisionH1l.AR.r] =
exp((cumsum1l_n[not.reached.decisionH1l.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR1l_n.l[not.reached.decisionH1l.AR.l] =
exp((cumsum1l_n[not.reached.decisionH1l.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N1l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N1l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N1r.AR[accepted.by.both1r] = pmax(N1r.AR.r[accepted.by.both1r],
N1r.AR.l[accepted.by.both1r])
N1r.AR[onlyrejected.by.right1r] = N1r.AR.r[onlyrejected.by.right1r]
N1r.AR[onlyrejected.by.left1r] = N1r.AR.l[onlyrejected.by.left1r]
N1r.AR[rejected.by.both1r] = pmin(N1r.AR.r[rejected.by.both1r],
N1r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N1l.AR[accepted.by.both1l] = pmax(N1l.AR.r[accepted.by.both1l],
N1l.AR.l[accepted.by.both1l])
N1l.AR[onlyrejected.by.right1l] = N1l.AR.r[onlyrejected.by.right1l]
N1l.AR[onlyrejected.by.left1l] = N1l.AR.l[onlyrejected.by.left1l]
N1l.AR[rejected.by.both1l] = pmin(N1l.AR.r[rejected.by.both1l],
N1l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN0 = mean(N0.AR)
EN1r = mean(N1r.AR)
EN1l = mean(N1l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: ", round(EN1r, 2)))
print(paste(" On the left: ", round(EN1l, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = N0.AR, 'right' = N1r.AR, 'left' = N1l.AR),
'EN' = c(EN0, EN1r, EN1l), "theta.UMPBT" = theta.UMPBT, "theta1" = theta1,
"Type2.fixed.design" = c(Type2.fixed_design(theta = theta1$right, test.type = 'oneZ', side = 'right',
theta0 = theta0, sigma = sigma,
N = N.max, Type1 = Type1.target/2),
Type2.fixed_design(theta = theta1$left, test.type = 'oneZ', side = 'left',
theta0 = theta0, sigma = sigma,
N = N.max, Type1 = Type1.target/2)),
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneZ', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}
}
}
design.MSPRT_oneT = function(side = 'right', theta0 = 0, theta1 = T,
Type1.target =.005, Type2.target = .2,
N.max, batch.size,
nReplicate = 1e+6, verbose = T, seed = 1){
if(side!='both'){
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
nAnalyses = length(batch.size)
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch.size = c(0, cumsum(batch.size))
if(is.logical(theta1)&&(theta1==F)){
if(verbose==T){
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
signed_t.alpha = (2*(side=='right')-1)*qt(Type1.target, df = N.max -1, lower.tail = F)
cumSS0_n = cumsum0_n = LR0_n = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N0.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs0_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
})
}else{
obs0_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + rowSums(obs0_n)
cumSS0_n[not.reached.decisionH0.AR] =
cumSS0_n[not.reached.decisionH0.AR] + rowSums(obs0_n^2)
xbar0_n = cumsum0_n[not.reached.decisionH0.AR]/batch.size[n+1]
divisor.s0_n.sq =
cumSS0_n[not.reached.decisionH0.AR] - ((cumsum0_n[not.reached.decisionH0.AR])^2)/batch.size[n+1]
LR0_n[not.reached.decisionH0.AR] =
((1 + (batch.size[n+1]*((xbar0_n - theta0)^2))/divisor.s0_n.sq)/
(1 + (batch.size[n+1]*((xbar0_n - (theta0 + signed_t.alpha*
sqrt(divisor.s0_n.sq/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq))^(batch.size[n+1]/2)
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN0 = mean(N0.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("=========================================================================")
cat('\n')
}
return(list("TypeI.attained" = actual.type1.error.AR,
"N" = list('H0' = N0.AR), "EN" = EN0, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneT', 'side' = side, 'theta0' = theta0,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = fixed_design.alt(test.type = 'oneT', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, Type2 = Type2.target)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
signed_t.alpha = (2*(side=='right')-1)*qt(Type1.target, df = N.max -1, lower.tail = F)
cumSS0_n = cumSS1_n = cumsum0_n = cumsum1_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N0.AR = N1.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs0_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
})
}else{
obs0_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + rowSums(obs0_n)
cumSS0_n[not.reached.decisionH0.AR] =
cumSS0_n[not.reached.decisionH0.AR] + rowSums(obs0_n^2)
xbar0_n = cumsum0_n[not.reached.decisionH0.AR]/batch.size[n+1]
divisor.s0_n.sq =
cumSS0_n[not.reached.decisionH0.AR] - ((cumsum0_n[not.reached.decisionH0.AR])^2)/batch.size[n+1]
LR0_n[not.reached.decisionH0.AR] =
((1 + (batch.size[n+1]*((xbar0_n - theta0)^2))/divisor.s0_n.sq)/
(1 + (batch.size[n+1]*((xbar0_n - (theta0 + signed_t.alpha*
sqrt(divisor.s0_n.sq/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq))^(batch.size[n+1]/2)
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
if(length(not.reached.decisionH1.AR)>1){
obs1_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
})
}else{
obs1_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + rowSums(obs1_n)
cumSS1_n[not.reached.decisionH1.AR] =
cumSS1_n[not.reached.decisionH1.AR] + rowSums(obs1_n^2)
xbar1_n = cumsum1_n[not.reached.decisionH1.AR]/batch.size[n+1]
divisor.s1_n.sq =
cumSS1_n[not.reached.decisionH1.AR] - ((cumsum1_n[not.reached.decisionH1.AR])^2)/batch.size[n+1]
LR1_n[not.reached.decisionH1.AR] =
((1 + (batch.size[n+1]*((xbar1_n - theta0)^2))/divisor.s1_n.sq)/
(1 + (batch.size[n+1]*((xbar1_n - (theta0 + signed_t.alpha*
sqrt(divisor.s1_n.sq/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1_n.sq))^(batch.size[n+1]/2)
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN0 = mean(N0.AR)
EN1 = mean(N1.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print(paste("Expected sample size at the alternative: ", round(EN1, 2)))
print("=========================================================================")
cat('\n')
}
return(list("TypeI.attained" = actual.type1.error.AR,
"TypeII.attained" = actual.type2.error.AR,
"N" = list('H0' = N0.AR, 'H1' = N1.AR), "EN" = c(EN0, EN1),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneT', 'side' = side, 'theta0' = theta0,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else{
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
signed_t.alpha = (2*(side=='right')-1)*qt(Type1.target, df = N.max -1, lower.tail = F)
cumSS0_n = cumSS1_n = cumsum0_n = cumsum1_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N0.AR = N1.AR = rep(N.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs0_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
})
}else{
obs0_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + rowSums(obs0_n)
cumSS0_n[not.reached.decisionH0.AR] =
cumSS0_n[not.reached.decisionH0.AR] + rowSums(obs0_n^2)
xbar0_n = cumsum0_n[not.reached.decisionH0.AR]/batch.size[n+1]
divisor.s0_n.sq =
cumSS0_n[not.reached.decisionH0.AR] - ((cumsum0_n[not.reached.decisionH0.AR])^2)/batch.size[n+1]
LR0_n[not.reached.decisionH0.AR] =
((1 + (batch.size[n+1]*((xbar0_n - theta0)^2))/divisor.s0_n.sq)/
(1 + (batch.size[n+1]*((xbar0_n - (theta0 + signed_t.alpha*
sqrt(divisor.s0_n.sq/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq))^(batch.size[n+1]/2)
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N0.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
if(length(not.reached.decisionH1.AR)>1){
obs1_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
})
}else{
obs1_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + rowSums(obs1_n)
cumSS1_n[not.reached.decisionH1.AR] =
cumSS1_n[not.reached.decisionH1.AR] + rowSums(obs1_n^2)
xbar1_n = cumsum1_n[not.reached.decisionH1.AR]/batch.size[n+1]
divisor.s1_n.sq =
cumSS1_n[not.reached.decisionH1.AR] - ((cumsum1_n[not.reached.decisionH1.AR])^2)/batch.size[n+1]
LR1_n[not.reached.decisionH1.AR] =
((1 + (batch.size[n+1]*((xbar1_n - theta0)^2))/divisor.s1_n.sq)/
(1 + (batch.size[n+1]*((xbar1_n - (theta0 + signed_t.alpha*
sqrt(divisor.s1_n.sq/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1_n.sq))^(batch.size[n+1]/2)
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN0 = mean(N0.AR)
EN1 = mean(N1.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print(paste("Expected sample size at the alternative: ", round(EN1, 2)))
print("=========================================================================")
cat('\n')
}
return(list("TypeI.attained" = actual.type1.error.AR,
"TypeII.attained" = actual.type2.error.AR,
"N" = list('H0' = N0.AR, 'H1' = N1.AR), "EN" = c(EN0, EN1),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneT', 'side' = side, 'theta0' = theta0,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}
}else{
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
nAnalyses = length(batch.size)
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch.size = c(0, cumsum(batch.size))
if(is.logical(theta1)&&(theta1==F)){
if(verbose==T){
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
t.alpha = qt(Type1.target/2, df = N.max -1, lower.tail = F)
cumSS0_n = cumsum0_n = LR0_n.r = LR0_n.l = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs0_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
})
}else{
obs0_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + rowSums(obs0_n)
cumSS0_n[not.reached.decisionH0.AR] =
cumSS0_n[not.reached.decisionH0.AR] + rowSums(obs0_n^2)
xbar0_n.r = cumsum0_n[not.reached.decisionH0.AR.r]/batch.size[n+1]
divisor.s0_n.sq.r =
cumSS0_n[not.reached.decisionH0.AR.r] -
((cumsum0_n[not.reached.decisionH0.AR.r])^2)/batch.size[n+1]
xbar0_n.l = cumsum0_n[not.reached.decisionH0.AR.l]/batch.size[n+1]
divisor.s0_n.sq.l =
cumSS0_n[not.reached.decisionH0.AR.l] -
((cumsum0_n[not.reached.decisionH0.AR.l])^2)/batch.size[n+1]
LR0_n.r[not.reached.decisionH0.AR.r] =
((1 + (batch.size[n+1]*((xbar0_n.r - theta0)^2))/divisor.s0_n.sq.r)/
(1 + (batch.size[n+1]*((xbar0_n.r -
(theta0 + t.alpha*
sqrt(divisor.s0_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq.r))^(batch.size[n+1]/2)
LR0_n.l[not.reached.decisionH0.AR.l] =
((1 + (batch.size[n+1]*((xbar0_n.l - theta0)^2))/divisor.s0_n.sq.l)/
(1 + (batch.size[n+1]*((xbar0_n.l -
(theta0 - t.alpha*
sqrt(divisor.s0_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN0 = mean(N0.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
'N' = list('H0' = N0.AR), 'EN' = EN0, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneT', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = list('right' = fixed_design.alt(test.type = 'oneT', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, Type2 = Type2.target),
'left' = fixed_design.alt(test.type = 'oneT', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, Type2 = Type2.target))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
t.alpha = qt(Type1.target/2, df = N.max -1, lower.tail = F)
cumSS0_n = cumSS1r_n = cumSS1l_n =
cumsum0_n = cumsum1r_n = cumsum1l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = N1r.AR = N1r.AR.r = N1r.AR.l =
N1l.AR = N1l.AR.r = N1l.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs0_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
})
}else{
obs0_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + rowSums(obs0_n)
cumSS0_n[not.reached.decisionH0.AR] =
cumSS0_n[not.reached.decisionH0.AR] + rowSums(obs0_n^2)
xbar0_n.r = cumsum0_n[not.reached.decisionH0.AR.r]/batch.size[n+1]
divisor.s0_n.sq.r =
cumSS0_n[not.reached.decisionH0.AR.r] -
((cumsum0_n[not.reached.decisionH0.AR.r])^2)/batch.size[n+1]
xbar0_n.l = cumsum0_n[not.reached.decisionH0.AR.l]/batch.size[n+1]
divisor.s0_n.sq.l =
cumSS0_n[not.reached.decisionH0.AR.l] -
((cumsum0_n[not.reached.decisionH0.AR.l])^2)/batch.size[n+1]
LR0_n.r[not.reached.decisionH0.AR.r] =
((1 + (batch.size[n+1]*((xbar0_n.r - theta0)^2))/divisor.s0_n.sq.r)/
(1 + (batch.size[n+1]*((xbar0_n.r -
(theta0 + t.alpha*
sqrt(divisor.s0_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq.r))^(batch.size[n+1]/2)
LR0_n.l[not.reached.decisionH0.AR.l] =
((1 + (batch.size[n+1]*((xbar0_n.l - theta0)^2))/divisor.s0_n.sq.l)/
(1 + (batch.size[n+1]*((xbar0_n.l -
(theta0 - t.alpha*
sqrt(divisor.s0_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
if(length(not.reached.decisionH1r.AR)>1){
obs1r_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right, 1)
})
}else{
obs1r_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1r_n[not.reached.decisionH1r.AR] =
cumsum1r_n[not.reached.decisionH1r.AR] + rowSums(obs1r_n)
cumSS1r_n[not.reached.decisionH1r.AR] =
cumSS1r_n[not.reached.decisionH1r.AR] + rowSums(obs1r_n^2)
xbar1r_n.r = cumsum1r_n[not.reached.decisionH1r.AR.r]/batch.size[n+1]
divisor.s1r_n.sq.r =
cumSS1r_n[not.reached.decisionH1r.AR.r] -
((cumsum1r_n[not.reached.decisionH1r.AR.r])^2)/batch.size[n+1]
xbar1r_n.l = cumsum1r_n[not.reached.decisionH1r.AR.l]/batch.size[n+1]
divisor.s1r_n.sq.l =
cumSS1r_n[not.reached.decisionH1r.AR.l] -
((cumsum1r_n[not.reached.decisionH1r.AR.l])^2)/batch.size[n+1]
LR1r_n.r[not.reached.decisionH1r.AR.r] =
((1 + (batch.size[n+1]*((xbar1r_n.r - theta0)^2))/divisor.s1r_n.sq.r)/
(1 + (batch.size[n+1]*((xbar1r_n.r -
(theta0 + t.alpha*
sqrt(divisor.s1r_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1r_n.sq.r))^(batch.size[n+1]/2)
LR1r_n.l[not.reached.decisionH1r.AR.l] =
((1 + (batch.size[n+1]*((xbar1r_n.l - theta0)^2))/divisor.s1r_n.sq.l)/
(1 + (batch.size[n+1]*((xbar1r_n.l -
(theta0 - t.alpha*
sqrt(divisor.s1r_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1r_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N1r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N1r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
if(length(not.reached.decisionH1l.AR)>1){
obs1l_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left, 1)
})
}else{
obs1l_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1l_n[not.reached.decisionH1l.AR] =
cumsum1l_n[not.reached.decisionH1l.AR] + rowSums(obs1l_n)
cumSS1l_n[not.reached.decisionH1l.AR] =
cumSS1l_n[not.reached.decisionH1l.AR] + rowSums(obs1l_n^2)
xbar1l_n.r = cumsum1l_n[not.reached.decisionH1l.AR.r]/batch.size[n+1]
divisor.s1l_n.sq.r =
cumSS1l_n[not.reached.decisionH1l.AR.r] -
((cumsum1l_n[not.reached.decisionH1l.AR.r])^2)/batch.size[n+1]
xbar1l_n.l = cumsum1l_n[not.reached.decisionH1l.AR.l]/batch.size[n+1]
divisor.s1l_n.sq.l =
cumSS1l_n[not.reached.decisionH1l.AR.l] -
((cumsum1l_n[not.reached.decisionH1l.AR.l])^2)/batch.size[n+1]
LR1l_n.r[not.reached.decisionH1l.AR.r] =
((1 + (batch.size[n+1]*((xbar1l_n.r - theta0)^2))/divisor.s1l_n.sq.r)/
(1 + (batch.size[n+1]*((xbar1l_n.r -
(theta0 + t.alpha*
sqrt(divisor.s1l_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1l_n.sq.r))^(batch.size[n+1]/2)
LR1l_n.l[not.reached.decisionH1l.AR.l] =
((1 + (batch.size[n+1]*((xbar1l_n.l - theta0)^2))/divisor.s1l_n.sq.l)/
(1 + (batch.size[n+1]*((xbar1l_n.l -
(theta0 - t.alpha*
sqrt(divisor.s1l_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1l_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N1l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N1l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N1r.AR[accepted.by.both1r] = pmax(N1r.AR.r[accepted.by.both1r],
N1r.AR.l[accepted.by.both1r])
N1r.AR[onlyrejected.by.right1r] = N1r.AR.r[onlyrejected.by.right1r]
N1r.AR[onlyrejected.by.left1r] = N1r.AR.l[onlyrejected.by.left1r]
N1r.AR[rejected.by.both1r] = pmin(N1r.AR.r[rejected.by.both1r],
N1r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N1l.AR[accepted.by.both1l] = pmax(N1l.AR.r[accepted.by.both1l],
N1l.AR.l[accepted.by.both1l])
N1l.AR[onlyrejected.by.right1l] = N1l.AR.r[onlyrejected.by.right1l]
N1l.AR[onlyrejected.by.left1l] = N1l.AR.l[onlyrejected.by.left1l]
N1l.AR[rejected.by.both1l] = pmin(N1l.AR.r[rejected.by.both1l],
N1l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN0 = mean(N0.AR)
EN1r = mean(N1r.AR)
EN1l = mean(N1l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: ", round(EN1r, 2)))
print(paste(" On the left: ", round(EN1l, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = N0.AR, 'right' = N1r.AR, 'left' = N1l.AR),
'EN' = c(EN0, EN1r, EN1l),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneT', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}else{
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
t.alpha = qt(Type1.target/2, df = N.max -1, lower.tail = F)
cumSS0_n = cumSS1r_n = cumSS1l_n =
cumsum0_n = cumsum1r_n = cumsum1l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N0.AR = N0.AR.r = N0.AR.l = N1r.AR = N1r.AR.r = N1r.AR.l =
N1l.AR = N1l.AR.r = N1l.AR.l = rep(N.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs0_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
})
}else{
obs0_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum0_n[not.reached.decisionH0.AR] =
cumsum0_n[not.reached.decisionH0.AR] + rowSums(obs0_n)
cumSS0_n[not.reached.decisionH0.AR] =
cumSS0_n[not.reached.decisionH0.AR] + rowSums(obs0_n^2)
xbar0_n.r = cumsum0_n[not.reached.decisionH0.AR.r]/batch.size[n+1]
divisor.s0_n.sq.r =
cumSS0_n[not.reached.decisionH0.AR.r] -
((cumsum0_n[not.reached.decisionH0.AR.r])^2)/batch.size[n+1]
xbar0_n.l = cumsum0_n[not.reached.decisionH0.AR.l]/batch.size[n+1]
divisor.s0_n.sq.l =
cumSS0_n[not.reached.decisionH0.AR.l] -
((cumsum0_n[not.reached.decisionH0.AR.l])^2)/batch.size[n+1]
LR0_n.r[not.reached.decisionH0.AR.r] =
((1 + (batch.size[n+1]*((xbar0_n.r - theta0)^2))/divisor.s0_n.sq.r)/
(1 + (batch.size[n+1]*((xbar0_n.r -
(theta0 + t.alpha*
sqrt(divisor.s0_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq.r))^(batch.size[n+1]/2)
LR0_n.l[not.reached.decisionH0.AR.l] =
((1 + (batch.size[n+1]*((xbar0_n.l - theta0)^2))/divisor.s0_n.sq.l)/
(1 + (batch.size[n+1]*((xbar0_n.l -
(theta0 - t.alpha*
sqrt(divisor.s0_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s0_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N0.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N0.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
if(length(not.reached.decisionH1r.AR)>1){
obs1r_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right, 1)
})
}else{
obs1r_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1r_n[not.reached.decisionH1r.AR] =
cumsum1r_n[not.reached.decisionH1r.AR] + rowSums(obs1r_n)
cumSS1r_n[not.reached.decisionH1r.AR] =
cumSS1r_n[not.reached.decisionH1r.AR] + rowSums(obs1r_n^2)
xbar1r_n.r = cumsum1r_n[not.reached.decisionH1r.AR.r]/batch.size[n+1]
divisor.s1r_n.sq.r =
cumSS1r_n[not.reached.decisionH1r.AR.r] -
((cumsum1r_n[not.reached.decisionH1r.AR.r])^2)/batch.size[n+1]
xbar1r_n.l = cumsum1r_n[not.reached.decisionH1r.AR.l]/batch.size[n+1]
divisor.s1r_n.sq.l =
cumSS1r_n[not.reached.decisionH1r.AR.l] -
((cumsum1r_n[not.reached.decisionH1r.AR.l])^2)/batch.size[n+1]
LR1r_n.r[not.reached.decisionH1r.AR.r] =
((1 + (batch.size[n+1]*((xbar1r_n.r - theta0)^2))/divisor.s1r_n.sq.r)/
(1 + (batch.size[n+1]*((xbar1r_n.r -
(theta0 + t.alpha*
sqrt(divisor.s1r_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1r_n.sq.r))^(batch.size[n+1]/2)
LR1r_n.l[not.reached.decisionH1r.AR.l] =
((1 + (batch.size[n+1]*((xbar1r_n.l - theta0)^2))/divisor.s1r_n.sq.l)/
(1 + (batch.size[n+1]*((xbar1r_n.l -
(theta0 - t.alpha*
sqrt(divisor.s1r_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1r_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N1r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N1r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
if(length(not.reached.decisionH1l.AR)>1){
obs1l_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left, 1)
})
}else{
obs1l_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1l_n[not.reached.decisionH1l.AR] =
cumsum1l_n[not.reached.decisionH1l.AR] + rowSums(obs1l_n)
cumSS1l_n[not.reached.decisionH1l.AR] =
cumSS1l_n[not.reached.decisionH1l.AR] + rowSums(obs1l_n^2)
xbar1l_n.r = cumsum1l_n[not.reached.decisionH1l.AR.r]/batch.size[n+1]
divisor.s1l_n.sq.r =
cumSS1l_n[not.reached.decisionH1l.AR.r] -
((cumsum1l_n[not.reached.decisionH1l.AR.r])^2)/batch.size[n+1]
xbar1l_n.l = cumsum1l_n[not.reached.decisionH1l.AR.l]/batch.size[n+1]
divisor.s1l_n.sq.l =
cumSS1l_n[not.reached.decisionH1l.AR.l] -
((cumsum1l_n[not.reached.decisionH1l.AR.l])^2)/batch.size[n+1]
LR1l_n.r[not.reached.decisionH1l.AR.r] =
((1 + (batch.size[n+1]*((xbar1l_n.r - theta0)^2))/divisor.s1l_n.sq.r)/
(1 + (batch.size[n+1]*((xbar1l_n.r -
(theta0 + t.alpha*
sqrt(divisor.s1l_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1l_n.sq.r))^(batch.size[n+1]/2)
LR1l_n.l[not.reached.decisionH1l.AR.l] =
((1 + (batch.size[n+1]*((xbar1l_n.l - theta0)^2))/divisor.s1l_n.sq.l)/
(1 + (batch.size[n+1]*((xbar1l_n.l -
(theta0 - t.alpha*
sqrt(divisor.s1l_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1l_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N1l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N1l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N0.AR[accepted.by.both0] = pmax(N0.AR.r[accepted.by.both0],
N0.AR.l[accepted.by.both0])
N0.AR[onlyrejected.by.right0] = N0.AR.r[onlyrejected.by.right0]
N0.AR[onlyrejected.by.left0] = N0.AR.l[onlyrejected.by.left0]
N0.AR[rejected.by.both0] = pmin(N0.AR.r[rejected.by.both0],
N0.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N1r.AR[accepted.by.both1r] = pmax(N1r.AR.r[accepted.by.both1r],
N1r.AR.l[accepted.by.both1r])
N1r.AR[onlyrejected.by.right1r] = N1r.AR.r[onlyrejected.by.right1r]
N1r.AR[onlyrejected.by.left1r] = N1r.AR.l[onlyrejected.by.left1r]
N1r.AR[rejected.by.both1r] = pmin(N1r.AR.r[rejected.by.both1r],
N1r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N1l.AR[accepted.by.both1l] = pmax(N1l.AR.r[accepted.by.both1l],
N1l.AR.l[accepted.by.both1l])
N1l.AR[onlyrejected.by.right1l] = N1l.AR.r[onlyrejected.by.right1l]
N1l.AR[onlyrejected.by.left1l] = N1l.AR.l[onlyrejected.by.left1l]
N1l.AR[rejected.by.both1l] = pmin(N1l.AR.r[rejected.by.both1l],
N1l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN0 = mean(N0.AR)
EN1r = mean(N1r.AR)
EN1l = mean(N1l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: ", round(EN0, 2)))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: ", round(EN1r, 2)))
print(paste(" On the left: ", round(EN1l, 2)))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = N0.AR, 'right' = N1r.AR, 'left' = N1l.AR),
'EN' = c(EN0, EN1r, EN1l),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'oneT', 'side' = side, 'theta0' = theta0, 'sigma' = sigma,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'N.max' = N.max, 'batch.size' = diff(batch.size), 'nAnalyses' = nAnalyses,
'nReplicate' = nReplicate, 'seed' = seed))
}
}
}
design.MSPRT_twoZ = function(side = 'right', theta0 = 0, theta1 = T,
Type1.target =.005, Type2.target = .2,
N1.max, N2.max, sigma1 = 1, sigma2 = 1,
batch1.size, batch2.size,
nReplicate = 1e+6, verbose = T, seed = 1){
if(side!='both'){
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
nAnalyses = length(batch1.size)
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
if(is.logical(theta1)&&(theta1==F)){
theta.UMPBT = UMPBT.alt(test.type = 'twoZ', side = side, theta0 = theta0,
N1 = N1.max, N2 = N2.max, Type1 = Type1.target,
sigma1 = sigma1, sigma2 = sigma2)
if(verbose==T){
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum10_n = cumsum20_n = LR0_n = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N10.AR = rep(N1.max, nReplicate)
N20.AR = rep(N2.max, nReplicate)
not.reached.decisionH0.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum10_n = rnorm(length(not.reached.decisionH0.AR),
(batch1.size[n+1]-batch1.size[n])*(theta0/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum20_n = rnorm(length(not.reached.decisionH0.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta0/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + sum10_n
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + sum20_n
LR0_n[not.reached.decisionH0.AR] =
exp(-(((theta.UMPBT^2) - (theta0^2)) -
2*(theta.UMPBT - theta0)*
(cumsum10_n[not.reached.decisionH0.AR]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N10.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch1.size[n+1]
N20.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch2.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", actual.type1.error.AR))
print(paste(" Expected sample size under H0: Group 1 - ", round(EN10, 2),
", Group 2 - ", round(EN20, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20)),
"theta.UMPBT" = theta.UMPBT, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoZ', 'side' = side, 'theta0' = theta0,
'sigma1' = sigma1, 'sigma2' = sigma2, 'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = fixed_design.alt(test.type = 'twoZ', side = side, theta0 = theta0,
N1 = N1.max, N2 = N2.max, Type1 = Type1.target,
Type2 = Type2.target, sigma1 = 1, sigma2 = 1)
theta.UMPBT = UMPBT.alt(test.type = 'twoZ', side = side, theta0 = theta0,
N1 = N1.max, N2 = N2.max, Type1 = Type1.target,
sigma1 = sigma1, sigma2 = sigma2)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum10_n = cumsum20_n = cumsum11_n = cumsum21_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N10.AR = N11.AR = rep(N1.max, nReplicate)
N20.AR = N21.AR = rep(N2.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum10_n = rnorm(length(not.reached.decisionH0.AR),
(batch1.size[n+1]-batch1.size[n])*(theta0/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum20_n = rnorm(length(not.reached.decisionH0.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta0/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + sum10_n
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + sum20_n
LR0_n[not.reached.decisionH0.AR] =
exp(-(((theta.UMPBT^2) - (theta0^2)) -
2*(theta.UMPBT - theta0)*
(cumsum10_n[not.reached.decisionH0.AR]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N10.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch1.size[n+1]
N20.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch2.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
sum11_n = rnorm(length(not.reached.decisionH1.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21_n = rnorm(length(not.reached.decisionH1.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + sum11_n
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + sum21_n
LR1_n[not.reached.decisionH1.AR] =
exp(-(((theta.UMPBT^2) - (theta0^2)) -
2*(theta.UMPBT - theta0)*
(cumsum11_n[not.reached.decisionH1.AR]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N11.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch1.size[n+1]
N21.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch2.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste(" Expected sample size under H0: Group 1 - ", round(EN10, 2),
", Group 2 - ", round(EN20, 2), sep = ''))
print(paste(" Expected sample size at the alternative: Group 1 - ", round(EN11, 2),
", Group 2 - ", round(EN21, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = actual.type2.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'H1' = list('Group1' = N11.AR, 'Group2' = N21.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'H1' = list('Group1' = EN11, 'Group2' = EN21)),
"theta.UMPBT" = theta.UMPBT,
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoZ', 'side' = side, 'theta0' = theta0,
'sigma1' = sigma1, 'sigma2' = sigma2, 'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else{
theta.UMPBT = UMPBT.alt(test.type = 'twoZ', side = side, theta0 = theta0,
N1 = N1.max, N2 = N2.max, Type1 = Type1.target,
sigma1 = sigma1, sigma2 = sigma2)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
cumsum10_n = cumsum20_n = cumsum11_n = cumsum21_n = LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N10.AR = N11.AR = rep(N1.max, nReplicate)
N20.AR = N21.AR = rep(N2.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum10_n = rnorm(length(not.reached.decisionH0.AR),
(batch1.size[n+1]-batch1.size[n])*(theta0/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum20_n = rnorm(length(not.reached.decisionH0.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta0/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + sum10_n
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + sum20_n
LR0_n[not.reached.decisionH0.AR] =
exp(-(((theta.UMPBT^2) - (theta0^2)) -
2*(theta.UMPBT - theta0)*
(cumsum10_n[not.reached.decisionH0.AR]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N10.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch1.size[n+1]
N20.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch2.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
sum11_n = rnorm(length(not.reached.decisionH1.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21_n = rnorm(length(not.reached.decisionH1.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + sum11_n
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + sum21_n
LR1_n[not.reached.decisionH1.AR] =
exp(-(((theta.UMPBT^2) - (theta0^2)) -
2*(theta.UMPBT - theta0)*
(cumsum11_n[not.reached.decisionH1.AR]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N11.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch1.size[n+1]
N21.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch2.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste(" Expected sample size under H0: Group 1 - ", round(EN10, 2),
", Group 2 - ", round(EN20, 2), sep = ''))
print(paste(" Expected sample size at the alternative: Group 1 - ", round(EN11, 2),
", Group 2 - ", round(EN21, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = actual.type2.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'H1' = list('Group1' = N11.AR, 'Group2' = N21.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'H1' = list('Group1' = EN11, 'Group2' = EN21)),
"theta.UMPBT" = theta.UMPBT,
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoZ', 'side' = side, 'theta0' = theta0,
'sigma1' = sigma1, 'sigma2' = sigma2, 'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}
}else{
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
nAnalyses = length(batch1.size)
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
if(is.logical(theta1)&&(theta1==F)){
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'twoZ', side = 'right',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2),
'left' = UMPBT.alt(test.type = 'twoZ', side = 'left',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2))
if(verbose==T){
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum10_n = cumsum20_n = LR0_n.r = LR0_n.l = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N10.AR = N10.AR.r = N10.AR.l = rep(N1.max, nReplicate)
N20.AR = N20.AR.r = N20.AR.l = rep(N2.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum10_n = rnorm(length(not.reached.decisionH0.AR),
(batch1.size[n+1]-batch1.size[n])*(theta0/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum20_n = rnorm(length(not.reached.decisionH0.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta0/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + sum10_n
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + sum20_n
LR0_n.r[not.reached.decisionH0.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum10_n[not.reached.decisionH0.AR.r]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR0_n.l[not.reached.decisionH0.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum10_n[not.reached.decisionH0.AR.l]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N10.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch1.size[n+1]
N20.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N10.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch1.size[n+1]
N20.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N10.AR[accepted.by.both0] = pmax(N10.AR.r[accepted.by.both0],
N10.AR.l[accepted.by.both0])
N10.AR[onlyrejected.by.right0] = N10.AR.r[onlyrejected.by.right0]
N10.AR[onlyrejected.by.left0] = N10.AR.l[onlyrejected.by.left0]
N10.AR[rejected.by.both0] = pmin(N10.AR.r[rejected.by.both0],
N10.AR.l[rejected.by.both0])
N20.AR[accepted.by.both0] = pmax(N20.AR.r[accepted.by.both0],
N20.AR.l[accepted.by.both0])
N20.AR[onlyrejected.by.right0] = N20.AR.r[onlyrejected.by.right0]
N20.AR[onlyrejected.by.left0] = N20.AR.l[onlyrejected.by.left0]
N20.AR[rejected.by.both0] = pmin(N20.AR.r[rejected.by.both0],
N20.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: Group 1 - ", round(EN10, 2),
', Group 2 - ', round(EN20, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20)),
"theta.UMPBT" = theta.UMPBT, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoZ', 'side' = side, 'theta0' = theta0,
'sigma1' = sigma1, 'sigma2' = sigma2, 'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = list('right' = fixed_design.alt(test.type = 'twoZ', side = 'right',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
Type2 = Type2.target, sigma1 = sigma1, sigma2 = sigma2),
'left' = fixed_design.alt(test.type = 'twoZ', side = 'left',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
Type2 = Type2.target, sigma1 = sigma1, sigma2 = sigma2))
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'twoZ', side = 'right',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2),
'left' = UMPBT.alt(test.type = 'twoZ', side = 'left',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum10_n = cumsum20_n = cumsum11r_n = cumsum21r_n = cumsum11l_n = cumsum21l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N10.AR = N10.AR.r = N10.AR.l =
N11r.AR = N11r.AR.r = N11r.AR.l =
N11l.AR = N11l.AR.r = N11l.AR.l = rep(N1.max, nReplicate)
N20.AR = N20.AR.r = N20.AR.l =
N21r.AR = N21r.AR.r = N21r.AR.l =
N21l.AR = N21l.AR.r = N21l.AR.l = rep(N2.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum10_n = rnorm(length(not.reached.decisionH0.AR),
(batch1.size[n+1]-batch1.size[n])*(theta0/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum20_n = rnorm(length(not.reached.decisionH0.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta0/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + sum10_n
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + sum20_n
LR0_n.r[not.reached.decisionH0.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum10_n[not.reached.decisionH0.AR.r]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR0_n.l[not.reached.decisionH0.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum10_n[not.reached.decisionH0.AR.l]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N10.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch1.size[n+1]
N20.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N10.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch1.size[n+1]
N20.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
sum11r_n = rnorm(length(not.reached.decisionH1r.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1$right/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21r_n = rnorm(length(not.reached.decisionH1r.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1$right/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11r_n[not.reached.decisionH1r.AR] =
cumsum11r_n[not.reached.decisionH1r.AR] + sum11r_n
cumsum21r_n[not.reached.decisionH1r.AR] =
cumsum21r_n[not.reached.decisionH1r.AR] + sum21r_n
LR1r_n.r[not.reached.decisionH1r.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum11r_n[not.reached.decisionH1r.AR.r]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR1r_n.l[not.reached.decisionH1r.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum11r_n[not.reached.decisionH1r.AR.l]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N11r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch1.size[n+1]
N21r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N11r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch1.size[n+1]
N21r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
sum11l_n = rnorm(length(not.reached.decisionH1l.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1$left/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21l_n = rnorm(length(not.reached.decisionH1l.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1$left/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11l_n[not.reached.decisionH1l.AR] =
cumsum11l_n[not.reached.decisionH1l.AR] + sum11l_n
cumsum21l_n[not.reached.decisionH1l.AR] =
cumsum21l_n[not.reached.decisionH1l.AR] + sum21l_n
LR1l_n.r[not.reached.decisionH1l.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum11l_n[not.reached.decisionH1l.AR.r]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR1l_n.l[not.reached.decisionH1l.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum11l_n[not.reached.decisionH1l.AR.l]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N11l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch1.size[n+1]
N21l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N11l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch1.size[n+1]
N21l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N10.AR[accepted.by.both0] = pmax(N10.AR.r[accepted.by.both0],
N10.AR.l[accepted.by.both0])
N10.AR[onlyrejected.by.right0] = N10.AR.r[onlyrejected.by.right0]
N10.AR[onlyrejected.by.left0] = N10.AR.l[onlyrejected.by.left0]
N10.AR[rejected.by.both0] = pmin(N10.AR.r[rejected.by.both0],
N10.AR.l[rejected.by.both0])
N20.AR[accepted.by.both0] = pmax(N20.AR.r[accepted.by.both0],
N20.AR.l[accepted.by.both0])
N20.AR[onlyrejected.by.right0] = N20.AR.r[onlyrejected.by.right0]
N20.AR[onlyrejected.by.left0] = N20.AR.l[onlyrejected.by.left0]
N20.AR[rejected.by.both0] = pmin(N20.AR.r[rejected.by.both0],
N20.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N11r.AR[accepted.by.both1r] = pmax(N11r.AR.r[accepted.by.both1r],
N11r.AR.l[accepted.by.both1r])
N11r.AR[onlyrejected.by.right1r] = N11r.AR.r[onlyrejected.by.right1r]
N11r.AR[onlyrejected.by.left1r] = N11r.AR.l[onlyrejected.by.left1r]
N11r.AR[rejected.by.both1r] = pmin(N11r.AR.r[rejected.by.both1r],
N11r.AR.l[rejected.by.both1r])
N21r.AR[accepted.by.both1r] = pmax(N21r.AR.r[accepted.by.both1r],
N21r.AR.l[accepted.by.both1r])
N21r.AR[onlyrejected.by.right1r] = N21r.AR.r[onlyrejected.by.right1r]
N21r.AR[onlyrejected.by.left1r] = N21r.AR.l[onlyrejected.by.left1r]
N21r.AR[rejected.by.both1r] = pmin(N21r.AR.r[rejected.by.both1r],
N21r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N11l.AR[accepted.by.both1l] = pmax(N11l.AR.r[accepted.by.both1l],
N11l.AR.l[accepted.by.both1l])
N11l.AR[onlyrejected.by.right1l] = N11l.AR.r[onlyrejected.by.right1l]
N11l.AR[onlyrejected.by.left1l] = N11l.AR.l[onlyrejected.by.left1l]
N11l.AR[rejected.by.both1l] = pmin(N11l.AR.r[rejected.by.both1l],
N11l.AR.l[rejected.by.both1l])
N21l.AR[accepted.by.both1l] = pmax(N21l.AR.r[accepted.by.both1l],
N21l.AR.l[accepted.by.both1l])
N21l.AR[onlyrejected.by.right1l] = N21l.AR.r[onlyrejected.by.right1l]
N21l.AR[onlyrejected.by.left1l] = N21l.AR.l[onlyrejected.by.left1l]
N21l.AR[rejected.by.both1l] = pmin(N21l.AR.r[rejected.by.both1l],
N21l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN10 = mean(N10.AR)
EN11r = mean(N11r.AR)
EN11l = mean(N11l.AR)
EN20 = mean(N20.AR)
EN21r = mean(N21r.AR)
EN21l = mean(N21l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: Group 1 - ", round(EN10, 2),
', Group 2 - ', round(EN20, 2), sep = ''))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: Group 1 - ", round(EN11r, 2),
', Group 2 - ', round(EN21r, 2), sep = ''))
print(paste(" On the left: Group 1 - ", round(EN11l, 2),
', Group 2 - ', round(EN21l, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'right' = list('Group1' = N11r.AR, 'Group2' = N21r.AR),
'left' = list('Group1' = N11l.AR, 'Group2' = N21l.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'right' = list('Group1' = EN11r, 'Group2' = EN21r),
'left' = list('Group1' = EN11l, 'Group2' = EN21l)),
"theta.UMPBT" = theta.UMPBT,
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoZ', 'side' = side, 'theta0' = theta0,
'sigma1' = sigma1, 'sigma2' = sigma2, 'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else{
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'twoZ', side = 'right',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2),
'left' = UMPBT.alt(test.type = 'twoZ', side = 'left',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
cumsum10_n = cumsum20_n = cumsum11r_n = cumsum21r_n = cumsum11l_n = cumsum21l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N10.AR = N10.AR.r = N10.AR.l =
N11r.AR = N11r.AR.r = N11r.AR.l =
N11l.AR = N11l.AR.r = N11l.AR.l = rep(N1.max, nReplicate)
N20.AR = N20.AR.r = N20.AR.l =
N21r.AR = N21r.AR.r = N21r.AR.l =
N21l.AR = N21l.AR.r = N21l.AR.l = rep(N2.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
sum10_n = rnorm(length(not.reached.decisionH0.AR),
(batch1.size[n+1]-batch1.size[n])*(theta0/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum20_n = rnorm(length(not.reached.decisionH0.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta0/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + sum10_n
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + sum20_n
LR0_n.r[not.reached.decisionH0.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum10_n[not.reached.decisionH0.AR.r]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR0_n.l[not.reached.decisionH0.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum10_n[not.reached.decisionH0.AR.l]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N10.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch1.size[n+1]
N20.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N10.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch1.size[n+1]
N20.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
sum11r_n = rnorm(length(not.reached.decisionH1r.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1$right/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21r_n = rnorm(length(not.reached.decisionH1r.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1$right/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11r_n[not.reached.decisionH1r.AR] =
cumsum11r_n[not.reached.decisionH1r.AR] + sum11r_n
cumsum21r_n[not.reached.decisionH1r.AR] =
cumsum21r_n[not.reached.decisionH1r.AR] + sum21r_n
LR1r_n.r[not.reached.decisionH1r.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum11r_n[not.reached.decisionH1r.AR.r]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR1r_n.l[not.reached.decisionH1r.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum11r_n[not.reached.decisionH1r.AR.l]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N11r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch1.size[n+1]
N21r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N11r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch1.size[n+1]
N21r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
sum11l_n = rnorm(length(not.reached.decisionH1l.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1$left/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21l_n = rnorm(length(not.reached.decisionH1l.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1$left/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11l_n[not.reached.decisionH1l.AR] =
cumsum11l_n[not.reached.decisionH1l.AR] + sum11l_n
cumsum21l_n[not.reached.decisionH1l.AR] =
cumsum21l_n[not.reached.decisionH1l.AR] + sum21l_n
LR1l_n.r[not.reached.decisionH1l.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum11l_n[not.reached.decisionH1l.AR.r]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR1l_n.l[not.reached.decisionH1l.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum11l_n[not.reached.decisionH1l.AR.l]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N11l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch1.size[n+1]
N21l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N11l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch1.size[n+1]
N21l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N10.AR[accepted.by.both0] = pmax(N10.AR.r[accepted.by.both0],
N10.AR.l[accepted.by.both0])
N10.AR[onlyrejected.by.right0] = N10.AR.r[onlyrejected.by.right0]
N10.AR[onlyrejected.by.left0] = N10.AR.l[onlyrejected.by.left0]
N10.AR[rejected.by.both0] = pmin(N10.AR.r[rejected.by.both0],
N10.AR.l[rejected.by.both0])
N20.AR[accepted.by.both0] = pmax(N20.AR.r[accepted.by.both0],
N20.AR.l[accepted.by.both0])
N20.AR[onlyrejected.by.right0] = N20.AR.r[onlyrejected.by.right0]
N20.AR[onlyrejected.by.left0] = N20.AR.l[onlyrejected.by.left0]
N20.AR[rejected.by.both0] = pmin(N20.AR.r[rejected.by.both0],
N20.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N11r.AR[accepted.by.both1r] = pmax(N11r.AR.r[accepted.by.both1r],
N11r.AR.l[accepted.by.both1r])
N11r.AR[onlyrejected.by.right1r] = N11r.AR.r[onlyrejected.by.right1r]
N11r.AR[onlyrejected.by.left1r] = N11r.AR.l[onlyrejected.by.left1r]
N11r.AR[rejected.by.both1r] = pmin(N11r.AR.r[rejected.by.both1r],
N11r.AR.l[rejected.by.both1r])
N21r.AR[accepted.by.both1r] = pmax(N21r.AR.r[accepted.by.both1r],
N21r.AR.l[accepted.by.both1r])
N21r.AR[onlyrejected.by.right1r] = N21r.AR.r[onlyrejected.by.right1r]
N21r.AR[onlyrejected.by.left1r] = N21r.AR.l[onlyrejected.by.left1r]
N21r.AR[rejected.by.both1r] = pmin(N21r.AR.r[rejected.by.both1r],
N21r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N11l.AR[accepted.by.both1l] = pmax(N11l.AR.r[accepted.by.both1l],
N11l.AR.l[accepted.by.both1l])
N11l.AR[onlyrejected.by.right1l] = N11l.AR.r[onlyrejected.by.right1l]
N11l.AR[onlyrejected.by.left1l] = N11l.AR.l[onlyrejected.by.left1l]
N11l.AR[rejected.by.both1l] = pmin(N11l.AR.r[rejected.by.both1l],
N11l.AR.l[rejected.by.both1l])
N21l.AR[accepted.by.both1l] = pmax(N21l.AR.r[accepted.by.both1l],
N21l.AR.l[accepted.by.both1l])
N21l.AR[onlyrejected.by.right1l] = N21l.AR.r[onlyrejected.by.right1l]
N21l.AR[onlyrejected.by.left1l] = N21l.AR.l[onlyrejected.by.left1l]
N21l.AR[rejected.by.both1l] = pmin(N21l.AR.r[rejected.by.both1l],
N21l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN10 = mean(N10.AR)
EN11r = mean(N11r.AR)
EN11l = mean(N11l.AR)
EN20 = mean(N20.AR)
EN21r = mean(N21r.AR)
EN21l = mean(N21l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: Group 1 - ", round(EN10, 2),
', Group 2 - ', round(EN20, 2), sep = ''))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: Group 1 - ", round(EN11r, 2),
', Group 2 - ', round(EN21r, 2), sep = ''))
print(paste(" On the left: Group 1 - ", round(EN11l, 2),
', Group 2 - ', round(EN21l, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'right' = list('Group1' = N11r.AR, 'Group2' = N21r.AR),
'left' = list('Group1' = N11l.AR, 'Group2' = N21l.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'right' = list('Group1' = EN11r, 'Group2' = EN21r),
'left' = list('Group1' = EN11l, 'Group2' = EN21l)),
"theta.UMPBT" = theta.UMPBT,
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoZ', 'side' = side, 'theta0' = theta0,
'sigma1' = sigma1, 'sigma2' = sigma2, 'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}
}
}
design.MSPRT_twoT = function(side = 'right', theta0 = 0, theta1 = T,
Type1.target =.005, Type2.target = .2,
N1.max, N2.max, batch1.size, batch2.size,
nReplicate = 1e+6, verbose = T, seed = 1){
if(side!='both'){
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
nAnalyses = length(batch1.size)
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
if(is.logical(theta1)&&(theta1==F)){
if(verbose==T){
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
signed_t.alpha = (2*(side=='right')-1)*
qt(Type1.target, df = N1.max + N2.max -2, lower.tail = F)
cumSS10_n = cumSS20_n = cumsum10_n = cumsum20_n =
LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N10.AR = rep(N1.max, nReplicate)
N20.AR = rep(N2.max, nReplicate)
not.reached.decisionH0.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
obs10_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
})
obs20_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
})
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + rowSums(obs10_n)
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + rowSums(obs20_n)
cumSS10_n[not.reached.decisionH0.AR] =
cumSS10_n[not.reached.decisionH0.AR] + rowSums(obs10_n^2)
cumSS20_n[not.reached.decisionH0.AR] =
cumSS20_n[not.reached.decisionH0.AR] + rowSums(obs20_n^2)
xbar.diff0_n = cumsum10_n[not.reached.decisionH0.AR]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR]/batch2.size[n+1]
divisor.pooled.sd0_n.sq =
cumSS10_n[not.reached.decisionH0.AR] - ((cumsum10_n[not.reached.decisionH0.AR])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR] - ((cumsum20_n[not.reached.decisionH0.AR])^2)/batch2.size[n+1]
LR0_n[not.reached.decisionH0.AR] =
((1 + ((xbar.diff0_n - theta0)^2)/(divisor.pooled.sd0_n.sq*
(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n -
(theta0 + signed_t.alpha*
sqrt((divisor.pooled.sd0_n.sq/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N10.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch1.size[n+1]
N20.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch2.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste(" Expected sample size under H0: Group 1 - ", round(EN10, 2),
", Group 2 - ", round(EN20, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20)),
"Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoT', 'side' = side, 'theta0' = theta0,
'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = fixed_design.alt(test.type = 'twoT', side = side, theta0 = theta0,
N1 = N1.max, N2 = N2.max, Type1 = Type1.target,
Type2 = Type2.target)
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
signed_t.alpha = (2*(side=='right')-1)*
qt(Type1.target, df = N1.max + N2.max -2, lower.tail = F)
cumSS10_n = cumSS20_n = cumSS11_n = cumSS21_n =
cumsum10_n = cumsum20_n = cumsum11_n = cumsum21_n =
LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N10.AR = N11.AR = rep(N1.max, nReplicate)
N20.AR = N21.AR = rep(N2.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
obs10_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
})
obs20_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
})
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + rowSums(obs10_n)
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + rowSums(obs20_n)
cumSS10_n[not.reached.decisionH0.AR] =
cumSS10_n[not.reached.decisionH0.AR] + rowSums(obs10_n^2)
cumSS20_n[not.reached.decisionH0.AR] =
cumSS20_n[not.reached.decisionH0.AR] + rowSums(obs20_n^2)
xbar.diff0_n = cumsum10_n[not.reached.decisionH0.AR]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR]/batch2.size[n+1]
divisor.pooled.sd0_n.sq =
cumSS10_n[not.reached.decisionH0.AR] - ((cumsum10_n[not.reached.decisionH0.AR])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR] - ((cumsum20_n[not.reached.decisionH0.AR])^2)/batch2.size[n+1]
LR0_n[not.reached.decisionH0.AR] =
((1 + ((xbar.diff0_n - theta0)^2)/(divisor.pooled.sd0_n.sq*
(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n -
(theta0 + signed_t.alpha*
sqrt((divisor.pooled.sd0_n.sq/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N10.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch1.size[n+1]
N20.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch2.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
obs11_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1/2, 1)
})
obs21_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), -theta1/2, 1)
})
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + rowSums(obs11_n)
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + rowSums(obs21_n)
cumSS11_n[not.reached.decisionH1.AR] =
cumSS11_n[not.reached.decisionH1.AR] + rowSums(obs11_n^2)
cumSS21_n[not.reached.decisionH1.AR] =
cumSS21_n[not.reached.decisionH1.AR] + rowSums(obs21_n^2)
xbar.diff1_n = cumsum11_n[not.reached.decisionH1.AR]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR]/batch2.size[n+1]
divisor.pooled.sd1_n.sq =
cumSS11_n[not.reached.decisionH1.AR] - ((cumsum11_n[not.reached.decisionH1.AR])^2)/batch1.size[n+1] +
cumSS21_n[not.reached.decisionH1.AR] - ((cumsum21_n[not.reached.decisionH1.AR])^2)/batch2.size[n+1]
LR1_n[not.reached.decisionH1.AR] =
((1 + ((xbar.diff1_n - theta0)^2)/(divisor.pooled.sd1_n.sq*
(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1_n -
(theta0 + signed_t.alpha*
sqrt((divisor.pooled.sd1_n.sq/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N11.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch1.size[n+1]
N21.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch2.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste(" Expected sample size under H0: Group 1 - ", round(EN10, 2),
", Group 2 - ", round(EN20, 2), sep = ''))
print(paste(" Expected sample size at the alternative: Group 1 - ", round(EN11, 2),
", Group 2 - ", round(EN21, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = actual.type2.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'H1' = list('Group1' = N11.AR, 'Group2' = N21.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'H1' = list('Group1' = EN11, 'Group2' = EN21)),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoT', 'side' = side, 'theta0' = theta0,
'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else{
if(verbose==T){
print(paste("Alternative under comparison: ", round(theta1, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
signed_t.alpha = (2*(side=='right')-1)*
qt(Type1.target, df = N1.max + N2.max -2, lower.tail = F)
cumSS10_n = cumSS20_n = cumSS11_n = cumSS21_n =
cumsum10_n = cumsum20_n = cumsum11_n = cumsum21_n =
LR0_n = LR1_n = numeric(nReplicate)
type1.error.AR = type2.error.AR = rep(F, nReplicate)
N10.AR = N11.AR = rep(N1.max, nReplicate)
N20.AR = N21.AR = rep(N2.max, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
obs10_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
})
obs20_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
})
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + rowSums(obs10_n)
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + rowSums(obs20_n)
cumSS10_n[not.reached.decisionH0.AR] =
cumSS10_n[not.reached.decisionH0.AR] + rowSums(obs10_n^2)
cumSS20_n[not.reached.decisionH0.AR] =
cumSS20_n[not.reached.decisionH0.AR] + rowSums(obs20_n^2)
xbar.diff0_n = cumsum10_n[not.reached.decisionH0.AR]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR]/batch2.size[n+1]
divisor.pooled.sd0_n.sq =
cumSS10_n[not.reached.decisionH0.AR] - ((cumsum10_n[not.reached.decisionH0.AR])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR] - ((cumsum20_n[not.reached.decisionH0.AR])^2)/batch2.size[n+1]
LR0_n[not.reached.decisionH0.AR] =
((1 + ((xbar.diff0_n - theta0)^2)/(divisor.pooled.sd0_n.sq*
(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n -
(theta0 + signed_t.alpha*
sqrt((divisor.pooled.sd0_n.sq/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]<=RejectH1.threshold)
RejectedH0.underH0_n.AR = which(LR0_n[not.reached.decisionH0.AR]>=RejectH0.threshold)
reached.decisionH0_n.AR = union(AcceptedH0.underH0_n.AR, RejectedH0.underH0_n.AR)
if(length(reached.decisionH0_n.AR)>0){
N10.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch1.size[n+1]
N20.AR[not.reached.decisionH0.AR[reached.decisionH0_n.AR]] = batch2.size[n+1]
type1.error.AR[not.reached.decisionH0.AR[RejectedH0.underH0_n.AR]] = T
not.reached.decisionH0.AR = not.reached.decisionH0.AR[-reached.decisionH0_n.AR]
}
}
if(length(not.reached.decisionH1.AR)>0){
obs11_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1/2, 1)
})
obs21_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), -theta1/2, 1)
})
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + rowSums(obs11_n)
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + rowSums(obs21_n)
cumSS11_n[not.reached.decisionH1.AR] =
cumSS11_n[not.reached.decisionH1.AR] + rowSums(obs11_n^2)
cumSS21_n[not.reached.decisionH1.AR] =
cumSS21_n[not.reached.decisionH1.AR] + rowSums(obs21_n^2)
xbar.diff1_n = cumsum11_n[not.reached.decisionH1.AR]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR]/batch2.size[n+1]
divisor.pooled.sd1_n.sq =
cumSS11_n[not.reached.decisionH1.AR] - ((cumsum11_n[not.reached.decisionH1.AR])^2)/batch1.size[n+1] +
cumSS21_n[not.reached.decisionH1.AR] - ((cumsum21_n[not.reached.decisionH1.AR])^2)/batch2.size[n+1]
LR1_n[not.reached.decisionH1.AR] =
((1 + ((xbar.diff1_n - theta0)^2)/(divisor.pooled.sd1_n.sq*
(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1_n -
(theta0 + signed_t.alpha*
sqrt((divisor.pooled.sd1_n.sq/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N11.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch1.size[n+1]
N21.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch2.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
setTxtProgressBar(pb, n)
}
nNot.reached.decisionH0.AR = length(not.reached.decisionH0.AR)
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
RejectH0.threshold -
max(LR0_n[not.reached.decisionH0.AR]))))
termination.threshold.AR = (floor(max(LR0_n[not.reached.decisionH0.AR])*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01,
min(LR0_n[not.reached.decisionH0.AR]) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(LR0_n[not.reached.decisionH0.AR]))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(LR0_n[not.reached.decisionH0.AR]))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(min(cumRejFreq_not.reached.decisionH0.AR)>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold.AR)/nReplicate
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", RejectH0.threshold))
print(paste("Termination threshold: ", termination.threshold.AR))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Attained Type II error probability: ", round(actual.type2.error.AR, 4)))
print(paste(" Expected sample size under H0: Group 1 - ", round(EN10, 2),
", Group 2 - ", round(EN20, 2), sep = ''))
print(paste(" Expected sample size at the alternative: Group 1 - ", round(EN11, 2),
", Group 2 - ", round(EN21, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = actual.type2.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'H1' = list('Group1' = N11.AR, 'Group2' = N21.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'H1' = list('Group1' = EN11, 'Group2' = EN21)),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoT', 'side' = side, 'theta0' = theta0,
'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}
}else{
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
nAnalyses = length(batch1.size)
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
if(is.logical(theta1)&&(theta1==F)){
if(verbose==T){
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
t.alpha = qt(Type1.target/2, df = N1.max + N2.max -2, lower.tail = F)
cumSS10_n = cumSS20_n = cumsum10_n = cumsum20_n = LR0_n.r = LR0_n.l = numeric(nReplicate)
type1.error.AR = rep(F, nReplicate)
N10.AR = N10.AR.r = N10.AR.l = rep(N1.max, nReplicate)
N20.AR = N20.AR.r = N20.AR.l = rep(N2.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs10_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
})
}else{
obs10_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH0.AR)>1){
obs20_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
})
}else{
obs20_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + rowSums(obs10_n)
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + rowSums(obs20_n)
cumSS10_n[not.reached.decisionH0.AR] =
cumSS10_n[not.reached.decisionH0.AR] + rowSums(obs10_n^2)
cumSS20_n[not.reached.decisionH0.AR] =
cumSS20_n[not.reached.decisionH0.AR] + rowSums(obs20_n^2)
xbar.diff0_n.r = cumsum10_n[not.reached.decisionH0.AR.r]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.r]/batch2.size[n+1]
divisor.pooled.sd0_n.sq.r =
cumSS10_n[not.reached.decisionH0.AR.r] -
((cumsum10_n[not.reached.decisionH0.AR.r])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR.r] -
((cumsum20_n[not.reached.decisionH0.AR.r])^2)/batch2.size[n+1]
xbar.diff0_n.l = cumsum10_n[not.reached.decisionH0.AR.l]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.l]/batch2.size[n+1]
divisor.pooled.sd0_n.sq.l =
cumSS10_n[not.reached.decisionH0.AR.l] -
((cumsum10_n[not.reached.decisionH0.AR.l])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR.l] -
((cumsum20_n[not.reached.decisionH0.AR.l])^2)/batch2.size[n+1]
LR0_n.r[not.reached.decisionH0.AR.r] =
((1 + ((xbar.diff0_n.r - theta0)^2)/
(divisor.pooled.sd0_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd0_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR0_n.l[not.reached.decisionH0.AR.l] =
((1 + ((xbar.diff0_n.l - theta0)^2)/
(divisor.pooled.sd0_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd0_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N10.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch1.size[n+1]
N20.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N10.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch1.size[n+1]
N20.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N10.AR[accepted.by.both0] = pmax(N10.AR.r[accepted.by.both0],
N10.AR.l[accepted.by.both0])
N10.AR[onlyrejected.by.right0] = N10.AR.r[onlyrejected.by.right0]
N10.AR[onlyrejected.by.left0] = N10.AR.l[onlyrejected.by.left0]
N10.AR[rejected.by.both0] = pmin(N10.AR.r[rejected.by.both0],
N10.AR.l[rejected.by.both0])
N20.AR[accepted.by.both0] = pmax(N20.AR.r[accepted.by.both0],
N20.AR.l[accepted.by.both0])
N20.AR[onlyrejected.by.right0] = N20.AR.r[onlyrejected.by.right0]
N20.AR[onlyrejected.by.left0] = N20.AR.l[onlyrejected.by.left0]
N20.AR[rejected.by.both0] = pmin(N20.AR.r[rejected.by.both0],
N20.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
EN10 = mean(N10.AR)
EN20 = mean(N20.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: Group 1 - ", round(EN10, 2),
', Group 2 - ', round(EN20, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20)),
"Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoT', 'side' = side, 'theta0' = theta0,
'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else if(is.logical(theta1)&&(theta1==T)){
theta1 = list('right' = fixed_design.alt(test.type = 'twoT', side = 'right',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2, Type2 = Type2.target),
'left' = fixed_design.alt(test.type = 'twoT', side = 'left',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2, Type2 = Type2.target))
if(verbose==T){
print("Alternative under comparison:")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
t.alpha = qt(Type1.target/2, df = N1.max + N2.max -2, lower.tail = F)
cumSS10_n = cumSS20_n = cumSS11r_n = cumSS21r_n = cumSS11l_n = cumSS21l_n =
cumsum10_n = cumsum20_n = cumsum11r_n = cumsum21r_n = cumsum11l_n = cumsum21l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N10.AR = N10.AR.r = N10.AR.l =
N11r.AR = N11r.AR.r = N11r.AR.l =
N11l.AR = N11l.AR.r = N11l.AR.l = rep(N1.max, nReplicate)
N20.AR = N20.AR.r = N20.AR.l =
N21r.AR = N21r.AR.r = N21r.AR.l =
N21l.AR = N21l.AR.r = N21l.AR.l = rep(N2.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs10_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
})
}else{
obs10_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH0.AR)>1){
obs20_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
})
}else{
obs20_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + rowSums(obs10_n)
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + rowSums(obs20_n)
cumSS10_n[not.reached.decisionH0.AR] =
cumSS10_n[not.reached.decisionH0.AR] + rowSums(obs10_n^2)
cumSS20_n[not.reached.decisionH0.AR] =
cumSS20_n[not.reached.decisionH0.AR] + rowSums(obs20_n^2)
xbar.diff0_n.r = cumsum10_n[not.reached.decisionH0.AR.r]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.r]/batch2.size[n+1]
divisor.pooled.sd0_n.sq.r =
cumSS10_n[not.reached.decisionH0.AR.r] -
((cumsum10_n[not.reached.decisionH0.AR.r])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR.r] -
((cumsum20_n[not.reached.decisionH0.AR.r])^2)/batch2.size[n+1]
xbar.diff0_n.l = cumsum10_n[not.reached.decisionH0.AR.l]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.l]/batch2.size[n+1]
divisor.pooled.sd0_n.sq.l =
cumSS10_n[not.reached.decisionH0.AR.l] -
((cumsum10_n[not.reached.decisionH0.AR.l])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR.l] -
((cumsum20_n[not.reached.decisionH0.AR.l])^2)/batch2.size[n+1]
LR0_n.r[not.reached.decisionH0.AR.r] =
((1 + ((xbar.diff0_n.r - theta0)^2)/
(divisor.pooled.sd0_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd0_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR0_n.l[not.reached.decisionH0.AR.l] =
((1 + ((xbar.diff0_n.l - theta0)^2)/
(divisor.pooled.sd0_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd0_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N10.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch1.size[n+1]
N20.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N10.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch1.size[n+1]
N20.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
if(length(not.reached.decisionH1r.AR)>1){
obs11r_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right/2, 1)
})
}else{
obs11r_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH1r.AR)>1){
obs21r_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), -theta1$right/2, 1)
})
}else{
obs21r_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), -theta1$right/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum11r_n[not.reached.decisionH1r.AR] =
cumsum11r_n[not.reached.decisionH1r.AR] + rowSums(obs11r_n)
cumsum21r_n[not.reached.decisionH1r.AR] =
cumsum21r_n[not.reached.decisionH1r.AR] + rowSums(obs21r_n)
cumSS11r_n[not.reached.decisionH1r.AR] =
cumSS11r_n[not.reached.decisionH1r.AR] + rowSums(obs11r_n^2)
cumSS21r_n[not.reached.decisionH1r.AR] =
cumSS21r_n[not.reached.decisionH1r.AR] + rowSums(obs21r_n^2)
xbar.diff1r_n.r = cumsum11r_n[not.reached.decisionH1r.AR.r]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.r]/batch2.size[n+1]
divisor.pooled.sd1r_n.sq.r =
cumSS11r_n[not.reached.decisionH1r.AR.r] -
((cumsum11r_n[not.reached.decisionH1r.AR.r])^2)/batch1.size[n+1] +
cumSS21r_n[not.reached.decisionH1r.AR.r] -
((cumsum21r_n[not.reached.decisionH1r.AR.r])^2)/batch2.size[n+1]
xbar.diff1r_n.l = cumsum11r_n[not.reached.decisionH1r.AR.l]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.l]/batch2.size[n+1]
divisor.pooled.sd1r_n.sq.l =
cumSS11r_n[not.reached.decisionH1r.AR.l] -
((cumsum11r_n[not.reached.decisionH1r.AR.l])^2)/batch1.size[n+1] +
cumSS21r_n[not.reached.decisionH1r.AR.l] -
((cumsum21r_n[not.reached.decisionH1r.AR.l])^2)/batch2.size[n+1]
LR1r_n.r[not.reached.decisionH1r.AR.r] =
((1 + ((xbar.diff1r_n.r - theta0)^2)/
(divisor.pooled.sd1r_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1r_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd1r_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1r_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR1r_n.l[not.reached.decisionH1r.AR.l] =
((1 + ((xbar.diff1r_n.l - theta0)^2)/
(divisor.pooled.sd1r_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1r_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd1r_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1r_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N11r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch1.size[n+1]
N21r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N11r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch1.size[n+1]
N21r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
if(length(not.reached.decisionH1l.AR)>1){
obs11l_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left/2, 1)
})
}else{
obs11l_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH1l.AR)>1){
obs21l_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), -theta1$left/2, 1)
})
}else{
obs21l_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), -theta1$left/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum11l_n[not.reached.decisionH1l.AR] =
cumsum11l_n[not.reached.decisionH1l.AR] + rowSums(obs11l_n)
cumsum21l_n[not.reached.decisionH1l.AR] =
cumsum21l_n[not.reached.decisionH1l.AR] + rowSums(obs21l_n)
cumSS11l_n[not.reached.decisionH1l.AR] =
cumSS11l_n[not.reached.decisionH1l.AR] + rowSums(obs11l_n^2)
cumSS21l_n[not.reached.decisionH1l.AR] =
cumSS21l_n[not.reached.decisionH1l.AR] + rowSums(obs21l_n^2)
xbar.diff1l_n.r = cumsum11l_n[not.reached.decisionH1l.AR.r]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.r]/batch2.size[n+1]
divisor.pooled.sd1l_n.sq.r =
cumSS11l_n[not.reached.decisionH1l.AR.r] -
((cumsum11l_n[not.reached.decisionH1l.AR.r])^2)/batch1.size[n+1] +
cumSS21l_n[not.reached.decisionH1l.AR.r] -
((cumsum21l_n[not.reached.decisionH1l.AR.r])^2)/batch2.size[n+1]
xbar.diff1l_n.l = cumsum11l_n[not.reached.decisionH1l.AR.l]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.l]/batch2.size[n+1]
divisor.pooled.sd1l_n.sq.l =
cumSS11l_n[not.reached.decisionH1l.AR.l] -
((cumsum11l_n[not.reached.decisionH1l.AR.l])^2)/batch1.size[n+1] +
cumSS21l_n[not.reached.decisionH1l.AR.l] -
((cumsum21l_n[not.reached.decisionH1l.AR.l])^2)/batch2.size[n+1]
LR1l_n.r[not.reached.decisionH1l.AR.r] =
((1 + ((xbar.diff1l_n.r - theta0)^2)/
(divisor.pooled.sd1l_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1l_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd1l_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1l_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR1l_n.l[not.reached.decisionH1l.AR.l] =
((1 + ((xbar.diff1l_n.l - theta0)^2)/
(divisor.pooled.sd1l_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1l_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd1l_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1l_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N11l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch1.size[n+1]
N21l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N11l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch1.size[n+1]
N21l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N10.AR[accepted.by.both0] = pmax(N10.AR.r[accepted.by.both0],
N10.AR.l[accepted.by.both0])
N10.AR[onlyrejected.by.right0] = N10.AR.r[onlyrejected.by.right0]
N10.AR[onlyrejected.by.left0] = N10.AR.l[onlyrejected.by.left0]
N10.AR[rejected.by.both0] = pmin(N10.AR.r[rejected.by.both0],
N10.AR.l[rejected.by.both0])
N20.AR[accepted.by.both0] = pmax(N20.AR.r[accepted.by.both0],
N20.AR.l[accepted.by.both0])
N20.AR[onlyrejected.by.right0] = N20.AR.r[onlyrejected.by.right0]
N20.AR[onlyrejected.by.left0] = N20.AR.l[onlyrejected.by.left0]
N20.AR[rejected.by.both0] = pmin(N20.AR.r[rejected.by.both0],
N20.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N11r.AR[accepted.by.both1r] = pmax(N11r.AR.r[accepted.by.both1r],
N11r.AR.l[accepted.by.both1r])
N11r.AR[onlyrejected.by.right1r] = N11r.AR.r[onlyrejected.by.right1r]
N11r.AR[onlyrejected.by.left1r] = N11r.AR.l[onlyrejected.by.left1r]
N11r.AR[rejected.by.both1r] = pmin(N11r.AR.r[rejected.by.both1r],
N11r.AR.l[rejected.by.both1r])
N21r.AR[accepted.by.both1r] = pmax(N21r.AR.r[accepted.by.both1r],
N21r.AR.l[accepted.by.both1r])
N21r.AR[onlyrejected.by.right1r] = N21r.AR.r[onlyrejected.by.right1r]
N21r.AR[onlyrejected.by.left1r] = N21r.AR.l[onlyrejected.by.left1r]
N21r.AR[rejected.by.both1r] = pmin(N21r.AR.r[rejected.by.both1r],
N21r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N11l.AR[accepted.by.both1l] = pmax(N11l.AR.r[accepted.by.both1l],
N11l.AR.l[accepted.by.both1l])
N11l.AR[onlyrejected.by.right1l] = N11l.AR.r[onlyrejected.by.right1l]
N11l.AR[onlyrejected.by.left1l] = N11l.AR.l[onlyrejected.by.left1l]
N11l.AR[rejected.by.both1l] = pmin(N11l.AR.r[rejected.by.both1l],
N11l.AR.l[rejected.by.both1l])
N21l.AR[accepted.by.both1l] = pmax(N21l.AR.r[accepted.by.both1l],
N21l.AR.l[accepted.by.both1l])
N21l.AR[onlyrejected.by.right1l] = N21l.AR.r[onlyrejected.by.right1l]
N21l.AR[onlyrejected.by.left1l] = N21l.AR.l[onlyrejected.by.left1l]
N21l.AR[rejected.by.both1l] = pmin(N21l.AR.r[rejected.by.both1l],
N21l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN10 = mean(N10.AR)
EN11r = mean(N11r.AR)
EN11l = mean(N11l.AR)
EN20 = mean(N20.AR)
EN21r = mean(N21r.AR)
EN21l = mean(N21l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: Group 1 - ", round(EN10, 2),
', Group 2 - ', round(EN20, 2), sep = ''))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: Group 1 - ", round(EN11r, 2),
', Group 2 - ', round(EN21r, 2), sep = ''))
print(paste(" On the left: Group 1 - ", round(EN11l, 2),
', Group 2 - ', round(EN21l, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'right' = list('Group1' = N11r.AR, 'Group2' = N21r.AR),
'left' = list('Group1' = N11l.AR, 'Group2' = N21l.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'right' = list('Group1' = EN11r, 'Group2' = EN21r),
'left' = list('Group1' = EN11l, 'Group2' = EN21l)),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoT', 'side' = side, 'theta0' = theta0,
'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}else{
if(verbose==T){
print("Alternative under comparison: ")
print("-------------------------------------------------------------------------")
print(paste(' On the right: ', round(theta1$right, 3), sep = ""))
print(paste(' On the left: ', round(theta1$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the Termination threshold ...")
}
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
t.alpha = qt(Type1.target/2, df = N1.max + N2.max -2, lower.tail = F)
cumSS10_n = cumSS20_n = cumSS11r_n = cumSS21r_n = cumSS11l_n = cumSS21l_n =
cumsum10_n = cumsum20_n = cumsum11r_n = cumsum21r_n = cumsum11l_n = cumsum21l_n =
LR0_n.r = LR0_n.l = LR1r_n.r = LR1r_n.l = LR1l_n.r = LR1l_n.l = numeric(nReplicate)
type1.error.AR = PowerH1r.AR = PowerH1l.AR = rep(F, nReplicate)
N10.AR = N10.AR.r = N10.AR.l =
N11r.AR = N11r.AR.r = N11r.AR.l =
N11l.AR = N11l.AR.r = N11l.AR.l = rep(N1.max, nReplicate)
N20.AR = N20.AR.r = N20.AR.l =
N21r.AR = N21r.AR.r = N21r.AR.l =
N21l.AR = N21l.AR.r = N21l.AR.l = rep(N2.max, nReplicate)
decision.underH0.AR.r = decision.underH0.AR.l =
decision.underH1r.AR.r = decision.underH1r.AR.l =
decision.underH1l.AR.r = decision.underH1l.AR.l = rep(NA, nReplicate)
not.reached.decisionH0.AR = not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.l =
not.reached.decisionH1r.AR = not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.l =
not.reached.decisionH1l.AR = not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH0.AR)>0){
if(length(not.reached.decisionH0.AR)>1){
obs10_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
})
}else{
obs10_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), theta0/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH0.AR)>1){
obs20_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
})
}else{
obs20_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH0.AR), -theta0/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum10_n[not.reached.decisionH0.AR] =
cumsum10_n[not.reached.decisionH0.AR] + rowSums(obs10_n)
cumsum20_n[not.reached.decisionH0.AR] =
cumsum20_n[not.reached.decisionH0.AR] + rowSums(obs20_n)
cumSS10_n[not.reached.decisionH0.AR] =
cumSS10_n[not.reached.decisionH0.AR] + rowSums(obs10_n^2)
cumSS20_n[not.reached.decisionH0.AR] =
cumSS20_n[not.reached.decisionH0.AR] + rowSums(obs20_n^2)
xbar.diff0_n.r = cumsum10_n[not.reached.decisionH0.AR.r]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.r]/batch2.size[n+1]
divisor.pooled.sd0_n.sq.r =
cumSS10_n[not.reached.decisionH0.AR.r] -
((cumsum10_n[not.reached.decisionH0.AR.r])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR.r] -
((cumsum20_n[not.reached.decisionH0.AR.r])^2)/batch2.size[n+1]
xbar.diff0_n.l = cumsum10_n[not.reached.decisionH0.AR.l]/batch1.size[n+1] -
cumsum20_n[not.reached.decisionH0.AR.l]/batch2.size[n+1]
divisor.pooled.sd0_n.sq.l =
cumSS10_n[not.reached.decisionH0.AR.l] -
((cumsum10_n[not.reached.decisionH0.AR.l])^2)/batch1.size[n+1] +
cumSS20_n[not.reached.decisionH0.AR.l] -
((cumsum20_n[not.reached.decisionH0.AR.l])^2)/batch2.size[n+1]
LR0_n.r[not.reached.decisionH0.AR.r] =
((1 + ((xbar.diff0_n.r - theta0)^2)/
(divisor.pooled.sd0_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd0_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR0_n.l[not.reached.decisionH0.AR.l] =
((1 + ((xbar.diff0_n.l - theta0)^2)/
(divisor.pooled.sd0_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff0_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd0_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd0_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]<=RejectH1.threshold
RejectedH0.underH0_n.AR.r = LR0_n.r[not.reached.decisionH0.AR.r]>=RejectH0.threshold
reached.decisionH0_n.AR.r = AcceptedH0.underH0_n.AR.r|RejectedH0.underH0_n.AR.r
if(any(reached.decisionH0_n.AR.r)){
decision.underH0.AR.r[not.reached.decisionH0.AR.r[AcceptedH0.underH0_n.AR.r]] = 'A'
decision.underH0.AR.r[not.reached.decisionH0.AR.r[RejectedH0.underH0_n.AR.r]] = 'R'
N10.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch1.size[n+1]
N20.AR.r[not.reached.decisionH0.AR.r[reached.decisionH0_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH0.AR.r = not.reached.decisionH0.AR.r[!reached.decisionH0_n.AR.r]
}
AcceptedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]<=RejectH1.threshold
RejectedH0.underH0_n.AR.l = LR0_n.l[not.reached.decisionH0.AR.l]>=RejectH0.threshold
reached.decisionH0_n.AR.l = AcceptedH0.underH0_n.AR.l|RejectedH0.underH0_n.AR.l
if(any(reached.decisionH0_n.AR.l)){
decision.underH0.AR.l[not.reached.decisionH0.AR.l[AcceptedH0.underH0_n.AR.l]] = 'A'
decision.underH0.AR.l[not.reached.decisionH0.AR.l[RejectedH0.underH0_n.AR.l]] = 'R'
N10.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch1.size[n+1]
N20.AR.l[not.reached.decisionH0.AR.l[reached.decisionH0_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH0.AR.l = not.reached.decisionH0.AR.l[!reached.decisionH0_n.AR.l]
}
not.reached.decisionH0.AR = union(not.reached.decisionH0.AR.r,
not.reached.decisionH0.AR.l)
}
if(length(not.reached.decisionH1r.AR)>0){
if(length(not.reached.decisionH1r.AR)>1){
obs11r_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right/2, 1)
})
}else{
obs11r_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), theta1$right/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH1r.AR)>1){
obs21r_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), -theta1$right/2, 1)
})
}else{
obs21r_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1r.AR), -theta1$right/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum11r_n[not.reached.decisionH1r.AR] =
cumsum11r_n[not.reached.decisionH1r.AR] + rowSums(obs11r_n)
cumsum21r_n[not.reached.decisionH1r.AR] =
cumsum21r_n[not.reached.decisionH1r.AR] + rowSums(obs21r_n)
cumSS11r_n[not.reached.decisionH1r.AR] =
cumSS11r_n[not.reached.decisionH1r.AR] + rowSums(obs11r_n^2)
cumSS21r_n[not.reached.decisionH1r.AR] =
cumSS21r_n[not.reached.decisionH1r.AR] + rowSums(obs21r_n^2)
xbar.diff1r_n.r = cumsum11r_n[not.reached.decisionH1r.AR.r]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.r]/batch2.size[n+1]
divisor.pooled.sd1r_n.sq.r =
cumSS11r_n[not.reached.decisionH1r.AR.r] -
((cumsum11r_n[not.reached.decisionH1r.AR.r])^2)/batch1.size[n+1] +
cumSS21r_n[not.reached.decisionH1r.AR.r] -
((cumsum21r_n[not.reached.decisionH1r.AR.r])^2)/batch2.size[n+1]
xbar.diff1r_n.l = cumsum11r_n[not.reached.decisionH1r.AR.l]/batch1.size[n+1] -
cumsum21r_n[not.reached.decisionH1r.AR.l]/batch2.size[n+1]
divisor.pooled.sd1r_n.sq.l =
cumSS11r_n[not.reached.decisionH1r.AR.l] -
((cumsum11r_n[not.reached.decisionH1r.AR.l])^2)/batch1.size[n+1] +
cumSS21r_n[not.reached.decisionH1r.AR.l] -
((cumsum21r_n[not.reached.decisionH1r.AR.l])^2)/batch2.size[n+1]
LR1r_n.r[not.reached.decisionH1r.AR.r] =
((1 + ((xbar.diff1r_n.r - theta0)^2)/
(divisor.pooled.sd1r_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1r_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd1r_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1r_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR1r_n.l[not.reached.decisionH1r.AR.l] =
((1 + ((xbar.diff1r_n.l - theta0)^2)/
(divisor.pooled.sd1r_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1r_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd1r_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1r_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.r = LR1r_n.r[not.reached.decisionH1r.AR.r]>=RejectH0.threshold
reached.decisionH1r_n.AR.r = AcceptedH0.underH1r_n.AR.r|RejectedH0.underH1r_n.AR.r
if(any(reached.decisionH1r_n.AR.r)){
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[AcceptedH0.underH1r_n.AR.r]] = 'A'
decision.underH1r.AR.r[not.reached.decisionH1r.AR.r[RejectedH0.underH1r_n.AR.r]] = 'R'
N11r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch1.size[n+1]
N21r.AR.r[not.reached.decisionH1r.AR.r[reached.decisionH1r_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1r.AR.r = not.reached.decisionH1r.AR.r[!reached.decisionH1r_n.AR.r]
}
AcceptedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]<=RejectH1.threshold
RejectedH0.underH1r_n.AR.l = LR1r_n.l[not.reached.decisionH1r.AR.l]>=RejectH0.threshold
reached.decisionH1r_n.AR.l = AcceptedH0.underH1r_n.AR.l|RejectedH0.underH1r_n.AR.l
if(any(reached.decisionH1r_n.AR.l)){
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[AcceptedH0.underH1r_n.AR.l]] = 'A'
decision.underH1r.AR.l[not.reached.decisionH1r.AR.l[RejectedH0.underH1r_n.AR.l]] = 'R'
N11r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch1.size[n+1]
N21r.AR.l[not.reached.decisionH1r.AR.l[reached.decisionH1r_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1r.AR.l = not.reached.decisionH1r.AR.l[!reached.decisionH1r_n.AR.l]
}
not.reached.decisionH1r.AR = union(not.reached.decisionH1r.AR.r,
not.reached.decisionH1r.AR.l)
}
if(length(not.reached.decisionH1l.AR)>0){
if(length(not.reached.decisionH1l.AR)>1){
obs11l_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left/2, 1)
})
}else{
obs11l_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), theta1$left/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH1l.AR)>1){
obs21l_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), -theta1$left/2, 1)
})
}else{
obs21l_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1l.AR), -theta1$left/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum11l_n[not.reached.decisionH1l.AR] =
cumsum11l_n[not.reached.decisionH1l.AR] + rowSums(obs11l_n)
cumsum21l_n[not.reached.decisionH1l.AR] =
cumsum21l_n[not.reached.decisionH1l.AR] + rowSums(obs21l_n)
cumSS11l_n[not.reached.decisionH1l.AR] =
cumSS11l_n[not.reached.decisionH1l.AR] + rowSums(obs11l_n^2)
cumSS21l_n[not.reached.decisionH1l.AR] =
cumSS21l_n[not.reached.decisionH1l.AR] + rowSums(obs21l_n^2)
xbar.diff1l_n.r = cumsum11l_n[not.reached.decisionH1l.AR.r]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.r]/batch2.size[n+1]
divisor.pooled.sd1l_n.sq.r =
cumSS11l_n[not.reached.decisionH1l.AR.r] -
((cumsum11l_n[not.reached.decisionH1l.AR.r])^2)/batch1.size[n+1] +
cumSS21l_n[not.reached.decisionH1l.AR.r] -
((cumsum21l_n[not.reached.decisionH1l.AR.r])^2)/batch2.size[n+1]
xbar.diff1l_n.l = cumsum11l_n[not.reached.decisionH1l.AR.l]/batch1.size[n+1] -
cumsum21l_n[not.reached.decisionH1l.AR.l]/batch2.size[n+1]
divisor.pooled.sd1l_n.sq.l =
cumSS11l_n[not.reached.decisionH1l.AR.l] -
((cumsum11l_n[not.reached.decisionH1l.AR.l])^2)/batch1.size[n+1] +
cumSS21l_n[not.reached.decisionH1l.AR.l] -
((cumsum21l_n[not.reached.decisionH1l.AR.l])^2)/batch2.size[n+1]
LR1l_n.r[not.reached.decisionH1l.AR.r] =
((1 + ((xbar.diff1l_n.r - theta0)^2)/
(divisor.pooled.sd1l_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1l_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd1l_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1l_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR1l_n.l[not.reached.decisionH1l.AR.l] =
((1 + ((xbar.diff1l_n.l - theta0)^2)/
(divisor.pooled.sd1l_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1l_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd1l_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1l_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.r = LR1l_n.r[not.reached.decisionH1l.AR.r]>=RejectH0.threshold
reached.decisionH1l_n.AR.r = AcceptedH0.underH1l_n.AR.r|RejectedH0.underH1l_n.AR.r
if(any(reached.decisionH1l_n.AR.r)){
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[AcceptedH0.underH1l_n.AR.r]] = 'A'
decision.underH1l.AR.r[not.reached.decisionH1l.AR.r[RejectedH0.underH1l_n.AR.r]] = 'R'
N11l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch1.size[n+1]
N21l.AR.r[not.reached.decisionH1l.AR.r[reached.decisionH1l_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1l.AR.r = not.reached.decisionH1l.AR.r[!reached.decisionH1l_n.AR.r]
}
AcceptedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]<=RejectH1.threshold
RejectedH0.underH1l_n.AR.l = LR1l_n.l[not.reached.decisionH1l.AR.l]>=RejectH0.threshold
reached.decisionH1l_n.AR.l = AcceptedH0.underH1l_n.AR.l|RejectedH0.underH1l_n.AR.l
if(any(reached.decisionH1l_n.AR.l)){
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[AcceptedH0.underH1l_n.AR.l]] = 'A'
decision.underH1l.AR.l[not.reached.decisionH1l.AR.l[RejectedH0.underH1l_n.AR.l]] = 'R'
N11l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch1.size[n+1]
N21l.AR.l[not.reached.decisionH1l.AR.l[reached.decisionH1l_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1l.AR.l = not.reached.decisionH1l.AR.l[!reached.decisionH1l_n.AR.l]
}
not.reached.decisionH1l.AR = union(not.reached.decisionH1l.AR.r,
not.reached.decisionH1l.AR.l)
}
setTxtProgressBar(pb, n)
}
accepted.by.both0 = intersect(which(decision.underH0.AR.r=='A'),
which(decision.underH0.AR.l=='A'))
onlyrejected.by.right0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l!='R'))
onlyrejected.by.left0 = intersect(which(decision.underH0.AR.r!='R'),
which(decision.underH0.AR.l=='R'))
rejected.by.both0 = intersect(which(decision.underH0.AR.r=='R'),
which(decision.underH0.AR.l=='R'))
N10.AR[accepted.by.both0] = pmax(N10.AR.r[accepted.by.both0],
N10.AR.l[accepted.by.both0])
N10.AR[onlyrejected.by.right0] = N10.AR.r[onlyrejected.by.right0]
N10.AR[onlyrejected.by.left0] = N10.AR.l[onlyrejected.by.left0]
N10.AR[rejected.by.both0] = pmin(N10.AR.r[rejected.by.both0],
N10.AR.l[rejected.by.both0])
N20.AR[accepted.by.both0] = pmax(N20.AR.r[accepted.by.both0],
N20.AR.l[accepted.by.both0])
N20.AR[onlyrejected.by.right0] = N20.AR.r[onlyrejected.by.right0]
N20.AR[onlyrejected.by.left0] = N20.AR.l[onlyrejected.by.left0]
N20.AR[rejected.by.both0] = pmin(N20.AR.r[rejected.by.both0],
N20.AR.l[rejected.by.both0])
onlyaccepted.by.right0 = intersect(which(decision.underH0.AR.r=='A'),
which(is.na(decision.underH0.AR.l)))
onlyaccepted.by.left0 = intersect(which(is.na(decision.underH0.AR.r)),
which(decision.underH0.AR.l=='A'))
both.inconclusive0 = intersect(which(is.na(decision.underH0.AR.r)),
which(is.na(decision.underH0.AR.l)))
all.inconclusive0 = c(onlyaccepted.by.right0, onlyaccepted.by.left0,
both.inconclusive0)
nNot.reached.decisionH0.AR = length(all.inconclusive0)
type1.error.AR[c(onlyrejected.by.right0, onlyrejected.by.left0,
rejected.by.both0)] = T
accepted.by.both1r = intersect(which(decision.underH1r.AR.r=='A'),
which(decision.underH1r.AR.l=='A'))
onlyrejected.by.right1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l!='R'))
onlyrejected.by.left1r = intersect(which(decision.underH1r.AR.r!='R'),
which(decision.underH1r.AR.l=='R'))
rejected.by.both1r = intersect(which(decision.underH1r.AR.r=='R'),
which(decision.underH1r.AR.l=='R'))
N11r.AR[accepted.by.both1r] = pmax(N11r.AR.r[accepted.by.both1r],
N11r.AR.l[accepted.by.both1r])
N11r.AR[onlyrejected.by.right1r] = N11r.AR.r[onlyrejected.by.right1r]
N11r.AR[onlyrejected.by.left1r] = N11r.AR.l[onlyrejected.by.left1r]
N11r.AR[rejected.by.both1r] = pmin(N11r.AR.r[rejected.by.both1r],
N11r.AR.l[rejected.by.both1r])
N21r.AR[accepted.by.both1r] = pmax(N21r.AR.r[accepted.by.both1r],
N21r.AR.l[accepted.by.both1r])
N21r.AR[onlyrejected.by.right1r] = N21r.AR.r[onlyrejected.by.right1r]
N21r.AR[onlyrejected.by.left1r] = N21r.AR.l[onlyrejected.by.left1r]
N21r.AR[rejected.by.both1r] = pmin(N21r.AR.r[rejected.by.both1r],
N21r.AR.l[rejected.by.both1r])
onlyaccepted.by.right1r = intersect(which(decision.underH1r.AR.r=='A'),
which(is.na(decision.underH1r.AR.l)))
onlyaccepted.by.left1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(decision.underH1r.AR.l=='A'))
both.inconclusive1r = intersect(which(is.na(decision.underH1r.AR.r)),
which(is.na(decision.underH1r.AR.l)))
all.inconclusive1r = c(onlyaccepted.by.right1r, onlyaccepted.by.left1r,
both.inconclusive1r)
nNot.reached.decisionH1r.AR = length(all.inconclusive1r)
PowerH1r.AR[c(onlyrejected.by.right1r, onlyrejected.by.left1r,
rejected.by.both1r)] = T
accepted.by.both1l = intersect(which(decision.underH1l.AR.r=='A'),
which(decision.underH1l.AR.l=='A'))
onlyrejected.by.right1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l!='R'))
onlyrejected.by.left1l = intersect(which(decision.underH1l.AR.r!='R'),
which(decision.underH1l.AR.l=='R'))
rejected.by.both1l = intersect(which(decision.underH1l.AR.r=='R'),
which(decision.underH1l.AR.l=='R'))
N11l.AR[accepted.by.both1l] = pmax(N11l.AR.r[accepted.by.both1l],
N11l.AR.l[accepted.by.both1l])
N11l.AR[onlyrejected.by.right1l] = N11l.AR.r[onlyrejected.by.right1l]
N11l.AR[onlyrejected.by.left1l] = N11l.AR.l[onlyrejected.by.left1l]
N11l.AR[rejected.by.both1l] = pmin(N11l.AR.r[rejected.by.both1l],
N11l.AR.l[rejected.by.both1l])
N21l.AR[accepted.by.both1l] = pmax(N21l.AR.r[accepted.by.both1l],
N21l.AR.l[accepted.by.both1l])
N21l.AR[onlyrejected.by.right1l] = N21l.AR.r[onlyrejected.by.right1l]
N21l.AR[onlyrejected.by.left1l] = N21l.AR.l[onlyrejected.by.left1l]
N21l.AR[rejected.by.both1l] = pmin(N21l.AR.r[rejected.by.both1l],
N21l.AR.l[rejected.by.both1l])
onlyaccepted.by.right1l = intersect(which(decision.underH1l.AR.r=='A'),
which(is.na(decision.underH1l.AR.l)))
onlyaccepted.by.left1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(decision.underH1l.AR.l=='A'))
both.inconclusive1l = intersect(which(is.na(decision.underH1l.AR.r)),
which(is.na(decision.underH1l.AR.l)))
all.inconclusive1l = c(onlyaccepted.by.right1l, onlyaccepted.by.left1l,
both.inconclusive1l)
nNot.reached.decisionH1l.AR = length(all.inconclusive1l)
PowerH1l.AR[c(onlyrejected.by.right1l, onlyrejected.by.left1l,
rejected.by.both1l)] = T
type1.error.spent.AR = mean(type1.error.AR)
if(nNot.reached.decisionH0.AR==0){
nDecimal.accuracy = 2
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
term.thresh.possible.choices =
c(LR0_n.r[onlyaccepted.by.left0],
LR0_n.l[onlyaccepted.by.right0],
pmin(LR0_n.r[both.inconclusive0], LR0_n.l[both.inconclusive0]))
type1.error.max.AR = type1.error.spent.AR + nNot.reached.decisionH0.AR/nReplicate
if(type1.error.spent.AR>Type1.target){
max.LR0_n = max(term.thresh.possible.choices)
nDecimal.accuracy = ceiling(-log10(min(0.01, RejectH0.threshold - max.LR0_n)))
termination.threshold.AR = (floor(max.LR0_n*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else if(type1.error.max.AR<=Type1.target){
nDecimal.accuracy = ceiling(-log10(min(0.01, min(term.thresh.possible.choices) -
RejectH1.threshold)))
termination.threshold.AR = (floor(RejectH1.threshold*(10^nDecimal.accuracy)) + 1)/
(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.max.AR
}else{
uniqLR0.not.reached.decisionH0.inc.AR = sort(unique(term.thresh.possible.choices))
cumRejFreq_not.reached.decisionH0.AR = cumsum(rev(as.numeric(table(term.thresh.possible.choices))))
nNewRejects.AR = floor(nReplicate*(Type1.target - type1.error.spent.AR))
if(cumRejFreq_not.reached.decisionH0.AR[1]>nNewRejects.AR){
nDecimal.accuracy =
ceiling(-log10(min(0.01, RejectH0.threshold -
uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)])))
termination.threshold.AR =
(floor(uniqLR0.not.reached.decisionH0.inc.AR[length(uniqLR0.not.reached.decisionH0.inc.AR)]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR
}else{
opt.indx.AR = max(which(cumRejFreq_not.reached.decisionH0.AR<=nNewRejects.AR))
min.rej.indx.AR = length(uniqLR0.not.reached.decisionH0.inc.AR) - (opt.indx.AR - 1)
nDecimal.accuracy = ceiling(-log10(min(0.01,
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR] -
uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1])))
termination.threshold.AR = (floor(uniqLR0.not.reached.decisionH0.inc.AR[min.rej.indx.AR-1]*
(10^nDecimal.accuracy)) + 1)/(10^nDecimal.accuracy)
actual.type1.error.AR = type1.error.spent.AR +
cumRejFreq_not.reached.decisionH0.AR[opt.indx.AR]/nReplicate
}
}
}
actual.PowerH1r.AR.r = mean(PowerH1r.AR) +
sum(c(LR1r_n.r[onlyaccepted.by.left1r],
LR1r_n.l[onlyaccepted.by.right1r],
pmax(LR1r_n.r[both.inconclusive1r], LR1r_n.l[both.inconclusive1r]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1r.AR = 1 - actual.PowerH1r.AR.r
actual.PowerH1l.AR.r = mean(PowerH1l.AR) +
sum(c(LR1l_n.r[onlyaccepted.by.left1l],
LR1l_n.l[onlyaccepted.by.right1l],
pmax(LR1l_n.r[both.inconclusive1l], LR1l_n.l[both.inconclusive1l]))>=
termination.threshold.AR)/nReplicate
actual.type2.errorH1l.AR = 1 - actual.PowerH1l.AR.r
EN10 = mean(N10.AR)
EN11r = mean(N11r.AR)
EN11l = mean(N11l.AR)
EN20 = mean(N20.AR)
EN21r = mean(N21r.AR)
EN21l = mean(N21l.AR)
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3)))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3)))
print(paste("Termination threshold: ", round(termination.threshold.AR, 3)))
print(paste("Attained Type I error probability: ", round(actual.type1.error.AR, 4)))
print(paste("Expected sample size under H0: Group 1 - ", round(EN10, 2),
', Group 2 - ', round(EN20, 2), sep = ''))
print("Attained Type II error probability:")
print(paste(" On the right: ", round(actual.type2.errorH1r.AR, 4)))
print(paste(" On the left: ", round(actual.type2.errorH1l.AR, 4)))
print("Expected sample size at the alternatives:")
print(paste(" On the right: Group 1 - ", round(EN11r, 2),
', Group 2 - ', round(EN21r, 2), sep = ''))
print(paste(" On the left: Group 1 - ", round(EN11l, 2),
', Group 2 - ', round(EN21l, 2), sep = ''))
print("=========================================================================")
cat('\n')
}
return(list("Type1.attained" = actual.type1.error.AR,
"Type2.attained" = c(actual.type2.errorH1r.AR, actual.type2.errorH1l.AR),
'N' = list('H0' = list('Group1' = N10.AR, 'Group2' = N20.AR),
'right' = list('Group1' = N11r.AR, 'Group2' = N21r.AR),
'left' = list('Group1' = N11l.AR, 'Group2' = N21l.AR)),
'EN' = list('H0' = list('Group1' = EN10, 'Group2' = EN20),
'right' = list('Group1' = EN11r, 'Group2' = EN21r),
'left' = list('Group1' = EN11l, 'Group2' = EN21l)),
"theta1" = theta1, "Type2.fixed.design" = Type2.target,
"RejectH0.threshold" = RejectH0.threshold, "RejectH1.threshold" = RejectH1.threshold,
"termination.threshold" = termination.threshold.AR,
'test.type' = 'twoT', 'side' = side, 'theta0' = theta0,
'N1.max' = N1.max, 'N2.max' = N2.max,
'Type1.target' = Type1.target, 'Type2.target' = Type2.target,
'batch1.size' = diff(batch1.size), 'batch2.size' = diff(batch2.size),
'nAnalyses' = nAnalyses, 'nReplicate' = nReplicate, 'seed' = seed))
}
}
}
design.MSPRT = function(test.type, side = 'right', theta0, theta1 = T,
Type1.target = .005, Type2.target = .2,
N.max, N1.max, N2.max,
sigma = 1, sigma1 = 1, sigma2 = 1,
batch.size, batch1.size, batch2.size,
nReplicate = 1e+6, verbose = T, seed = 1){
if((test.type!="oneProp") & (test.type!="oneZ") & (test.type!="oneT") &
(test.type!="twoZ") & (test.type!="twoT")){
return(print("Unknown 'test type'. Has to be one of 'oneProp', 'oneZ', 'oneT', 'twoZ' or 'twoT'."))
}
if(test.type=='oneProp'){
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
if(missing(theta0)) theta0 = 0.5
return(design.MSPRT_oneProp(side = side, theta0 = theta0, theta1 = theta1,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
nReplicate = nReplicate,
verbose = verbose, seed = seed))
}else if(test.type=='oneZ'){
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
if(missing(theta0)) theta0 = 0
return(design.MSPRT_oneZ(side = side, theta0 = theta0, theta1 = theta1,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, sigma = sigma,
batch.size = batch.size,
nReplicate = nReplicate,
verbose = verbose, seed = seed))
}else if(test.type=='oneT'){
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
if(missing(theta0)) theta0 = 0
return(design.MSPRT_oneT(side = side, theta0 = theta0, theta1 = theta1,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
nReplicate = nReplicate,
verbose = verbose, seed = seed))
}else if(test.type=='twoZ'){
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
if(missing(theta0)) theta0 = 0
return(design.MSPRT_twoZ(side = side, theta0 = theta0, theta1 = theta1,
Type1.target = Type1.target, Type2.target = Type2.target,
N1.max = N1.max, N2.max = N2.max,
sigma1 = sigma1, sigma2 = sigma2,
batch1.size = batch1.size, batch2.size = batch2.size,
nReplicate = nReplicate, verbose = verbose, seed = seed))
}else if(test.type=='twoT'){
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
if(missing(theta0)) theta0 = 0
return(design.MSPRT_twoT(side = side, theta0 = theta0, theta1 = theta1,
Type1.target = Type1.target, Type2.target = Type2.target,
N1.max = N1.max, N2.max = N2.max,
batch1.size = batch1.size, batch2.size = batch2.size,
nReplicate = nReplicate, verbose = verbose, seed = seed))
}
}
OCandASN.MSPRT_oneProp = function(theta, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0.5,
Type1.target =.005, Type2.target = .2,
N.max, batch.size,
nReplicate = 1e+6, nCore = max(1, detectCores() - 1),
verbose = T, seed = 1){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
UMPBT = design.MSPRT.object$UMPBT
nAnalyses = design.MSPRT.object$nAnalyses
nReplicate = design.MSPRT.object$nReplicate
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", design.MSPRT.object$termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(UMPBT$theta[1], 3), " & ",
round(UMPBT$theta[2], 3), " with respective probabilities ",
round(UMPBT$mix.prob[1], 3), " & ", 1 - round(UMPBT$mix.prob[1], 3), sep = ''))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}else{
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
UMPBT = UMPBT.alt(test.type = 'oneProp', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", design.MSPRT.object$termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(UMPBT$theta[1], 3), " & ",
round(UMPBT$theta[2], 3), " with respective probabilities ",
round(UMPBT$mix.prob[1], 3), " & ", 1 - round(UMPBT$mix.prob[1], 3), sep = ''))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
cumsum1_n = LR1_n = numeric(nReplicate)
type2.error.AR = rep(F, nReplicate)
N1.AR = rep(N.max, nReplicate)
not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rbinom(length(not.reached.decisionH1.AR),
batch.size[n+1]-batch.size[n], theta1)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n[not.reached.decisionH1.AR] =
UMPBT$mix.prob[1]*(((1 - UMPBT$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$theta[1])))^cumsum1_n[not.reached.decisionH1.AR] +
(1 - UMPBT$mix.prob[2])*(((1 - UMPBT$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$theta[2])))^cumsum1_n[not.reached.decisionH1.AR]
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold)/nReplicate
EN1 = mean(N1.AR)
c(theta1, actual.type2.error.AR, EN1)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 3, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print(paste('Expected sample size: ',
paste(round(out.OCandASN$EN, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}else{
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nReplicate = design.MSPRT.object$nReplicate
UMPBT = design.MSPRT.object$UMPBT
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", design.MSPRT.object$termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(UMPBT$right$theta[1], 3), " & ",
round(UMPBT$right$theta[2], 3), " with respective probabilities ",
round(UMPBT$right$mix.prob[1], 3), " & ", 1 - round(UMPBT$right$mix.prob[1], 3),
sep = ""))
print(paste(' On the left: ', round(UMPBT$left$theta[1], 3), " & ",
round(UMPBT$left$theta[2], 3), " with respective probabilities ",
round(UMPBT$left$mix.prob[1], 3), " & ", 1 - round(UMPBT$left$mix.prob[1], 3),
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}else{
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
UMPBT = list('right' = UMPBT.alt(test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max, Type1 = Type1.target/2),
'left' = UMPBT.alt(test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max, Type1 = Type1.target/2))
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", design.MSPRT.object$termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(UMPBT$right$theta[1], 3), " & ",
round(UMPBT$right$theta[2], 3), " with respective probabilities ",
round(UMPBT$right$mix.prob[1], 3), " & ", 1 - round(UMPBT$right$mix.prob[1], 3),
sep = ""))
print(paste(' On the left: ', round(UMPBT$left$theta[1], 3), " & ",
round(UMPBT$left$theta[2], 3), " with respective probabilities ",
round(UMPBT$left$mix.prob[1], 3), " & ", 1 - round(UMPBT$left$mix.prob[1], 3),
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
cumsum1_n = LR1_n.r = LR1_n.l = numeric(nReplicate)
PowerH1.AR = rep(F, nReplicate)
N1.AR = N1.AR.r = N1.AR.l = rep(N.max, nReplicate)
decision.underH1.AR.r = decision.underH1.AR.l = rep(NA, nReplicate)
not.reached.decisionH1.AR = not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.l =
1:nReplicate
set.seed(seed)
pb = txtProgressBar(min = 1, max = nAnalyses, style = 3)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rbinom(length(not.reached.decisionH1.AR),
batch.size[n+1]-batch.size[n], theta1)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n.r[not.reached.decisionH1.AR.r] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum1_n[not.reached.decisionH1.AR.r] +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum1_n[not.reached.decisionH1.AR.r]
LR1_n.l[not.reached.decisionH1.AR.l] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum1_n[not.reached.decisionH1.AR.l] +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum1_n[not.reached.decisionH1.AR.l]
AcceptedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]<=RejectH1.threshold
RejectedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]>=RejectH0.threshold
reached.decisionH1_n.AR.r = AcceptedH0.underH1_n.AR.r|RejectedH0.underH1_n.AR.r
if(any(reached.decisionH1_n.AR.r)){
decision.underH1.AR.r[not.reached.decisionH1.AR.r[AcceptedH0.underH1_n.AR.r]] = 'A'
decision.underH1.AR.r[not.reached.decisionH1.AR.r[RejectedH0.underH1_n.AR.r]] = 'R'
N1.AR.r[not.reached.decisionH1.AR.r[reached.decisionH1_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.r[!reached.decisionH1_n.AR.r]
}
AcceptedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]<=RejectH1.threshold
RejectedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]>=RejectH0.threshold
reached.decisionH1_n.AR.l = AcceptedH0.underH1_n.AR.l|RejectedH0.underH1_n.AR.l
if(any(reached.decisionH1_n.AR.l)){
decision.underH1.AR.l[not.reached.decisionH1.AR.l[AcceptedH0.underH1_n.AR.l]] = 'A'
decision.underH1.AR.l[not.reached.decisionH1.AR.l[RejectedH0.underH1_n.AR.l]] = 'R'
N1.AR.l[not.reached.decisionH1.AR.l[reached.decisionH1_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1.AR.l = not.reached.decisionH1.AR.l[!reached.decisionH1_n.AR.l]
}
not.reached.decisionH1.AR = union(not.reached.decisionH1.AR.r,
not.reached.decisionH1.AR.l)
}
}
accepted.by.both1 = intersect(which(decision.underH1.AR.r=='A'),
which(decision.underH1.AR.l=='A'))
onlyrejected.by.right1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l!='R'))
onlyrejected.by.left1 = intersect(which(decision.underH1.AR.r!='R'),
which(decision.underH1.AR.l=='R'))
rejected.by.both1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l=='R'))
N1.AR[accepted.by.both1] = pmax(N1.AR.r[accepted.by.both1],
N1.AR.l[accepted.by.both1])
N1.AR[onlyrejected.by.right1] = N1.AR.r[onlyrejected.by.right1]
N1.AR[onlyrejected.by.left1] = N1.AR.l[onlyrejected.by.left1]
N1.AR[rejected.by.both1] = pmin(N1.AR.r[rejected.by.both1],
N1.AR.l[rejected.by.both1])
onlyaccepted.by.right1 = intersect(which(decision.underH1.AR.r=='A'),
which(is.na(decision.underH1.AR.l)))
onlyaccepted.by.left1 = intersect(which(is.na(decision.underH1.AR.r)),
which(decision.underH1.AR.l=='A'))
both.inconclusive1 = intersect(which(is.na(decision.underH1.AR.r)),
which(is.na(decision.underH1.AR.l)))
all.inconclusive1 = c(onlyaccepted.by.right1, onlyaccepted.by.left1,
both.inconclusive1)
nNot.reached.decisionH1.AR = length(all.inconclusive1)
PowerH1.AR[c(onlyrejected.by.right1, onlyrejected.by.left1,
rejected.by.both1)] = T
actual.PowerH1.AR.r = mean(PowerH1.AR) +
sum(c(LR1_n.r[onlyaccepted.by.left1],
LR1_n.l[onlyaccepted.by.right1],
pmax(LR1_n.r[both.inconclusive1], LR1_n.l[both.inconclusive1]))>=
termination.threshold)/nReplicate
actual.type2.errorH1.AR = 1 - actual.PowerH1.AR.r
EN1 = mean(N1.AR)
c(theta1, actual.type2.errorH1.AR, EN1)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 3, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print(paste('Expected sample size: ',
paste(round(out.OCandASN$EN, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}
}
OCandASN.MSPRT_oneZ = function(theta, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N.max, sigma = 1, batch.size,
nReplicate = 1e+6, nCore = max(1, detectCores() - 1),
verbose = T, seed = 1){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma = design.MSPRT.object$sigma
termination.threshold = design.MSPRT.object$termination.threshold
nReplicate = design.MSPRT.object$nReplicate
theta.UMPBT = design.MSPRT.object$theta.UMPBT
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}else{
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
theta.UMPBT = UMPBT.alt(test.type = 'oneZ', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, sigma = sigma)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
cumsum1_n = LR1_n = numeric(nReplicate)
type2.error.AR = rep(F, nReplicate)
N1.AR = rep(N.max, nReplicate)
not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rnorm(length(not.reached.decisionH1.AR),
(batch.size[n+1]-batch.size[n])*theta1,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n[not.reached.decisionH1.AR] =
exp((cumsum1_n[not.reached.decisionH1.AR]*(theta.UMPBT - theta0) -
((batch.size[n+1]*((theta.UMPBT^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold)/nReplicate
EN1 = mean(N1.AR)
c(theta1, actual.type2.error.AR, EN1)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 3, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print(paste('Expected sample size: ',
paste(round(out.OCandASN$EN, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}else{
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma = design.MSPRT.object$sigma
termination.threshold = design.MSPRT.object$termination.threshold
nReplicate = design.MSPRT.object$nReplicate
theta.UMPBT = design.MSPRT.object$theta.UMPBT
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}else{
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses = length(batch.size)
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'oneZ', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma),
'left' = UMPBT.alt(test.type = 'oneZ', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma))
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
cumsum1_n = LR1_n.r = LR1_n.l = numeric(nReplicate)
PowerH1.AR = rep(F, nReplicate)
N1.AR = N1.AR.r = N1.AR.l = rep(N.max, nReplicate)
decision.underH1.AR.r = decision.underH1.AR.l = rep(NA, nReplicate)
not.reached.decisionH1.AR = not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.l =
1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
sum1_n = rnorm(length(not.reached.decisionH1.AR),
(batch.size[n+1]-batch.size[n])*theta1,
sqrt(batch.size[n+1]-batch.size[n])*sigma)
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + sum1_n
LR1_n.r[not.reached.decisionH1.AR.r] =
exp((cumsum1_n[not.reached.decisionH1.AR.r]*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
LR1_n.l[not.reached.decisionH1.AR.l] =
exp((cumsum1_n[not.reached.decisionH1.AR.l]*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]<=RejectH1.threshold
RejectedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]>=RejectH0.threshold
reached.decisionH1_n.AR.r = AcceptedH0.underH1_n.AR.r|RejectedH0.underH1_n.AR.r
if(any(reached.decisionH1_n.AR.r)){
decision.underH1.AR.r[not.reached.decisionH1.AR.r[AcceptedH0.underH1_n.AR.r]] = 'A'
decision.underH1.AR.r[not.reached.decisionH1.AR.r[RejectedH0.underH1_n.AR.r]] = 'R'
N1.AR.r[not.reached.decisionH1.AR.r[reached.decisionH1_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.r[!reached.decisionH1_n.AR.r]
}
AcceptedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]<=RejectH1.threshold
RejectedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]>=RejectH0.threshold
reached.decisionH1_n.AR.l = AcceptedH0.underH1_n.AR.l|RejectedH0.underH1_n.AR.l
if(any(reached.decisionH1_n.AR.l)){
decision.underH1.AR.l[not.reached.decisionH1.AR.l[AcceptedH0.underH1_n.AR.l]] = 'A'
decision.underH1.AR.l[not.reached.decisionH1.AR.l[RejectedH0.underH1_n.AR.l]] = 'R'
N1.AR.l[not.reached.decisionH1.AR.l[reached.decisionH1_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1.AR.l = not.reached.decisionH1.AR.l[!reached.decisionH1_n.AR.l]
}
not.reached.decisionH1.AR = union(not.reached.decisionH1.AR.r,
not.reached.decisionH1.AR.l)
}
}
accepted.by.both1 = intersect(which(decision.underH1.AR.r=='A'),
which(decision.underH1.AR.l=='A'))
onlyrejected.by.right1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l!='R'))
onlyrejected.by.left1 = intersect(which(decision.underH1.AR.r!='R'),
which(decision.underH1.AR.l=='R'))
rejected.by.both1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l=='R'))
N1.AR[accepted.by.both1] = pmax(N1.AR.r[accepted.by.both1],
N1.AR.l[accepted.by.both1])
N1.AR[onlyrejected.by.right1] = N1.AR.r[onlyrejected.by.right1]
N1.AR[onlyrejected.by.left1] = N1.AR.l[onlyrejected.by.left1]
N1.AR[rejected.by.both1] = pmin(N1.AR.r[rejected.by.both1],
N1.AR.l[rejected.by.both1])
onlyaccepted.by.right1 = intersect(which(decision.underH1.AR.r=='A'),
which(is.na(decision.underH1.AR.l)))
onlyaccepted.by.left1 = intersect(which(is.na(decision.underH1.AR.r)),
which(decision.underH1.AR.l=='A'))
both.inconclusive1 = intersect(which(is.na(decision.underH1.AR.r)),
which(is.na(decision.underH1.AR.l)))
all.inconclusive1 = c(onlyaccepted.by.right1, onlyaccepted.by.left1,
both.inconclusive1)
nNot.reached.decisionH1.AR = length(all.inconclusive1)
PowerH1.AR[c(onlyrejected.by.right1, onlyrejected.by.left1,
rejected.by.both1)] = T
actual.PowerH1.AR = mean(PowerH1.AR) +
sum(c(LR1_n.r[onlyaccepted.by.left1],
LR1_n.l[onlyaccepted.by.right1],
pmax(LR1_n.r[both.inconclusive1], LR1_n.l[both.inconclusive1]))>=
termination.threshold)/nReplicate
actual.type2.errorH1.AR = 1 - actual.PowerH1.AR
EN1 = mean(N1.AR)
c(theta1, actual.type2.errorH1.AR, EN1)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 3, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print(paste('Expected sample size: ',
paste(round(out.OCandASN$EN, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}
}
OCandASN.MSPRT_oneT = function(theta, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N.max, batch.size,
nReplicate = 1e+6, nCore = max(1, detectCores() - 1),
verbose = T, seed = 1){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nReplicate = design.MSPRT.object$nReplicate
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}else{
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
nAnalyses = length(batch.size)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
signed_t.alpha = (2*(side=='right')-1)*qt(Type1.target, df = N.max -1, lower.tail = F)
cumSS1_n = cumsum1_n = LR1_n = numeric(nReplicate)
type2.error.AR = rep(F, nReplicate)
N1.AR = rep(N.max, nReplicate)
not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
if(length(not.reached.decisionH1.AR)>1){
obs1_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
})
}else{
obs1_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + rowSums(obs1_n)
cumSS1_n[not.reached.decisionH1.AR] =
cumSS1_n[not.reached.decisionH1.AR] + rowSums(obs1_n^2)
xbar1_n = cumsum1_n[not.reached.decisionH1.AR]/batch.size[n+1]
divisor.s1_n.sq =
cumSS1_n[not.reached.decisionH1.AR] - ((cumsum1_n[not.reached.decisionH1.AR])^2)/batch.size[n+1]
LR1_n[not.reached.decisionH1.AR] =
((1 + (batch.size[n+1]*((xbar1_n - theta0)^2))/divisor.s1_n.sq)/
(1 + (batch.size[n+1]*((xbar1_n - (theta0 + signed_t.alpha*
sqrt(divisor.s1_n.sq/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1_n.sq))^(batch.size[n+1]/2)
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N1.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold)/nReplicate
EN1 = mean(N1.AR)
c(theta1, actual.type2.error.AR, EN1)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 3, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print(paste('Expected sample size: ',
paste(round(out.OCandASN$EN, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}else{
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nReplicate = design.MSPRT.object$nReplicate
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}else{
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
nAnalyses = length(batch.size)
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("==========================================================================")
print("OC and ASN of the group sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("OC and ASN of the sequential MSPRT for a one-sample t test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch.size = c(0, cumsum(batch.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
t.alpha = qt(Type1.target/2, df = N.max -1, lower.tail = F)
cumSS1_n = cumsum1_n = LR1_n.r = LR1_n.l = numeric(nReplicate)
PowerH1.AR = rep(F, nReplicate)
N1.AR = N1.AR.r = N1.AR.l = rep(N.max, nReplicate)
decision.underH1.AR.r = decision.underH1.AR.l = rep(NA, nReplicate)
not.reached.decisionH1.AR = not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.l =
1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
if(length(not.reached.decisionH1.AR)>1){
obs1_n = mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
})
}else{
obs1_n = matrix(mapply(X = 1:(batch.size[n+1]-batch.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1, 1)
}), nrow = 1, ncol = batch.size[n+1]-batch.size[n],
byrow = T)
}
cumsum1_n[not.reached.decisionH1.AR] =
cumsum1_n[not.reached.decisionH1.AR] + rowSums(obs1_n)
cumSS1_n[not.reached.decisionH1.AR] =
cumSS1_n[not.reached.decisionH1.AR] + rowSums(obs1_n^2)
xbar1_n.r = cumsum1_n[not.reached.decisionH1.AR.r]/batch.size[n+1]
divisor.s1_n.sq.r =
cumSS1_n[not.reached.decisionH1.AR.r] -
((cumsum1_n[not.reached.decisionH1.AR.r])^2)/batch.size[n+1]
xbar1_n.l = cumsum1_n[not.reached.decisionH1.AR.l]/batch.size[n+1]
divisor.s1_n.sq.l =
cumSS1_n[not.reached.decisionH1.AR.l] -
((cumsum1_n[not.reached.decisionH1.AR.l])^2)/batch.size[n+1]
LR1_n.r[not.reached.decisionH1.AR.r] =
((1 + (batch.size[n+1]*((xbar1_n.r - theta0)^2))/divisor.s1_n.sq.r)/
(1 + (batch.size[n+1]*((xbar1_n.r -
(theta0 + t.alpha*
sqrt(divisor.s1_n.sq.r/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1_n.sq.r))^(batch.size[n+1]/2)
LR1_n.l[not.reached.decisionH1.AR.l] =
((1 + (batch.size[n+1]*((xbar1_n.l - theta0)^2))/divisor.s1_n.sq.l)/
(1 + (batch.size[n+1]*((xbar1_n.l -
(theta0 - t.alpha*
sqrt(divisor.s1_n.sq.l/(N.max*(batch.size[n+1]-1)))))^2))/
divisor.s1_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]<=RejectH1.threshold
RejectedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]>=RejectH0.threshold
reached.decisionH1_n.AR.r = AcceptedH0.underH1_n.AR.r|RejectedH0.underH1_n.AR.r
if(any(reached.decisionH1_n.AR.r)){
decision.underH1.AR.r[not.reached.decisionH1.AR.r[AcceptedH0.underH1_n.AR.r]] = 'A'
decision.underH1.AR.r[not.reached.decisionH1.AR.r[RejectedH0.underH1_n.AR.r]] = 'R'
N1.AR.r[not.reached.decisionH1.AR.r[reached.decisionH1_n.AR.r]] = batch.size[n+1]
not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.r[!reached.decisionH1_n.AR.r]
}
AcceptedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]<=RejectH1.threshold
RejectedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]>=RejectH0.threshold
reached.decisionH1_n.AR.l = AcceptedH0.underH1_n.AR.l|RejectedH0.underH1_n.AR.l
if(any(reached.decisionH1_n.AR.l)){
decision.underH1.AR.l[not.reached.decisionH1.AR.l[AcceptedH0.underH1_n.AR.l]] = 'A'
decision.underH1.AR.l[not.reached.decisionH1.AR.l[RejectedH0.underH1_n.AR.l]] = 'R'
N1.AR.l[not.reached.decisionH1.AR.l[reached.decisionH1_n.AR.l]] = batch.size[n+1]
not.reached.decisionH1.AR.l = not.reached.decisionH1.AR.l[!reached.decisionH1_n.AR.l]
}
not.reached.decisionH1.AR = union(not.reached.decisionH1.AR.r,
not.reached.decisionH1.AR.l)
}
}
accepted.by.both1 = intersect(which(decision.underH1.AR.r=='A'),
which(decision.underH1.AR.l=='A'))
onlyrejected.by.right1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l!='R'))
onlyrejected.by.left1 = intersect(which(decision.underH1.AR.r!='R'),
which(decision.underH1.AR.l=='R'))
rejected.by.both1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l=='R'))
N1.AR[accepted.by.both1] = pmax(N1.AR.r[accepted.by.both1],
N1.AR.l[accepted.by.both1])
N1.AR[onlyrejected.by.right1] = N1.AR.r[onlyrejected.by.right1]
N1.AR[onlyrejected.by.left1] = N1.AR.l[onlyrejected.by.left1]
N1.AR[rejected.by.both1] = pmin(N1.AR.r[rejected.by.both1],
N1.AR.l[rejected.by.both1])
onlyaccepted.by.right1 = intersect(which(decision.underH1.AR.r=='A'),
which(is.na(decision.underH1.AR.l)))
onlyaccepted.by.left1 = intersect(which(is.na(decision.underH1.AR.r)),
which(decision.underH1.AR.l=='A'))
both.inconclusive1 = intersect(which(is.na(decision.underH1.AR.r)),
which(is.na(decision.underH1.AR.l)))
all.inconclusive1 = c(onlyaccepted.by.right1, onlyaccepted.by.left1,
both.inconclusive1)
nNot.reached.decisionH1.AR = length(all.inconclusive1)
PowerH1.AR[c(onlyrejected.by.right1, onlyrejected.by.left1,
rejected.by.both1)] = T
actual.PowerH1.AR.r = mean(PowerH1.AR) +
sum(c(LR1_n.r[onlyaccepted.by.left1],
LR1_n.l[onlyaccepted.by.right1],
pmax(LR1_n.r[both.inconclusive1], LR1_n.l[both.inconclusive1]))>=
termination.threshold)/nReplicate
actual.type2.errorH1.AR = 1 - actual.PowerH1.AR.r
EN1 = mean(N1.AR)
c(theta1, actual.type2.errorH1.AR, EN1)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 3, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print(paste('Expected sample size: ',
paste(round(out.OCandASN$EN, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}
}
OCandASN.MSPRT_twoZ = function(theta, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N1.max, N2.max, sigma1 = 1, sigma2 = 1,
batch1.size, batch2.size,
nReplicate = 1e+6, nCore = max(1, detectCores() - 1),
verbose = T, seed = 1){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma1 = design.MSPRT.object$sigma1
sigma2 = design.MSPRT.object$sigma2
termination.threshold = design.MSPRT.object$termination.threshold
theta.UMPBT = design.MSPRT.object$theta.UMPBT
nReplicate = design.MSPRT.object$nReplicate
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("=========================================================================")
print("OC and ASN of the group sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("OC and ASN of the sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}else{
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
nAnalyses = length(batch1.size)
theta.UMPBT = UMPBT.alt(test.type = 'twoZ', side = side, theta0 = theta0,
N1 = N1.max, N2 = N2.max, Type1 = Type1.target,
sigma1 = sigma1, sigma2 = sigma2)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
cumsum11_n = cumsum21_n = LR1_n = numeric(nReplicate)
type2.error.AR = rep(F, nReplicate)
N11.AR = rep(N1.max, nReplicate)
N21.AR = rep(N2.max, nReplicate)
not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
sum11_n = rnorm(length(not.reached.decisionH1.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21_n = rnorm(length(not.reached.decisionH1.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + sum11_n
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + sum21_n
LR1_n[not.reached.decisionH1.AR] =
exp(-(((theta.UMPBT^2) - (theta0^2)) -
2*(theta.UMPBT - theta0)*
(cumsum11_n[not.reached.decisionH1.AR]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N11.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch1.size[n+1]
N21.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch2.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold)/nReplicate
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
c(theta1, actual.type2.error.AR, EN11, EN21)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 4, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN1', 'EN2')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print("Expected sample size:")
print(paste(' Group 1 - ', paste(round(out.OCandASN$EN1, 2), collapse = ', '), sep = ''))
print(paste(' Group 2 - ', paste(round(out.OCandASN$EN2, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}else{
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma1 = design.MSPRT.object$sigma1
sigma2 = design.MSPRT.object$sigma2
termination.threshold = design.MSPRT.object$termination.threshold
theta.UMPBT = design.MSPRT.object$theta.UMPBT
nReplicate = design.MSPRT.object$nReplicate
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("=========================================================================")
print("OC and ASN of the group sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("OC and ASN of the sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}else{
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
nAnalyses = length(batch1.size)
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'twoZ', side = 'right',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2),
'left' = UMPBT.alt(test.type = 'twoZ', side = 'left',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2))
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("=========================================================================")
print("OC and ASN of the group sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("OC and ASN of the sequential MSPRT for a two-sample z test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
cumsum11_n = cumsum21_n = LR1_n.r = LR1_n.l = numeric(nReplicate)
PowerH1.AR = rep(F, nReplicate)
N11.AR = N11.AR.r = N11.AR.l = rep(N1.max, nReplicate)
N21.AR = N21.AR.r = N21.AR.l = rep(N2.max, nReplicate)
decision.underH1.AR.r = decision.underH1.AR.l = rep(NA, nReplicate)
not.reached.decisionH1.AR = not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.l =
1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
sum11_n = rnorm(length(not.reached.decisionH1.AR),
(batch1.size[n+1]-batch1.size[n])*(theta1/2),
sqrt(batch1.size[n+1]-batch1.size[n])*sigma1)
sum21_n = rnorm(length(not.reached.decisionH1.AR),
-(batch2.size[n+1]-batch2.size[n])*(theta1/2),
sqrt(batch2.size[n+1]-batch2.size[n])*sigma2)
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + sum11_n
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + sum21_n
LR1_n.r[not.reached.decisionH1.AR.r] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) -
2*(theta.UMPBT$right - theta0)*
(cumsum11_n[not.reached.decisionH1.AR.r]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR.r]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
LR1_n.l[not.reached.decisionH1.AR.l] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) -
2*(theta.UMPBT$left - theta0)*
(cumsum11_n[not.reached.decisionH1.AR.l]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR.l]/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]<=RejectH1.threshold
RejectedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]>=RejectH0.threshold
reached.decisionH1_n.AR.r = AcceptedH0.underH1_n.AR.r|RejectedH0.underH1_n.AR.r
if(any(reached.decisionH1_n.AR.r)){
decision.underH1.AR.r[not.reached.decisionH1.AR.r[AcceptedH0.underH1_n.AR.r]] = 'A'
decision.underH1.AR.r[not.reached.decisionH1.AR.r[RejectedH0.underH1_n.AR.r]] = 'R'
N11.AR.r[not.reached.decisionH1.AR.r[reached.decisionH1_n.AR.r]] = batch1.size[n+1]
N21.AR.r[not.reached.decisionH1.AR.r[reached.decisionH1_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.r[!reached.decisionH1_n.AR.r]
}
AcceptedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]<=RejectH1.threshold
RejectedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]>=RejectH0.threshold
reached.decisionH1_n.AR.l = AcceptedH0.underH1_n.AR.l|RejectedH0.underH1_n.AR.l
if(any(reached.decisionH1_n.AR.l)){
decision.underH1.AR.l[not.reached.decisionH1.AR.l[AcceptedH0.underH1_n.AR.l]] = 'A'
decision.underH1.AR.l[not.reached.decisionH1.AR.l[RejectedH0.underH1_n.AR.l]] = 'R'
N11.AR.l[not.reached.decisionH1.AR.l[reached.decisionH1_n.AR.l]] = batch1.size[n+1]
N21.AR.l[not.reached.decisionH1.AR.l[reached.decisionH1_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1.AR.l = not.reached.decisionH1.AR.l[!reached.decisionH1_n.AR.l]
}
not.reached.decisionH1.AR = union(not.reached.decisionH1.AR.r,
not.reached.decisionH1.AR.l)
}
}
accepted.by.both1 = intersect(which(decision.underH1.AR.r=='A'),
which(decision.underH1.AR.l=='A'))
onlyrejected.by.right1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l!='R'))
onlyrejected.by.left1 = intersect(which(decision.underH1.AR.r!='R'),
which(decision.underH1.AR.l=='R'))
rejected.by.both1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l=='R'))
N11.AR[accepted.by.both1] = pmax(N11.AR.r[accepted.by.both1],
N11.AR.l[accepted.by.both1])
N11.AR[onlyrejected.by.right1] = N11.AR.r[onlyrejected.by.right1]
N11.AR[onlyrejected.by.left1] = N11.AR.l[onlyrejected.by.left1]
N11.AR[rejected.by.both1] = pmin(N11.AR.r[rejected.by.both1],
N11.AR.l[rejected.by.both1])
N21.AR[accepted.by.both1] = pmax(N21.AR.r[accepted.by.both1],
N21.AR.l[accepted.by.both1])
N21.AR[onlyrejected.by.right1] = N21.AR.r[onlyrejected.by.right1]
N21.AR[onlyrejected.by.left1] = N21.AR.l[onlyrejected.by.left1]
N21.AR[rejected.by.both1] = pmin(N21.AR.r[rejected.by.both1],
N21.AR.l[rejected.by.both1])
onlyaccepted.by.right1 = intersect(which(decision.underH1.AR.r=='A'),
which(is.na(decision.underH1.AR.l)))
onlyaccepted.by.left1 = intersect(which(is.na(decision.underH1.AR.r)),
which(decision.underH1.AR.l=='A'))
both.inconclusive1 = intersect(which(is.na(decision.underH1.AR.r)),
which(is.na(decision.underH1.AR.l)))
all.inconclusive1 = c(onlyaccepted.by.right1, onlyaccepted.by.left1,
both.inconclusive1)
nNot.reached.decisionH1.AR = length(all.inconclusive1)
PowerH1.AR[c(onlyrejected.by.right1, onlyrejected.by.left1,
rejected.by.both1)] = T
actual.PowerH1.AR = mean(PowerH1.AR) +
sum(c(LR1_n.r[onlyaccepted.by.left1],
LR1_n.l[onlyaccepted.by.right1],
pmax(LR1_n.r[both.inconclusive1], LR1_n.l[both.inconclusive1]))>=
termination.threshold)/nReplicate
actual.type2.errorH1.AR = 1 - actual.PowerH1.AR
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
c(theta1, actual.type2.errorH1.AR, EN11, EN21)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 4, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN1', 'EN2')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print("Expected sample size:")
print(paste(' Group 1 - ', paste(round(out.OCandASN$EN1, 2), collapse = ', '), sep = ''))
print(paste(' Group 2 - ', paste(round(out.OCandASN$EN2, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}
}
OCandASN.MSPRT_twoT = function(theta, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N1.max, N2.max, batch1.size, batch2.size,
nReplicate = 1e+6, nCore = max(1, detectCores() - 1),
verbose = T, seed = 1){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nReplicate = design.MSPRT.object$nReplicate
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("=========================================================================")
print("Designing the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Designing the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}else{
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
nAnalyses = length(batch1.size)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("OC and ASN of the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("OC and ASN of the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
signed_t.alpha = (2*(side=='right')-1)*
qt(Type1.target, df = N1.max + N2.max -2, lower.tail = F)
cumSS11_n = cumSS21_n = cumsum11_n = cumsum21_n = LR1_n = numeric(nReplicate)
type2.error.AR = rep(F, nReplicate)
N11.AR = rep(N1.max, nReplicate)
N21.AR = rep(N2.max, nReplicate)
not.reached.decisionH1.AR = 1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
obs11_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1/2, 1)
})
obs21_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), -theta1/2, 1)
})
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + rowSums(obs11_n)
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + rowSums(obs21_n)
cumSS11_n[not.reached.decisionH1.AR] =
cumSS11_n[not.reached.decisionH1.AR] + rowSums(obs11_n^2)
cumSS21_n[not.reached.decisionH1.AR] =
cumSS21_n[not.reached.decisionH1.AR] + rowSums(obs21_n^2)
xbar.diff1_n = cumsum11_n[not.reached.decisionH1.AR]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR]/batch2.size[n+1]
divisor.pooled.sd1_n.sq =
cumSS11_n[not.reached.decisionH1.AR] - ((cumsum11_n[not.reached.decisionH1.AR])^2)/batch1.size[n+1] +
cumSS21_n[not.reached.decisionH1.AR] - ((cumsum21_n[not.reached.decisionH1.AR])^2)/batch2.size[n+1]
LR1_n[not.reached.decisionH1.AR] =
((1 + ((xbar.diff1_n - theta0)^2)/(divisor.pooled.sd1_n.sq*
(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1_n -
(theta0 + signed_t.alpha*
sqrt((divisor.pooled.sd1_n.sq/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]<=RejectH1.threshold)
RejectedH0.underH1_n.AR = which(LR1_n[not.reached.decisionH1.AR]>=RejectH0.threshold)
reached.decisionH1_n.AR = union(AcceptedH0.underH1_n.AR, RejectedH0.underH1_n.AR)
if(length(reached.decisionH1_n.AR)>0){
N11.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch1.size[n+1]
N21.AR[not.reached.decisionH1.AR[reached.decisionH1_n.AR]] = batch2.size[n+1]
type2.error.AR[not.reached.decisionH1.AR[AcceptedH0.underH1_n.AR]] = T
not.reached.decisionH1.AR = not.reached.decisionH1.AR[-reached.decisionH1_n.AR]
}
}
}
actual.type2.error.AR = mean(type2.error.AR) +
sum(LR1_n[not.reached.decisionH1.AR]<termination.threshold)/nReplicate
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
c(theta1, actual.type2.error.AR, EN11, EN21)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 4, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN1', 'EN2')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print("Expected sample size:")
print(paste(' Group 1 - ', paste(round(out.OCandASN$EN1, 2), collapse = ', '), sep = ''))
print(paste(' Group 2 - ', paste(round(out.OCandASN$EN2, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}else{
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
nAnalyses = design.MSPRT.object$nAnalyses
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nReplicate = design.MSPRT.object$nReplicate
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("OC and ASN of the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("OC and ASN of the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}else{
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
nAnalyses = length(batch1.size)
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("OC and ASN of the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("OC and ASN of the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Total number of sequential analyses: ", nAnalyses, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste('Parameter value(s) where OC and ASN is desired: ',
paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
print("Calculating the OC and ASN ...")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
}
registerDoParallel(cores = nCore)
out.OCandASN = foreach(theta1 = theta, .combine = 'rbind') %dopar% {
t.alpha = qt(Type1.target/2, df = N1.max + N2.max -2, lower.tail = F)
cumSS11_n = cumSS21_n = cumsum11_n = cumsum21_n =
LR1_n.r = LR1_n.l = numeric(nReplicate)
PowerH1.AR = rep(F, nReplicate)
N11.AR = N11.AR.r = N11.AR.l = rep(N1.max, nReplicate)
N21.AR = N21.AR.r = N21.AR.l = rep(N2.max, nReplicate)
decision.underH1.AR.r = decision.underH1.AR.l = rep(NA, nReplicate)
not.reached.decisionH1.AR = not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.l =
1:nReplicate
set.seed(seed)
for(n in 1:nAnalyses){
if(length(not.reached.decisionH1.AR)>0){
if(length(not.reached.decisionH1.AR)>1){
obs11_n = mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1/2, 1)
})
}else{
obs11_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), theta1/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
if(length(not.reached.decisionH1.AR)>1){
obs21_n = mapply(X = 1:(batch2.size[n+1]-batch2.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), -theta1/2, 1)
})
}else{
obs21_n = matrix(mapply(X = 1:(batch1.size[n+1]-batch1.size[n]),
FUN = function(X){
rnorm(length(not.reached.decisionH1.AR), -theta1/2, 1)
}), nrow = 1, ncol = batch1.size[n+1]-batch1.size[n],
byrow = T)
}
cumsum11_n[not.reached.decisionH1.AR] =
cumsum11_n[not.reached.decisionH1.AR] + rowSums(obs11_n)
cumsum21_n[not.reached.decisionH1.AR] =
cumsum21_n[not.reached.decisionH1.AR] + rowSums(obs21_n)
cumSS11_n[not.reached.decisionH1.AR] =
cumSS11_n[not.reached.decisionH1.AR] + rowSums(obs11_n^2)
cumSS21_n[not.reached.decisionH1.AR] =
cumSS21_n[not.reached.decisionH1.AR] + rowSums(obs21_n^2)
xbar.diff1_n.r = cumsum11_n[not.reached.decisionH1.AR.r]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR.r]/batch2.size[n+1]
divisor.pooled.sd1_n.sq.r =
cumSS11_n[not.reached.decisionH1.AR.r] -
((cumsum11_n[not.reached.decisionH1.AR.r])^2)/batch1.size[n+1] +
cumSS21_n[not.reached.decisionH1.AR.r] -
((cumsum21_n[not.reached.decisionH1.AR.r])^2)/batch2.size[n+1]
xbar.diff1_n.l = cumsum11_n[not.reached.decisionH1.AR.l]/batch1.size[n+1] -
cumsum21_n[not.reached.decisionH1.AR.l]/batch2.size[n+1]
divisor.pooled.sd1_n.sq.l =
cumSS11_n[not.reached.decisionH1.AR.l] -
((cumsum11_n[not.reached.decisionH1.AR.l])^2)/batch1.size[n+1] +
cumSS21_n[not.reached.decisionH1.AR.l] -
((cumsum21_n[not.reached.decisionH1.AR.l])^2)/batch2.size[n+1]
LR1_n.r[not.reached.decisionH1.AR.r] =
((1 + ((xbar.diff1_n.r - theta0)^2)/
(divisor.pooled.sd1_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1_n.r -
(theta0 + t.alpha*
sqrt((divisor.pooled.sd1_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
LR1_n.l[not.reached.decisionH1.AR.l] =
((1 + ((xbar.diff1_n.l - theta0)^2)/
(divisor.pooled.sd1_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff1_n.l -
(theta0 - t.alpha*
sqrt((divisor.pooled.sd1_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))))^2)/
(divisor.pooled.sd1_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]<=RejectH1.threshold
RejectedH0.underH1_n.AR.r = LR1_n.r[not.reached.decisionH1.AR.r]>=RejectH0.threshold
reached.decisionH1_n.AR.r = AcceptedH0.underH1_n.AR.r|RejectedH0.underH1_n.AR.r
if(any(reached.decisionH1_n.AR.r)){
decision.underH1.AR.r[not.reached.decisionH1.AR.r[AcceptedH0.underH1_n.AR.r]] = 'A'
decision.underH1.AR.r[not.reached.decisionH1.AR.r[RejectedH0.underH1_n.AR.r]] = 'R'
N11.AR.r[not.reached.decisionH1.AR.r[reached.decisionH1_n.AR.r]] = batch1.size[n+1]
N21.AR.r[not.reached.decisionH1.AR.r[reached.decisionH1_n.AR.r]] = batch2.size[n+1]
not.reached.decisionH1.AR.r = not.reached.decisionH1.AR.r[!reached.decisionH1_n.AR.r]
}
AcceptedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]<=RejectH1.threshold
RejectedH0.underH1_n.AR.l = LR1_n.l[not.reached.decisionH1.AR.l]>=RejectH0.threshold
reached.decisionH1_n.AR.l = AcceptedH0.underH1_n.AR.l|RejectedH0.underH1_n.AR.l
if(any(reached.decisionH1_n.AR.l)){
decision.underH1.AR.l[not.reached.decisionH1.AR.l[AcceptedH0.underH1_n.AR.l]] = 'A'
decision.underH1.AR.l[not.reached.decisionH1.AR.l[RejectedH0.underH1_n.AR.l]] = 'R'
N11.AR.l[not.reached.decisionH1.AR.l[reached.decisionH1_n.AR.l]] = batch1.size[n+1]
N21.AR.l[not.reached.decisionH1.AR.l[reached.decisionH1_n.AR.l]] = batch2.size[n+1]
not.reached.decisionH1.AR.l = not.reached.decisionH1.AR.l[!reached.decisionH1_n.AR.l]
}
not.reached.decisionH1.AR = union(not.reached.decisionH1.AR.r,
not.reached.decisionH1.AR.l)
}
}
accepted.by.both1 = intersect(which(decision.underH1.AR.r=='A'),
which(decision.underH1.AR.l=='A'))
onlyrejected.by.right1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l!='R'))
onlyrejected.by.left1 = intersect(which(decision.underH1.AR.r!='R'),
which(decision.underH1.AR.l=='R'))
rejected.by.both1 = intersect(which(decision.underH1.AR.r=='R'),
which(decision.underH1.AR.l=='R'))
N11.AR[accepted.by.both1] = pmax(N11.AR.r[accepted.by.both1],
N11.AR.l[accepted.by.both1])
N11.AR[onlyrejected.by.right1] = N11.AR.r[onlyrejected.by.right1]
N11.AR[onlyrejected.by.left1] = N11.AR.l[onlyrejected.by.left1]
N11.AR[rejected.by.both1] = pmin(N11.AR.r[rejected.by.both1],
N11.AR.l[rejected.by.both1])
N21.AR[accepted.by.both1] = pmax(N21.AR.r[accepted.by.both1],
N21.AR.l[accepted.by.both1])
N21.AR[onlyrejected.by.right1] = N21.AR.r[onlyrejected.by.right1]
N21.AR[onlyrejected.by.left1] = N21.AR.l[onlyrejected.by.left1]
N21.AR[rejected.by.both1] = pmin(N21.AR.r[rejected.by.both1],
N21.AR.l[rejected.by.both1])
onlyaccepted.by.right1 = intersect(which(decision.underH1.AR.r=='A'),
which(is.na(decision.underH1.AR.l)))
onlyaccepted.by.left1 = intersect(which(is.na(decision.underH1.AR.r)),
which(decision.underH1.AR.l=='A'))
both.inconclusive1 = intersect(which(is.na(decision.underH1.AR.r)),
which(is.na(decision.underH1.AR.l)))
all.inconclusive1 = c(onlyaccepted.by.right1, onlyaccepted.by.left1,
both.inconclusive1)
nNot.reached.decisionH1.AR = length(all.inconclusive1)
PowerH1.AR[c(onlyrejected.by.right1, onlyrejected.by.left1,
rejected.by.both1)] = T
actual.PowerH1.AR = mean(PowerH1.AR) +
sum(c(LR1_n.r[onlyaccepted.by.left1],
LR1_n.l[onlyaccepted.by.right1],
pmax(LR1_n.r[both.inconclusive1], LR1_n.l[both.inconclusive1]))>=
termination.threshold)/nReplicate
actual.type2.errorH1.AR = 1 - actual.PowerH1.AR
EN11 = mean(N11.AR)
EN21 = mean(N21.AR)
c(theta1, actual.type2.errorH1.AR, EN11, EN21)
}
if(length(theta)==1) out.OCandASN = matrix(data = out.OCandASN, nrow = 1,
ncol = 4, byrow = T)
out.OCandASN = as.data.frame(out.OCandASN)
colnames(out.OCandASN) = c('theta', 'acceptH0.prob', 'EN1', 'EN2')
if(verbose==T){
cat('\n')
print('Done.')
print("-------------------------------------------------------------------------")
cat('\n\n')
print("=========================================================================")
print("Performance summary:")
print("=========================================================================")
print(paste('Parameter value(s): ', paste(round(theta, 3), collapse = ', '), sep = ''))
print(paste('Probability of accepting H0: ',
paste(round(out.OCandASN$acceptH0.prob, 3), collapse = ', '), sep = ''))
print("Expected sample size:")
print(paste(' Group 1 - ', paste(round(out.OCandASN$EN1, 2), collapse = ', '), sep = ''))
print(paste(' Group 2 - ', paste(round(out.OCandASN$EN2, 2), collapse = ', '), sep = ''))
print("=========================================================================")
cat('\n')
}
return(out.OCandASN)
}
}
OCandASN.MSPRT = function(theta, design.MSPRT.object,
termination.threshold, test.type,
side = 'right', theta0,
Type1.target =.005, Type2.target = .2,
N.max, N1.max, N2.max,
sigma = 1, sigma1 = 1, sigma2 = 1,
batch.size, batch1.size, batch2.size,
nReplicate = 1e+6, nCore = max(1, detectCores() - 1),
verbose = T, seed = 1){
if(!missing(design.MSPRT.object)){
test.type = design.MSPRT.object$test.type
}else{
if((test.type!="oneProp") & (test.type!="oneZ") & (test.type!="oneT") &
(test.type!="twoZ") & (test.type!="twoT")){
return(print("Unknown 'test type'. Has to be one of 'oneProp', 'oneZ', 'oneT', 'twoZ' or 'twoT'."))
}
}
if(test.type=='oneProp'){
if(!missing(design.MSPRT.object)){
return(OCandASN.MSPRT_oneProp(theta = theta,
design.MSPRT.object = design.MSPRT.object,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}else{
return(OCandASN.MSPRT_oneProp(theta = theta,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}
}else if(test.type=='oneZ'){
if(!missing(design.MSPRT.object)){
return(OCandASN.MSPRT_oneZ(theta = theta,
design.MSPRT.object = design.MSPRT.object,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}else{
return(OCandASN.MSPRT_oneZ(theta = theta,
termination.threshold = termination.threshold,
side = side, theta0 = theta0, sigma = sigma,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}
}else if(test.type=='oneT'){
if(!missing(design.MSPRT.object)){
return(OCandASN.MSPRT_oneT(theta = theta,
design.MSPRT.object = design.MSPRT.object,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}else{
return(OCandASN.MSPRT_oneT(theta = theta,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}
}else if(test.type=='twoZ'){
if(!missing(design.MSPRT.object)){
return(OCandASN.MSPRT_twoZ(theta = theta,
design.MSPRT.object = design.MSPRT.object,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}else{
return(OCandASN.MSPRT_twoZ(theta = theta,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N1.max = N1.max, N2.max = N2.max,
sigma1 = sigma1, sigma2 = sigma2,
batch1.size = batch1.size,
batch2.size = batch2.size,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}
}else if(test.type=='twoT'){
if(!missing(design.MSPRT.object)){
return(OCandASN.MSPRT_twoT(theta = theta,
design.MSPRT.object = design.MSPRT.object,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}else{
return(OCandASN.MSPRT_twoT(theta = theta,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N1.max = N1.max, N2.max = N2.max,
batch1.size = batch1.size,
batch2.size = batch2.size,
nReplicate = nReplicate, nCore = nCore,
verbose = verbose, seed = seed))
}
}
}
implement.MSPRT_oneProp = function(obs, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0.5,
Type1.target =.005, Type2.target = .2,
N.max, batch.size,
verbose = T, plot.it = 2){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
UMPBT = design.MSPRT.object$UMPBT
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(UMPBT$theta[1], 3), " & ",
round(UMPBT$theta[2], 3), " with respective probabilities ",
round(UMPBT$mix.prob[1], 3), " & ", 1 - round(UMPBT$mix.prob[1], 3), sep = ''))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses.max = length(batch.size)
if(missing(theta0)) theta0 = 0.5
UMPBT = UMPBT.alt(test.type = 'oneProp', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(UMPBT$theta[1], 3), " & ",
round(UMPBT$theta[2], 3), " with respective probabilities ",
round(UMPBT$mix.prob[1], 3), " & ", 1 - round(UMPBT$mix.prob[1], 3), sep = ''))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}
cumsum_n = 0
reached.decision = F
rejectH0 = NA
LR = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum_n = cumsum_n + sum(obs[(batch.size[n]+1):batch.size[n+1]])
LR[n] =
UMPBT$mix.prob[1]*(((1 - UMPBT$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$theta[1])))^cumsum_n +
(1 - UMPBT$mix.prob[2])*(((1 - UMPBT$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$theta[2])))^cumsum_n
AcceptedH0_n = LR[n]<=RejectH1.threshold
RejectedH0_n = LR[n]>=RejectH0.threshold
reached.decision = AcceptedH0_n||RejectedH0_n
if(reached.decision){
n0 = batch.size[n+1]
rejectH0 = RejectedH0_n
if(rejectH0){
decision = 'reject.null'
}else{decision = 'reject.alt'}
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n0 = N.max
rejectH0 = LR[nAnalyses]>=termination.threshold
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n0 = batch.size[nAnalyses+1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.test = max(which(!is.na(LR)))
if(plot.it==0){
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'UMPBT' = UMPBT))
}else if(plot.it!=0){
if(side=='right'){
testname = bquote('Right-sided one-sample proportion test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}else{
testname = bquote('Left-sided one-sample proportion test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}
if((!reached.decision)&&(nAnalyses.test==nAnalyses.max)){
ylow = RejectH1.threshold
yup = RejectH0.threshold
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Wtd. likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Wtd. likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
ylow = min(LR, na.rm = T)
yup = max(LR, na.rm = T)
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n = ', n0, ')', sep = '')
if(LR[nAnalyses.test]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else{
ylow = RejectH1.threshold
yup = RejectH0.threshold
}
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Wtd. likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Wtd. likelihood ratio',
x = 'Steps in sequential analyses')
}
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'UMPBT' = UMPBT,
'ggplot.object' = seqcompare))
}
}else{
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
UMPBT = design.MSPRT.object$UMPBT
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", design.MSPRT.object$nAnalyses,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(UMPBT$right$theta[1], 3), " & ",
round(UMPBT$right$theta[2], 3), " with respective probabilities ",
round(UMPBT$right$mix.prob[1], 3), " & ", 1 - round(UMPBT$right$mix.prob[1], 3),
sep = ""))
print(paste(' On the left: ', round(UMPBT$left$theta[1], 3), " & ",
round(UMPBT$left$theta[2], 3), " with respective probabilities ",
round(UMPBT$left$mix.prob[1], 3), " & ", 1 - round(UMPBT$left$mix.prob[1], 3),
sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses.max = length(batch.size)
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(missing(theta0)) theta0 = 0.5
UMPBT = list('right' = UMPBT.alt(test.type = 'oneProp', side = 'right',
theta0 = theta0, N = N.max, Type1 = Type1.target/2),
'left' = UMPBT.alt(test.type = 'oneProp', side = 'left',
theta0 = theta0, N = N.max, Type1 = Type1.target/2))
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample proportion test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(UMPBT$right$theta[1], 3), " & ",
round(UMPBT$right$theta[2], 3), " with respective probabilities ",
round(UMPBT$right$mix.prob[1], 3), " & ", 1 - round(UMPBT$right$mix.prob[1], 3),
sep = ""))
print(paste(' On the left: ', round(UMPBT$left$theta[1], 3), " & ",
round(UMPBT$left$theta[2], 3), " with respective probabilities ",
round(UMPBT$left$mix.prob[1], 3), " & ", 1 - round(UMPBT$left$mix.prob[1], 3),
sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}
cumsum_n = 0
reached.decision.r = reached.decision.l = reached.decision = F
rejectH0 = NA
LR.r = LR.l = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum_n = cumsum_n + sum(obs[(batch.size[n]+1):batch.size[n+1]])
if(!reached.decision.r){
LR.r[n] =
UMPBT$right$mix.prob[1]*(((1 - UMPBT$right$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[1])))^cumsum_n +
(1 - UMPBT$right$mix.prob[2])*(((1 - UMPBT$right$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$right$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$right$theta[2])))^cumsum_n
AcceptedH0_n.r = LR.r[n]<=RejectH1.threshold
RejectedH0_n.r = LR.r[n]>=RejectH0.threshold
reached.decision.r = AcceptedH0_n.r||RejectedH0_n.r
}
if(!reached.decision.l){
LR.l[n] =
UMPBT$left$mix.prob[1]*(((1 - UMPBT$left$theta[1])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[1]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[1])))^cumsum_n +
(1 - UMPBT$left$mix.prob[2])*(((1 - UMPBT$left$theta[2])/(1 - theta0))^batch.size[n+1])*
((UMPBT$left$theta[2]*(1 - theta0))/(theta0*(1 - UMPBT$left$theta[2])))^cumsum_n
AcceptedH0_n.l = LR.l[n]<=RejectH1.threshold
RejectedH0_n.l = LR.l[n]>=RejectH0.threshold
reached.decision.l = AcceptedH0_n.l||RejectedH0_n.l
}
if(AcceptedH0_n.r&&AcceptedH0_n.l){
rejectH0 = F
decision = 'reject.alt'
n0 = batch.size[n+1]
reached.decision = T
}else if(RejectedH0_n.r||RejectedH0_n.l){
rejectH0 = T
decision = 'reject.null'
n0 = batch.size[n+1]
reached.decision = T
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n0 = N.max
if(AcceptedH0_n.l&&(!reached.decision.r)){
rejectH0 = LR.r[nAnalyses]>=termination.threshold
}else if(AcceptedH0_n.r&&(!reached.decision.l)){
rejectH0 = LR.l[nAnalyses]>=termination.threshold
}else if((!reached.decision.r)&&(!reached.decision.l)){
rejectH0 = max(LR.r[nAnalyses], LR.l[nAnalyses])>=termination.threshold
}else{rejectH0 = F}
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n0 = batch.size[nAnalyses + 1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.r = max(which(!is.na(LR.r)))
nAnalyses.l = max(which(!is.na(LR.l)))
if(plot.it==0){
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'UMPBT' = UMPBT))
}else if(plot.it!=0){
testname = paste('Two-sided one-sample proportion test ( \u03B1 =', Type1.target,', ',
'\u03B2 =',Type2.target,')')
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n = ', n0, ')', sep = '')
}
if((!reached.decision.l)&&(nAnalyses.l==nAnalyses.max)){
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Wtd. likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided one-sample proportion test at ', Type1.target/2),
y = 'Wtd. likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.l){
ylow.l = min(LR.l, na.rm = T)
yup.l = max(LR.l, na.rm = T)
}else if(RejectedH0_n.l){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else if((!reached.decision.l)&&(nAnalyses.l<nAnalyses.max)){
if(LR[nAnalyses.l]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else{
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
}
}
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Wtd. likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided one-sample proportion test at ', Type1.target/2),
y = 'Wtd. likelihood ratio',
x = 'Steps in sequential analyses')
}
if((!reached.decision.r)&&(nAnalyses.r==nAnalyses.max)){
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Wtd. likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided one-sample proportion test at ', Type1.target/2),
y = 'Wtd. likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.r){
ylow.r = min(LR.r, na.rm = T)
yup.r = max(LR.r, na.rm = T)
}else if(RejectedH0_n.r){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else if((!reached.decision.r)&&(nAnalyses.r<nAnalyses.max)){
if(LR[nAnalyses.r]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else{
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
}
}
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Wtd. likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided one-sample proportion test at ', Type1.target/2),
y = 'Wtd. likelihood ratio',
x = 'Steps in sequential analyses')
}
seqcompare = annotate_figure(ggarrange(seqcompare.l, seqcompare.r,
nrow = 1, ncol = 2,
legend = 'bottom', common.legend = T),
top = text_grob(paste(testname, '\n', plot.subtitle, '\n'),
size = 25, hjust = .5))
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'UMPBT' = UMPBT,
'ggplot.object' = seqcompare))
}
}
}
implement.MSPRT_oneZ = function(obs, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N.max, sigma = 1, batch.size,
verbose = T, plot.it = 2){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma = design.MSPRT.object$sigma
termination.threshold = design.MSPRT.object$termination.threshold
theta.UMPBT = design.MSPRT.object$theta.UMPBT
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses.max = length(batch.size)
if(missing(theta0)) theta0 = 0
theta.UMPBT = UMPBT.alt(test.type = 'oneZ', side = side, theta0 = theta0,
N = N.max, Type1 = Type1.target, sigma = sigma)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}
cumsum_n = 0
reached.decision = F
rejectH0 = NA
LR = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum_n = cumsum_n + sum(obs[(batch.size[n]+1):batch.size[n+1]])
LR[n] =
exp((cumsum_n*(theta.UMPBT - theta0) -
((batch.size[n+1]*((theta.UMPBT^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0_n = LR[n]<=RejectH1.threshold
RejectedH0_n = LR[n]>=RejectH0.threshold
reached.decision = AcceptedH0_n||RejectedH0_n
if(reached.decision){
n0 = batch.size[n+1]
rejectH0 = RejectedH0_n
if(rejectH0){
decision = 'reject.null'
}else{decision = 'reject.alt'}
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n0 = N.max
rejectH0 = LR[nAnalyses]>=termination.threshold
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n0 = batch.size[nAnalyses+1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.test = max(which(!is.na(LR)))
if(plot.it==0){
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT))
}else if(plot.it!=0){
if(side=='right'){
testname = bquote('Right-sided one-sample z test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}else{
testname = bquote('Left-sided one-sample z test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}
if((!reached.decision)&&(nAnalyses.test==nAnalyses.max)){
ylow = RejectH1.threshold
yup = RejectH0.threshold
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
ylow = min(LR, na.rm = T)
yup = max(LR, na.rm = T)
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n = ', n0, ')', sep = '')
if(LR[nAnalyses.test]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else{
ylow = RejectH1.threshold
yup = RejectH0.threshold
}
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT,
'ggplot.object' = seqcompare))
}
}else{
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma = design.MSPRT.object$sigma
termination.threshold = design.MSPRT.object$termination.threshold
theta.UMPBT = design.MSPRT.object$theta.UMPBT
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
nAnalyses.max = length(batch.size)
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(missing(theta0)) theta0 = 0
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'oneZ', side = 'right',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma),
'left' = UMPBT.alt(test.type = 'oneZ', side = 'left',
theta0 = theta0, N = N.max,
Type1 = Type1.target/2, sigma = sigma))
if(verbose){
if(any(batch.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a one-sample z test:")
print("==========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("Known standard deviation: ", sigma, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}
cumsum_n = 0
reached.decision.r = reached.decision.l = reached.decision = F
rejectH0 = NA
LR.r = LR.l = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum_n = cumsum_n + sum(obs[(batch.size[n]+1):batch.size[n+1]])
if(!reached.decision.r){
LR.r[n] =
exp((cumsum_n*(theta.UMPBT$right - theta0) -
((batch.size[n+1]*((theta.UMPBT$right^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0_n.r = LR.r[n]<=RejectH1.threshold
RejectedH0_n.r = LR.r[n]>=RejectH0.threshold
reached.decision.r = AcceptedH0_n.r||RejectedH0_n.r
}
if(!reached.decision.l){
LR.l[n] =
exp((cumsum_n*(theta.UMPBT$left - theta0) -
((batch.size[n+1]*((theta.UMPBT$left^2) - (theta0^2)))/2))/(sigma^2))
AcceptedH0_n.l = LR.l[n]<=RejectH1.threshold
RejectedH0_n.l = LR.l[n]>=RejectH0.threshold
reached.decision.l = AcceptedH0_n.l||RejectedH0_n.l
}
if(AcceptedH0_n.r&&AcceptedH0_n.l){
rejectH0 = F
decision = 'reject.alt'
n0 = batch.size[n+1]
reached.decision = T
}else if(RejectedH0_n.r||RejectedH0_n.l){
rejectH0 = T
decision = 'reject.null'
n0 = batch.size[n+1]
reached.decision = T
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n0 = N.max
if(AcceptedH0_n.l&&(!reached.decision.r)){
rejectH0 = LR.r[nAnalyses]>=termination.threshold
}else if(AcceptedH0_n.r&&(!reached.decision.l)){
rejectH0 = LR.l[nAnalyses]>=termination.threshold
}else if((!reached.decision.r)&&(!reached.decision.l)){
rejectH0 = max(LR.r[nAnalyses], LR.l[nAnalyses])>=termination.threshold
}else{rejectH0 = F}
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n0 = batch.size[nAnalyses + 1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.r = max(which(!is.na(LR.r)))
nAnalyses.l = max(which(!is.na(LR.l)))
if(plot.it==0){
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = theta.UMPBT))
}else if(plot.it!=0){
testname = paste('Two-sided one-sample z test ( \u03B1 =', Type1.target,', ',
'\u03B2 =',Type2.target,')')
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n = ', n0, ')', sep = '')
}
if((!reached.decision.l)&&(nAnalyses.l==nAnalyses.max)){
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided one-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.l){
ylow.l = min(LR.l, na.rm = T)
yup.l = max(LR.l, na.rm = T)
}else if(RejectedH0_n.l){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else if((!reached.decision.l)&&(nAnalyses.l<nAnalyses.max)){
if(LR[nAnalyses.l]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else{
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
}
}
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided one-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}
if((!reached.decision.r)&&(nAnalyses.r==nAnalyses.max)){
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided one-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.r){
ylow.r = min(LR.r, na.rm = T)
yup.r = max(LR.r, na.rm = T)
}else if(RejectedH0_n.r){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else if((!reached.decision.r)&&(nAnalyses.r<nAnalyses.max)){
if(LR[nAnalyses.r]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else{
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
}
}
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided one-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}
seqcompare = annotate_figure(ggarrange(seqcompare.l, seqcompare.r,
nrow = 1, ncol = 2,
legend = 'bottom', common.legend = T),
top = text_grob(paste(testname, '\n', plot.subtitle, '\n'),
size = 25, hjust = .5))
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = theta.UMPBT,
'ggplot.object' = seqcompare))
}
}
}
implement.MSPRT_oneT = function(obs, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N.max, batch.size,
verbose = T, plot.it = 2){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", design.MSPRT.object$termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
nAnalyses.max = length(batch.size)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(missing(theta0)) theta0 = 0
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold,
sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}
signed_t.alpha = (2*(side=='right')-1)*qt(Type1.target, df = N.max -1,
lower.tail = F)
cumSS_n = cumsum_n = 0
reached.decision = F
rejectH0 = NA
theta.UMPBT = LR = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum_n = cumsum_n + sum(obs[(batch.size[n]+1):batch.size[n+1]])
cumSS_n = cumSS_n + sum(obs[(batch.size[n]+1):batch.size[n+1]]^2)
xbar_n = cumsum_n/batch.size[n+1]
divisor.s_n.sq = cumSS_n - (cumsum_n^2)/batch.size[n+1]
theta.UMPBT[n] = theta0 + signed_t.alpha*
sqrt(divisor.s_n.sq/(N.max*(batch.size[n+1]-1)))
LR[n] =
((1 + (batch.size[n+1]*((xbar_n - theta0)^2))/divisor.s_n.sq)/
(1 + (batch.size[n+1]*((xbar_n - theta.UMPBT[n])^2))/
divisor.s_n.sq))^(batch.size[n+1]/2)
AcceptedH0_n = LR[n]<=RejectH1.threshold
RejectedH0_n = LR[n]>=RejectH0.threshold
reached.decision = AcceptedH0_n||RejectedH0_n
if(reached.decision){
n0 = batch.size[n+1]
rejectH0 = RejectedH0_n
if(rejectH0){
decision = 'reject.null'
}else{decision = 'reject.alt'}
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n0 = N.max
rejectH0 = LR[nAnalyses]>=termination.threshold
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n0 = batch.size[nAnalyses+1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.test = max(which(!is.na(LR)))
if(plot.it==0){
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT[1:nAnalyses.test]))
}else if(plot.it!=0){
if(side=='right'){
testname = bquote('Right-sided one-sample t test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}else{
testname = bquote('Left-sided one-sample t test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}
if((!reached.decision)&&(nAnalyses.test==nAnalyses.max)){
ylow = RejectH1.threshold
yup = RejectH0.threshold
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}else{
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
ylow = min(LR, na.rm = T)
yup = max(LR, na.rm = T)
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n = ', n0, ')', sep = '')
if(LR[nAnalyses.test]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else{
ylow = RejectH1.threshold
yup = RejectH0.threshold
}
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT[1:nAnalyses.test],
'ggplot.object' = seqcompare))
}
}else{
if(!missing(design.MSPRT.object)){
batch.size = design.MSPRT.object$batch.size
N.max = design.MSPRT.object$N.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
nAnalyses.max = length(batch.size)
if(missing(theta0)) theta0 = 0
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch.size[1]>2)||any(batch.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a one-sample t test:")
print("=========================================================================")
}
print(paste("Maximum available sample size: ", N.max, sep = ""))
print(paste('Batch sizes: ', paste(batch.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max, sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
}
batch.size = c(0, cumsum(batch.size))
nAnalyses = max(which(batch.size<=length(obs))) - 1
}
t.alpha = qt(Type1.target/2, df = N.max -1, lower.tail = F)
cumSS_n = cumsum_n = 0
reached.decision.r = reached.decision.l = reached.decision = F
rejectH0 = NA
theta.UMPBT.r = theta.UMPBT.l = LR.r = LR.l = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum_n = cumsum_n + sum(obs[(batch.size[n]+1):batch.size[n+1]])
cumSS_n = cumSS_n + sum(obs[(batch.size[n]+1):batch.size[n+1]]^2)
if(!reached.decision.r){
xbar_n.r = cumsum_n/batch.size[n+1]
divisor.s_n.sq.r = cumSS_n - ((cumsum_n)^2)/batch.size[n+1]
theta.UMPBT.r[n] = theta0 + t.alpha*
sqrt(divisor.s_n.sq.r/(N.max*(batch.size[n+1]-1)))
LR.r[n] =
((1 + (batch.size[n+1]*((xbar_n.r - theta0)^2))/divisor.s_n.sq.r)/
(1 + (batch.size[n+1]*((xbar_n.r - theta.UMPBT.r[n])^2))/
divisor.s_n.sq.r))^(batch.size[n+1]/2)
AcceptedH0_n.r = LR.r[n]<=RejectH1.threshold
RejectedH0_n.r = LR.r[n]>=RejectH0.threshold
reached.decision.r = AcceptedH0_n.r||RejectedH0_n.r
}
if(!reached.decision.l){
xbar_n.l = cumsum_n/batch.size[n+1]
divisor.s_n.sq.l = cumSS_n - ((cumsum_n)^2)/batch.size[n+1]
theta.UMPBT.l[n] = theta0 - t.alpha*
sqrt(divisor.s_n.sq.l/(N.max*(batch.size[n+1]-1)))
LR.l[n] =
((1 + (batch.size[n+1]*((xbar_n.l - theta0)^2))/divisor.s_n.sq.l)/
(1 + (batch.size[n+1]*((xbar_n.l - theta.UMPBT.l[n])^2))/
divisor.s_n.sq.l))^(batch.size[n+1]/2)
AcceptedH0_n.l = LR.l[n]<=RejectH1.threshold
RejectedH0_n.l = LR.l[n]>=RejectH0.threshold
reached.decision.l = AcceptedH0_n.l||RejectedH0_n.l
}
if(AcceptedH0_n.r&&AcceptedH0_n.l){
rejectH0 = F
decision = 'reject.alt'
n0 = batch.size[n+1]
reached.decision = T
}else if(RejectedH0_n.r||RejectedH0_n.l){
rejectH0 = T
decision = 'reject.null'
n0 = batch.size[n+1]
reached.decision = T
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n0 = N.max
if(AcceptedH0_n.l&&(!reached.decision.r)){
rejectH0 = LR.r[nAnalyses]>=termination.threshold
}else if(AcceptedH0_n.r&&(!reached.decision.l)){
rejectH0 = LR.l[nAnalyses]>=termination.threshold
}else if((!reached.decision.r)&&(!reached.decision.l)){
rejectH0 = max(LR.r[nAnalyses], LR.l[nAnalyses])>=termination.threshold
}else{rejectH0 = F}
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n0 = batch.size[nAnalyses + 1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: ", n0, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.r = max(which(!is.na(LR.r)))
nAnalyses.l = max(which(!is.na(LR.l)))
if(plot.it==0){
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = list('right' = theta.UMPBT.r[1:nAnalyses.r],
'left' = theta.UMPBT.l[1:nAnalyses.l])))
}else if(plot.it!=0){
testname = paste('Two-sided one-sample t test ( \u03B1 =', Type1.target,', ',
'\u03B2 =',Type2.target,')')
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n = ', n0, ')', sep = '')
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n = ', n0, ')', sep = '')
}
if((!reached.decision.l)&&(nAnalyses.l==nAnalyses.max)){
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided one-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.l){
ylow.l = min(LR.l, na.rm = T)
yup.l = max(LR.l, na.rm = T)
}else if(RejectedH0_n.l){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else if((!reached.decision.l)&&(nAnalyses.l<nAnalyses.max)){
if(LR[nAnalyses.l]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else{
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
}
}
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided one-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}
if((!reached.decision.r)&&(nAnalyses.r==nAnalyses.max)){
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided one-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.r){
ylow.r = min(LR.r, na.rm = T)
yup.r = max(LR.r, na.rm = T)
}else if(RejectedH0_n.r){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else if((!reached.decision.r)&&(nAnalyses.r<nAnalyses.max)){
if(LR[nAnalyses.r]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else{
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
}
}
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided one-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}
seqcompare = annotate_figure(ggarrange(seqcompare.l, seqcompare.r,
nrow = 1, ncol = 2,
legend = 'bottom', common.legend = T),
top = text_grob(paste(testname, '\n', plot.subtitle, '\n'),
size = 25, hjust = .5))
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n' = n0, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = list('right' = theta.UMPBT.r[1:nAnalyses.r],
'left' = theta.UMPBT.l[1:nAnalyses.l]),
'ggplot.object' = seqcompare))
}
}
}
implement.MSPRT_twoZ = function(obs1, obs2, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N1.max, N2.max,
sigma1 = 1, sigma2 = 1,
batch1.size, batch2.size,
verbose = T, plot.it = 2){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma1 = design.MSPRT.object$sigma1
sigma2 = design.MSPRT.object$sigma2
termination.threshold = design.MSPRT.object$termination.threshold
theta.UMPBT = design.MSPRT.object$theta.UMPBT
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}else{
if(!missing(obs)) print("'obs' is ignored. Not required in two-sample tests.")
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
nAnalyses.max = length(batch1.size)
if(missing(theta0)) theta0 = 0
theta.UMPBT = UMPBT.alt(test.type = 'twoZ', side = side, theta0 = theta0,
N1 = N1.max, N2 = N2.max, Type1 = Type1.target,
sigma1 = sigma1, sigma2 = sigma2)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print(paste("The UMPBT alternative is: ", round(theta.UMPBT, 3)))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}
cumsum1_n = cumsum2_n = 0
reached.decision = F
rejectH0 = NA
LR = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum1_n = cumsum1_n + sum(obs1[(batch1.size[n]+1):batch1.size[n+1]])
cumsum2_n = cumsum2_n + sum(obs2[(batch2.size[n]+1):batch2.size[n+1]])
LR[n] =
exp(-(((theta.UMPBT^2) - (theta0^2)) - 2*(theta.UMPBT - theta0)*
(cumsum1_n/batch1.size[n+1] - cumsum2_n/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0_n = LR[n]<=RejectH1.threshold
RejectedH0_n = LR[n]>=RejectH0.threshold
reached.decision = AcceptedH0_n||RejectedH0_n
if(reached.decision){
n1 = batch1.size[n+1]
n2 = batch2.size[n+1]
rejectH0 = RejectedH0_n
if(rejectH0){
decision = 'reject.null'
}else{decision = 'reject.alt'}
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n1 = N1.max
n2 = N2.max
rejectH0 = LR[nAnalyses]>=termination.threshold
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n1 = batch1.size[nAnalyses+1]
n2 = batch2.size[nAnalyses+1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.test = max(which(!is.na(LR)))
if(plot.it==0){
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT))
}else if(plot.it!=0){
if(side=='right'){
testname = bquote('Right-sided two-sample z test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}else{
testname = bquote('Left-sided two-sample z test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}
if((!reached.decision)&&(nAnalyses.test==nAnalyses.max)){
ylow = RejectH1.threshold
yup = RejectH0.threshold
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
ylow = min(LR, na.rm = T)
yup = max(LR, na.rm = T)
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
if(LR[nAnalyses.test]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else{
ylow = RejectH1.threshold
yup = RejectH0.threshold
}
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT,
'ggplot.object' = seqcompare))
}
}else{
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
sigma1 = design.MSPRT.object$sigma1
sigma2 = design.MSPRT.object$sigma2
termination.threshold = design.MSPRT.object$termination.threshold
theta.UMPBT = design.MSPRT.object$theta.UMPBT
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}else{
if(!missing(obs)) print("'obs' is ignored. Not required in two-sample tests.")
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
nAnalyses.max = length(batch1.size)
if(missing(theta0)) theta0 = 0
theta.UMPBT = list('right' = UMPBT.alt(test.type = 'twoZ', side = 'right',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2),
'left' = UMPBT.alt(test.type = 'twoZ', side = 'left',
theta0 = theta0, N1 = N1.max, N2 = N2.max,
Type1 = Type1.target/2,
sigma1 = sigma1, sigma2 = sigma2))
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if(any(batch1.size>1)||any(batch2.size>1)){
cat('\n')
print("==========================================================================")
print("Implementing the group sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}else{
cat('\n')
print("==========================================================================")
print("Implementing the sequential MSPRT for a two-sample z test:")
print("==========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma1, sep = ""))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste(" Known standard deviation: ", sigma2, sep = ""))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
print("The UMPBT alternative:")
print(paste(' On the right: ', round(theta.UMPBT$right, 3), sep = ""))
print(paste(' On the left: ', round(theta.UMPBT$left, 3), sep = ""))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}
cumsum1_n = cumsum2_n = 0
reached.decision.r = reached.decision.l = reached.decision = F
rejectH0 = NA
LR.r = LR.l = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum1_n = cumsum1_n + sum(obs1[(batch1.size[n]+1):batch1.size[n+1]])
cumsum2_n = cumsum2_n + sum(obs2[(batch2.size[n]+1):batch2.size[n+1]])
if(!reached.decision.r){
LR.r[n] =
exp(-(((theta.UMPBT$right^2) - (theta0^2)) - 2*(theta.UMPBT$right - theta0)*
(cumsum1_n/batch1.size[n+1] - cumsum2_n/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0_n.r = LR.r[n]<=RejectH1.threshold
RejectedH0_n.r = LR.r[n]>=RejectH0.threshold
reached.decision.r = AcceptedH0_n.r||RejectedH0_n.r
}
if(!reached.decision.l){
LR.l[n] =
exp(-(((theta.UMPBT$left^2) - (theta0^2)) - 2*(theta.UMPBT$left - theta0)*
(cumsum1_n/batch1.size[n+1] - cumsum2_n/batch2.size[n+1]))/
(2*((sigma1^2)/batch1.size[n+1] + (sigma2^2)/batch2.size[n+1])))
AcceptedH0_n.l = LR.l[n]<=RejectH1.threshold
RejectedH0_n.l = LR.l[n]>=RejectH0.threshold
reached.decision.l = AcceptedH0_n.l||RejectedH0_n.l
}
if(AcceptedH0_n.r&&AcceptedH0_n.l){
rejectH0 = F
decision = 'reject.alt'
n1 = batch1.size[n+1]
n2 = batch2.size[n+1]
reached.decision = T
}else if(RejectedH0_n.r||RejectedH0_n.l){
rejectH0 = T
decision = 'reject.null'
n1 = batch1.size[n+1]
n2 = batch2.size[n+1]
reached.decision = T
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n1 = N1.max
n2 = N2.max
if(AcceptedH0_n.l&&(!reached.decision.r)){
rejectH0 = LR.r[nAnalyses]>=termination.threshold
}else if(AcceptedH0_n.r&&(!reached.decision.l)){
rejectH0 = LR.l[nAnalyses]>=termination.threshold
}else if((!reached.decision.r)&&(!reached.decision.l)){
rejectH0 = max(LR.r[nAnalyses], LR.l[nAnalyses])>=termination.threshold
}else{rejectH0 = F}
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n1 = batch1.size[nAnalyses+1]
n2 = batch2.size[nAnalyses+1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.r = max(which(!is.na(LR.r)))
nAnalyses.l = max(which(!is.na(LR.l)))
if(plot.it==0){
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = theta.UMPBT))
}else if(plot.it!=0){
testname = paste('Two-sided two-sample z test ( \u03B1 =', Type1.target,', ',
'\u03B2 =',Type2.target,')')
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}
if((!reached.decision.l)&&(nAnalyses.l==nAnalyses.max)){
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided two-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.l){
ylow.l = min(LR.l, na.rm = T)
yup.l = max(LR.l, na.rm = T)
}else if(RejectedH0_n.l){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else if((!reached.decision.l)&&(nAnalyses.l<nAnalyses.max)){
if(LR[nAnalyses.l]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else{
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
}
}
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided two-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}
if((!reached.decision.r)&&(nAnalyses.r==nAnalyses.max)){
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided two-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.r){
ylow.r = min(LR.r, na.rm = T)
yup.r = max(LR.r, na.rm = T)
}else if(RejectedH0_n.r){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else if((!reached.decision.r)&&(nAnalyses.r<nAnalyses.max)){
if(LR[nAnalyses.r]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else{
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
}
}
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Likelihood ratio'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided two-sample z test at ', Type1.target/2),
y = 'Likelihood ratio',
x = 'Steps in sequential analyses')
}
seqcompare = annotate_figure(ggarrange(seqcompare.l, seqcompare.r,
nrow = 1, ncol = 2,
legend = 'bottom', common.legend = T),
top = text_grob(paste(testname, '\n', plot.subtitle, '\n'),
size = 25, hjust = .5))
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = theta.UMPBT,
'ggplot.object' = seqcompare))
}
}
}
implement.MSPRT_twoT = function(obs1, obs2, design.MSPRT.object,
termination.threshold,
side = 'right', theta0 = 0,
Type1.target =.005, Type2.target = .2,
N1.max, N2.max,
batch1.size, batch2.size,
verbose = T, plot.it = 2){
if(!missing(design.MSPRT.object)) side = design.MSPRT.object$side
if(side!='both'){
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}else{
if(!missing(obs)) print("'obs' is ignored. Not required in two-sample tests.")
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
nAnalyses.max = length(batch1.size)
RejectH1.threshold = Type2.target/(1 - Type1.target)
RejectH0.threshold = (1 - Type2.target)/Type1.target
if(missing(theta0)) theta0 = 0
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}
signed_t.alpha = (2*(side=='right')-1)*
qt(Type1.target, df = N1.max + N2.max -2, lower.tail = F)
cumsum1_n = cumsum2_n = cumSS1_n = cumSS2_n = 0
reached.decision = F
rejectH0 = NA
LR = theta.UMPBT = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum1_n = cumsum1_n + sum(obs1[(batch1.size[n]+1):batch1.size[n+1]])
cumsum2_n = cumsum2_n + sum(obs2[(batch2.size[n]+1):batch2.size[n+1]])
cumSS1_n = cumSS1_n + sum(obs1[(batch1.size[n]+1):batch1.size[n+1]]^2)
cumSS2_n = cumSS2_n + sum(obs2[(batch2.size[n]+1):batch2.size[n+1]]^2)
xbar.diff_n = cumsum1_n/batch1.size[n+1] - cumsum2_n/batch2.size[n+1]
divisor.pooled.sd_n.sq =
cumSS1_n - ((cumsum1_n)^2)/batch1.size[n+1] +
cumSS2_n - ((cumsum2_n)^2)/batch2.size[n+1]
theta.UMPBT[n] = theta0 + signed_t.alpha*
sqrt((divisor.pooled.sd_n.sq/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))
LR[n] =
((1 + ((xbar.diff_n - theta0)^2)/
(divisor.pooled.sd_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff_n - theta.UMPBT[n])^2)/
(divisor.pooled.sd_n.sq*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0_n = LR[n]<=RejectH1.threshold
RejectedH0_n = LR[n]>=RejectH0.threshold
reached.decision = AcceptedH0_n||RejectedH0_n
if(reached.decision){
n1 = batch1.size[n+1]
n2 = batch2.size[n+1]
rejectH0 = RejectedH0_n
if(rejectH0){
decision = 'reject.null'
}else{decision = 'reject.alt'}
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n1 = N1.max
n2 = N2.max
rejectH0 = LR[nAnalyses]>=termination.threshold
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n1 = batch1.size[nAnalyses+1]
n2 = batch2.size[nAnalyses+1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.test = max(which(!is.na(LR)))
if(plot.it==0){
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT[1:nAnalyses.test]))
}else if(plot.it!=0){
if(side=='right'){
testname = bquote('Right-sided two-sample t test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}else{
testname = bquote('Left-sided two-sample t test ('~
alpha~'='~.(Type1.target)~', '~
beta~'='~.(Type2.target)~')')
}
if((!reached.decision)&&(nAnalyses.test==nAnalyses.max)){
ylow = RejectH1.threshold
yup = RejectH0.threshold
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}else{
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
ylow = min(LR, na.rm = T)
yup = max(LR, na.rm = T)
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
if(LR[nAnalyses.test]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow = RejectH1.threshold
yup = max(LR, na.rm = T)
}else{
ylow = RejectH1.threshold
yup = RejectH0.threshold
}
}
df = rbind.data.frame(data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.test,
'yval' = LR[1:nAnalyses.test],
'type' = 'LR'))
df$type = factor(as.character(df$type),
levels = c('A', 'R', 'LR'))
seqcompare = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.test)) +
ylim(c(ylow, yup)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = testname, subtitle = plot.subtitle,
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = LR[1:nAnalyses.test], 'theta.UMPBT' = theta.UMPBT[1:nAnalyses.test],
'ggplot.object' = seqcompare))
}
}else{
if(!missing(design.MSPRT.object)){
batch1.size = design.MSPRT.object$batch1.size
batch2.size = design.MSPRT.object$batch2.size
N1.max = design.MSPRT.object$N1.max
N2.max = design.MSPRT.object$N2.max
Type1.target = design.MSPRT.object$Type1.target
Type2.target = design.MSPRT.object$Type2.target
theta0 = design.MSPRT.object$theta0
termination.threshold = design.MSPRT.object$termination.threshold
nAnalyses.max = design.MSPRT.object$nAnalyses
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}else{
if(!missing(obs)) print("'obs' is ignored. Not required in two-sample tests.")
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
nAnalyses.max = length(batch1.size)
if(missing(theta0)) theta0 = 0
RejectH1.threshold = Type2.target/(1 - Type1.target/2)
RejectH0.threshold = (1 - Type2.target)/(Type1.target/2)
if(verbose){
if((batch1.size[1]>2)||any(batch1.size[-1]>1)||
(batch2.size[1]>2)||any(batch2.size[-1]>1)){
cat('\n')
print("=========================================================================")
print("Implementing the group sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}else{
cat('\n')
print("=========================================================================")
print("Implementing the sequential MSPRT for a two-sample t test:")
print("=========================================================================")
}
print("Group 1:")
print(paste(" Maximum available sample sizes: ", N1.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch1.size, collapse = ', '), sep = ''))
print("Group 2:")
print(paste(" Maximum available sample sizes: ", N2.max, sep = ""))
print(paste(' Batch sizes: ', paste(batch2.size, collapse = ', '), sep = ''))
print(paste("Maximum number of sequential analyses: ", nAnalyses.max,
sep = ""))
print(paste("Targeted Type I error probability: ", Type1.target, sep = ""))
print(paste("Targeted Type II error probability: ", Type2.target, sep = ""))
print(paste("Hypothesized value under H0: ", theta0, sep = ""))
print(paste("Direction of the H1: ", side, sep = ""))
print(paste("H1 rejection threshold: ", round(RejectH1.threshold, 3), sep = ''))
print(paste("H0 rejection threshold: ", round(RejectH0.threshold, 3), sep = ''))
print(paste("Termination threshold: ", termination.threshold, sep = ""))
print("-------------------------------------------------------------------------")
}
batch1.size = c(0, cumsum(batch1.size))
batch2.size = c(0, cumsum(batch2.size))
nAnalyses = min(max(which(batch1.size<=length(obs1))),
max(which(batch2.size<=length(obs2)))) - 1
}
t.alpha = qt(Type1.target/2, df = N1.max + N2.max -2, lower.tail = F)
cumsum1_n = cumsum2_n = cumSS1_n = cumSS2_n = 0
reached.decision.r = reached.decision.l = reached.decision = F
rejectH0 = NA
LR.r = LR.l = theta.UMPBT.r = theta.UMPBT.l = rep(NA, nAnalyses)
for(n in 1:nAnalyses){
if(!reached.decision){
cumsum1_n = cumsum1_n + sum(obs1[(batch1.size[n]+1):batch1.size[n+1]])
cumsum2_n = cumsum2_n + sum(obs2[(batch2.size[n]+1):batch2.size[n+1]])
cumSS1_n = cumSS1_n + sum(obs1[(batch1.size[n]+1):batch1.size[n+1]]^2)
cumSS2_n = cumSS2_n + sum(obs2[(batch2.size[n]+1):batch2.size[n+1]]^2)
if(!reached.decision.r){
xbar.diff_n.r = cumsum1_n/batch1.size[n+1] - cumsum2_n/batch2.size[n+1]
divisor.pooled.sd_n.sq.r = cumSS1_n - ((cumsum1_n)^2)/batch1.size[n+1] +
cumSS2_n - ((cumsum2_n)^2)/batch2.size[n+1]
theta.UMPBT.r[n] = theta0 + t.alpha*
sqrt((divisor.pooled.sd_n.sq.r/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))
LR.r[n] =
((1 + ((xbar.diff_n.r - theta0)^2)/
(divisor.pooled.sd_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff_n.r - theta.UMPBT.r[n])^2)/
(divisor.pooled.sd_n.sq.r*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0_n.r = LR.r[n]<=RejectH1.threshold
RejectedH0_n.r = LR.r[n]>=RejectH0.threshold
reached.decision.r = AcceptedH0_n.r||RejectedH0_n.r
}
if(!reached.decision.l){
xbar.diff_n.l = cumsum1_n/batch1.size[n+1] - cumsum2_n/batch2.size[n+1]
divisor.pooled.sd_n.sq.l = cumSS1_n - ((cumsum1_n)^2)/batch1.size[n+1] +
cumSS2_n - ((cumsum2_n)^2)/batch2.size[n+1]
theta.UMPBT.l[n] = theta0 - t.alpha*
sqrt((divisor.pooled.sd_n.sq.l/(batch1.size[n+1] + batch2.size[n+1] -2))*
(1/N1.max + 1/N2.max))
LR.l[n] =
((1 + ((xbar.diff_n.l - theta0)^2)/
(divisor.pooled.sd_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1])))/
(1 + ((xbar.diff_n.l - theta.UMPBT.l[n])^2)/
(divisor.pooled.sd_n.sq.l*(1/batch1.size[n+1] + 1/batch2.size[n+1]))))^((batch1.size[n+1] + batch2.size[n+1])/2)
AcceptedH0_n.l = LR.l[n]<=RejectH1.threshold
RejectedH0_n.l = LR.l[n]>=RejectH0.threshold
reached.decision.l = AcceptedH0_n.l||RejectedH0_n.l
}
if(AcceptedH0_n.r&&AcceptedH0_n.l){
rejectH0 = F
decision = 'reject.alt'
n1 = batch1.size[n+1]
n2 = batch2.size[n+1]
reached.decision = T
}else if(RejectedH0_n.r||RejectedH0_n.l){
rejectH0 = T
decision = 'reject.null'
n1 = batch1.size[n+1]
n2 = batch2.size[n+1]
reached.decision = T
}
}
}
if(!reached.decision){
if(nAnalyses==nAnalyses.max){
n1 = N1.max
n2 = N2.max
if(AcceptedH0_n.l&&(!reached.decision.r)){
rejectH0 = LR.r[nAnalyses]>=termination.threshold
}else if(AcceptedH0_n.r&&(!reached.decision.l)){
rejectH0 = LR.l[nAnalyses]>=termination.threshold
}else if((!reached.decision.r)&&(!reached.decision.l)){
rejectH0 = max(LR.r[nAnalyses], LR.l[nAnalyses])>=termination.threshold
}else{rejectH0 = F}
if(rejectH0){
decision = 'reject.null'
}else if(!rejectH0){decision = 'reject.alt'}
}else{
n1 = batch1.size[nAnalyses+1]
n2 = batch2.size[nAnalyses+1]
decision = 'continue'
}
}
if(verbose==T){
if(decision=='continue'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Continue sampling')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.null'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the null hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}else if(decision=='reject.alt'){
cat('\n')
print("=========================================================================")
print("Sequential comparison summary:")
print("=========================================================================")
print('Decision: Reject the alternative hypothesis')
print(paste("Sample size used: Group 1 - ", n1,
", Group 2 - ", n2, sep = ''))
print("=========================================================================")
cat('\n')
}
}
nAnalyses.r = max(which(!is.na(LR.r)))
nAnalyses.l = max(which(!is.na(LR.l)))
if(plot.it==0){
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = list('right' = theta.UMPBT.r[1:nAnalyses.r],
'left' = theta.UMPBT.l[1:nAnalyses.l])))
}else if(plot.it!=0){
testname = paste('Two-sided two-sample t test ( \u03B1 =', Type1.target,', ',
'\u03B2 =',Type2.target,')')
if(decision=="reject.alt"){
plot.subtitle =
paste('Reject the alternative hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}else if(decision=="reject.null"){
plot.subtitle =
paste('Reject the null hypothesis (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}else if(decision=="continue"){
plot.subtitle =
paste('Continue sampling (n1 = ', n1,
', n2 = ', n2, ')', sep = '')
}
if((!reached.decision.l)&&(nAnalyses.l==nAnalyses.max)){
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided two-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.l){
ylow.l = min(LR.l, na.rm = T)
yup.l = max(LR.l, na.rm = T)
}else if(RejectedH0_n.l){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else if((!reached.decision.l)&&(nAnalyses.l<nAnalyses.max)){
if(LR[nAnalyses.l]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.l = RejectH1.threshold
yup.l = max(LR.l, na.rm = T)
}else{
ylow.l = RejectH1.threshold
yup.l = RejectH0.threshold
}
}
df.l = rbind.data.frame(data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.l,
'yval' = LR.l[1:nAnalyses.l],
'type' = 'LR'))
df.l$type = factor(as.character(df.l$type),
levels = c('A', 'R', 'LR'))
seqcompare.l = ggplot(data = df.l,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.l)) +
ylim(c(ylow.l, yup.l)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Left-sided two-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}
if((!reached.decision.r)&&(nAnalyses.r==nAnalyses.max)){
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'),
data.frame('xval' = nAnalyses.max,
'yval' = termination.threshold,
'type' = 'term.thresh'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR', 'term.thresh'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH1.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color="forestgreen", size = 1) +
geom_segment(aes(x = nAnalyses.max, y = RejectH0.threshold,
xend = nAnalyses.max, yend = termination.threshold),
color = "red2", size=1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor', 'Termination threshold'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue', 'term.thresh' = 'black'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1,0),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided two-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}else{
if(AcceptedH0_n.r){
ylow.r = min(LR.r, na.rm = T)
yup.r = max(LR.r, na.rm = T)
}else if(RejectedH0_n.r){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else if((!reached.decision.r)&&(nAnalyses.r<nAnalyses.max)){
if(LR[nAnalyses.r]<(RejectH1.threshold + RejectH0.threshold)/2){
ylow.r = RejectH1.threshold
yup.r = max(LR.r, na.rm = T)
}else{
ylow.r = RejectH1.threshold
yup.r = RejectH0.threshold
}
}
df.r = rbind.data.frame(data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH1.threshold,
'type' = 'A'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = RejectH0.threshold,
'type' = 'R'),
data.frame('xval' = 1:nAnalyses.r,
'yval' = LR.r[1:nAnalyses.r],
'type' = 'LR'))
df.r$type = factor(as.character(df.r$type),
levels = c('A', 'R', 'LR'))
seqcompare.r = ggplot(data = df.r,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(colour = type), size = 1) +
geom_point(aes(colour = type), size = 2) +
xlim(c(1, nAnalyses.r)) +
ylim(c(ylow.r, yup.r)) +
scale_color_manual(labels = c('Reject Alternative', 'Reject Null',
'Bayes factor'),
values = c('A' = 'forestgreen', 'R' = 'red2',
'LR' = 'dodgerblue'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(1,1,1),
shape = 16))) +
theme(plot.title = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=18),
legend.position = 'bottom') +
labs(title = paste('Right-sided two-sample t test at ', Type1.target/2),
y = 'Bayes factor',
x = 'Steps in sequential analyses')
}
seqcompare = annotate_figure(ggarrange(seqcompare.l, seqcompare.r,
nrow = 1, ncol = 2,
legend = 'bottom', common.legend = T),
top = text_grob(paste(testname, '\n', plot.subtitle, '\n'),
size = 25, hjust = .5))
if(plot.it==2) suppressWarnings(print(seqcompare))
return(list('n1' = n1, 'n2' = n2, 'decision' = decision,
'RejectH1.threshold' = RejectH1.threshold, 'RejectH0.threshold' = RejectH0.threshold,
'LR' = list('right' = LR.r[1:nAnalyses.r], 'left' = LR.l[1:nAnalyses.l]),
'theta.UMPBT' = list('right' = theta.UMPBT.r[1:nAnalyses.r],
'left' = theta.UMPBT.l[1:nAnalyses.l]),
'ggplot.object' = seqcompare))
}
}
}
implement.MSPRT = function(obs, obs1, obs2, design.MSPRT.object,
termination.threshold, test.type,
side = 'right', theta0,
Type1.target =.005, Type2.target = .2,
N.max, N1.max, N2.max,
sigma = 1, sigma1 = 1, sigma2 = 1,
batch.size, batch1.size, batch2.size,
verbose = T, plot.it = 2){
if(!missing(design.MSPRT.object)){
test.type = design.MSPRT.object$test.type
}else{
if((test.type!="oneProp") & (test.type!="oneZ") & (test.type!="oneT") &
(test.type!="twoZ") & (test.type!="twoT")){
return(print("Unknown 'test type'. Has to be one of 'oneProp', 'oneZ', 'oneT', 'twoZ' or 'twoT'."))
}
}
if(test.type=='oneProp'){
if(!missing(design.MSPRT.object)){
return(suppressWarnings(implement.MSPRT_oneProp(obs = obs, design.MSPRT.object = design.MSPRT.object,
verbose = verbose, plot.it = plot.it)))
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
if(missing(theta0)) theta0 = 0.5
return(suppressWarnings(implement.MSPRT_oneProp(obs = obs,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
verbose = verbose, plot.it = plot.it)))
}
}else if(test.type=='oneZ'){
if(!missing(design.MSPRT.object)){
return(suppressWarnings(implement.MSPRT_oneZ(obs = obs, design.MSPRT.object = design.MSPRT.object,
verbose = verbose, plot.it = plot.it)))
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = rep(1, N.max)}
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch sizes should add up to N.max")
}
}
if(missing(theta0)) theta0 = 0
return(suppressWarnings(implement.MSPRT_oneZ(obs = obs,
termination.threshold = termination.threshold,
side = side, theta0 = theta0, sigma = sigma,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
verbose = verbose, plot.it = plot.it)))
}
}else if(test.type=='oneT'){
if(!missing(design.MSPRT.object)){
return(suppressWarnings(implement.MSPRT_oneT(obs = obs, design.MSPRT.object = design.MSPRT.object,
verbose = verbose, plot.it = plot.it)))
}else{
if(!missing(obs1)) print("'obs1' is ignored. Not required in one-sample tests.")
if(!missing(obs2)) print("'obs2' is ignored. Not required in one-sample tests.")
if(!missing(batch1.size)) print("'batch1.size' is ignored. Not required in one-sample tests.")
if(!missing(batch2.size)) print("'batch2.size' is ignored. Not required in one-sample tests.")
if(!missing(N1.max)) print("'N1.max' is ignored. Not required in one-sample tests.")
if(!missing(N2.max)) print("'N2.max' is ignored. Not required in one-sample tests.")
if(missing(batch.size)){
if(missing(N.max)){
return("Either 'batch.size' or 'N.max' needs to be specified")
}else{batch.size = c(2, rep(1, N.max-2))}
}else{
if(batch.size[1]<2){
return("First batch size should be at least 2")
}else{
if(missing(N.max)){
N.max = sum(batch.size)
}else{
if(sum(batch.size)!=N.max) return("Sum of batch.size should add up to N.max")
}
}
}
if(missing(theta0)) theta0 = 0
return(suppressWarnings(implement.MSPRT_oneT(obs = obs,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N.max = N.max, batch.size = batch.size,
verbose = verbose, plot.it = plot.it)))
}
}else if(test.type=='twoZ'){
if(!missing(design.MSPRT.object)){
return(suppressWarnings(implement.MSPRT_twoZ(obs1 = obs1, obs2 = obs2,
design.MSPRT.object = design.MSPRT.object,
verbose = verbose, plot.it = plot.it)))
}else{
if(!missing(obs)) print("'obs' is ignored. Not required in two-sample tests.")
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return(print("Either 'batch1.size' or 'N1.max' needs to be specified"))
}else{batch1.size = rep(1, N1.max)}
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return(print("Sum of batch1.size should add up to N1.max"))
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return(print("Either 'batch2.size' or 'N2.max' needs to be specified"))
}else{batch2.size = rep(1, N2.max)}
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N1.max) return(print("Sum of batch2.size should add up to N2.max"))
}
}
if(missing(theta0)) theta0 = 0
return(suppressWarnings(implement.MSPRT_twoZ(obs1 = obs1, obs2 = obs2,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N1.max = N1.max, N2.max = N2.max,
sigma1 = sigma1, sigma2 = sigma2,
batch1.size = batch1.size, batch2.size = batch2.size,
verbose = verbose, plot.it = plot.it)))
}
}else if(test.type=='twoT'){
if(!missing(design.MSPRT.object)){
return(suppressWarnings(implement.MSPRT_twoT(obs1 = obs1, obs2 = obs2,
design.MSPRT.object = design.MSPRT.object,
verbose = verbose, plot.it = plot.it)))
}else{
if(!missing(obs)) print("'obs' is ignored. Not required in two-sample tests.")
if(!missing(batch.size)) print("'batch.size' is ignored. Not required in two-sample tests.")
if(!missing(N.max)) print("'N.max' is ignored. Not required in two-sample tests.")
if((!missing(batch1.size)) && (!missing(batch2.size)) &&
(length(batch1.size)!=length(batch2.size))) return("Lenghts of batch1.size and batch2.size should be same")
if(missing(batch1.size)){
if(missing(N1.max)){
return("Either 'batch1.size' or 'N1.max' needs to be specified")
}else{batch1.size = c(2, rep(1, N1.max-2))}
}else{
if(batch1.size[1]<2){
return("First batch size in Group 1 should be at least 2")
}else{
if(missing(N1.max)){
N1.max = sum(batch1.size)
}else{
if(sum(batch1.size)!=N1.max) return("Sum of batch1.size should add up to N1.max")
}
}
}
if(missing(batch2.size)){
if(missing(N2.max)){
return("Either 'batch2.size' or 'N2.max' needs to be specified")
}else{batch2.size = c(2, rep(1, N2.max-2))}
}else{
if(batch2.size[1]<2){
return("First batch size in Group 2 should be at least 2")
}else{
if(missing(N2.max)){
N2.max = sum(batch2.size)
}else{
if(sum(batch2.size)!=N2.max) return("Sum of batch2.size should add up to N2.max")
}
}
}
if(missing(theta0)) theta0 = 0
return(suppressWarnings(implement.MSPRT_twoT(obs1 = obs1, obs2 = obs2,
termination.threshold = termination.threshold,
side = side, theta0 = theta0,
Type1.target = Type1.target,
Type2.target = Type2.target,
N1.max = N1.max, N2.max = N2.max,
batch1.size = batch1.size, batch2.size = batch2.size,
verbose = verbose, plot.it = plot.it)))
}
}
}
effectiveN.oneProp = function(N, side = "right", Type1 = 0.005, theta0 = 0.5,
plot.it = T){
N.seq = seq(1, N, by = 1)
if(side=="right"){
UMPBT.seq = mapply(n = N.seq,
FUN = function(n){
c.alpha = qbinom(p = Type1, size = n, prob = theta0, lower.tail = F)
solve.delta.outer =
nleqslv::nleqslv(x = 3,
fn = function(delta){
out.optimize.UMPBTobjective =
optimize(interval = c(theta0, 1),
f = function(p){
(log(delta) - n*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
out.optimize.UMPBTobjective$objective - c.alpha
})
out.optimize.UMPBTobjective.outer =
optimize(interval = c(theta0, 1),
f = function(p){
(log(solve.delta.outer$x) - n*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
round(out.optimize.UMPBTobjective.outer$minimum, 5)
})
u = N.eff = rep(NA, N)
i.change = numeric()
u[1] = UMPBT.seq[1]
N.eff[1] = N.seq[1]
i.change = i = 1
while (i<N) {
if(UMPBT.seq[i+1]<u[i]){
u[i+1] = UMPBT.seq[i+1]
N.eff[i+1] = N.seq[i+1]
i.change = c(i.change, i+1)
}else{
u[i+1] = u[i]
N.eff[i+1] = N.eff[i]
}
i = i+1
}
if(plot.it){
range.UMPBT = range(UMPBT.seq)
df = rbind.data.frame(data.frame('xval' = N.seq,
'yval' = UMPBT.seq,
'type' = 'UMPBT'),
data.frame('xval' = N.seq,
'yval' = u,
'type' = 'decreasing'),
data.frame('xval' = N.seq[i.change],
'yval' = u[i.change],
'type' = 'effective'),
data.frame('xval' = rep(N.eff[N], 2),
'yval' = range.UMPBT,
'type' = 'effectiveN'))
df$type = factor(as.character(df$type),
levels = c('UMPBT', 'decreasing', 'effective', 'effectiveN'))
plot.df = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(linetype = type, colour = type), size = 0.5) +
geom_vline(xintercept = N.eff[N], size = 0.5, colour = 'blue') +
scale_linetype_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'
),
values = c("dashed", "dashed", "blank", "solid"),
guide = guide_legend(nrow = 2)) +
geom_point(aes(colour = type, shape = type, size = type)) +
scale_shape_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'
),
values = c(16, 16, 1, 0),
guide = guide_legend(nrow = 2)) +
scale_size_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'
),
values = c(3, 3, 5, 0.1),
guide = guide_legend(nrow = 2)) +
scale_color_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'
),
values = c('black', 'red2', 'forestgreen', 'blue'),
guide = guide_legend(nrow = 2)) +
annotate('text', x = N.eff[N]-1, size = 5,
y = (UMPBT.seq[1] + UMPBT.seq[N])/2,
label = paste('N = ', N.eff[N], sep = '')) +
ylim(range.UMPBT) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=15),
legend.position = 'bottom') +
labs(title = 'One-sample proportion test',
subtitle = paste('Design the MSPRT using N = ', N.eff[N], sep = ''),
y = 'UMPBT alternatives', x = 'Sample size')
suppressWarnings(print(plot.df))
}
}else if(side=="left"){
UMPBT.seq = mapply(n = N.seq,
FUN = function(n){
c.alpha = qbinom(p = Type1, size = n, prob = theta0)
solve.delta.outer =
nleqslv::nleqslv(x = 3,
fn = function(delta){
out.optimize.UMPBTobjective =
optimize(interval = c(0, theta0), maximum = T,
f = function(p){
(log(delta) - n*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
out.optimize.UMPBTobjective$objective - c.alpha
})
out.optimize.UMPBTobjective.outer =
optimize(interval = c(0, theta0), maximum = T,
f = function(p){
(log(solve.delta.outer$x) - n*(log(1 - p) - log(1 - theta0)))/
(log(p/(1 - p)) - log(theta0/(1 - theta0)))
})
round(out.optimize.UMPBTobjective.outer$maximum, 5)
})
u = N.eff = rep(NA, N)
i.change = numeric()
u[1] = UMPBT.seq[1]
N.eff[1] = N.seq[1]
i.change = i = 1
while (i<N) {
if(UMPBT.seq[i+1]>u[i]){
u[i+1] = UMPBT.seq[i+1]
N.eff[i+1] = N.seq[i+1]
i.change = c(i.change, i+1)
}else{
u[i+1] = u[i]
N.eff[i+1] = N.eff[i]
}
i = i+1
}
if(plot.it){
range.UMPBT = range(UMPBT.seq)
df = rbind.data.frame(data.frame('xval' = N.seq,
'yval' = UMPBT.seq,
'type' = 'UMPBT'),
data.frame('xval' = N.seq,
'yval' = u,
'type' = 'decreasing'),
data.frame('xval' = N.seq[i.change],
'yval' = u[i.change],
'type' = 'effective'),
data.frame('xval' = rep(N.eff[N], 2),
'yval' = range.UMPBT,
'type' = 'effectiveN'))
df$type = factor(as.character(df$type),
levels = c('UMPBT', 'decreasing', 'effective', 'effectiveN'))
plot.df = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(linetype = type, colour = type), size = 0.5) +
geom_vline(xintercept = N.eff[N], size = 0.5, colour = 'blue') +
scale_linetype_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'),
values = c("dashed", "dashed", "blank", "solid"),
guide = guide_legend(nrow = 2)) +
geom_point(aes(colour = type, shape = type, size = type)) +
scale_shape_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'),
values = c(16, 16, 1, 0),
guide = guide_legend(nrow = 2)) +
scale_size_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'),
values = c(3, 3, 5, 0.1),
guide = guide_legend(nrow = 2)) +
scale_color_manual(labels = c('Original point UMPBT alternatives',
'Decreasing point UMPBT alternatives',
'Desirable maximum sample size values',
'The effective N'),
values = c('black', 'red2', 'forestgreen', 'blue'),
guide = guide_legend(nrow = 2)) +
annotate('text', x = N.eff[N]-1, size = 5,
y = (UMPBT.seq[1] + UMPBT.seq[N])/2,
label = paste('N = ', N.eff[N], sep = '')) +
ylim(range.UMPBT) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=15),
legend.position = 'bottom') +
labs(title = 'One-sample proportion test',
subtitle = paste('Design the MSPRT using N = ', N.eff[N], sep = ''),
y = 'UMPBT alternatives', x = 'Sample size')
suppressWarnings(print(plot.df))
}
}
return(N.eff[N])
}
Nstar = function(test.type, N, N1, N2,
N.increment = 1, N1.increment = 1, N2.increment = 1,
lower.signif = 0.05, higher.signif = 0.005,
theta0, side = "right", Type2.target = 0.2,
theta, sigma = 1, sigma1 = 1, sigma2 = 1, plot.it = T){
if((test.type!="oneProp") & (test.type!="oneZ") & (test.type!="oneT") &
(test.type!="twoZ") & (test.type!="twoT")){
return(print("Unknown 'test type'. Has to be one of 'oneProp', 'oneZ', 'oneT', 'twoZ' or 'twoT'."))
}
if(any(test.type==c('oneProp', 'oneT'))){
if(missing(theta)) theta = fixed_design.alt(test.type = test.type, side = side, theta0 = theta0,
N = N, Type1 = lower.signif, Type2 = Type2.target)
i = 0
incr.seq = 1
N.seq = N
Type2.seq = Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0, N = N.seq[i+1], Type1 = higher.signif)
i = 1
if(Type2.seq[i]>Type2.target){
while(Type2.seq[i]>Type2.target){
incr.seq = c(incr.seq, i+1)
N.seq = c(N.seq, N.seq[i] + N.increment)
Type2.seq = c(Type2.seq,
Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0, N = N.seq[i+1], Type1 = higher.signif))
i = i+1
}
}
if(plot.it){
df = rbind.data.frame(data.frame('xval' = incr.seq,
'yval' = Type2.seq,
'type' = 'type2'),
data.frame('xval' = incr.seq[i],
'yval' = Type2.seq[i],
'type' = 'chosen'),
data.frame('xval' = incr.seq[i],
'yval' = c(Type2.seq[1], Type2.seq[i]),
'type' = 'chosen.vline'),
data.frame('xval' = incr.seq,
'yval' = Type2.target,
'type' = 'desired.type2'))
df$type = factor(as.character(df$type),
levels = c('type2', 'chosen', 'chosen.vline', 'desired.type2'))
plot.df = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(linetype = type, colour = type), size = 0.5) +
geom_vline(xintercept = incr.seq[i], size = 0.5, colour = 'blue') +
geom_hline(yintercept = Type2.target, size = 0.5, colour = 'forestgreen') +
scale_linetype_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c("dashed", "solid", "solid", "solid"),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
geom_point(aes(colour = type, shape = type, size = type)) +
scale_shape_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(16, 16, 0, 0),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_size_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(3, 3, 0.001, 0.001),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_color_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c('black', 'red2', 'blue', 'forestgreen'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=15),
legend.position = 'bottom') +
labs(title = bquote('N'^'*'~'='~.(N.seq[i])),
y = paste('Type II error probability at ', round(theta, 4), sep = ''),
x = 'Steps of sample size increment')
suppressWarnings(print(plot.df))
}
return(N.seq[i])
}else if(test.type=='oneZ'){
if(missing(theta)) theta = fixed_design.alt(test.type = test.type, side = side, theta0 = theta0, sigma = sigma,
N = N, Type1 = lower.signif, Type2 = Type2.target)
i = 0
incr.seq = 1
N.seq = N
Type2.seq = Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0, sigma = sigma, N = N.seq[i+1], Type1 = higher.signif)
i = 1
if(Type2.seq[i]>Type2.target){
while(Type2.seq[i]>Type2.target){
incr.seq = c(incr.seq, i+1)
N.seq = c(N.seq, N.seq[i] + N.increment)
Type2.seq = c(Type2.seq,
Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0, sigma = sigma, N = N.seq[i+1], Type1 = higher.signif))
i = i + 1
}
}
if(plot.it){
df = rbind.data.frame(data.frame('xval' = incr.seq,
'yval' = Type2.seq,
'type' = 'type2'),
data.frame('xval' = incr.seq[i],
'yval' = Type2.seq[i],
'type' = 'chosen'),
data.frame('xval' = incr.seq[i],
'yval' = c(Type2.seq[1], Type2.seq[i]),
'type' = 'chosen.vline'),
data.frame('xval' = incr.seq,
'yval' = Type2.target,
'type' = 'desired.type2'))
df$type = factor(as.character(df$type),
levels = c('type2', 'chosen', 'chosen.vline', 'desired.type2'))
plot.df = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(linetype = type, colour = type), size = 0.5) +
geom_vline(xintercept = incr.seq[i], size = 0.5, colour = 'blue') +
geom_hline(yintercept = Type2.target, size = 0.5, colour = 'forestgreen') +
scale_linetype_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c("dashed", "solid", "solid", "solid"),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
geom_point(aes(colour = type, shape = type, size = type)) +
scale_shape_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(16, 16, 0, 0),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_size_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(3, 3, 0.001, 0.001),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_color_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c('black', 'red2', 'blue', 'forestgreen'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=15),
legend.position = 'bottom') +
labs(title = bquote('N'^'*'~'='~.(N.seq[i])),
y = paste('Type II error probability at ', round(theta, 4), sep = ''),
x = 'Steps of sample size increment')
suppressWarnings(print(plot.df))
}
return(N.seq[i])
}else if(test.type=='twoZ'){
if(missing(theta)) theta = fixed_design.alt(test.type = test.type, side = side, theta0 = theta0,
sigma1 = sigma1, sigma2 = sigma2,
N1 = N1, N2 = N2, Type1 = lower.signif, Type2 = Type2.target)
i = 0
incr.seq = 1
N1.seq = N1
N2.seq = N2
Type2.seq = Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0, sigma1 = sigma1, sigma2 = sigma2,
N1 = N1.seq[i+1], N2 = N2.seq[i+1], Type1 = higher.signif)
i = 1
if(Type2.seq[i]>Type2.target){
while(Type2.seq[i]>Type2.target){
incr.seq = c(incr.seq, i+1)
N1.seq = c(N1.seq, N1.seq[i] + N1.increment)
N2.seq = c(N2.seq, N2.seq[i] + N2.increment)
Type2.seq = c(Type2.seq,
Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0, sigma1 = sigma1, sigma2 = sigma2,
N1 = N1.seq[i+1], N2 = N2.seq[i+1], Type1 = higher.signif))
i = i + 1
}
}
if(plot.it){
df = rbind.data.frame(data.frame('xval' = incr.seq,
'yval' = Type2.seq,
'type' = 'type2'),
data.frame('xval' = incr.seq[i],
'yval' = Type2.seq[i],
'type' = 'chosen'),
data.frame('xval' = incr.seq[i],
'yval' = c(Type2.seq[1], Type2.seq[i]),
'type' = 'chosen.vline'),
data.frame('xval' = incr.seq,
'yval' = Type2.target,
'type' = 'desired.type2'))
df$type = factor(as.character(df$type),
levels = c('type2', 'chosen', 'chosen.vline', 'desired.type2'))
plot.df = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(linetype = type, colour = type), size = 0.5) +
geom_vline(xintercept = incr.seq[i], size = 0.5, colour = 'blue') +
geom_hline(yintercept = Type2.target, size = 0.5, colour = 'forestgreen') +
scale_linetype_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c("dashed", "solid", "solid", "solid"),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
geom_point(aes(colour = type, shape = type, size = type)) +
scale_shape_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(16, 16, 0, 0),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_size_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(3, 3, 0.001, 0.001),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_color_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c('black', 'red2', 'blue', 'forestgreen'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=15),
legend.position = 'bottom') +
labs(title = bquote('N'[1]^'*'~'='~.(N1.seq[i])~', N'[2]^'*'~'='~.(N2.seq[i])),
y = paste('Type II error probability at ', round(theta, 4), sep = ''),
x = 'Steps of sample size increment')
suppressWarnings(print(plot.df))
}
return(c(N1.seq[i], N2.seq[i]))
}else if(test.type=='twoT'){
if(missing(theta)) theta = fixed_design.alt(test.type = test.type, side = side, theta0 = theta0,
N1 = N1, N2 = N2, Type1 = lower.signif, Type2 = Type2.target)
i = 0
incr.seq = 1
N1.seq = N1
N2.seq = N2
Type2.seq = Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0,
N1 = N1.seq[i+1], N2 = N2.seq[i+1], Type1 = higher.signif)
i = 1
if(Type2.seq[i]>Type2.target){
while(Type2.seq[i]>Type2.target){
incr.seq = c(incr.seq, i+1)
N1.seq = c(N1.seq, N1.seq[i] + N1.increment)
N2.seq = c(N2.seq, N2.seq[i] + N2.increment)
Type2.seq = c(Type2.seq,
Type2.fixed_design(theta = theta, test.type = test.type, side = side,
theta0 = theta0,
N1 = N1.seq[i+1], N2 = N2.seq[i+1], Type1 = higher.signif))
i = i + 1
}
}
if(plot.it){
df = rbind.data.frame(data.frame('xval' = incr.seq,
'yval' = Type2.seq,
'type' = 'type2'),
data.frame('xval' = incr.seq[i],
'yval' = Type2.seq[i],
'type' = 'chosen'),
data.frame('xval' = incr.seq[i],
'yval' = c(Type2.seq[1], Type2.seq[i]),
'type' = 'chosen.vline'),
data.frame('xval' = incr.seq,
'yval' = Type2.target,
'type' = 'desired.type2'))
df$type = factor(as.character(df$type),
levels = c('type2', 'chosen', 'chosen.vline', 'desired.type2'))
plot.df = ggplot(data = df,
aes(x = xval, y = yval, group = type)) +
geom_line(aes(linetype = type, colour = type), size = 0.5) +
geom_vline(xintercept = incr.seq[i], size = 0.5, colour = 'blue') +
geom_hline(yintercept = Type2.target, size = 0.5, colour = 'forestgreen') +
scale_linetype_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c("dashed", "solid", "solid", "solid"),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
geom_point(aes(colour = type, shape = type, size = type)) +
scale_shape_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(16, 16, 0, 0),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_size_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c(3, 3, 0.001, 0.001),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
scale_color_manual(labels = c('Type II error probabilities for \ndifferent sample sizes',
'Type II error probability for the \nchosen sample size',
'The chosen sample size',
'Desired Type II error probability'),
values = c('black', 'red2', 'blue', 'forestgreen'),
guide = guide_legend(nrow = 2,
override.aes = list(linetype = c(2,0,1,1)))) +
theme(plot.title = element_text(size = 25),
plot.subtitle = element_text(size = 22),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18),
axis.text.x = element_text(color = "black", size = 15),
axis.text.y = element_text(color = "black", size = 15),
panel.border = element_rect(linetype = "solid", fill = NA, size = 1.2),
panel.background = element_blank(), legend.title = element_blank(),
legend.key.width = unit(1.4, "cm"),
legend.spacing.x = unit(1, 'cm'), legend.text = element_text(size=15),
legend.position = 'bottom') +
labs(title = bquote('N'[1]^'*'~'='~.(N1.seq[i])~', N'[2]^'*'~'='~.(N2.seq[i])),
y = paste('Type II error probability at ', round(theta, 4), sep = ''),
x = 'Steps of sample size increment')
suppressWarnings(print(plot.df))
}
return(c(N1.seq[i], N2.seq[i]))
}
}
|
gce_get_zone <- function(project,
zone) {
url <- sprintf("https://www.googleapis.com/compute/v1/projects/%s/zones/%s",
project, zone)
f <- gar_api_generator(url,
"GET",
data_parse_function = function(x) x)
zone <- f()
structure(zone, class = "gce_zone")
}
gce_list_zones <- function(project,
filter = NULL,
maxResults = NULL,
pageToken = NULL) {
url <- sprintf("https://www.googleapis.com/compute/v1/projects/%s/zones", project)
pars <- list(filter = filter,
maxResults = maxResults,
pageToken = pageToken)
pars <- rmNullObs(pars)
f <- gar_api_generator(url,
"GET",
pars_args = pars,
data_parse_function = function(x) x)
f()
}
gce_global_zone <- function(zone){
if(inherits(zone, "gce_zone")){
zone <- zone$name
}
stopifnot(inherits(zone, "character"),
length(zone) == 1)
.gce_env$zone <- zone
message("Set default zone name to '", zone,"'")
return(invisible(.gce_env$zone))
}
gce_get_global_zone <- function(){
if(!exists("zone", envir = .gce_env)){
stop("zone is NULL and couldn't find global zone name.
Set it via gce_global_zone")
}
.gce_env$zone
}
|
marca <-
function(T)
{
if (T<15) marca<-c(1:T)
else{
b<-signif(T,-1)/10
marca<- c(1,seq(b,T, by=b))
}
return(marca)
}
|
pfvn <-
function (x, r, q)
{
ifelse(isTRUE("Multilevel" %in% attr(x, "class")) == TRUE,
x <- x$mlnet, NA)
mx <- norm(as.matrix(x), type = "F")
note <- NULL
n <- dim(x)[1]
if (missing(q) == TRUE) {
q <- (n - 1)
}
else {
if (isTRUE(q < 2) == TRUE) {
q <- 2
warning("'q' is set to the minimum possible value of 2.")
}
}
ifelse(missing(r) == TRUE, r <- Inf, NA)
ifelse(isTRUE(is.data.frame(x) == TRUE) == TRUE, x <- as.matrix(x),
NA)
if (isTRUE(is.array(x) == TRUE) == FALSE)
stop("Input data must be data frame, matrix or array type.")
if (isTRUE(is.na(dim(x)[3]) == TRUE) == TRUE) {
Q <- x
D <- x
if (isTRUE(isSymmetric(x) == TRUE) == TRUE) {
sim <- "Symmetric"
for (k in seq(2, q)) {
QO <- Q
for (i in seq_len(n)) {
for (j in seq_len(n)) {
if (r == Inf) {
Q[i, j] <- min(pmax(x[i, ], QO[, j]))
}
else {
Q[i, j] <- min(x[i, ]^r + QO[, j]^r)^(1/r)
}
if (D[i, j] > Q[i, j]) {
D[i, j] <- Q[i, j]
}
}
rm(j)
}
rm(i)
}
rm(k)
for (i in seq_len(n)) {
for (j in seq_len(n)) {
if (D[i, j] < x[i, j]) {
Q[i, j] <- Inf
}
}
rm(j)
}
rm(i)
QQ <- Q
}
else {
sim <- "NonSymmetric"
note <- paste("For non-symmetyric arrays, triangle inequality only for r=",
r, "and q=", q, "(?) is supported")
QQ <- ti(x)
}
}
else if (isTRUE(is.na(dim(x)[3]) == FALSE) == TRUE) {
sim <- NULL
QQ <- array(NA, dim = c(dim(x)[1], dim(x)[2], dim(x)[3]),
dimnames = list(dimnames(x)[[1]], dimnames(x)[[2]],
dimnames(x)[[3]]))
for (K in seq_len(dim(x)[3])) {
X <- x[, , K]
Q <- x[, , K]
D <- x[, , K]
if (isTRUE(isSymmetric(X) == TRUE) == TRUE) {
ifelse(isTRUE(length(sim) == 0) == TRUE, sim <- "Symmetric",
NA)
for (k in seq(2, q)) {
QO <- Q
for (i in seq_len(n)) {
for (j in seq_len(n)) {
if (r == Inf) {
Q[i, j] <- min(pmax(X[i, ], QO[, j]))
}
else {
Q[i, j] <- min(X[i, ]^r + QO[, j]^r)^(1/r)
}
if (D[i, j] > Q[i, j]) {
D[i, j] <- Q[i, j]
}
}
rm(j)
}
rm(i)
}
rm(k)
for (i in seq_len(n)) {
for (j in seq_len(n)) {
if (D[i, j] < X[i, j]) {
Q[i, j] <- Inf
}
}
rm(j)
}
rm(i)
}
else {
sim <- "NonSymmetric"
Q <- ti(X)
}
QQ[, , K] <- Q
}
rm(K)
}
ifelse(isTRUE(length(note) > 0L) == TRUE, lst <- list(max = mx,
r = r, q = q, Q = QQ, Note = note), lst <- list(max = mx,
r = r, q = q, Q = QQ))
class(lst) <- c("pathfinder", sim)
return(lst)
}
|
vector2Q <- function(p){
m <- 0.5 + sqrt(1+4*length(p))/2
p <- exp(p)
Q <- matrix(0, ncol=m, nrow=m)
k <- 1
for (j in 1:m){
for (i in 1:m){
if (i!=j){
Q[i,j] <- p[k]
k <- k+1
}
}
}
diag(Q) <- -(Q %*% rep(1, m))
return(Q)
}
|
randtest.hist <-
function(results.file="raw_results_run1.csv",
df=1,
p.val=0.05,
main="Default",
xlim=NULL,
PCTSlcol = "black",
vlcol=c("red","orange"),
...)
{
crit.val.nom <- qchisq(1-p.val, df=df)
results <- read.csv(results.file)
if (!isClass("xpose.data") || !isClass("xpose.prefs")) {
createXposeClasses()
}
xpobj <- new("xpose.data",
Runno="PsN Randomization Test",
Data = NULL)
if (is.readable.file("xpose.ini")) {
xpobj <- xpose.read(xpobj, file="xpose.ini")
} else {
rhome <- R.home()
xdefini <- paste(rhome, "\\library\\xpose4\\xpose.ini", sep="")
if (is.readable.file(xdefini)) {
xpobj <- xpose.read(xpobj, file=xdefini)
}else{
xdefini2 <- paste(rhome, "\\library\\xpose4\\xpose.ini", sep="")
if (is.readable.file(xdefini2)) {
xpobj <- xpose.read(xpobj, file=xdefini2)
}
}
}
results$ID <-1
results$WRES <- 1
num_na <- length(results$deltaofv[is.na(results$deltaofv)])
if(num_na>0){
warning("Removing ",num_na," NONMEM runs that did not result in OFV values")
results <- results[!is.na(results$deltaofv),]
}
Data(xpobj,keep.structure=T) <- results[-c(1,2),]
crit.val.emp <- quantile(xpobj@Data$deltaofv,probs=p.val)
orig = results$deltaofv[2]
xpose.plot.histogram("deltaofv",
xpobj,
bins.per.panel.equal=FALSE,
xlim = if(is.null(xlim)){c(min(c(orig,crit.val.emp,xpobj@Data$deltaofv))-1,
max(c(orig,crit.val.emp,xpobj@Data$deltaofv,0))+0.2)},
showPCTS=TRUE,
PCTS=c(p.val),
PCTSlcol = PCTSlcol,
vline=c(orig,-crit.val.nom),
vlcol=vlcol,
main=if(main=="Default"){"Change in OFV for Randomization Test"}else{main},
key=list(
columns = 1,
lines = list(type="l",col =c(vlcol,PCTSlcol)),
text = list(c("Original data", "Nominal", "Empirical (rand. test)")),
corner=c(0.05,0.95),
border=T,
alpha.background=1,
background = "white"
),
...
)
}
|
DJI <- function(level){
x <- NULL
if(level==1){
x1 <- github.cssegisanddata.covid19(country = "Djibouti")
x2 <- ourworldindata.org(id = "DJI")
x <- full_join(x1, x2, by = "date")
}
return(x)
}
|
significance_analysis <-
function(x, n) {
num_groups = length(x)
p = x/n
my_rank = rank(-p)
pt = prop.test(x=x, n=n)
lower = rep(NA, num_groups)
upper = rep(NA, num_groups)
significance = rep(NA, num_groups)
best = rep(0, num_groups)
b = best_binomial_bandit(x, n)
if (pt$p.value < 0.05) {
is_best = 1
for (cur_rank in sort(unique(my_rank))) {
cur_indices = which(my_rank==cur_rank)
if (length(cur_indices) >= 1) {
cur_index = max(cur_indices)
ranks_above = my_rank[my_rank > cur_rank]
if (length(ranks_above) > 0) {
comparison_index = min(which(my_rank==min(ranks_above)))
pt = prop.test(x=x[c(cur_index, comparison_index)], n=n[c(cur_index, comparison_index)], conf.level = (1 - 0.05))
significance[cur_indices] = pt$p.value
lower[cur_indices] = pt$conf.int[1]
upper[cur_indices] = pt$conf.int[2]
best[cur_indices] = is_best
if (pt$p.value < 0.05) {
is_best = 0
}
}
}
}
}
return(data.frame(successes=x, totals=n, estimated_proportion=p, lower=lower, upper=upper, significance=significance, rank=my_rank, best=best, p_best=b))
}
|
remove(list = ls())
library(MortalityLaws)
library(testthat)
x1 <- c(0, 1, seq(5, 100, by = 5))
mx <- c(.08592, .00341, .00099, .00073, .00169, .00296, .00364,
.00544, .00539, .01460, .01277, .02694, .01703, .04331,
.03713, .07849, .09307, .13990, .18750, .22500, .25000,
.30000)
names(mx) <- x1
M1 <- function() MortalityLaw(x = x1,
mx = mx,
law = law,
fit.this.x = x2,
opt.method = opt.method)
M2 <- function() MortalityLaw(x = x2,
mx = mx[paste(x2)],
law = law,
fit.this.x = x2,
opt.method = opt.method)
opt.method = "LF2"
testFN <- function(M1, M2) {
test_that(paste(law, "Model"), {
expect_identical(fitted(M1)[paste(x2)], fitted(M2))
expect_identical(fitted(M1)[paste(x2)], predict(M1, x = x2))
expect_identical(fitted(M1), predict(M1, x = x1))
expect_identical(fitted(M1), predict(M2, x = x1))
expect_identical(coef(M1), coef(M2))
expect_false(is.null(plot(M1)))
expect_false(is.null(plot(M2)))
})
}
law = "gompertz"
x2 = seq(40, 75, by = 5)
testFN(M1(), M2())
law = "gompertz0"
x2 = seq(40, 75, by = 5)
testFN(M1(), M2())
law = "invgompertz"
x2 = seq(5, 30, by = 5)
testFN(M1(), M2())
law = "makeham"
x2 = seq(35, 90, by = 5)
testFN(M1(), M2())
law = "makeham0"
x2 = seq(35, 90, by = 5)
testFN(M1(), M2())
law = "opperman"
x2 = c(0,1, seq(5, 25, by = 5))
testFN(M1(), M2())
law = "thiele"
x2 = x1
testFN(M1(), M2())
law = "wittstein"
x2 = x1
testFN(M1(), M2())
law = "perks"
x2 = seq(20, 80, 5)
testFN(M1(), M2())
law = "weibull"
x2 = c(0, 1, 5, 10, 15)
testFN(M1(), M2())
law = "invweibull"
x2 = seq(10, 30, 5)
testFN(M1(), M2())
law = "vandermaen"
x2 = seq(20, 95, by = 5)
testFN(M1(), M2())
law = "vandermaen2"
x2 = seq(60, 95, by = 5)
testFN(M1(), M2())
law = "strehler_mildvan"
x2 = seq(40, 75, by = 5)
testFN(M1(), M2())
law = "quadratic"
x2 = seq(60, 95, by = 5)
testFN(M1(), M2())
law = "beard"
x2 = seq(60, 95, by = 5)
testFN(M1(), M2())
law = "beard_makeham"
x2 = seq(60, 95, by = 5)
testFN(M1(), M2())
law = "ggompertz"
x2 = seq(60, 95, by = 5)
testFN(M1(), M2())
law = "siler"
x2 = x1
testFN(M1(), M2())
law = "HP"
x2 = x1
testFN(M1(), M2())
law = "HP2"
x2 = x1
testFN(M1(), M2())
law = "HP3"
x2 = x1
testFN(M1(), M2())
law = "HP4"
x2 = x1
testFN(M1(), M2())
law = "rogersplanck"
x2 = x1
testFN(M1(), M2())
law = "martinelle"
x2 = c(0, 1, seq(5, 75, 5))
testFN(M1(), M2())
law = "carriere1"
x2 = x1
testFN(M1(), M2())
law = "carriere2"
x2 = x1
testFN(M1(), M2())
law = "kostaki"
x2 = x1
testFN(M1(), M2())
law = "kannisto"
x2 = c(80, 85, 90, 95)
testFN(M1(), M2())
law = "kannisto_makeham"
x2 = c(80, 85, 90, 95)
testFN(M1(), M2())
|
fmpc_13f_cik_list <- function() {
Result <- fmpc_get_url('cik_list?')
Result <- hlp_chkResult(Result)
dplyr::as_tibble(Result)
}
fmpc_13f_cik_search <- function(query = 'Berkshire') {
URL = paste0('cik-search/',gsub(' ','%20',query),'?')
Result <- fmpc_get_url(URL)
Result <- hlp_chkResult(Result)
dplyr::as_tibble(Result)
}
fmpc_13f_cik_name <- function(cik = '0001067983') {
cikReq = unique(cik)
Result <- hlp_bindURLs(paste0('cik/',cikReq,'?'))
Result <- hlp_chkResult(Result)
Result
}
fmpc_13f_data <- function(cik = '0001067983',
date = '2019-12-31') {
fillingDate <- NULL
cikPull = unique(cik)
datePull = unique(lubridate::ceiling_date(as.Date(date), unit = 'quarter') - 1)
checkDate = unique(date) != datePull
if (TRUE %in% checkDate) warning('13F can only be pulled for quarter end.', call. = FALSE)
CrossCikDate = tidyr::crossing(cik = cikPull, date = datePull) %>%
dplyr::mutate(URL = paste0('form-thirteen/',cik,'?date=',date,'&'))
cikDate = hlp_bindURLs(CrossCikDate$URL)
hlp_respCheck(cikPull,cikDate$cik,'Missing cik(s) for fmpc_13f_data: ')
hlp_respCheck(datePull,unique(cikDate$date),'Missing date(s) fmpc_13f_data: ')
if (is.null(cikDate)) return(NULL)
cikDate %>%
dplyr::distinct() %>%
dplyr::mutate_at(dplyr::vars(date,fillingDate),as.Date)
}
fmpc_rss_sec <- function(limit = 100) {
Result <- fmpc_get_url(paste0('rss_feed?limit=',limit,'&'))
Result <- hlp_chkResult(Result)
dplyr::as_tibble(Result)
}
fmpc_held_by_mfs <- function(symbols = c('AAPL')) {
symbReq = hlp_symbolCheck(symbols)
mf_df = data.frame(URL = paste0('mutual-fund-holder/',symbReq,'?'),
label = gsub('%5E','\\^',symbReq))
mutualFundDF = hlp_bindURLs(mf_df$URL, label_df = mf_df, label_name = 'symbol')
hlp_respCheck(symbReq,mutualFundDF$symbol,'fmpc_held_by_mfs: ')
mutualFundDF
}
fmpc_holdings_etf <- function(etfs = c('SPY'),
holding = c('symbol', 'sector', 'country')) {
etfReq = hlp_symbolCheck(etfs)
if (missing(holding)) holding = 'symbol'
if (!(holding %in% c('symbol', 'sector', 'country'))){
stop('Holding must be one of the following: symbol, sector, or country')
}
holdReq = switch(holding, 'symbol' = 'holder', 'sector' = 'sector-weightings', 'country' = 'country-weightings')
etf_df = data.frame(URL = paste0('etf-',holdReq,'/',etfReq,'?'),
label = etfReq)
etfDF = hlp_bindURLs(etf_df$URL, label_df = etf_df, label_name = 'etf')
hlp_respCheck(etfReq,etfDF$etf,'fmpc_holdings_etf: ')
etfDF
}
|
get_pcawg_gene_value <- function(identifier) {
host <- "pcawgHub"
dataset <- "tophat_star_fpkm_uq.v2_aliquot_gl.sp.log"
expression <- get_data(dataset, identifier, host)
unit <- "log2(fpkm-uq+0.001)"
report_dataset_info(dataset)
res <- list(data = expression, unit = unit)
res
}
get_pcawg_fusion_value <- function(identifier) {
host <- "pcawgHub"
dataset <- "pcawg3_fusions_PKU_EBI.gene_centric.sp.xena"
expression <- get_data(dataset, identifier, host)
unit <- "binary fusion call, 1 fusion, 0 otherwise"
report_dataset_info(dataset)
res <- list(data = expression, unit = unit)
res
}
get_pcawg_promoter_value <- function(identifier, type = c("raw", "relative", "outlier")) {
host <- "pcawgHub"
type <- match.arg(type)
if (type == "raw") {
dataset <- "rawPromoterActivity.sp"
unit <- "raw promoter activity"
} else if (type == "relative") {
dataset <- "relativePromoterActivity.sp"
unit <- "portion of transcription activity of the gene driven by the promoter"
} else {
dataset <- "promoterCentricTable_0.2_1.0.sp"
unit <- "-1 (low expression), 0 (normal), 1 (high expression)"
}
if (!startsWith(identifier, "prmtr")) {
map <- load_data("pcawg_promoter_id")
id_map <- map[names(map) == identifier]
if (length(id_map) > 1) {
expression <- purrr::reduce(
purrr::map(
as.character(id_map),
~ get_data(dataset, ., host)
), `+`
)
} else {
expression <- get_data(dataset, as.character(id_map), host)
}
} else {
expression <- get_data(dataset, identifier, host)
}
report_dataset_info(dataset)
res <- list(data = expression, unit = unit)
res
}
get_pcawg_miRNA_value <- function(identifier, norm_method = c("TMM", "UQ")) {
host <- "pcawgHub"
norm_method <- match.arg(norm_method)
if (norm_method == "TMM") {
dataset <- "x3t2m1.mature.TMM.mirna.matrix.log"
unit <- "log2(cpm-TMM+0.1)"
} else {
dataset <- "x3t2m1.mature.UQ.mirna.matrix.log"
unit <- "log2(cpm-uq+0.1)"
}
expression <- get_data(dataset, identifier, host)
report_dataset_info(dataset)
res <- list(data = expression, unit = unit)
res
}
get_pcawg_APOBEC_mutagenesis_value <- function(identifier = c(
"tCa_MutLoad_MinEstimate", "APOBECtCa_enrich",
"A3A_or_A3B", "APOBEC_tCa_enrich_quartile", "APOBECrtCa_enrich",
"APOBECytCa_enrich", "APOBECytCa_enrich-APOBECrtCa_enrich",
"BH_Fisher_p-value_tCa", "ntca+tgan", "rtCa_to_G+rtCa_to_T",
"rtca+tgay", "tCa_to_G+tCa_to_T",
"ytCa_rtCa_BH_Fisher_p-value", "ytCa_rtCa_Fisher_p-value", "ytCa_to_G+ytCa_to_T",
"ytca+tgar"
)) {
identifier <- match.arg(identifier)
host <- "pcawgHub"
dataset <- "MAF_Aug31_2016_sorted_A3A_A3B_comparePlus.sp"
expression <- get_data(dataset, identifier, host)
unit <- ""
report_dataset_info(dataset)
res <- list(data = expression, unit = unit)
res
}
|
library(portfolio)
load("portfolio.expandData.test.RData")
result <- expandData(test)
stopifnot(
all.equal(truth$id, result@data$id),
all.equal(truth$price, result@data$price),
all.equal(truth$in.var, result@data$in.var)
)
|
if(getRversion() >= "2.15.1") {
utils::globalVariables(c("lower", "upper", "label", "y"))
}
plotBoundary <- function(b1, b0, p, glrTables=NULL, tol=1e-7, legend=FALSE, textXOffset=2, textYSkip=2) {
boundary <- computeBoundary(b1=b1, b0=b0, p=p, glrTables=glrTables)
estimate <- boundary$estimate
N <- length(boundary$upper)
d <- data.frame(x=1:N, lower=boundary$lower, upper=boundary$upper)
plot <- ggplot()
plot <- plot + geom_step(aes(x=x, y=lower), data=d, colour="blue") +
geom_step(aes(x=x, y=upper), data=d, colour = 'red')
plot <- plot + theme(legend.position = "none")
plot <- plot + scale_x_continuous('Total No. of AEs') +
scale_y_continuous('No. of Vaccine AEs')
x <- floor(sum(range(d$upper, na.rm=TRUE)/2))
y1 <- d$upper[x] + 2
plot <- plot + geom_text(aes(x, y, label=label),
data=data.frame(x=floor(x/2), y=y1, label="Reject H_0"),
color="red", hjust=0.0)
y2 <- d$lower[x] - 2
plot <- plot + geom_text(aes(x,y,label=label),
data=data.frame(x=ceiling((x + length(d$upper))/2), y=y2, label="Accept H_0"),
color="blue", hjust=0.0)
if (legend) {
leg1 <- paste("Hypothesis: (p[0] *\",\" * p[1]) * \"=\" * (", p[1], "* \",\" * ", p[2], ")",
sep="")
leg2 <- paste("SGLR *\" \" * Boundaries: (b[0] *\",\" * b[1]) * \"=\" * (", b0, "*\",\" * ", b1, ")",
sep="")
leg3 <- paste("Type *\" \" * I * \", \" * II * \" \" * Errors: (alpha *\", \"* beta) *\"=\" * (",
round(estimate[1], 5), "*\", \" * ", round(estimate[2], 5), ")", sep="")
leg4 <- paste("Max.* \"
top <- max(d$upper, na.rm=TRUE)
plot <- plot + geom_text(aes(x,y,label=label),
data=data.frame(x=textXOffset, y=top, label=leg1),
parse=TRUE, hjust=0.0)
plot <- plot + geom_text(aes(x,y,label=label),
data=data.frame(x=textXOffset, y=top-textYSkip, label=leg2),
parse=TRUE, hjust=0.0)
plot <- plot + geom_text(aes(x,y,label=label),
data=data.frame(x=textXOffset, y=top-2*textYSkip, label=leg3),
parse=TRUE, hjust=0.0)
plot <- plot + geom_text(aes(x,y,label=label),
data=data.frame(x=textXOffset, y=top-3*textYSkip, label=leg4),
parse=TRUE, hjust=0.0)
}
plot
}
|
scope.logistic = function ( x, y, gamma = 8, lambda = NULL, nlambda = 100, lambda_min_ratio = 0.01, nfolds = 5, include_intercept = TRUE, return_full_beta = FALSE,
max_iter = 1000, max_out_iter = 1000, early_stopping = ifelse(pshrink > 1, TRUE, FALSE), early_stopping_rounds = 20, early_stopping_criterion = "AIC", noise_variance = NULL,
terminate_eps = 1e-7, silent = TRUE, only_cross_validate = FALSE, grid_safe = 10, block_order = NULL, fold_assignment = NULL, zero_penalty = FALSE) {
inv.logit = function ( x ) return(exp(x) / ( 1 + exp(x) ))
logit = function( x ) return(log( x / ( 1 + x )))
scopemod = list()
attr(scopemod,"class")<-"scope.logistic"
scopemod$cverrors = NULL
scopemod$lambdaseq = NULL
scopemod$beta.full = NULL
scopemod$beta.best = NULL
scopemod$fold.assign = NULL
n = length(y)
p = dim(x)[ 2 ]
factor_ind = rep(F, p)
for ( j in 1:p ) {
if (( class(x[ , j ]) != "numeric" ) && ( class(x[ , j ]) != "numeric" )) factor_ind[ j ] = T
}
xshrink = data.frame(x[ , factor_ind, drop = F ])
if ( include_intercept == FALSE ) {
xlinear = as.matrix(x[ , !factor_ind, drop = F ])
} else {
xlinear = as.matrix(cbind(1, x[ , !factor_ind, drop = F ]))
}
plinear = dim(xlinear)[ 2 ]
pshrink = dim(xshrink)[ 2 ]
for ( j in 1:pshrink ) xshrink[ , j ] = as.factor(xshrink[ , j ])
include_intercept = FALSE
P = solve(t(xlinear) %*% xlinear) %*% t(xlinear)
catnumbers = rep(0, pshrink)
mcpContribution = rep(0, pshrink)
catnames = list()
for ( j in 1:pshrink ) {
catnames[[ j ]] = levels(xshrink[ , j ])
catnumbers[ j ] = length(catnames[[ j ]])
}
if ( is.null(lambda) ) {
pathlength = nlambda
} else {
if ( is.null(dim(lambda)) ) {
lambda = t(as.matrix(lambda))
}
pathlength = dim(lambda)[ 2 ]
}
coefficientshrink = list()
if ( is.null(block_order) ) block_order = sample(1:pshrink)
for ( j in 1:pshrink ) {
coefficientshrink[[ j ]] = matrix(0, catnumbers[ j ], pathlength)
rownames(coefficientshrink[[ j ]]) = catnames[[ j ]]
}
coefficientlinear = matrix(0, plinear, pathlength)
beta = rep(0, plinear)
subaverages = list()
weights = list()
weightsbool = list()
for ( j in 1:pshrink ) {
weights[[ j ]] = rep(0, catnumbers[ j ])
weightsbool[[ j ]] = rep(FALSE, catnumbers[ j ])
subaverages[[ j ]] = rep(0, catnumbers[ j ])
for ( k in 1:catnumbers[ j ] ) {
weights[[ j ]][ k ] = sum(xshrink[ , j ] == catnames[[ j ]][ k ]) / n
}
weightsbool[[ j ]] = (weights[[ j ]] > 0)
}
partialresiduals = y
beta = P %*% partialresiduals
partialresiduals = partialresiduals - xlinear %*% beta
minstdev = Inf
for ( j in 1:pshrink ) {
subaverages[[ j ]] = tapply(partialresiduals, xshrink[ , j ], mean)[ catnames[[ j ]] ]
minstdev = min(minstdev, sqrt(var(subaverages[[ j ]][ weightsbool[[ j ]] ] * sqrt(n * weights[[ j ]][ weightsbool[[ j ]] ]))))
}
if ( is.null(noise_variance) ) {
noise_variance = 0.0125 * minstdev
}
if ( is.null(lambda) ) {
baseseq = as.matrix(exp(seq(log( 8 * noise_variance / sqrt(n)), log(lambda_min_ratio * 8 * noise_variance / sqrt(n)), length = nlambda)))
lambda = t(baseseq %*% (catnumbers^(0.5)))
} else {
if (sum(lambda <= 0) > 0) {
stop('All lambda values must be strictly positive')
} else if (dim(lambda)[ 1 ] != pshrink) {
stop('lambda must be pshrink times pathlength matrix with each row a positive decreasing sequence')
} else for (j in 1:pshrink) {
if (sum(diff(lambda[ j, ]) > 0) > 0) {
stop('lambda sequence for each categorical variable must be decreasing')
}
}
}
if ( zero_penalty == TRUE ) {
lambda = lambda[ , 1:2 ]
lambda[ , 2 ] = rep(0, pshrink)
}
if ( nfolds > 1 ) {
if ( is.null(fold_assignment) ) {
fold_assignment = as.integer(sample(ceiling((1:n)*nfolds/n)))
scopemod$fold.assign = fold_assignment
}
cverrors = matrix(0, n, dim(lambda)[ 2 ])
removecounter = 0
counter = 0
for ( k in 1:nfolds ) {
if ( silent == FALSE ) print(paste0("Fold ", k))
yfold = y[ (fold_assignment != k), drop = FALSE ]
xlinearfold = xlinear[ (fold_assignment != k), , drop = FALSE ]
xshrinkfold = xshrink[ (fold_assignment != k), , drop = FALSE ]
yremove = y[ (fold_assignment == k), drop = FALSE ]
xlinearremove = xlinear[ (fold_assignment == k), , drop = FALSE ]
xshrinkremove = xshrink[ (fold_assignment == k), , drop = FALSE ]
nremove = length(yremove)
keepidentifier = rep(TRUE, nremove)
for ( i in 1:nremove ) {
for ( j in 1:pshrink ) {
if ( xshrinkremove[ i, j ] %in% xshrinkfold[ , j ] == FALSE ) {
keepidentifier[ i ] = FALSE
removecounter = removecounter + 1
}
}
}
yremove = yremove[ keepidentifier, drop = FALSE ]
xlinearremove = xlinearremove[ keepidentifier, , drop = FALSE ]
xshrinkremove = xshrinkremove[ keepidentifier, , drop = FALSE ]
cvsolution = core_scope.logistic(yfold, xlinearfold, xshrinkfold, block_order, k, gamma, (early_stopping_criterion == "AIC"), early_stopping_criterion, lambda, terminate_eps,
!include_intercept, max_iter, max_out_iter, early_stopping, early_stopping_rounds,
silent, grid_safe)
if ( k == 1 ) {
lambda = cvsolution[[ 4 ]]
if ( is.null(dim(lambda)) ) {
lambda = t(as.matrix(lambda))
}
}
cvtemp = xlinearremove %*% cvsolution[[ 1 ]]
for ( j in 1:pshrink ) {
cvtemp = cvtemp + cvsolution[[ 2 ]][[ j ]][ xshrinkremove[ , j], ]
}
cverrorstemp = abs(yremove - inv.logit(cvtemp))
cverrors[ (counter + 1):(counter + length(yremove)), 1:dim(cverrorstemp)[ 2 ] ] = as.numeric(cverrorstemp)
counter = counter + length(yremove)
}
cverrors = as.matrix(cverrors[ 1:(n - removecounter), 1:dim(cverrorstemp)[ 2 ] ])
if ( removecounter > 0 ) {
warning(paste0(removecounter, " observations removed from test sets; number of evaluated predictions is ", n - removecounter, "."))
}
cverrors = colMeans(cverrors > 0.5)
cverrors[ is.na(cverrors) ] = Inf
scopemod$cverrors = cverrors
if ( only_cross_validate == TRUE ) {
return(scopemod)
}
pathlengthfinal = which.min(cverrors)
lambdaseqused = lambda
lambda = lambda[ , 1:pathlengthfinal, drop = FALSE ]
if ( silent == FALSE ) print(paste0("Minimal cross-validation error = ", min(cverrors), " at pathpoint ", pathlengthfinal))
scopemod$lambda = lambdaseqused
fullsolution = core_scope.logistic(y, xlinear, xshrink, block_order, 2, gamma, (early_stopping_criterion == "AIC"), early_stopping_criterion, lambda, terminate_eps,
!include_intercept, max_iter, max_out_iter, early_stopping, early_stopping_rounds,
silent, grid_safe )
if ( return_full_beta == TRUE ) {
scopemod$beta.full = list()
scopemod$beta.full[[ 1 ]] = fullsolution[[ 1 ]]
scopemod$beta.full[[ 2 ]] = fullsolution[[ 2 ]]
}
fullsolution[[ 1 ]] = matrix(fullsolution[[ 1 ]], plinear, pathlengthfinal)[ , pathlengthfinal ]
for ( j in 1:pshrink ) {
fullsolution[[ 2 ]][[ j ]] = as.matrix(fullsolution[[ 2 ]][[ j ]])[ , pathlengthfinal ]
}
fullsolution = list(fullsolution[[ 1 ]], fullsolution[[ 2 ]])
scopemod$beta.best = list()
scopemod$beta.best[[ 1 ]] = fullsolution[[ 1 ]]
scopemod$beta.best[[ 2 ]] = fullsolution[[ 2 ]]
return(scopemod)
} else {
solution = core_scope.logistic(y, xlinear, xshrink, block_order, 1, gamma, (early_stopping_criterion == "AIC"), early_stopping_criterion, lambda, terminate_eps,
!include_intercept, max_iter, max_out_iter, early_stopping, early_stopping_rounds,
silent, grid_safe )
pathlengthfinal = dim(solution[[ 2 ]][[ 1 ]])[ 2 ]
if ( plinear > 1 ) {
solution[[ 1 ]] = solution[[ 1 ]][ , 1:pathlengthfinal ]
} else {
solution[[ 1 ]] = solution[[ 1 ]][ 1:pathlengthfinal ]
}
for ( j in 1:pshrink ) {
if ( pathlengthfinal > 1 ) {
solution[[ 2 ]][[ j ]] = solution[[ 2 ]][[ j ]][ , 1:pathlengthfinal ]
}
}
fullsolution = list()
fullsolution$beta.full[[ 1 ]] = solution[[ 1 ]]
fullsolution$beta.full[[ 2 ]] = solution[[ 2 ]]
scopemod$beta.full = fullsolution$beta.full
lambda = lambda[ , 1:pathlengthfinal ]
scopemod$lambda = lambda
return(scopemod)
}
}
|
library(knotR)
filename <- "8_9.svg"
a <- reader(filename)
sym89 <- symmetry_object(a,xver=7)
a <- symmetrize(a,sym89)
ou89 <- matrix(c(
17,06,
05,15,
14,03,
02,18,
09,01,
23,11,
10,21,
19,09
),ncol=2,byrow=TRUE)
jj <-
knotoptim(filename,
symobj = sym89,
ou = ou89,
prob = 0,
iterlim=1000, print.level=2)
)
write_svg(jj, filename,safe=FALSE)
dput(jj,file=sub('.svg','.S',filename))
|
backgroundIndex <- function(img, bg_condition) {
img_dims <- dim(img)
flattened_img <- img
dim(flattened_img) <- c(img_dims[1] * img_dims[2],
img_dims[3])
if (class(bg_condition) == "bg_rect") {
lower <- bg_condition$lower
upper <- bg_condition$upper
idx <- which((lower[1] <= img[ , , 1] &
img[ , , 1] <= upper[1]) &
(lower[2] <= img[ , , 2] &
img[ , , 2] <= upper[2]) &
(lower[3] <= img[ , , 3] &
img[ , , 3] <= upper[3]))
} else if (class(bg_condition) == "bg_t") {
if (ncol(flattened_img) != 4) {
warning("Image has no transparency channel; clustering all pixels")
idx <- character(0)
} else {
idx <- which(round(flattened_img[ , 4]) < 1)
}
} else if (class(bg_condition) == "bg_sphere") {
stop("Center/radius masking coming soon...")
} else if (class(bg_condition) == "bg_none") {
idx <- character(0)
} else {
stop("bg_condition must be output from backgroundCondition()")
}
flattened_img <- flattened_img[ , 1:3]
img_dims[3] <- 3
if (length(idx) == 0) {
non_bg <- flattened_img
idx_flat <- idx
message("No pixels satisfying masking conditions; clustering all pixels")
} else {
non_bg <- flattened_img[-idx, ]
idx_flat <- idx
idx <- arrayInd(idx_flat, .dim = dim(flattened_img))
}
bg_index <- list(flattened_img = flattened_img,
img_dims = img_dims,
non_bg = non_bg[ , 1:3],
idx = idx,
idx_flat = idx_flat)
class(bg_index) <- "bg_index"
return(bg_index)
}
|
scaleColumns <- function(df){
scaled_df <- as.data.frame(
apply(df, 2,
function(x){
(x - min(x, na.rm = T))/(max(x, na.rm = T) - min(x, na.rm = T))
})
)
return(scaled_df)
}
|
[
{
"title": "Infinite generators in R",
"href": "https://cartesianfaith.com/2013/01/05/infinite-generators-in-r/"
},
{
"title": "Encrypt user’s password with md5 for you Shiny-app",
"href": "https://web.archive.org/web/http://withr.me/blog/2014/02/14/encrypt-users-password-with-md5-for-you-shiny-app/"
},
{
"title": "A Case Study in Reproducible Model Building",
"href": "http://jfisher-usgs.github.io/r/2016/08/04/wrv-case-study"
},
{
"title": "oro.nifti 0.1.5",
"href": "http://rigorousanalytics.blogspot.com/2010/06/oronifti-015.html"
},
{
"title": "state-by-state pendulum",
"href": "https://web.archive.org/web/http://jackman.stanford.edu/blog/?p=1725"
},
{
"title": "One week left to enter the $20,000 \"Applications of R\" contest",
"href": "http://blog.revolutionanalytics.com/2011/10/r-contest-deadline-oct-31.html"
},
{
"title": "Boxplots and Beyond – Part II: Asymmetry",
"href": "http://exploringdatablog.blogspot.com/2011/02/boxplots-and-beyond-part-ii-asymmetry.html"
},
{
"title": "New R User Group at Berkeley",
"href": "http://blog.revolutionanalytics.com/2012/02/new-r-user-group-at-berkeley.html"
},
{
"title": "Interactive time series with dygraphs",
"href": "https://blog.rstudio.org/2015/04/14/interactive-time-series-with-dygraphs/"
},
{
"title": "RcppExamples 0.1.5 and RcppClassicExamples 0.1.0",
"href": "http://dirk.eddelbuettel.com/blog/2012/12/29/"
},
{
"title": "Search r documentation and manuals with Rdocumentation",
"href": "https://www.datacamp.com/community/blog/help"
},
{
"title": "Nov 20 Data Science Talklet: Incorporating Text Data into Your Feature Set",
"href": "http://www.obscureanalytics.com/2014/11/22/nov-20-data-science-talklet-incorporating-text-data-into-your-feature-set/"
},
{
"title": "Pills, half pills and probabilities",
"href": "http://freakonometrics.hypotheses.org/3322"
},
{
"title": "Using Discussion Forum Activity to Estimate Analytics Software Market Share",
"href": "http://r4stats.com/2015/10/19/using-discussion-forum-activity-to-estimate-analytics-software-market-share/"
},
{
"title": "New project: RInside",
"href": "http://dirk.eddelbuettel.com/blog/2009/02/12/"
},
{
"title": "NYC is a city that does sleep, a bit",
"href": "http://blog.revolutionanalytics.com/2015/03/nyc-is-a-city-that-does-sleep-a-bit.html"
},
{
"title": "Compound Poisson and vectorized computations",
"href": "http://blog.free.fr/"
},
{
"title": "RcppArmadillo 0.3.820",
"href": "http://dirk.eddelbuettel.com/blog/2013/05/13/"
},
{
"title": "Resources for Learning R in Iraq?",
"href": "https://benmazzotta.wordpress.com/2009/05/06/resources-for-learning-r-in-iraq/"
},
{
"title": "Is it crowded in here?",
"href": "http://jcarroll.com.au/2016/03/09/is-it-crowded-in-here/"
},
{
"title": "Oldies but Goldies: Statistical Graphics Books",
"href": "https://www.r-bloggers.com/oldies-but-goldies-statistical-graphics-books/"
},
{
"title": "Notes from the Kölner R meeting, 26 June 2015",
"href": "http://www.magesblog.com/2015/06/notes-from-kolner-r-meeting-26-june-2015.html"
},
{
"title": "New R User Group in Slovenia",
"href": "http://blog.revolutionanalytics.com/2010/07/new-r-user-group-in-slovenia.html"
},
{
"title": "Crayfish or crawdad? Mapping US dialect variations with R",
"href": "http://blog.revolutionanalytics.com/2013/06/r-and-language.html"
},
{
"title": "Learning Statistics on Youtube",
"href": "http://flavioazevedo.com/stats-and-r-blog/2016/9/13/learning-r-on-youtube"
},
{
"title": "Lambda.r 1.1.0 released",
"href": "https://cartesianfaith.com/2013/01/25/lambda-r-1-1-0-released/"
},
{
"title": "The Win-Vector R data science value pack",
"href": "http://www.win-vector.com/blog/2015/03/the-win-vector-r-data-science-value-pack/"
},
{
"title": "Euro 2016 Squads Part Deux",
"href": "https://gjabel.wordpress.com/2016/06/21/euro-2016-squads-part-deux/"
},
{
"title": "“R for Developers” Course | May 30-31",
"href": "http://www.milanor.net/blog/r-for-developers/"
},
{
"title": "ggplot2 primer in 10 minutes",
"href": "https://robertgrantstats.wordpress.com/2012/10/15/ggplot2-primer-in-10-minutes/"
},
{
"title": "Learning R — Documentation",
"href": "http://mazamascience.com/WorkingWithData/?p=619"
},
{
"title": "Kendall Rank Coefficient by GPU",
"href": "http://www.r-tutor.com/gpu-computing/correlation/kendall-rank-coefficient"
},
{
"title": "Using MANOVA to Analyse a Banking Crisis Exercises",
"href": "http://r-exercises.com/2016/08/24/using-manova-to-analyse-banking-crises/"
},
{
"title": "Slides from my online forecasting course",
"href": "https://www.r-bloggers.com/slides-from-my-online-forecasting-course/"
},
{
"title": "Evolving Domestic Frontier",
"href": "http://timelyportfolio.blogspot.com/2011/11/evolving-domestic-frontier.html"
},
{
"title": "Top 77 R posts for 2014 (+R jobs)",
"href": "https://www.r-bloggers.com/77-most-read-r-posts-r-jobs-for-2014/"
},
{
"title": "Next Kölner R User Meeting: 12 April 2013",
"href": "http://www.magesblog.com/2013/04/next-kolner-r-user-meeting-12-april-2013.html"
},
{
"title": "Array exercises",
"href": "http://r-exercises.com/2015/12/01/array-exercises/"
},
{
"title": "MCMC and faster Gibbs Sampling using Rcpp",
"href": "http://dirk.eddelbuettel.com/blog/2011/07/14/"
},
{
"title": "The Joy of Visualizations",
"href": "http://blog.revolutionanalytics.com/2010/11/the-joy-of-visualizations.html"
},
{
"title": "Normalising data within groups",
"href": "https://aghaynes.wordpress.com/2012/06/21/normalising-data-within-groups/"
},
{
"title": "Recovering Marginal Effects and Standard Errors of Interactions Terms Pt. II: Implement and Visualize",
"href": "https://web.archive.org/web/http://davenportspatialanalytics.squarespace.com/journal/2012/3/9/recovering-marginal-effects-and-standard-errors-of-interacti.html"
},
{
"title": "Model for nothing – and the bootstrap for free",
"href": "https://web.archive.org/web/http://timotheepoisot.fr/2011/01/model-%E2%80%93-bootstrap-free/"
},
{
"title": "Unprincipled Component Analysis",
"href": "http://www.win-vector.com/blog/2014/02/unprincipled-component-analysis/?utm_source=rss&utm_medium=rss&utm_campaign=unprincipled-component-analysis"
},
{
"title": "Zurich, Aug 2012 – Swiss SBBI Data",
"href": "https://www.rmetrics.org/SBBIDataAugust2012"
},
{
"title": "Symmetric set differences in R",
"href": "http://helmingstay.blogspot.com/2013/06/symmetric-set-differences-in-r.html"
},
{
"title": "devtools 1.4 now available",
"href": "https://blog.rstudio.org/2013/11/27/devtools-1-4/"
},
{
"title": "On Panel Sizes",
"href": "https://web.archive.org/web/http://flovv.github.io/www.nypon.de/Panel-Sizes/"
},
{
"title": "Survey: R used by more data miners than any other tool",
"href": "http://blog.revolutionanalytics.com/2011/03/survey-r-used-by-more-data-miners-than-any-other-tool.html"
},
{
"title": "Great Maps with ggplot2",
"href": "http://spatial.ly/2012/02/great-maps-ggplot2/"
}
]
|
NULL
covcor.check.y = function(y)
{
if (!is.null(y))
comm.stop("only supported when argument 'y' is NULL")
}
cov.shaq = function (x, y=NULL, use="everything", method="pearson")
{
covcor.check.y(y)
crossprod(scale(x, TRUE, FALSE)) / (nrow(x) - 1)
}
cor.shaq = function (x, y=NULL, use="everything", method="pearson")
{
covcor.check.y(y)
crossprod(scale(x, TRUE, TRUE)) / (nrow(x) - 1)
}
setMethod("cov", signature(x="shaq"), cov.shaq)
setMethod("cor", signature(x="shaq"), cor.shaq)
|
Component.Notification <- function(status = "info", context = "") {
return(fluidRow(
box(
width = 12,
closable = T,
enable_label = T,
label_text = "New",
label_status = "warning",
solidHeader = T,
status = status,
title = tagList(icon("bullhorn"), i18n$t("お知らせ")),
collapsible = T,
collapsed = T,
tags$small(context)
)
))
}
|
knitr::opts_chunk$set(comment = "
library(LPWC)
data(simdata)
simdata[1:5, ]
str(simdata)
timepoints <- c(0, 2, 4, 6, 8, 18, 24, 32, 48, 72)
timepoints
library(ggplot2)
set.seed(29876)
a <- rbind(c(rep(0, 5), 8, 0), c(rep(0, 4), 4.3, 0, 0)) + rnorm(2, 0, 0.5)
dat <- data.frame(intensity = as.vector(a), time = rep(c(0, 5, 15, 30, 45, 60, 75), each = 2), genes = factor(rep(c(1, 2), 7)))
a2 <- a
a2[1, ] <- c(a2[1, 2:7], NA)
dat2 <- data.frame(intensity = as.vector(a2), time = rep(c(0, 5, 15, 30, 45, 60, 75), each = 2), genes = factor(rep(c(1, 2), 7)))
a3 <- a
a3[2, ] <- c(NA, a3[2, 1:6])
a3[1, ] <- c(a3[1, 2:7], NA)
dat3 <- data.frame(intensity = as.vector(a3), time = rep(c(0, 5, 15, 30, 45, 60, 75), each = 2), genes = factor(rep(c(1, 2), 7)))
plot1 <- ggplot(dat, aes(x= time, y = intensity, group = genes)) + geom_line(aes(color = genes), size = 1.5) + labs(x = "Time (min)") + labs(y = "Intensity")
plot1
row1 <- c(0, 5, 15, 30, 45, 60, 75)
knitr::kable(t(data.frame(Original = row1, Gene1 = row1, Gene2 = row1)), align = 'c')
plot2 <- ggplot(dat2, aes(x= time, y = intensity, group = genes)) + geom_line(aes(color = genes), size = 1.5) +
labs(x = "Time (min)") + labs(y = "Intensity")
plot2
row2 <- c(5, 15, 30, 45, 60, 75, "-")
knitr::kable(t(data.frame(Original = row1, Gene1 = row2, Gene2 = row1)), align = 'c')
plot3 <- ggplot(dat3, aes(x= time, y = intensity, group = genes)) + geom_line(aes(color = genes), size = 1.5) +
labs(x = "Time (min)") + labs(y = "Intensity")
plot3
row3 <- c("-", 0, 5, 15, 30, 45, 60)
knitr::kable(t(data.frame(Original = row1, Gene1 = row2, Gene2 = row3)), align = 'c')
LPWC::corr.bestlag(simdata[49:58, ], timepoints = timepoints, max.lag = 2, penalty = "high", iter = 10)
dist <- 1 - LPWC::corr.bestlag(simdata[11:20, ], timepoints = timepoints, max.lag = 2, penalty = "low", iter = 10)$corr
plot(hclust(dist))
dist <- 1 - LPWC::corr.bestlag(simdata[11:20, ], timepoints = timepoints, max.lag = 2, penalty = "low", iter = 10)$corr
cutree(hclust(dist), k = 3)
sessionInfo()
|
plot.BayesMallows <- function(x, burnin = x$burnin, parameter = "alpha", items = NULL, ...){
if(is.null(burnin)){
stop("Please specify the burnin.")
}
if(x$nmc <= burnin) stop("burnin must be <= nmc")
stopifnot(parameter %in% c("alpha", "rho", "cluster_probs", "cluster_assignment", "theta"))
if(parameter == "alpha") {
df <- dplyr::filter(x$alpha, .data$iteration > burnin)
p <- ggplot2::ggplot(df, ggplot2::aes(x = .data$value)) +
ggplot2::geom_density() +
ggplot2::xlab(expression(alpha)) +
ggplot2::ylab("Posterior density")
if(x$n_clusters > 1){
p <- p + ggplot2::facet_wrap(~ .data$cluster, scales = "free_x")
}
return(p)
} else if(parameter == "rho") {
if(is.null(items) && x$n_items > 5){
message("Items not provided by user. Picking 5 at random.")
items <- sample.int(x$n_items, 5)
} else if (is.null(items) && x$n_items > 0) {
items <- seq.int(from = 1, to = x$n_items)
}
if(!is.character(items)){
items <- x$items[items]
}
df <- dplyr::filter(x$rho, .data$iteration > burnin, .data$item %in% items)
df <- dplyr::group_by(df, .data$cluster, .data$item, .data$value)
df <- dplyr::summarise(df, n = dplyr::n())
df <- dplyr::mutate(df, pct = .data$n / sum(.data$n))
p <- ggplot2::ggplot(df, ggplot2::aes(x = .data$value, y = .data$pct)) +
ggplot2::geom_col() +
ggplot2::scale_x_continuous(labels = scalefun) +
ggplot2::xlab("rank") +
ggplot2::ylab("Posterior probability")
if(x$n_clusters == 1){
p <- p + ggplot2::facet_wrap(~ .data$item)
} else {
p <- p + ggplot2::facet_wrap(~ .data$cluster + .data$item)
}
return(p)
} else if(parameter == "cluster_probs"){
df <- dplyr::filter(x$cluster_probs, .data$iteration > burnin)
ggplot2::ggplot(df, ggplot2::aes(x = .data$value)) +
ggplot2::geom_density() +
ggplot2::xlab(expression(tau[c])) +
ggplot2::ylab("Posterior density") +
ggplot2::facet_wrap(~ .data$cluster)
} else if(parameter == "cluster_assignment"){
if(is.null(x$cluster_assignment)){
stop("Please rerun compute_mallows with save_clus = TRUE")
}
df <- assign_cluster(x, burnin = burnin, soft = FALSE, expand = FALSE)
df <- dplyr::arrange(df, .data$map_cluster)
assessor_order <- dplyr::pull(df, .data$assessor)
df <- assign_cluster(x, burnin = burnin, soft = TRUE, expand = TRUE)
df <- dplyr::mutate(df, assessor = factor(.data$assessor, levels = assessor_order))
ggplot2::ggplot(df, ggplot2::aes(.data$assessor, .data$cluster)) +
ggplot2::geom_tile(ggplot2::aes(fill = .data$probability)) +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
axis.title.y = ggplot2::element_blank(),
axis.ticks.x = ggplot2::element_blank(),
axis.text.x = ggplot2::element_blank()
) +
ggplot2::xlab(paste0("Assessors (", min(assessor_order), " - ", max(assessor_order), ")"))
} else if(parameter == "theta") {
if(is.null(x$theta)){
stop("Please run compute_mallows with error_model = 'bernoulli'.")
}
df <- dplyr::filter(x$theta, .data$iteration > burnin)
p <- ggplot2::ggplot(df, ggplot2::aes(x = .data$value)) +
ggplot2::geom_density() +
ggplot2::xlab(expression(theta)) +
ggplot2::ylab("Posterior density")
return(p)
}
}
|
rotation_f = function(a) matrix(c(cos(a), sin(a), -sin(a), cos(a)), 2, 2)
|
design.rcbd <-
function (trt, r,serie=2,seed=0,kinds="Super-Duper",first=TRUE,continue=FALSE,randomization=TRUE )
{
number<-10
if(serie>0) number<-10^serie
ntr <- length(trt)
if (seed == 0) {
genera<-runif(1)
seed <-.Random.seed[3]
}
set.seed(seed,kinds)
parameters<-list(design="rcbd",trt=trt,r=r,serie=serie,seed=seed,kinds=kinds,randomization)
mtr <-trt
if(randomization)mtr <- sample(trt, ntr, replace = FALSE)
block <- c(rep(1, ntr))
for (y in 2:r) {
block <- c(block, rep(y, ntr))
if(randomization)mtr <- c(mtr, sample(trt, ntr, replace = FALSE))
}
if(randomization){
if(!first) mtr[1:ntr]<-trt
}
plots <- block*number+(1:ntr)
book <- data.frame(plots, block = as.factor(block), trt = as.factor(mtr))
names(book)[3] <- c(paste(deparse(substitute(trt))))
names(book)[3]<-c(paste(deparse(substitute(trt))))
if(continue){
start0<-10^serie
if(serie==0) start0<-0
book$plots<-start0+1:nrow(book)
}
outdesign<-list(parameters=parameters,sketch=matrix(book[,3], byrow = TRUE, ncol = ntr),book=book)
return(outdesign)
}
|
slurm_apply <- function(f, params, ..., jobname = NA, nodes = 2,
cpus_per_node = 2, processes_per_node = cpus_per_node,
preschedule_cores = TRUE, job_array_task_limit = NULL, global_objects = NULL,
add_objects = NULL, pkgs = rev(.packages()),
libPaths = NULL, rscript_path = NULL,
r_template = NULL, sh_template = NULL,
slurm_options = list(), submit = TRUE) {
if (!is.function(f)) {
stop("first argument to slurm_apply should be a function")
}
if (!is.data.frame(params)) {
stop("second argument to slurm_apply should be a data.frame")
}
if (is.null(names(params)) || (!is.primitive(f) && !"..." %in% names(formals(f)) && any(!names(params) %in% names(formals(f))))) {
stop("column names of params must match arguments of f")
}
if (!is.numeric(nodes) || length(nodes) != 1) {
stop("nodes should be a single number")
}
if (!is.numeric(cpus_per_node) || length(cpus_per_node) != 1) {
stop("cpus_per_node should be a single number")
}
if (!missing("add_objects")) {
warning("Argument add_objects is deprecated; use global_objects instead.", .call = FALSE)
global_objects <- add_objects
}
if(is.null(r_template)) {
r_template <- system.file("templates/slurm_run_R.txt", package = "rslurm")
}
if(is.null(sh_template)) {
sh_template <- system.file("templates/submit_sh.txt", package = "rslurm")
}
jobname <- make_jobname(jobname)
tmpdir <- paste0("_rslurm_", jobname)
dir.create(tmpdir, showWarnings = FALSE)
more_args <- list(...)
saveRDS(params, file = file.path(tmpdir, "params.RDS"))
saveRDS(f, file = file.path(tmpdir, "f.RDS"))
saveRDS(more_args, file = file.path(tmpdir, "more_args.RDS"))
if (!is.null(global_objects)) {
save(list = global_objects,
file = file.path(tmpdir, "add_objects.RData"),
envir = environment(f))
}
if (nrow(params) < cpus_per_node * nodes) {
nchunk <- cpus_per_node
} else {
nchunk <- ceiling(nrow(params) / nodes)
}
nodes <- ceiling(nrow(params) / nchunk)
template_r <- readLines(r_template)
script_r <- whisker::whisker.render(template_r,
list(pkgs = pkgs,
add_obj = !is.null(global_objects),
nchunk = nchunk,
cpus_per_node = cpus_per_node,
processes_per_node = processes_per_node,
preschedule_cores = preschedule_cores,
libPaths = libPaths))
writeLines(script_r, file.path(tmpdir, "slurm_run.R"))
template_sh <- readLines(sh_template)
slurm_options <- format_option_list(slurm_options)
if (is.null(rscript_path)){
rscript_path <- file.path(R.home("bin"), "Rscript")
}
script_sh <- whisker::whisker.render(template_sh,
list(max_node = nodes - 1,
job_array_task_limit = ifelse(is.null(job_array_task_limit), "", paste0("%", job_array_task_limit)),
cpus_per_node = cpus_per_node,
jobname = jobname,
flags = slurm_options$flags,
options = slurm_options$options,
rscript = rscript_path))
writeLines(script_sh, file.path(tmpdir, "submit.sh"))
if (submit && system('squeue', ignore.stdout = TRUE)) {
submit <- FALSE
cat("Cannot submit; no Slurm workload manager found\n")
}
if (submit) {
jobid <- submit_slurm_job(tmpdir)
} else {
jobid <- NA
cat(paste("Submission scripts output in directory", tmpdir,"\n"))
}
slurm_job(jobname, jobid, nodes)
}
|
context("assertions about row reduction functions in row-redux.R")
set.seed(1)
exmpl.data <- data.frame(x=c(8, 9, 6, 5, 9, 5, 6, 7, 8, 9, 6, 5, 5, 6, 7),
y=c(82, 91, 61, 49, 40, 49, 57, 74, 78, 90, 61, 49, 51, 62, 68))
nexmpl.data <- exmpl.data
nexmpl.data[12,2] <- NA
mnexmpl.data <- nexmpl.data
mnexmpl.data[12,1] <- NA
nanmnexmpl.data <- mnexmpl.data
nanmnexmpl.data[10,1] <- 0/0
manswers.mtcars <- c(8.95, 8.29, 8.94, 6.10, 5.43, 8.88, 9.14, 10.03, 22.59,
12.39, 11.06, 9.48, 5.59, 6.03, 11.20, 8.67, 12.26,
9.08, 14.95, 10.30, 13.43, 6.23, 5.79, 11.68, 6.72,
3.65, 18.36, 14.00, 21.57, 11.15, 19.19, 9.89)
manswers.iris <- c(2.28, 2.88, 2.13, 2.46, 2.58, 3.96, 2.89, 1.88, 3.39,
2.52, 3.50, 2.77, 2.79, 3.83, 9.84, 9.75, 5.78, 2.33,
4.52, 3.44, 2.68, 2.99, 3.93, 2.91, 5.41, 2.45, 1.98,
2.30, 2.68, 2.47, 1.99, 4.61, 8.88, 7.74, 1.99, 3.65,
5.82, 3.79, 3.16, 1.96, 2.57, 11.53, 3.32, 4.73, 4.91,
3.00, 4.48, 2.36, 3.18, 2.01, 5.33, 2.36, 5.27, 4.35,
4.13, 4.74, 4.68, 4.50, 3.40, 4.41, 7.72, 2.11, 7.61,
3.68, 1.11, 3.42, 6.60, 3.34, 9.97, 2.19, 10.77, 1.57,
6.08, 5.34, 1.97, 3.08, 5.69, 6.68, 2.82, 2.57, 2.82,
3.24, 0.92, 8.94, 9.72, 5.92, 3.74, 7.31, 2.28, 2.68,
5.85, 2.96, 1.50, 4.79, 2.38, 2.99, 1.92, 1.15, 5.17,
1.22, 10.22, 4.28, 2.66, 4.98, 2.35, 6.06, 13.52, 8.53,
4.57, 7.86, 3.99, 2.78, 2.96, 5.53, 11.47, 5.92, 3.99,
12.86, 8.03, 10.10, 4.04, 6.34, 8.83, 5.39, 3.16, 7.55,
5.32, 4.55, 1.81, 11.19, 6.56, 13.71, 2.55, 8.90, 17.55,
9.66, 8.37, 5.18, 5.09, 4.31, 6.04, 12.88, 4.28, 3.16,
7.83, 9.25, 6.20, 3.14, 7.68, 5.83)
manswers.exmpl <- c(1.28, 3.11, 0.25, 1.36, 12.82, 1.36, 0.26, 0.48, 0.88,
2.96, 0.25, 1.36, 1.29, 0.28, 0.06)
manswers.nexmpl <- c(1.17, 3.01, 0.23, 1.45, 12.04, 1.45, 0.31, 0.35, 0.83,
2.87, 0.23, NA, 1.34, 0.24, 0.04)
manswers.nexmpl.no.na <- manswers.nexmpl
manswers.nexmpl.no.na[12] <- 2.03
manswers.mnexmpl <- c(1.13, 2.91, 0.33, 1.62, 11.84, 1.62, 0.37, 0.40, 0.75,
2.76, 0.33, NA, 1.54, 0.36, 0.03)
manswers.mnexmpl.no.na <- manswers.mnexmpl
manswers.mnexmpl.no.na[12] <- 0
test_that("regular (non-robust) one works correctly", {
expect_equal(round(maha_dist(mtcars), 2), manswers.mtcars)
expect_equal(round(maha_dist(iris), 2), manswers.iris)
expect_equal(round(maha_dist(exmpl.data), 2), manswers.exmpl)
})
test_that("robust one works correctly", {
expect_equal(which.max(maha_dist(exmpl.data, robust=TRUE)), 5)
})
test_that("regular one works correctly with NAs", {
expect_equal(round(maha_dist(mtcars, keep.NA=FALSE), 2), manswers.mtcars)
expect_equal(round(maha_dist(nexmpl.data), 2), manswers.nexmpl)
expect_equal(round(maha_dist(nexmpl.data, keep.NA=FALSE), 2),
manswers.nexmpl.no.na)
expect_equal(round(maha_dist(mnexmpl.data), 2), manswers.mnexmpl)
expect_equal(round(maha_dist(mnexmpl.data, keep.NA=FALSE), 2),
manswers.mnexmpl.no.na)
})
test_that("maha_dist breaks like it is supposed to", {
expect_error(maha_dist(), "argument \"data\" is missing, with no default")
expect_error(maha_dist(lm(mpg ~ am, data=mtcars)),
"\"data\" must be a data.frame \\(or matrix\\)")
expect_error(maha_dist("William, it was really nothing"),
"\"data\" must be a data.frame \\(or matrix\\)")
expect_error(maha_dist(exmpl.data[,1, drop=FALSE]),
"\"data\" needs to have at least two columns")
expect_error(maha_dist(nexmpl.data, robust=TRUE),
"cannot use robust maha_dist with missing values")
})
test_that("num_row_NAs works correctly", {
expect_equal(num_row_NAs(iris), rep(0, 150))
expect_equal(num_row_NAs(exmpl.data), rep(0, 15))
expect_equal(num_row_NAs(nexmpl.data), c(rep(0, 11), 1, rep(0,3)))
expect_equal(num_row_NAs(mnexmpl.data), c(rep(0, 11), 2, rep(0,3)))
expect_equal(num_row_NAs(nanmnexmpl.data), c(rep(0, 11), 2, rep(0,3)))
expect_equal(num_row_NAs(nanmnexmpl.data, allow.NaN=TRUE),
c(rep(0, 9), 1, 0, 2, rep(0,3)))
})
test_that("num_row_NAs breaks correctly", {
expect_error(num_row_NAs(), "argument \"data\" is missing, with no default")
expect_error(num_row_NAs(exmpl.data[1,1]),
"\"data\" must be a data.frame \\(or matrix\\)")
})
this <- c("882")
names(this)[1] <- "1"
unname <- function(this){
names(this) <- NULL
this
}
test_that("col_concat works correctly", {
expect_equal(unname(col_concat(exmpl.data[1,])), "882")
expect_equal(unname(col_concat(head(exmpl.data))), c("882", "991", "661", "549", "940", "549"))
expect_equal(unname(col_concat(head(exmpl.data), sep="<>")), c("8<>82", "9<>91", "6<>61", "5<>49", "9<>40", "5<>49"))
expect_equal(unname(col_concat(tail(nexmpl.data))), c("990", "661", "5NA", "551", "662", "768"))
expect_equal(unname(col_concat(head(iris, n=2))), c("5.13.51.40.2setosa", "4.93.01.40.2setosa"))
})
test_that("col_concat breaks correctly", {
expect_error(col_concat(), "argument \"data\" is missing, with no default")
expect_error(col_concat(exmpl.data[1,1]),
"\"data\" must be a data.frame \\(or matrix\\)")
})
|
is.rapport <- function(x) inherits(x, 'rapport')
as.character.rapport.meta <- function(x, ...){
if (!inherits(x, 'rapport.meta'))
stop("Template metadata not provided.")
as.yaml(x)
}
as.character.rapport.inputs <- function(x, ...){
if (!inherits(x, 'rapport.inputs'))
stop("Template inputs not provided.")
as.yaml(x)
}
get.tags <- function(tag.type = c('all', 'header.open', 'header.close', 'comment.open', 'comment.close'), preset = c('user', 'default')){
t.type <- match.arg(tag.type)
t.preset <- match.arg(preset)
tag.default <- c(
header.open = '^<!--head$',
header.close = '^head-->$',
comment.open = '^<!--',
comment.close = '-->'
)
tag.default.names <- names(tag.default)
tag.current <- getOption('rapport.tags')
tag.current.names <- names(tag.current)
if (is.null(tag.current))
stop('Tag list does not exist.')
if (length(tag.default) != length(tag.current))
stop('Tag list incomplete.')
if (!all(sort(tag.default.names) == sort(tag.current.names))){
tgs <- paste(setdiff(tag.current.names, tag.default.names), collapse = ", ")
stopf('Tag list malformed!\nproblematic tags: %s', tgs)
}
res <- switch(t.preset,
user = {
if (t.type == 'all')
tag.current
else
tag.current[t.type]
},
default = {
tags.diff <- tag.current != tag.default
if (any(tags.diff)){
w <- paste(sprintf('`%s` set by user to:\t"%s"\t(default: "%s")\n', tag.current.names[tags.diff], tag.current[tags.diff], tag.default[tags.diff]), collapse = '')
warning(sprintf('Default tag values were changed!\n%s', w))
}
do.call(switch, c(EXPR = t.type, all = tag.default, tag.default))
},
stopf('Unknown preset option "%s"', t.preset)
)
return (res)
}
check.tpl <- function(txt, open.tag = get.tags('header.open'), close.tag = get.tags('header.close'), ...) {
hopen.ind <- grep(open.tag, txt, ...)[1]
hclose.ind <- grep(close.tag, txt, ...)[1]
if (!isTRUE(hopen.ind == 1L))
stop('Opening header tag not found in first line.')
if (is.na(hclose.ind))
stop('Closing header tag not found.')
if (hclose.ind - hopen.ind <= 1)
stop('Template header not found.')
h <- txt[(hopen.ind + 1):(hclose.ind - 1)]
if (all(trim.space(h) == ''))
stop('Template header is empty.')
b <- txt[(hclose.ind + 1):length(txt)]
if (hclose.ind == length(txt) || all(sapply(trim.space(b), function(x) x == '')))
stop('What good is a template if it has no body? http://bit.ly/11E5BQM')
}
rapport.ls <- function(...){
mc <- match.call()
if (is.null(mc$path))
mc$path <- c('./', getOption('rapport.paths'), system.file('templates', package = 'rapport'))
if (is.null(mc$pattern))
mc$pattern <- '^.+\\.rapport$'
mc[[1]] <- as.symbol('dir')
eval(mc)
}
tpl.list <- rapport.ls
rapport.path <- function()
getOption('rapport.path')
tpl.paths <- rapport.path
rapport.path.reset <- function()
options('rapport.path' = NULL)
tpl.paths.reset <- rapport.path.reset
rapport.path.add <- function(...) {
paths <- as.character(substitute(list(...)))[-1L]
if (!all(sapply(paths, is.character)))
stop('Wrong arguments (not characters) supplied!')
if (!all(file.exists(paths)))
stop('Specified paths do not exists on filesystem!')
options('rapport.path' = union(rapport.path(), paths))
invisible(TRUE)
}
tpl.paths.add <- rapport.path.add
rapport.path.remove <- function(...) {
paths <- as.character(substitute(list(...)))[-1L]
if (!all(sapply(paths, is.character)))
stop('Wrong arguments (not characters) supplied!')
if (!all(paths %in% rapport.path()))
warning('Specified paths were not added to custom paths list before!')
options('rapport.path' = setdiff(rapport.path(), paths))
invisible(TRUE)
}
tpl.paths.remove <- rapport.path.remove
|
getLinePosns <- function(axis.posns, endspace = 0.5)
{
endsonly <- FALSE
if (length(axis.posns) <= 2) endsonly <- TRUE
axis.posns <- sort(unique(axis.posns))
half.diffs <- diff(axis.posns)/2
if (endsonly)
line.posns <- c(axis.posns[1]-endspace,
axis.posns[2]+endspace)
else
line.posns <- c(axis.posns[1]-endspace,
axis.posns[1:(length(axis.posns)-1)] + half.diffs,
axis.posns[length(axis.posns)]+endspace)
return(line.posns)
}
"designGGPlot" <- function(design, labels = NULL, label.size = NULL,
row.factors = "Rows", column.factors = "Columns", scales.free = "free",
cellfillcolour.column=NULL, colour.values=NULL, cellalpha = 1,
celllinetype = "solid", celllinesize = 0.5, celllinecolour = "black",
cellheight = 1, cellwidth = 1,
reverse.x = FALSE, reverse.y = TRUE, x.axis.position = "top",
xlab, ylab, title, labeller = label_both,
title.size = 15, axis.text.size = 15,
blocksequence = FALSE, blockdefinition = NULL,
blocklinecolour = "blue", blocklinesize = 2,
printPlot = TRUE, ggplotFuncs = NULL, ...)
{
opts <- c("top", "bottom")
x.axis.position <- opts[check.arg.values(x.axis.position, opts)]
if (length(row.factors) == 1) {
grid.y <- row.factors
facet.y <- NULL
}
else
{
grid.y <- row.factors[length(row.factors)]
facet.y <- row.factors[-length(row.factors)]
if (reverse.y)
for (fac in facet.y)
design[fac] <- factor(design[[fac]], levels = rev(levels(design[[fac]])))
facet.y <- paste0("vars(", paste(facet.y, collapse = ","), ")")
}
if (length(column.factors) == 1) {
grid.x <- column.factors
facet.x <- NULL
}
else
{
grid.x <- column.factors[length(column.factors)]
facet.x <- column.factors[-length(column.factors)]
if (reverse.x)
for (fac in facet.x)
design[fac] <- factor(design[[fac]], levels = rev(levels(design[[fac]])))
facet.x <- paste0("vars(", paste(facet.x, collapse = ","), ")")
}
if (missing(xlab)) xlab <- grid.x
if (missing(ylab)) ylab <- grid.y
if (missing(title)) title <- paste("Plot of",labels,sep = " ")
plt <- ggplot(data = design, aes_string(x = grid.x, y = grid.y)) +
labs(x = xlab, y = ylab, title = title) +
theme(panel.background = element_blank(),
legend.position = "none",
title = element_text(size = title.size, face = "bold"),
axis.text = element_text(size = axis.text.size, face = "bold"),
strip.background = element_blank(),
strip.text = element_text(size=title.size, face="bold"))
if (!(is.null(colour.values)))
plt <- plt + scale_fill_manual(values = colour.values)
if (is.null(labels) && is.null(cellfillcolour.column))
stop("At least one of labels and cellfillcolour.column must be set")
if (is.null((cellfillcolour.column)))
plt <- plt + geom_tile(aes_string(fill = labels),
colour = celllinecolour, alpha = cellalpha,
linetype = celllinetype, size = celllinesize,
height = cellheight, width = cellwidth)
else
plt <- plt + geom_tile(aes_string(fill = cellfillcolour.column),
colour = celllinecolour, alpha = cellalpha,
linetype = celllinetype, size = celllinesize,
height = cellheight, width = cellwidth)
if (!is.null(labels))
{
if (!is.null(label.size))
plt <- plt + geom_text(aes_string(label = labels), size = label.size,
fontface = "bold", ...)
else
plt <- plt + geom_text(aes_string(label = labels), fontface = "bold", ...)
}
if (inherits(design[[grid.y]], what = "factor"))
{
nrows <- length(levels(design[[grid.y]]))
if (reverse.y)
plt <- plt + scale_y_discrete(limits = rev, expand = c(0,0))
else
plt <- plt + scale_y_discrete(expand = c(0,0))
}
else
{
rows <- sort(unique(design[[grid.y]]))
nrows <- length(rows)
row.posns <- getLinePosns(rows)
if (reverse.y)
plt <- plt + scale_y_reverse(limits = c(row.posns[c(1,length(row.posns))]),
expand = c(0,0))
else
plt <- plt + scale_y_continuous(limits = c(row.posns[c(1,length(row.posns))]),
expand = c(0,0))
}
if (inherits(design[[grid.x]], what = "factor"))
{
ncolumns <- length(levels(design[[grid.x]]))
if (reverse.x)
plt <- plt + scale_x_discrete(limits = rev, expand = c(0,0), position = x.axis.position)
else
plt <- plt + scale_x_discrete(expand = c(0,0), position = x.axis.position)
}
else
{
columns <- sort(unique(design[[grid.x]]))
ncolumns <- length(columns)
col.posns <- getLinePosns(columns)
if (reverse.x)
plt <- plt + scale_x_reverse(limits = c(col.posns[c(1,length(col.posns))]),
expand = c(0,0), position = x.axis.position)
else
plt <- plt + scale_x_continuous(limits = c(col.posns[c(1,length(col.posns))]),
expand = c(0,0), position = x.axis.position)
}
if (!is.null(facet.x))
{
if (!is.null(facet.y))
plt <- plt + facet_grid(rows = eval(parse(text=facet.y)),
cols = eval(parse(text=facet.x)),
labeller = labeller, scales = scales.free, as.table = FALSE)
else
plt <- plt + facet_grid(cols = eval(parse(text=facet.x)),
labeller = labeller, scales = scales.free, as.table = FALSE)
} else
{
if (!is.null(facet.y))
plt <- plt + facet_grid(rows = eval(parse(text=facet.y)),
labeller = labeller, scales = scales.free, as.table = FALSE)
}
if (!is.null(ggplotFuncs))
{
for (f in ggplotFuncs)
plt <- plt + f
}
if (!is.null(blockdefinition))
plt <- designBlocksGGPlot(plt, nrows = nrows, ncolumns = ncolumns,
blocksequence = blocksequence, blockdefinition = blockdefinition,
blocklinecolour = blocklinecolour, blocklinesize = blocklinesize,
printPlot = printPlot)
else
{
if (printPlot)
print(plt)
invisible(plt)
}
}
"plotarectangle" <- function(plt, xi,yi,xoff,yoff,nrows,ncolumns,nri,nci,blocklinesize,blocklinecolour)
{
ncimod <- nci
nrimod <- nri
if (xoff + nci > ncolumns)
{
ncimod <- ncolumns - xoff
}
if (yoff + nri > nrows)
{
nrimod <- nrows - yoff
}
lines.dat <- data.frame(x = xi + xoff + c(1, 1, ncimod, ncimod, 1),
y = yi + yoff + c(nrimod, 1, 1, nrimod, nrimod))
plt <- plt + geom_path(data = lines.dat, mapping = aes_string(x="x",y="y"),
colour = blocklinecolour, size = blocklinesize)
invisible(plt)
}
"designBlocksGGPlot" <- function(ggplot.obj, blockdefinition = NULL, blocksequence = FALSE,
originrow = 0, origincolumn = 0, nrows, ncolumns,
blocklinecolour = "blue", blocklinesize = 2, printPlot = TRUE)
{
if (!is.null(blockdefinition))
{
rstart <- originrow
cstart <- origincolumn
dims <- dim(blockdefinition)
xi <- c(-0.5, -0.5, 0.5, 0.5, -0.5)
yi <- c(0.5, -0.5, -0.5, 0.5, 0.5)
if (!blocksequence)
{
for (i in seq(dims[1]))
{
nri <- blockdefinition[i, 1]
nci <- blockdefinition[i, 2]
for (j in seq(ceiling((nrows - rstart)/nri)))
{
for (k in seq(ceiling((ncolumns - cstart)/nci)))
{
xoff <- nci * (k - 1) + cstart
yoff <- nri * (j - 1) + rstart
ggplot.obj <- plotarectangle(ggplot.obj, xi, yi, xoff, yoff,
nrows, ncolumns, nri, nci,
blocklinesize, blocklinecolour)
}
}
}
}
else
{
if (dims[1] > 1)
{
yoff <- rstart
for (k in seq(dims[1])) {
if (dims[2] > 2)
{
xoff <- cstart
nri <- blockdefinition[k, 1]
for (i in seq(2,dims[2])) {
nci <- blockdefinition[k, i]
ggplot.obj <- plotarectangle(ggplot.obj, xi, yi, xoff, yoff,
nrows, ncolumns, nri, nci,
blocklinesize, blocklinecolour)
xoff <- xoff + nci
}
}
else
{
nri <- blockdefinition[k, 1]
nci <- blockdefinition[k, 2]
for (j in seq(ceiling((ncolumns - cstart)/nci)))
{
xoff <- nci * (j - 1) + cstart
ggplot.obj <- plotarectangle(ggplot.obj, xi, yi, xoff, yoff,
nrows, ncolumns, nri, nci,
blocklinesize, blocklinecolour)
}
}
yoff <- yoff + nri
}
}
else
{
if (dims[2] > 2)
{
xoff <- cstart
nri <- blockdefinition[1, 1]
for (i in seq(2,dims[2]))
{
nci <- blockdefinition[1, i]
for (j in seq(ceiling(nrows/nri - rstart)))
{
yoff <- nri * (j - 1) + rstart
ggplot.obj <- plotarectangle(ggplot.obj, xi, yi, xoff, yoff,
nrows, ncolumns, nri, nci,
blocklinesize, blocklinecolour)
}
xoff <- xoff + nci
}
}
else
{
nri <- blockdefinition[1, 1]
nci <- blockdefinition[1, 2]
for (j in seq(ceiling((nrows - rstart)/nri)))
{
for (k in seq(ceiling((ncolumns - cstart)/nci)))
{
xoff <- nci * (k - 1) + cstart
yoff <- nri * (j - 1) + rstart
ggplot.obj <- plotarectangle(ggplot.obj, xi, yi, xoff, yoff,
nrows, ncolumns, nri, nci,
blocklinesize, blocklinecolour)
}
}
}
}
}
}
if (printPlot)
print(ggplot.obj)
invisible(ggplot.obj)
invisible(ggplot.obj)
}
|
"RSlo" <- function(x, r, n=length(x)) {
y <- sort(x)
( y[r] - mean(y[(r+1):(n-r)]) ) / sqrt( var(y[(r+1):(n-r)]) )
}
|
makeQuantileSurfaces <- function(probabilitySurface, rename = FALSE){
p <- probabilitySurface
f <- stats::ecdf(stats::na.omit(probabilitySurface[]))
quantile_surface <- p
quantile_surface[] <- f(p[])
if(rename == FALSE){
names(quantile_surface) <- names(p)
} else {
if(class(rename) != "character")
stop("argument 'rename' should be of character class.")
names(quantile_surface) <- paste0(names(p), rename)
}
return(quantile_surface)
}
|
clean.retrieval <- function(x, gunzip = TRUE) {
if (any(!file.exists(x)))
stop("Some of the meta.retrieval() output files seem not to exist. Please provide valid file paths to meta.retrieval() output files.", call. = FALSE)
if (gunzip)
message("Cleaning file names and unzipping files ...")
if (!gunzip)
message("Cleaning file names ...")
folder_files <- list.files(dirname(x)[1])
if (length(folder_files) == 0)
stop("Unfortunately, your specified folder '", x, "' does not include any files.", call. = FALSE)
file_ext <- "[.]*a$"
if (any(stringr::str_detect(folder_files, "[.]faa.gz$"))) {
seq_type <- "ncbi_protein"
file_ext <- "[.]faa$"
}
if (any(stringr::str_detect(folder_files, "[.]fna.gz$"))) {
seq_type <- "ncbi_nucleotide"
file_ext <- "[.]fna$"
}
if (any(stringr::str_detect(folder_files, "[.]gff.gz$"))) {
seq_type <- "ncbi_gff"
file_ext <- "[.]gff$"
}
if (any(stringr::str_detect(folder_files, "[.]out.gz$"))) {
seq_type <- "ncbi_rm"
file_ext <- "[.]out$"
}
if (any(stringr::str_detect(folder_files, "[.]gff3.gz$"))) {
seq_type <- "ensembl_gff3"
file_ext <- "[.]gff3$"
}
if (any(stringr::str_detect(folder_files, "[.]gtf.gz$"))) {
seq_type <- "ensembl_gtf"
file_ext <- "[.]gtf$"
}
if (any(stringr::str_detect(folder_files, "[.]fa.gz$"))) {
seq_type <- "ensembl_fasta"
file_ext <- "[.]fa$"
}
find_doc <- which(stringr::str_detect(folder_files, "doc_"))
find_md5 <- which(stringr::str_detect(folder_files, "md5checksum"))
find_documentaion <- which(stringr::str_detect(folder_files, "documentation"))
find_unzipped_files <- which(stringr::str_detect(folder_files, file_ext))
if (length(c(find_doc, find_md5, find_documentaion, find_unzipped_files)) > 0) {
folder_files_reduced <- folder_files[-c(find_doc, find_md5, find_documentaion, find_unzipped_files)]
}
if (length(folder_files_reduced) == 0) {
message("It seems that nothing needs to be done. All files are unzipped.")
return(file.path(x, folder_files[-c(find_doc, find_md5, find_documentaion)]))
} else {
input_files <- folder_files_reduced
}
input_files_without_appendix <- unlist(lapply(input_files, function(x) return(unlist(stringr::str_split(x, "[.]"))[1])))
file_ext <- stringr::str_replace(file_ext, "\\$", "")
file_ext <- stringr::str_replace(file_ext, "\\[.]", "")
if (gunzip)
output_files <- paste0(tidy_name(input_files_without_appendix), ".", file_ext)
if (!gunzip)
output_files <- paste0(tidy_name(input_files_without_appendix),".",file_ext,".gz")
if (!all(file.exists(file.path(dirname(x)[1], input_files))))
stop("Something went wrong during the cleaning process. Some input files seem not to exist.", call. = FALSE)
if (gunzip) {
for (i in seq_len(length(input_files))) {
if (file.exists(file.path(dirname(x)[1], input_files[i]))) {
message("Unzipping file ", input_files[i],"' ...")
R.utils::gunzip(file.path(dirname(x)[1], input_files[i]), destname = file.path(dirname(x)[1], output_files[i]))
}
}
}
message("Finished formatting.")
return(file.path(dirname(x)[1], output_files))
}
|
if(getRversion() >= "2.15.1") utils::globalVariables(c("config"))
NULL
|
rinvgamma<-function (n, shape, scale = 1)
{
return(1/rgamma(n, shape, scale))
}
|
print.CopyDetectMany<- function(x, ...){
cat("************************************************************************","\n")
cat("CopyDetect - An R Package to Compute Response Similarity Indices for Multiple-Choice Tests","\n")
cat("","\n")
cat("Version 1.3, released on October 2018","\n")
cat("","\n")
cat("Cengiz Zopluoglu","\n")
cat("","\n")
cat("Assistant Professor","\n")
cat("University of Miami - Department of Educational and Psychological Studies","\n")
cat("Research, Measurement, and Evaluation Program","\n")
cat("","\n")
cat("[email protected]","\n")
cat("*************************************************************************","\n")
cat("","\n")
cat("Processing Date: ",date(),"\n")
cat("","\n")
cat(" Probability Values Obtained from Various Response Similarity Indices \n")
cat("","\n")
x$output.manypairs[,5:12] <- round(x$output.manypairs[,5:12],3)
print(x$output.manypairs[,c(1,2,5:12)])
}
|
"ICAapp"
|
get.oc <- function (target, p.true, ncohort, cohortsize, n.earlystop = 100,
startdose = 1, titration = FALSE, p.saf = 0.6 * target, p.tox = 1.4 *
target, cutoff.eli = 0.95, extrasafe = FALSE, offset = 0.05,boundMTD=FALSE,
ntrial = 1000, seed = 6)
{
if (target < 0.05) {
stop("the target is too low!")
}
if (target > 0.6) {
stop("the target is too high!")
}
if ((target - p.saf) < (0.1 * target)) {
stop("the probability deemed safe cannot be higher than or too close to the target!")
}
if ((p.tox - target) < (0.1 * target)) {
stop("the probability deemed toxic cannot be lower than or too close to the target!")
}
if (offset >= 0.5) {
stop("the offset is too large!")
}
if (n.earlystop <= 6) {
warning("the value of n.earlystop is too low to ensure good operating characteristics. Recommend n.earlystop = 9 to 18.")
}
set.seed(seed)
if (cohortsize == 1)
titration = FALSE
lambda_e = log((1 - p.saf)/(1 - target))/log(target * (1 -
p.saf)/(p.saf * (1 - target)))
lambda_d = log((1 - target)/(1 - p.tox))/log(p.tox * (1 -
target)/(target * (1 - p.tox)))
ndose = length(p.true)
npts = ncohort * cohortsize
Y = matrix(rep(0, ndose * ntrial), ncol = ndose)
N = matrix(rep(0, ndose * ntrial), ncol = ndose)
dselect = rep(0, ntrial)
if (cohortsize > 1) {
temp = get.boundary(target, ncohort, cohortsize, n.earlystop=ncohort*cohortsize,
p.saf, p.tox, cutoff.eli, extrasafe)$full_boundary_tab
}
else {
temp = get.boundary(target, ncohort, cohortsize, n.earlystop=ncohort*cohortsize,
p.saf, p.tox, cutoff.eli, extrasafe)$boundary_tab
}
b.e = temp[2, ]
b.d = temp[3, ]
b.elim = temp[4, ]
for (trial in 1:ntrial) {
y <- rep(0, ndose)
n <- rep(0, ndose)
earlystop = 0
d = startdose
elimi = rep(0, ndose)
ft=TRUE
if (titration) {
z <- (runif(ndose) < p.true)
if (sum(z) == 0) {
d = ndose
n[1:ndose] = 1
}
else {
d = which(z == 1)[1]
n[1:d] = 1
y[d] = 1
}
}
for (i in 1:ncohort) {
if (titration && n[d] < cohortsize && ft){
ft=FALSE
y[d] = y[d] + sum(runif(cohortsize - 1) < p.true[d])
n[d] = n[d] + cohortsize - 1
}
else {
newcohort = runif(cohortsize)<p.true[d];
if((sum(n)+cohortsize) >= npts){
nremain = npts - sum(n);
y[d] = y[d] + sum(newcohort[1:nremain]);
n[d] = n[d] + nremain;
break;
}
else{
y[d] = y[d] + sum(newcohort);
n[d] = n[d] + cohortsize;
}
}
if (!is.na(b.elim[n[d]])) {
if (y[d] >= b.elim[n[d]]) {
elimi[d:ndose] = 1
if (d == 1) {
earlystop = 1
break
}
}
if (extrasafe) {
if (d == 1 && n[1] >= 3) {
if (1 - pbeta(target, y[1] + 1, n[1] - y[1] +
1) > cutoff.eli - offset) {
earlystop = 1
break
}
}
}
}
if(n[d]>=n.earlystop &&
(
(y[d]>b.e[n[d]] && y[d]<b.d[n[d]])||
(d==1 && y[d]>=b.d[n[d]]) ||
((d==ndose||elimi[d+1]==1) && y[d]<=b.e[n[d]])
)
) break;
if (y[d] <= b.e[n[d]] && d != ndose) {
if (elimi[d + 1] == 0)
d = d + 1
}
else if (y[d] >= b.d[n[d]] && d != 1) {
d = d - 1
}
else {
d = d
}
}
Y[trial, ] = y
N[trial, ] = n
if (earlystop == 1) {
dselect[trial] = 99
}
else {
dselect[trial] = select.mtd(target, n, y, cutoff.eli,
extrasafe, offset, boundMTD = boundMTD, p.tox=p.tox)$MTD
}
}
selpercent = rep(0, ndose)
nptsdose = apply(N, 2, mean)
ntoxdose = apply(Y, 2, mean)
for (i in 1:ndose) {
selpercent[i] = sum(dselect == i)/ntrial * 100
}
if (length(which(p.true == target)) > 0) {
if (which(p.true == target) == ndose - 1) {
overdosing60 = mean(N[, p.true > target] > 0.6 *
npts) * 100
overdosing80 = mean(N[, p.true > target] > 0.8 *
npts) * 100
}
else {
overdosing60 = mean(rowSums(N[, p.true > target]) >
0.6 * npts) * 100
overdosing80 = mean(rowSums(N[, p.true > target]) >
0.8 * npts) * 100
}
out = list(selpercent = selpercent, npatients = nptsdose,
ntox = ntoxdose, totaltox = sum(Y)/ntrial, totaln = sum(N)/ntrial,
percentstop = sum(dselect == 99)/ntrial * 100, overdose60 = overdosing60,
overdose80 = overdosing80, simu.setup = data.frame(target = target,
p.true = p.true, ncohort = ncohort, cohortsize = cohortsize,
startdose = startdose, p.saf = p.saf, p.tox = p.tox,
cutoff.eli = cutoff.eli, extrasafe = extrasafe,
offset = offset, ntrial = ntrial, dose = 1:ndose),
flowchart = TRUE, lambda_e = lambda_e, lambda_d = lambda_d)
}
else {
out = list(selpercent = selpercent, npatients = nptsdose,
ntox = ntoxdose, totaltox = sum(Y)/ntrial, totaln = sum(N)/ntrial,
percentstop = sum(dselect == 99)/ntrial * 100, simu.setup = data.frame(target = target,
p.true = p.true, ncohort = ncohort, cohortsize = cohortsize,
startdose = startdose, p.saf = p.saf, p.tox = p.tox,
cutoff.eli = cutoff.eli, extrasafe = extrasafe,
offset = offset, ntrial = ntrial, dose = 1:ndose),
flowchart = TRUE, lambda_e = lambda_e, lambda_d = lambda_d)
}
class(out)<-"boin"
return(out)
}
|
getOAuth <- function(x, verbose=TRUE){
if (class(x)[1]=="list"){
options("httr_oauth_cache"=FALSE)
app <- httr::oauth_app("twitter", key = x$consumer_key,
secret = x$consumer_secret)
credentials <- list(oauth_token = x$access_token,
oauth_token_secret = x$access_token_secret)
my_oauth <- httr::Token1.0$new(endpoint = httr::oauth_endpoints("twitter"),
params = list(as_header = TRUE),
app = app, credentials = credentials)
}
if (class(x)[1]=="OAuth"){
options("httr_oauth_cache"=FALSE)
app <- httr::oauth_app("twitter", key = x$consumerKey,
secret = x$consumerSecret)
credentials <- list(oauth_token = x$oauth_token,
oauth_token_secret = x$oauth_token_secret)
my_oauth <- httr::Token1.0$new(endpoint = httr::oauth_endpoints("twitter"),
params = list(as_header = TRUE),
app = app, credentials = credentials)
}
if (class(x)[1]=="Token1.0"){ my_oauth <- x }
if (class(x)[1] %in% c("list", "OAuth", "Token1.0") == FALSE && file.exists(x)){
info <- file.info(x)
if (info$isdir){
creds <- list.files(x, full.names=TRUE)
cr <- sample(creds, 1)
if (verbose){message(cr)}
load(cr)
my_oauth <- getOAuth(my_oauth)
}
if (!info$isdir){
if (!grepl("csv", x)){
if (verbose){message(x)}
load(x)
my_oauth <- getOAuth(my_oauth)
}
if (grepl("csv", x)){
d <- read.csv(x, stringsAsFactors=F)
creds <- d[sample(1:nrow(d),1),]
options("httr_oauth_cache"=FALSE)
app <- httr::oauth_app("twitter", key = creds$consumer_key,
secret = creds$consumer_secret)
credentials <- list(oauth_token = creds$access_token,
oauth_token_secret = creds$access_token_secret)
my_oauth <- httr::Token1.0$new(endpoint = httr::oauth_endpoints("twitter"),
params = list(as_header = TRUE),
app = app, credentials = credentials)
}
}
}
return(my_oauth)
}
getLimitFriends <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "friends,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$friends$`/friends/ids`$remaining)
}
getLimitRate <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "followers,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$application$`/application/rate_limit_status`$remaining)
}
getLimitFollowers <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "followers,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$followers$`/followers/ids`$remaining)
}
getLimitUsers <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "users,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$users$`/users/lookup`$remaining)
}
getLimitSearch <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "search")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$search$`/search/tweets`$remaining)
}
getLimitList <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "lists,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$lists$`/lists/members`$remaining)
}
getLimitRetweets <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "statuses,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$statuses$`/statuses/retweeters/ids`$remaining)
}
getLimitStatuses <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "statuses,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$statuses$`/statuses/lookup`$remaining)
}
getLimitTimeline <- function(my_oauth){
url <- "https://api.twitter.com/1.1/application/rate_limit_status.json"
params <- list(resources = "statuses,application")
query <- lapply(params, function(x) URLencode(as.character(x)))
url.data <- httr::GET(url, query=query, httr::config(token=my_oauth))
json.data <- httr::content(url.data)
return(json.data$resources$statuses$`/statuses/user_timeline`$remaining)
}
|
utils::globalVariables(c("Result"))
read.pgn <- function(con,add.tags = NULL,n.moves = T, extract.moves = 10,last.move = T,stat.moves = T,big.mode = F,quiet = F,ignore.other.games = F,source.movetext = F){
st <- Sys.time()
tags <- c(c("Event","Site","Date","Round","White","Black","Result"),add.tags)
if(big.mode) al = con
else{
al = readLines(con)
if("connection" %in% class(con)) close(con)
}
s <- "^\\[([\\S]+)\\s\"([\\S\\s]+|\\B)\"\\]$"
tmp1 <- gsub(s,"\\1",al,perl = T)
tmp2 <- gsub(s,"\\2",al, perl = T)
tmp3 <- grepl("^\\[[^%]+\\]$",al,perl = T)
tmp4 <- cumsum(grepl("\\[Event ",al))
tmp1[!tmp3] <- "Movetext"
r2 <- data.frame(tmp1,tmp2,tmp3,tmp4,stringsAsFactors = F)
gt <- paste(subset(r2,tmp1=="Movetext",select = c(tmp2))[,1],collapse = " ")
if(source.movetext) gt2 <- gt
gt <- gsub("{[^}]+}","",gt,perl = T)
gt <- gsub("\\((?>[^()]|(?R))*\\)","",gt,perl = T)
gt <- gsub("[\\?\\!]","",gt,perl = T)
gt <- gsub("[0-9]+\\.\\.\\.","",gt,perl = T)
gt <- gsub("\\$[0-9]+","",gt,perl = T)
for(i in c("1-0","1\\/2-1\\/2","0-1","\\*"))
gt <- unlist(strsplit(gt,split = i))
if(source.movetext) for(i in c("1-0","1\\/2-1\\/2","0-1","\\*")) gt2 <- unlist(strsplit(gt2,split = i))
r <- subset(r2,tmp1 == "Event",select = c(tmp4,tmp2))
colnames(r) <- c("GID","Event")
for(i in c(setdiff(tags,"Event"))){
tmp <- subset(r2,tmp1 == i,select = c(tmp4,tmp2))
colnames(tmp) <- c("GID",i)
r <- merge(r,tmp,all.x = T)
}
r$Movetext <- trimws(gsub("[[:space:]]+"," ",head(gt,nrow(r))))
if(source.movetext) r$SourceMovetext <- head(gt2,nrow(r))
tal <- tail(al,1)
if(big.mode) if(!grepl("\\[",tal)&!(tal=="")) {
r[nrow(r),"Movetext"] <- ""
}
if(big.mode) if(r[nrow(r),"Movetext"]=="") r <- r[-nrow(r),]
if(!quiet) message(paste0(Sys.time(),", successfully imported ",nrow(r)," games"))
if(n.moves||extract.moves)
r$NMoves <- n_moves(r$Movetext)
if(!quiet) message(paste0(Sys.time(),", N moves computed"))
if(extract.moves){
if(extract.moves==-1) {N <- max(r$NMoves)}
else {N <- extract.moves}
r <- cbind(r,extract_moves(r$Movetext,N,last.move = last.move))
if(!quiet) message(paste0(Sys.time(),", extract moves done")) }
if(stat.moves) {
r <- cbind(r,stat_moves(r$Movetext))
if(!quiet) message(paste0(Sys.time(),", stat moves computed"))
}
if(ignore.other.games)
{
nr <- nrow(r)
r <- subset(r,Result!="*")
r$Result <- factor(r$Result,levels = c("1-0","1/2-1/2","0-1"),labels=c("1-0","1/2-1/2","0-1"),ordered = T)
if(!quiet) message(paste0(Sys.time(),", subset done (",nr-nrow(r)," games with Result '*' removed) "))
}
else{
r$Result <- factor(r$Result,levels = c("1-0","1/2-1/2","0-1","*"),labels=c("1-0","1/2-1/2","0-1","*"),ordered = T)
}
r <- droplevels(r)
for(i in intersect(colnames(r),c("WhiteElo","BlackElo","SetUp")))
r[,i] <- as.integer(r[,i])
return(r[,-1])
}
|
R2 <- function(x, y){
if(length(x)!=length(y)){stop("r.sq measure: length of x must equal length of y")}
xh <- x-mean(x)
yh <- y-mean(y)
num <- sum(xh*yh)^2
den <- sum(xh^2)*sum(yh^2)
R2 <- num/den
return(R2)
}
cap1 <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s,1,1)), substring(s, 2),
sep="", collapse=" ")
}
pcdfs <- function(dof, order=6, ndecimals=3, dist='normal', par1=0, par2=1){
if(order>=7){stop(paste("order is too large (10M) -- calculation time too long. Make order<7. Fractions OK."))}
N=round(10^order,0)
bw=1/10^ndecimals
dN = dof*N
rnums <- rep(0,dN)
R2c <- rep(0,N)
if( dist=="normal") { rnums <- rnorm( n=dN, mean=par1, sd=par2)
} else if( dist=="uniform") { rnums <- runif( n=dN, min=par1, max=par2)
} else if( dist=="lognormal") { rnums <- rlnorm(n=dN, meanlog=par1, sdlog=par2)
} else if( dist=="poisson") { rnums <- rpois( n=dN, lambda=par1)
} else if( dist=="binomial") { rnums <- rbinom(n=dN, size=par1, prob=par2)}
x <- seq(1,dof)
xb <- mean(x)
xd <- x-xb
xd <- t(matrix(rep(xd, N), nrow=dof, ncol=N))
e <- matrix(rnums, nrow=N, ncol=dof)
eb <- rowSums(e)/dof
ed <- e-eb
n1 = xd*ed
n1s = rowSums(n1)
num = n1s*n1s
d1 = xd^2
d2 = ed^2
d1s = rowSums(d1)
d2s = rowSums(d2)
den = d1s*d2s
R2c = num/den
br = seq(0, 1, by=bw)
R2 = br[2:length(br)]
R2h = hist(R2c, breaks=br, plot=F)
pdf <- R2h$counts/sum(R2h$counts)
cdf <- cumsum(pdf)
R2df <- data.frame(R2, pdf, cdf)
return(R2df)
}
R2p <- function(dof, pct=0.95, ndecimals=3,...){
cdf <- pcdfs(dof, ndecimals=ndecimals,...)[,c(1,3)]
R2p <- cdf$R2[cdf[,2]>=pct][1]
R2p <- R2p + rnorm(1)*10^(-(ndecimals+2))
R2p <- round(R2p,ndecimals)
return(R2p)
}
R2k <- function(R2, dof, pct=0.95, ndecimals=3,...){
r2p <- R2p(dof=dof, pct=pct, ndecimals=ndecimals,...)
r2k <- (R2-r2p)/(1-r2p + 0.00000000001)
fl <- floor(r2p)
nd=rep(0,length(R2))
if(r2p-fl>0){
nd <- nchar(sapply(strsplit(as.character(r2p), ".",fixed=T), "[[", 2))}
r2k <- round(r2k, ndecimals)
return(r2k)
}
R2pTable <- function(doflist=NULL, pctlist=NULL, order=4, ndecimals=2,...){
if(is.null(doflist)){doflist=c(4,8,16,32,64,128)}
if(is.null(pctlist)){pctlist=c(0.7,0.9,0.95,0.99)}
nds <- length(doflist)
nps <- length(pctlist)
rownams = as.character(doflist)
colnams = as.character(pctlist)
shell <- matrix(nrow=nds, ncol=nps)
r2ptab <- matrix(mapply(function(x,i,j) R2p(doflist[i],pctlist[j], order=order, ndecimals=ndecimals,...), shell,row(shell),col(shell)), nrow=nds, ncol=nps)
r2ptab <- as.data.frame(r2ptab)
colnames(r2ptab) <- colnams
rownames(r2ptab) <- rownams
return(r2ptab)
}
plotpdf <- function(dof, order=4, dist='normal',...){
df <- pcdfs(dof=dof,order=order,dist=dist,...)
N = 10^order
dist2 <- sapply(dist, cap1)
mxy = max(df$pdf)
plot <- ggplot(df) +
geom_point(aes(R2, pdf),size=1) +
ggtitle(paste("Probability Density Function")) +
ylim(0,mxy) +
xlab(expression(R^2)) +
ylab("Probability Density") +
ggtitle(paste("Probability Density Function")) +
geom_text(aes(x=0.95,y=0.9*mxy,label=paste("Noise Distribution:",dist2,
"\nDegrees of Freedom:",dof,
"\nNumber of Samples:",floor(N))),size=3,hjust=1)
return(plot)
}
plotcdf <- function(dof, order=4, dist='normal',...){
r2cdf <- pcdfs(dof=dof,order=order,dist=dist,...)
cdf <- NULL
N = 10^order
dist2 <- sapply(dist, cap1)
mxy <- max(r2cdf$cdf)
plot <- ggplot(r2cdf) +
geom_point(aes(R2, cdf),size=1) +
ylim(0,mxy) +
xlab(expression(R^2)) +
ylab("Cumulative Probability") +
ggtitle(paste("Cumulative Probability Density Function")) +
geom_text(aes(x=0.95,y=0.3*mxy,label=paste("Noise Distribution:",dist2,
"\nDegrees of Freedom:",dof,
"\nNumber of Samples:",floor(N))),size=3,hjust=1)
return(plot)
}
plotR2p <- function(doflist=c(2:30), pctlist=c(0.95), order=4, ndecimals=3, ...){
if(length(pctlist)>5){stop(paste("Too many percentiles to calculate", length(pctlist)))}
doflist <- doflist[doflist>1]
doflim <- min(30, length(doflist))
doflist <- doflist[1:doflim]
pctlim <- min(5,length(pctlist))
pctlist <- pctlist[1:pctlim]
pctlist <- formatC(as.numeric(pctlist),width=(ndecimals+1),format='f',digits=ndecimals,flag='0')
doflength <- length(doflist)
pctlength <- length(pctlist)
mcolor <- c("black", "blue", "red", "green", "darkgreen")
sizes <- c(3.6, 3.2, 2.8, 2.4, 2.0)/2
r2pdf <- R2pTable(doflist=doflist, pctlist=pctlist, order=order,...)
mxy <- 0.9*max(r2pdf[,1])
N = 10^order
plt <- ggplot(r2pdf)
if(pctlength>=1){plt <- plt +
geom_point(aes(as.numeric(row.names(r2pdf)), r2pdf[,1]), color=mcolor[1], size=sizes[1]) +
geom_text(aes(x=max(doflist), y=mxy-0.00, label=paste0("p = ",pctlist[1])), color=mcolor[1], hjust=1, size=4)}
if(pctlength>=2){plt <- plt +
geom_point(aes(as.numeric(row.names(r2pdf)), r2pdf[,2]), color=mcolor[2], size=sizes[2]) +
geom_text(aes(x=max(doflist), y=mxy-0.05, label=paste0("p = ",pctlist[2])), color=mcolor[2], hjust=1, size=4)}
if(pctlength>=3){plt <- plt +
geom_point(aes(as.numeric(row.names(r2pdf)), r2pdf[,3]), color=mcolor[3], size=sizes[3]) +
geom_text(aes(x=max(doflist), y=mxy-0.10, label=paste0("p = ",pctlist[3])), color=mcolor[3], hjust=1, size=4)}
if(pctlength>=4){plt <- plt +
geom_point(aes(as.numeric(row.names(r2pdf)), r2pdf[,4]), color=mcolor[4], size=sizes[4]) +
geom_text(aes(x=max(doflist), y=mxy-0.15, label=paste0("p = ",pctlist[4])), color=mcolor[4], hjust=1, size=4)}
if(pctlength>=5){plt <- plt +
geom_point(aes(as.numeric(row.names(r2pdf)), r2pdf[,5]), color=mcolor[5], size=sizes[5]) +
geom_text(aes(x=max(doflist), y=mxy-0.20, label=paste0("p = ",pctlist[5])), color=mcolor[5], hjust=1, size=4)}
plt <- plt +
ggtitle("R2 Baseline Noise Level (R2p) \nfor Various Noise Percentiles (p)") +
xlab("Degrees of Freedom") +
ylab(expression(R^2)) +
geom_text(aes(x=max(doflist), y=mxy-0.25, label=paste0("Number of Samples:",N)), color='black', hjust=1, size=3)
return(plt)
}
plotR2k <- function(R2, doflist=c(2:30), pct=0.95, order=4, ndecimals=3,...){
pct <- pct[1]
df <- R2pTable(doflist=doflist, pctlist=pct, ndecimals=ndecimals, order=order,...)
df$R2k <- NA
n <- nrow(df)
for(i in 1:n){df$R2k[i] <- R2k(R2, dof=as.numeric(row.names(df)[i]), pct=pct, ndecimals=ndecimals, order=order,...)}
maxx=max(doflist)
plot <- ggplot(df) +
geom_point(aes(as.numeric(row.names(df)),df[,1]),color='red') +
geom_point(aes(as.numeric(row.names(df)),R2k),color='blue',na.rm=T) +
geom_hline(aes(yintercept=R2),color='black') +
ylim(0,1) +
xlab("Degrees of Freedom") +
ylab("R2") +
ggtitle("R2k for a Given Baseline Noise Level (R2p) and \na Constant Measured R2") +
geom_text(aes(x=maxx, y=0.17), label=paste0("Baseline Noise Level\np = ",pct), color='red', hjust=1) +
geom_text(aes(x=maxx, y=(R2-0.1)), label=paste0("R2k"), color='blue', hjust=1) +
geom_text(aes(x=maxx, y=(R2+0.05)), label=paste0("Measured R2 = ",R2), color='black',hjust=1)
return(plot)
}
plotR2Equiv <- function(R2, dof, pct=0.95, order=4, plot_pctr2=F,...){
mcolor <- c("red", "blue", "forestgreen", "slategray4", "gray20", "black")
df <- pcdfs(dof=dof, order=order,...)
doflist = c(2:30)
pctlist = c(pct)
if(plot_pctr2){
pct_R2 <- df$cdf[df$R2>=R2][1]
pctlist=c(pctlist,pct_R2)
}
doflength = length(doflist)
pctlength = length(pctlist)
ptable <- R2pTable(doflist=doflist,pctlist=pctlist,order=order,...)
r2p <- ptable[(dof-1),1]
r2k <- R2k(R2,dof=dof,...)
f = (R2-r2p)/(1-r2p)
ptable$R2Equiv <- f*(1-ptable[,1]) + ptable[,1]
tx = max(doflist[doflength])
if(length(ptable)==3){ptable <- ptable[c(1,3,2)]}
plt <- ggplot(ptable) +
geom_point(aes(as.numeric(row.names(ptable)),ptable[,1]),color=mcolor[1],size=2,na.rm=T) +
geom_point(aes(as.numeric(row.names(ptable)),ptable[,2]),color=mcolor[6],size=2,na.rm=T) +
geom_ribbon(aes(x=as.numeric(row.names(ptable)), ymin=ptable[,2], ymax=1),fill=mcolor[4],alpha=0.3,na.rm=T) +
geom_point(data=data.frame(R2,dof), aes(dof,R2),shape=8, color=mcolor[3],size=5,na.rm=T) +
ggtitle("Noise Baseline and R2 Equivalent (R2k)") +
xlab("Degrees of Freedom") +
ylab(expression(R^2)) +
geom_text(x=tx, y=0.80, label=paste0("R2 = ",R2," dof = ",dof), color=mcolor[3], hjust=1, size=4) +
geom_text(x=tx, y=0.75, label=paste0("R2k = ",r2k), color=mcolor[6], hjust=1, size=4) +
geom_text(x=tx, y=0.70, label=paste0("Noise Baseline: R2p = ",pctlist[1]), color=mcolor[1], hjust=1,size=4) +
geom_text(x=tx, y=0.65, label=paste0("Improved R2 Measure"), color=mcolor[4], hjust=1, size=4)
if(plot_pctr2){plt <- plt + geom_point(aes(as.numeric(row.names(ptable)),ptable[,3]),color=mcolor[2],size=2) +
geom_text(x=tx, y=0.60, label=paste0("R2 Noise Percentile = ",pctlist[2]), color=mcolor[2], hjust=1,size=4,na.rm=T)}
if(any(ptable[,2]<ptable[,1])){ plt <- plt +
geom_ribbon(aes(x=as.numeric(row.names(ptable)), ymin=ptable[,2], ymax=ptable[,1]),fill=mcolor[5],alpha=0.7,na.rm=T) +
geom_text(x=tx, y=0.55, label=paste0("Unacceptable Noise"), color=mcolor[5], hjust=1, size=4) +
geom_point(data=data.frame(R2,dof), aes(dof,R2),size=4,shape=8, color=mcolor[3],na.rm=T) }
return(plt)
}
|
plot_pvals <- function(pvals){
t <- c(1:length(pvals))
s <- (t/length(pvals))*0.05
df_plot_perm <- data.frame("y" = sort(pvals), "x" = c(1:length(pvals)))
ggplot()+ scale_y_log10()+
geom_point(data = df_plot_perm,aes_string(x = "x", y = "y", color = shQuote(viridis(4)[1])), size = 0.5)+
geom_line(data = df_plot_perm, aes_string(y = "s", x = "x",color = shQuote(viridis(4)[2])), size = 0.5) +
geom_line(data = df_plot_perm, aes_string(y = 0.05, x = "x", color = shQuote("red")), size = 0.5) +
scale_color_manual(name = "", labels = c("B-H limit", "p-values", "5% threshold"),
values = c(viridis(4)[c(1,2)], "red")) + xlab("rank") +
ylab("log10 scale") + xlim(0, length(df_plot_perm$y)) +
theme_bw()
}
|
"race_justice"
|
xsplineTangent.s1pos.s2pos.A0.A3.x <- function(px0, px1, px2, px3, py0, py1, py2, py3, s1, s2, t) {
(((((1/(-1 - s1) * ((t - s1)/(-1 - s1)) + ((t - s1)/(-1 -
s1)) * (1/(-1 - s1))) * ((t - s1)/(-1 - s1)) + ((t - s1)/(-1 -
s1)) * ((t - s1)/(-1 - s1)) * (1/(-1 - s1))) * (10 - (2 *
(-1 - s1) * (-1 - s1)) + (2 * (2 * (-1 - s1) * (-1 - s1)) -
15) * ((t - s1)/(-1 - s1)) + (6 - (2 * (-1 - s1) * (-1 -
s1))) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1))) + ((t -
s1)/(-1 - s1)) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1)) *
((2 * (2 * (-1 - s1) * (-1 - s1)) - 15) * (1/(-1 - s1)) +
((6 - (2 * (-1 - s1) * (-1 - s1))) * (1/(-1 - s1)) *
((t - s1)/(-1 - s1)) + (6 - (2 * (-1 - s1) * (-1 -
s1))) * ((t - s1)/(-1 - s1)) * (1/(-1 - s1))))) *
px0 + (((1/(-1 - s2) * ((t - 1 - s2)/(-1 - s2)) + ((t - 1 -
s2)/(-1 - s2)) * (1/(-1 - s2))) * ((t - 1 - s2)/(-1 - s2)) +
((t - 1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2)) * (1/(-1 -
s2))) * (10 - (2 * (-1 - s2) * (-1 - s2)) + (2 * (2 *
(-1 - s2) * (-1 - s2)) - 15) * ((t - 1 - s2)/(-1 - s2)) +
(6 - (2 * (-1 - s2) * (-1 - s2))) * ((t - 1 - s2)/(-1 - s2)) *
((t - 1 - s2)/(-1 - s2))) + ((t - 1 - s2)/(-1 - s2)) *
((t - 1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2)) * ((2 *
(2 * (-1 - s2) * (-1 - s2)) - 15) * (1/(-1 - s2)) + ((6 -
(2 * (-1 - s2) * (-1 - s2))) * (1/(-1 - s2)) * ((t - 1 -
s2)/(-1 - s2)) + (6 - (2 * (-1 - s2) * (-1 - s2))) * ((t -
1 - s2)/(-1 - s2)) * (1/(-1 - s2))))) * px1 + (((1/(1 + s1) *
((t + s1)/(1 + s1)) + ((t + s1)/(1 + s1)) * (1/(1 + s1))) *
((t + s1)/(1 + s1)) + ((t + s1)/(1 + s1)) * ((t + s1)/(1 +
s1)) * (1/(1 + s1))) * (10 - (2 * (1 + s1) * (1 + s1)) +
(2 * (2 * (1 + s1) * (1 + s1)) - 15) * ((t + s1)/(1 + s1)) +
(6 - (2 * (1 + s1) * (1 + s1))) * ((t + s1)/(1 + s1)) * ((t +
s1)/(1 + s1))) + ((t + s1)/(1 + s1)) * ((t + s1)/(1 +
s1)) * ((t + s1)/(1 + s1)) * ((2 * (2 * (1 + s1) * (1 + s1)) -
15) * (1/(1 + s1)) + ((6 - (2 * (1 + s1) * (1 + s1))) * (1/(1 +
s1)) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) * (1 + s1))) *
((t + s1)/(1 + s1)) * (1/(1 + s1))))) * px2 + (((1/(1 + s2) *
((t - 1 + s2)/(1 + s2)) + ((t - 1 + s2)/(1 + s2)) * (1/(1 +
s2))) * ((t - 1 + s2)/(1 + s2)) + ((t - 1 + s2)/(1 + s2)) *
((t - 1 + s2)/(1 + s2)) * (1/(1 + s2))) * (10 - (2 * (1 +
s2) * (1 + s2)) + (2 * (2 * (1 + s2) * (1 + s2)) - 15) *
((t - 1 + s2)/(1 + s2)) + (6 - (2 * (1 + s2) * (1 + s2))) *
((t - 1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2))) + ((t -
1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 +
s2)) * ((2 * (2 * (1 + s2) * (1 + s2)) - 15) * (1/(1 + s2)) +
((6 - (2 * (1 + s2) * (1 + s2))) * (1/(1 + s2)) * ((t - 1 +
s2)/(1 + s2)) + (6 - (2 * (1 + s2) * (1 + s2))) * ((t -
1 + s2)/(1 + s2)) * (1/(1 + s2))))) * px3)/(((t - s1)/(-1 -
s1)) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1)) * (10 -
(2 * (-1 - s1) * (-1 - s1)) + (2 * (2 * (-1 - s1) * (-1 -
s1)) - 15) * ((t - s1)/(-1 - s1)) + (6 - (2 * (-1 - s1) *
(-1 - s1))) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1))) +
((t - 1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2)) * ((t -
1 - s2)/(-1 - s2)) * (10 - (2 * (-1 - s2) * (-1 - s2)) +
(2 * (2 * (-1 - s2) * (-1 - s2)) - 15) * ((t - 1 - s2)/(-1 -
s2)) + (6 - (2 * (-1 - s2) * (-1 - s2))) * ((t -
1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2))) + ((t +
s1)/(1 + s1)) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1)) *
(10 - (2 * (1 + s1) * (1 + s1)) + (2 * (2 * (1 + s1) * (1 +
s1)) - 15) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) *
(1 + s1))) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1))) +
((t - 1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2)) * ((t -
1 + s2)/(1 + s2)) * (10 - (2 * (1 + s2) * (1 + s2)) +
(2 * (2 * (1 + s2) * (1 + s2)) - 15) * ((t - 1 + s2)/(1 +
s2)) + (6 - (2 * (1 + s2) * (1 + s2))) * ((t - 1 +
s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2)))) - (((t - s1)/(-1 -
s1)) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1)) * (10 -
(2 * (-1 - s1) * (-1 - s1)) + (2 * (2 * (-1 - s1) * (-1 -
s1)) - 15) * ((t - s1)/(-1 - s1)) + (6 - (2 * (-1 - s1) *
(-1 - s1))) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1))) *
px0 + ((t - 1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2)) *
((t - 1 - s2)/(-1 - s2)) * (10 - (2 * (-1 - s2) * (-1 - s2)) +
(2 * (2 * (-1 - s2) * (-1 - s2)) - 15) * ((t - 1 - s2)/(-1 -
s2)) + (6 - (2 * (-1 - s2) * (-1 - s2))) * ((t - 1 -
s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2))) * px1 + ((t +
s1)/(1 + s1)) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1)) *
(10 - (2 * (1 + s1) * (1 + s1)) + (2 * (2 * (1 + s1) * (1 +
s1)) - 15) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) *
(1 + s1))) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1))) *
px2 + ((t - 1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2)) *
((t - 1 + s2)/(1 + s2)) * (10 - (2 * (1 + s2) * (1 + s2)) +
(2 * (2 * (1 + s2) * (1 + s2)) - 15) * ((t - 1 + s2)/(1 +
s2)) + (6 - (2 * (1 + s2) * (1 + s2))) * ((t - 1 + s2)/(1 +
s2)) * ((t - 1 + s2)/(1 + s2))) * px3) * (((1/(-1 - s1) *
((t - s1)/(-1 - s1)) + ((t - s1)/(-1 - s1)) * (1/(-1 - s1))) *
((t - s1)/(-1 - s1)) + ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 -
s1)) * (1/(-1 - s1))) * (10 - (2 * (-1 - s1) * (-1 - s1)) +
(2 * (2 * (-1 - s1) * (-1 - s1)) - 15) * ((t - s1)/(-1 -
s1)) + (6 - (2 * (-1 - s1) * (-1 - s1))) * ((t - s1)/(-1 -
s1)) * ((t - s1)/(-1 - s1))) + ((t - s1)/(-1 - s1)) * ((t -
s1)/(-1 - s1)) * ((t - s1)/(-1 - s1)) * ((2 * (2 * (-1 -
s1) * (-1 - s1)) - 15) * (1/(-1 - s1)) + ((6 - (2 * (-1 -
s1) * (-1 - s1))) * (1/(-1 - s1)) * ((t - s1)/(-1 - s1)) +
(6 - (2 * (-1 - s1) * (-1 - s1))) * ((t - s1)/(-1 - s1)) *
(1/(-1 - s1)))) + (((1/(-1 - s2) * ((t - 1 - s2)/(-1 -
s2)) + ((t - 1 - s2)/(-1 - s2)) * (1/(-1 - s2))) * ((t -
1 - s2)/(-1 - s2)) + ((t - 1 - s2)/(-1 - s2)) * ((t - 1 -
s2)/(-1 - s2)) * (1/(-1 - s2))) * (10 - (2 * (-1 - s2) *
(-1 - s2)) + (2 * (2 * (-1 - s2) * (-1 - s2)) - 15) * ((t -
1 - s2)/(-1 - s2)) + (6 - (2 * (-1 - s2) * (-1 - s2))) *
((t - 1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2))) + ((t -
1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2)) * ((t - 1 -
s2)/(-1 - s2)) * ((2 * (2 * (-1 - s2) * (-1 - s2)) - 15) *
(1/(-1 - s2)) + ((6 - (2 * (-1 - s2) * (-1 - s2))) * (1/(-1 -
s2)) * ((t - 1 - s2)/(-1 - s2)) + (6 - (2 * (-1 - s2) * (-1 -
s2))) * ((t - 1 - s2)/(-1 - s2)) * (1/(-1 - s2))))) + (((1/(1 +
s1) * ((t + s1)/(1 + s1)) + ((t + s1)/(1 + s1)) * (1/(1 +
s1))) * ((t + s1)/(1 + s1)) + ((t + s1)/(1 + s1)) * ((t +
s1)/(1 + s1)) * (1/(1 + s1))) * (10 - (2 * (1 + s1) * (1 +
s1)) + (2 * (2 * (1 + s1) * (1 + s1)) - 15) * ((t + s1)/(1 +
s1)) + (6 - (2 * (1 + s1) * (1 + s1))) * ((t + s1)/(1 + s1)) *
((t + s1)/(1 + s1))) + ((t + s1)/(1 + s1)) * ((t + s1)/(1 +
s1)) * ((t + s1)/(1 + s1)) * ((2 * (2 * (1 + s1) * (1 + s1)) -
15) * (1/(1 + s1)) + ((6 - (2 * (1 + s1) * (1 + s1))) * (1/(1 +
s1)) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) * (1 + s1))) *
((t + s1)/(1 + s1)) * (1/(1 + s1))))) + (((1/(1 + s2) * ((t -
1 + s2)/(1 + s2)) + ((t - 1 + s2)/(1 + s2)) * (1/(1 + s2))) *
((t - 1 + s2)/(1 + s2)) + ((t - 1 + s2)/(1 + s2)) * ((t -
1 + s2)/(1 + s2)) * (1/(1 + s2))) * (10 - (2 * (1 + s2) *
(1 + s2)) + (2 * (2 * (1 + s2) * (1 + s2)) - 15) * ((t -
1 + s2)/(1 + s2)) + (6 - (2 * (1 + s2) * (1 + s2))) * ((t -
1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2))) + ((t - 1 +
s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 +
s2)) * ((2 * (2 * (1 + s2) * (1 + s2)) - 15) * (1/(1 + s2)) +
((6 - (2 * (1 + s2) * (1 + s2))) * (1/(1 + s2)) * ((t - 1 +
s2)/(1 + s2)) + (6 - (2 * (1 + s2) * (1 + s2))) * ((t -
1 + s2)/(1 + s2)) * (1/(1 + s2))))))/(((t - s1)/(-1 -
s1)) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1)) * (10 -
(2 * (-1 - s1) * (-1 - s1)) + (2 * (2 * (-1 - s1) * (-1 -
s1)) - 15) * ((t - s1)/(-1 - s1)) + (6 - (2 * (-1 - s1) *
(-1 - s1))) * ((t - s1)/(-1 - s1)) * ((t - s1)/(-1 - s1))) +
((t - 1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2)) * ((t -
1 - s2)/(-1 - s2)) * (10 - (2 * (-1 - s2) * (-1 - s2)) +
(2 * (2 * (-1 - s2) * (-1 - s2)) - 15) * ((t - 1 - s2)/(-1 -
s2)) + (6 - (2 * (-1 - s2) * (-1 - s2))) * ((t -
1 - s2)/(-1 - s2)) * ((t - 1 - s2)/(-1 - s2))) + ((t +
s1)/(1 + s1)) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1)) *
(10 - (2 * (1 + s1) * (1 + s1)) + (2 * (2 * (1 + s1) * (1 +
s1)) - 15) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) *
(1 + s1))) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1))) +
((t - 1 + s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2)) * ((t -
1 + s2)/(1 + s2)) * (10 - (2 * (1 + s2) * (1 + s2)) +
(2 * (2 * (1 + s2) * (1 + s2)) - 15) * ((t - 1 + s2)/(1 +
s2)) + (6 - (2 * (1 + s2) * (1 + s2))) * ((t - 1 +
s2)/(1 + s2)) * ((t - 1 + s2)/(1 + s2))))^2)
}
|
extract_features <- function(.data) {
feature_names <- unlist(purrr::map(
.data[[2]],
.f = function(feature) {
feature$get_name()
}
))
feature_actuals <- purrr::map(
.data[[2]],
.f = function(feature) {
feature
}
)
return(
tibble::tibble(
name = feature_names,
feature = feature_actuals
)
)
}
|
NULL
summary.RcppClock <- function(object, units = "auto", ...){
min_time <- min(object$timer[object$timer != 0])
if(is.na(min_time)) min_time <- 0
if(units == "auto"){
if(min_time > 1e8){
units <- "s"
} else if(min_time > 1e5){
units <- "ms"
} else if(min_time > 1e2){
units <- "us"
} else {
units <- "ns"
}
}
if(units == "s"){
object$timer <- object$timer / 1e9
} else if (units == "ms") {
object$timer <- object$timer / 1e6
} else if (units == "us") {
object$timer <- object$timer / 1e3
}
object <- data.frame("timer" = object$timer, "ticker" = object$ticker)
df2 <- aggregate(object$timer, list(ticker = object$ticker), mean)
colnames(df2)[2] <- "mean"
df2$sd <- aggregate(object$timer, list(ticker = object$ticker), sd)$x
df2$min <- aggregate(object$timer, list(ticker = object$ticker), min)$x
df2$max <- aggregate(object$timer, list(ticker = object$ticker), max)$x
object$timer <- 1
df2$neval <- aggregate(object$timer, list(ticker = object$ticker), sum)$x
long_units <- c("seconds", "milliseconds", "microseconds", "nanoseconds")
short_units <- c("s", "ms", "us", "ns")
attr(df2, "units") <- long_units[which(short_units == units)]
df2
}
print.RcppClock <- function(x, ...){
df <- summary(x, units = "auto")
cat("Unit:", attr(df, "units"), "\n")
print(df, digits = 4, row.names = FALSE)
invisible(x)
}
plot.RcppClock <- function(x, ...) {
min_time <- min(x$timer[x$timer != 0])
if(is.na(min_time)) min_time <- 0
if(min_time > 1e8) {
units <- "s"
x$timer <- x$timer / 1e9
} else if(min_time > 1e7) {
units <- "ms"
x$timer <- x$timer / 1e6
} else if(min_time > 1e2) {
units <- "us"
x$timer <- x$timer / 1e3
} else {
units <- "ns"
}
long_units <- c("seconds", "milliseconds", "microseconds", "nanoseconds")
short_units <- c("s", "ms", "us", "ns")
df <- data.frame("timer" = x$timer, "ticker" = x$ticker)
suppressWarnings(print(ggplot(df, aes_string(y = "ticker", x = "timer")) +
geom_violin() +
geom_jitter(height = 0.1) +
theme_classic() +
scale_x_continuous(trans = "log10") +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(y = "", x = paste0("runtime (", long_units[which(short_units == units)], ")"))))
}
|
createDistMat <-
function(ssn, predpts = NULL, o.write = FALSE, amongpreds = FALSE) {
if(amongpreds && (missing(predpts) || is.null(predpts)))
{
stop("A named collection of prediction points must be specified via the predpts option when amongpreds is TRUE")
}
if (!file.exists(file.path(ssn@path, "distance"))) {
dir.create(file.path(ssn@path, "distance"))
}
if (!file.exists(file.path(ssn@path, "distance", "obs"))) {
dir.create(file.path(ssn@path, "distance", "obs"))
}
if (!is.null(predpts)) {
if(!file.exists(file.path(ssn@path, "distance", predpts))) {
dir.create(file.path(ssn@path, "distance", predpts))
}
count <- 0
if(length(ssn@predpoints@ID) > 0) {
for (m in 1:length(ssn@predpoints@ID)) {
if (ssn@predpoints@ID[m] == predpts) {
pred.num <- m
count <- count + 1}
}
}
if (count==0) {
stop(predpts, " does not exist in SSN")}
if (count > 1) {
stop("SSN contains more than one copy of ", predpts)}
ssn@predpoints@SSNPoints[[pred.num]]@point.data$netID<- as.factor(ssn@predpoints@SSNPoints[[pred.num]]@point.data$netID)
}
if (is.null(predpts)) {
pred.num <- 0}
if (file.exists(file.path(ssn@path,"binaryID.db")) == FALSE)
stop("binaryID.db is missing from ssn object")
driver <- RSQLite::SQLite()
connect.name <- file.path(ssn@path,"binaryID.db")
connect <- dbConnect(SQLite(), connect.name)
on.exit({
dbDisconnect(connect)
})
if (file.exists(file.path(ssn@path, "binaryID.db")) == FALSE)
stop("binaryID.db is missing from ssn object")
ssn@obspoints@SSNPoints[[1]]@network.point.coords$NetworkID<-
as.factor(ssn@obspoints@SSNPoints[[1]]@network.point.coords$NetworkID)
net.count <- length(levels([email protected]$NetworkID))
warned.overwrite <- FALSE
for (i in 1:net.count) {
net.num <- levels([email protected]$NetworkID)[i]
ind.obs <- ssn@obspoints@SSNPoints[[1]]@network.point.coords$NetworkID == as.numeric(net.num)
site.no <- nrow(ssn@obspoints@SSNPoints[[1]]@network.point.coords[ind.obs,])
if (pred.num > 0) {
ind.preds <- ssn@predpoints@SSNPoints[[pred.num]]@network.point.coords$NetworkID == as.numeric(net.num)
pred.site.no <- nrow(ssn@predpoints@SSNPoints[[pred.num]]@network.point.coords[ind.preds,])
} else { pred.site.no <-0 }
if (site.no > 0) {
obs.pids<- sort(as.numeric(rownames(ssn@obspoints@SSNPoints[[1]]@network.point.coords[ind.obs,])))
if(!is.null(predpts)){
pred.pids<- sort(as.numeric(rownames(ssn@predpoints@SSNPoints[[pred.num]]@network.point.coords[ind.preds,])))
if(pred.site.no > 0){
current_distance_matrix_a <- matrix(NA, nrow = site.no, ncol = pred.site.no,
dimnames=list(obs.pids, pred.pids))
current_distance_matrix_b <- matrix(NA, nrow = pred.site.no, ncol = site.no,
dimnames=list(pred.pids, obs.pids))
}
}
net.name <- paste("net", net.num, sep = "")
workspace.name.a <- paste("dist.net", net.num, ".a.RData", sep = "")
workspace.name.b <- paste("dist.net", net.num, ".b.RData", sep = "")
bin.table <- dbReadTable(connect, net.name)
workspace.name <- paste("dist.net", net.num, ".RData", sep = "")
if(!o.write) {
exists <- file.exists(file.path(ssn@path, "distance", "obs", workspace.name))
if (!missing(predpts) && !is.null(predpts))
{
exists <- c(exists, file.exists(file.path(ssn@path,
"distance", predpts, workspace.name.a)),
file.exists(file.path(ssn@path, "distance",
predpts, workspace.name.b)))
}
if(all(exists))
{
if(!warned.overwrite) {
warned.overwrite <- TRUE
cat("Distance matrices already existed while o.write was set to FALSE. Not overwriting existing matrices\n")}
next
}
else if(any(exists) && any(!exists)) {
stop("o.write was set to FALSE and some (but not all) distance matrices already existed")}
}
current_distance_matrix <- matrix(NA, nrow = site.no, ncol = site.no,dimnames = list(obs.pids, obs.pids))
diag(current_distance_matrix)<- 0
rownames(current_distance_matrix) <- obs.pids
colnames(current_distance_matrix) <- obs.pids
locID.obi <- attributes(ssn@obspoints@SSNPoints[[1]]@network.point.coords[ind.obs,])$locID
ob.i <- as.data.frame(cbind(as.numeric(rownames(ssn@obspoints@SSNPoints[[1]]@network.point.coords[ind.obs,])),
as.numeric(levels(ssn@obspoints@SSNPoints[[1]]@network.point.coords$SegmentID[ind.obs]))[ssn@obspoints@SSNPoints[[1]]@network.point.coords$SegmentID[ind.obs]],
locID.obi[ind.obs]))
colnames(ob.i)<- c("pid","rid","locID")
ob.i$locID <- as.factor(ob.i$locID)
ob.i$binaryID <- bin.table$binaryID[match(ob.i$rid, bin.table$rid)]
ob.i <-ob.i[order(ob.i[,"pid"]),]
rownames(ob.i)<- ob.i$pid
ob.i_by_locID <- ob.i[order(ob.i[,"locID"]),]
ob.i_by_locID$pid <- as.numeric(ob.i_by_locID$pid)
ob.i_by_locID$locID <- as.numeric(ob.i_by_locID$locID)
ob.j_reordering <- order(ob.i_by_locID$pid)
locID.old <- -1
ind.dup <- !duplicated(ob.i_by_locID$locID)
for (j in 1:nrow(ob.i)) {
pid.i <- ob.i[j,"pid"]
locID.i <- ob.i[j, "locID"]
if (locID.i != locID.old) {
junk <- get.rid.fc(ob.i_by_locID[ind.dup,"binaryID"], ob.i$binaryID[j])
ob.j <- getObsRelationshipsDF(ssn, pid.i, junk, ind.dup, ob.i,
ob.i_by_locID,bin.table)
upDist.i <- ssn@obspoints@SSNPoints[[1]]@network.point.coords[paste(pid.i),
"DistanceUpstream"]
ob.j <-ob.j[ob.j_reordering,]
ind.fc<-ob.j$fc==1
dist.obs <- ifelse(ind.fc, upDist.i - ob.j$upDist.j,
upDist.i - ob.j$juncDist)
current_distance_matrix[,paste(pid.i)] <- ifelse(dist.obs<0, 0, dist.obs)
} else {
current_distance_matrix[,paste(pid.i)]<-
current_distance_matrix[,paste(pid.old)]
}
if (locID.i != locID.old) {
if (!is.null(predpts) && pred.site.no > 0) {
ob.j <- getPredRelationshipsDF(ssn, pred.num, ind.preds, bin.table, ob.i, j)
ob.j <-ob.j[order(ob.j[,"pid"]),]
ind.fc<-ob.j$fc==1
dist.a <- ifelse(ind.fc, ob.j$upDist.j-upDist.i, ob.j$upDist.j - ob.j$juncDist)
current_distance_matrix_a[paste(pid.i), ] <- ifelse(dist.a<0, 0, dist.a)
dist.b <- ifelse(ind.fc, upDist.i - ob.j$upDist.j, upDist.i - ob.j$juncDist)
current_distance_matrix_b[, paste(pid.i)] <- ifelse(dist.b<0, 0, dist.b)
}
} else {
if (!is.null(predpts) && pred.site.no > 0) {
current_distance_matrix_a[paste(pid.i),]<-
current_distance_matrix_a[paste(pid.old),]
current_distance_matrix_b[,paste(pid.i)]<-
current_distance_matrix_b[,paste(pid.old)]}
}
pid.old <- pid.i
locID.old <- locID.i
}
file_handle = file(file.path(ssn@path, "distance", "obs", workspace.name), open="wb")
serialize(current_distance_matrix, file_handle, ascii=FALSE)
close(file_handle)
if(pred.site.no > 0) {
file_handle = file(file.path(ssn@path, "distance", predpts, workspace.name.a), open="wb")
serialize(current_distance_matrix_a, file_handle, ascii=FALSE)
close(file_handle)
file_handle = file(file.path(ssn@path, "distance", predpts, workspace.name.b), open="wb")
serialize(current_distance_matrix_b, file_handle, ascii=FALSE)
close(file_handle)
}
}
if (amongpreds & pred.site.no > 0) {
workspace.name <- paste("dist.net", net.num, ".RData", sep = "")
pred.pids<- sort(as.numeric(rownames(ssn@predpoints@SSNPoints[[pred.num]]@network.point.coords[ind.preds,])))
net.name <- paste("net", net.num, sep = "")
bin.table <- dbReadTable(connect, net.name)
among_distance_matrix <- amongPredsDistMat(ssn, pred.pids, pred.num, bin.table)
file_handle = file(file.path(ssn@path, "distance", predpts, workspace.name),
open="wb")
serialize(among_distance_matrix, file_handle, ascii=FALSE)
close(file_handle)
}
}}
|
summary.BIFIE.lavaan.survey <- function(object, ... )
{
BIFIE.summary(object)
print(BIFIE_lavaan_summary(object$lavfit, ...))
cat("\n\nModel Fit Statistics\n")
print(object$fit)
}
|
logivec <- function(har.rule,label,nodenumb,newsim)
{
r.name <- rownames(har.rule)
logvec <- rep(TRUE, nrow(newsim))
for (i in 1:length(r.name)){
if(!is.infinite(har.rule[i,1]) | !is.infinite(har.rule[i,2])){
logvec <- newsim[, r.name[i]]>= har.rule[i,1] & newsim[, r.name[i]] < har.rule[i,2] & logvec
}
else if(!is.na(har.rule[i,3])) {
logvec <- sapply(newsim[,r.name[i]],function(x) grepl(x,har.rule[i,3])) & logvec
}
else logvec <- logvec
}
logvec[which(!newsim$rownn %in% nodenumb)] <- FALSE
logvec[which(is.na(logvec))] <- newsim$rownn[which(is.na(logvec))]==label
return(logvec)
}
|
on_ada_stumps_button_clicked <- function(button)
{
setGuiDefaultsAda(stumps=TRUE)
}
on_ada_stumps_checkbutton_toggled <- function(button)
{
if (theWidget("ada_stumps_checkbutton")$getActive())
setGuiDefaultsAda(stumps=TRUE)
else
setGuiDefaultsAda()
}
on_ada_defaults_button_clicked <- function(button)
{
setGuiDefaultsAda()
}
on_ada_importance_button_clicked <- function(button)
{
if (theWidget("model_boost_ada_radiobutton")$getActive())
plotImportanceAda()
else if (theWidget("model_boost_xgb_radiobutton")$getActive())
plotImportanceXgb()
}
on_ada_errors_button_clicked <- function(button)
{
if (theWidget("model_boost_ada_radiobutton")$getActive())
plotErrorsAda()
else if (theWidget("model_boost_xgb_radiobutton")$getActive())
plotErrorsXgb()
}
on_ada_list_button_clicked <- function(button)
{
listTreesAdaGui()
}
on_ada_draw_button_clicked <- function(button)
{
drawTreesAdaGui()
}
on_ada_continue_button_clicked <- function(button)
{
continueModelAdaGui()
}
on_help_ada_activate <- function(action, window)
{
displayHelpAda()
}
listTreesAdaGui <- function()
{
TV <- "ada_textview"
tree.num <- theWidget("ada_draw_spinbutton")$getValue()
if (tree.num > length(crs$ada$model$trees))
{
errorDialog(sprintf(Rtxt("You have requested tree number %d,",
"but there are only %d trees in the model.",
"Choose a tree number between 1 and %d."),
tree.num,
length(crs$ada$model$trees),
length(crs$ada$model$trees)))
return(FALSE)
}
display.cmd <- sprintf("listTreesAda(crs$ada, %d)", tree.num)
appendLog(sprintf(Rtxt("Display tree number %d."), tree.num), display.cmd)
addTextview(TV, collectOutput(display.cmd, TRUE), textviewSeparator())
setStatusBar(sprintf(Rtxt("Tree %d has been added to the textview.",
"You may need to scroll the textview to see it."),
tree.num))
}
drawTreesAdaGui <- function()
{
tree.num <- theWidget("ada_draw_spinbutton")$getValue()
if (tree.num > length(crs$ada$model$trees))
{
errorDialog(sprintf(Rtxt("You have requested tree number %d,",
"but there are only %d trees in the model.",
"Choose a tree number between 1 and %d."),
tree.num,
length(crs$ada$model$trees),
length(crs$ada$model$trees)))
return(FALSE)
}
draw.cmd <- sprintf('drawTreesAda(crs$ada, %d, ": %s")', tree.num,
paste(crs$dataname, "$", crs$target))
appendLog(sprintf(Rtxt("Display tree number %d."), tree.num), draw.cmd)
eval(parse(text=draw.cmd))
setStatusBar(sprintf(Rtxt("Tree %d has been drawn."), tree.num))
}
setGuiDefaultsAda <- function(stumps=FALSE)
{
theWidget("ada_target_label")$setText(Rtxt("No Target"))
xgb <- theWidget("model_boost_xgb_radiobutton")$getActive()
if (stumps)
{
theWidget("ada_maxdepth_spinbutton")$setValue(1)
theWidget("ada_minsplit_spinbutton")$setValue(0)
theWidget("ada_cp_spinbutton")$setValue(-1)
theWidget("ada_xval_spinbutton")$setValue(0)
theWidget("ada_max_depth_label")$setSensitive(FALSE)
theWidget("ada_min_split_label")$setSensitive(FALSE)
theWidget("ada_complexity_label")$setSensitive(FALSE)
theWidget("ada_xval_label")$setSensitive(FALSE)
theWidget("ada_maxdepth_spinbutton")$setSensitive(FALSE)
theWidget("ada_minsplit_spinbutton")$setSensitive(FALSE)
theWidget("ada_cp_spinbutton")$setSensitive(FALSE)
theWidget("ada_xval_spinbutton")$setSensitive(FALSE)
}
else
{
theWidget("ada_maxdepth_spinbutton")$setValue(ifelse(xgb,6,30))
theWidget("ada_minsplit_spinbutton")$setValue(20)
theWidget("ada_cp_spinbutton")$setValue(0.01)
theWidget("ada_xval_spinbutton")$setValue(10)
theWidget("ada_max_depth_label")$setSensitive(TRUE)
theWidget("ada_min_split_label")$setSensitive(!xgb)
theWidget("ada_complexity_label")$setSensitive(!xgb)
theWidget("ada_xval_label")$setSensitive(!xgb)
theWidget("ada_maxdepth_spinbutton")$setSensitive(TRUE)
theWidget("ada_minsplit_spinbutton")$setSensitive(!xgb)
theWidget("ada_cp_spinbutton")$setSensitive(!xgb)
theWidget("ada_xval_spinbutton")$setSensitive(!xgb)
}
}
showModelAdaExists <- function(state=!is.null(crs$ada))
{
xgb <- theWidget("model_boost_xgb_radiobutton")$getActive()
if (state)
{
theWidget("ada_importance_button")$show()
theWidget("ada_importance_button")$setSensitive(TRUE)
theWidget("ada_errors_button")$show()
theWidget("ada_errors_button")$setSensitive(TRUE)
if (!xgb) theWidget("ada_list_button")$show()
theWidget("ada_list_button")$setSensitive(!xgb)
if (!xgb) theWidget("ada_draw_button")$show()
theWidget("ada_draw_button")$setSensitive(!xgb)
if (!xgb) theWidget("ada_continue_button")$show()
theWidget("ada_continue_button")$setSensitive(!xgb)
if (!xgb) theWidget("ada_draw_spinbutton")$show()
theWidget("ada_draw_spinbutton")$setSensitive(!xgb)
}
else
{
theWidget("ada_importance_button")$hide()
theWidget("ada_errors_button")$hide()
theWidget("ada_list_button")$hide()
theWidget("ada_draw_button")$hide()
theWidget("ada_continue_button")$hide()
theWidget("ada_draw_spinbutton")$hide()
}
}
continueModelAdaGui <- function()
{
niter <- theWidget("ada_ntree_spinbutton")$getValue()
if (niter <= crs$ada$iter)
{
infoDialog(sprintf(Rtxt("The new Number of Trees, %d, is no larger",
"than the old Number of Trees, %d,",
"and so there is nothing to do.",
"You may like to choose a larger number of trees."),
niter, crs$ada$iter))
return()
}
set.cursor("watch")
continueModelAda(niter)
set.cursor()
}
|
fill.tbl_lazy <- function(.data, ..., .direction = c("down", "up")) {
sim_data <- simulate_vars(.data)
cols_to_fill <- syms(names(tidyselect::eval_select(expr(c(...)), sim_data)))
order_by_cols <- op_sort(.data)
.direction <- arg_match0(.direction, c("down", "up"))
if (is_empty(order_by_cols)) {
abort(
c(
x = "`.data` does not have explicit order.",
i = "Please use arrange() or window_order() to make determinstic."
)
)
}
if (.direction == "up") {
order_by_cols <- purrr::map(order_by_cols, ~ quo(-!!.x))
}
dbplyr_fill0(
.con = remote_con(.data),
.data = .data,
cols_to_fill = cols_to_fill,
order_by_cols = order_by_cols,
.direction = .direction
)
}
dbplyr_fill0 <- function(.con, .data, cols_to_fill, order_by_cols, .direction) {
UseMethod("dbplyr_fill0")
}
dbplyr_fill0.DBIConnection <- function(.con,
.data,
cols_to_fill,
order_by_cols,
.direction) {
grps <- op_grps(.data)
fill_sql <- purrr::map(
cols_to_fill,
~ win_over(
last_value_sql(.con, .x),
partition = if (!is_empty(grps)) escape(ident(op_grps(.data)), con = .con),
order = translate_sql(!!!order_by_cols, con = .con),
con = .con
)
) %>%
set_names(as.character(cols_to_fill))
.data %>%
transmute(
!!!syms(colnames(.data)),
!!!fill_sql
)
}
dbplyr_fill0.SQLiteConnection <- function(.con,
.data,
cols_to_fill,
order_by_cols,
.direction) {
partition_sql <- purrr::map(
cols_to_fill,
~ translate_sql(
cumsum(ifelse(is.na(!!.x), 0L, 1L)),
vars_order = translate_sql(!!!order_by_cols, con = .con),
vars_group = op_grps(.data),
)
) %>%
set_names(paste0("..dbplyr_partion_", seq_along(cols_to_fill)))
dp <- .data %>%
mutate(!!!partition_sql)
fill_sql <- purrr::map2(
cols_to_fill, names(partition_sql),
~ translate_sql(
max(!!.x, na.rm = TRUE),
con = .con,
vars_group = c(op_grps(.data), .y),
)
) %>%
set_names(purrr::map_chr(cols_to_fill, as_name))
dp %>%
transmute(
!!!syms(colnames(.data)),
!!!fill_sql
) %>%
select(!!!colnames(.data))
}
dbplyr_fill0.PostgreSQL <- dbplyr_fill0.SQLiteConnection
dbplyr_fill0.PqConnection <- dbplyr_fill0.SQLiteConnection
dbplyr_fill0.HDB <- dbplyr_fill0.SQLiteConnection
dbplyr_fill0.ACCESS <- dbplyr_fill0.SQLiteConnection
dbplyr_fill0.MariaDBConnection <- dbplyr_fill0.SQLiteConnection
dbplyr_fill0.MySQLConnection <- dbplyr_fill0.SQLiteConnection
dbplyr_fill0.MySQL <- dbplyr_fill0.SQLiteConnection
last_value_sql <- function(con, x) {
UseMethod("last_value_sql")
}
last_value_sql.DBIConnection <- function(con, x) {
build_sql("LAST_VALUE(", ident(as.character(x)), " IGNORE NULLS)", con = con)
}
last_value_sql.Hive <- function(con, x) {
translate_sql(last_value(!!x, TRUE), con = con)
}
globalVariables("last_value")
|
checksumXIF = function(fileName, ...) {
return(cpp_checksum(fileName))
}
|
library(hamcrest)
expected <- c(-0x1.0c36e9e2bc4d2p+0 + 0x0p+0i, -0x1.445604a2af506p-2 + 0x1.9806e7159367p-3i,
0x1.f16b4d6fba9d7p-1 + 0x1.d37268d4eded8p-5i, 0x1.724a081ca3476p-1 + -0x1.0c08c2f76eacdp+0i,
-0x1.df01ebdf91a54p-1 + 0x1.348e514b79ad6p-3i, -0x1.cb9de4e259588p-3 + -0x1.2d095741ca21p-2i,
0x1.e35ec93a3f197p-2 + 0x1.ce52b4f22260cp-4i, -0x1.e06821943dec3p-1 + -0x1.3b12848f1def7p-1i,
0x1.25535303934cp-6 + -0x1.a98690b2b64f2p-2i, -0x1.8eea748778926p-2 + 0x1.c117c287c1a8p-8i,
0x1.f2dad5e50d2dcp-3 + 0x1.4e61724f7afcfp-1i, 0x1.985dccb9ae21cp-2 + -0x1.e76a1b1c09ad4p-4i,
0x1.c81bec63a665cp+0 + 0x0p+0i, 0x1.985dccb9ae21ep-2 + 0x1.e76a1b1c09adfp-4i,
0x1.f2dad5e50d2e4p-3 + -0x1.4e61724f7afdp-1i, -0x1.8eea74877891dp-2 + -0x1.c117c287c1dp-8i,
0x1.25535303934bp-6 + 0x1.a98690b2b64f5p-2i, -0x1.e06821943dec6p-1 + 0x1.3b12848f1def6p-1i,
0x1.e35ec93a3f193p-2 + -0x1.ce52b4f22261p-4i, -0x1.cb9de4e259594p-3 + 0x1.2d095741ca21p-2i,
-0x1.df01ebdf91a54p-1 + -0x1.348e514b79addp-3i, 0x1.724a081ca3475p-1 + 0x1.0c08c2f76eacep+0i,
0x1.f16b4d6fba9d7p-1 + -0x1.d37268d4ededp-5i, -0x1.445604a2af4fep-2 + -0x1.9806e7159367p-3i
)
assertThat(stats:::fft(z=c(0.0324555631488638, 0.0311687013269092, 0.233266393502539,
-0.235029230487276, 0.0687990325456456, -0.339944754056818, -0.327608907825235,
-0.176636011202763, 0.0467078820368223, 0.164116768372802, 0.0492953179285646,
0.0241803411499137, 0.156955723107496, -0.281094774590679, -0.0687433091989791,
0.0586114721631971, 0.21400597103785, -0.19658683603818, -0.0453613071548341,
-0.127446284062493, -0.0994127476133393, -0.141442275195147,
0.106621969444523, -0.194591613621975))
, identicalTo( expected, tol = 1e-6 ) )
|
library("curl")
library("twitteR")
library("ROAuth")
library("syuzhet")
download.file(url="http://curl.haxx.se/ca/cacert.pem",destfile="cacert.pem")
consumerKey="uRDuync3BziwQnor1MZFBKp0x"
consumerSecret="t8QPLr7RKpAg4qa7vth1SBsDvoPKawwwdEhNRjdpY0mfMMdRnV"
AccessToken="14366551-Fga25zWM1YefkTb2TZYxsrx2LVVSsK0uSpF08sugW"
AccessTokenSecret="3ap8BZNVoBhE2GaMGLfuvuPF2OrHzM3MhGuPm96p3k6Cz"
cred <- OAuthFactory$new(consumerKey=consumerKey, consumerSecret=consumerSecret, requestURL='https://api.twitter.com/oauth/request_token', accessURL='https://api.twitter.com/oauth/access_token', authURL='https://api.twitter.com/oauth/authorize')
cred$handshake(cainfo="cacert.pem")
save(cred, file="twitter authentication.Rdata")
load("twitter authentication.Rdata")
setup_twitter_oauth(consumerKey, consumerSecret, AccessToken, AccessTokenSecret)
search.string <- "
no.of.tweets <- 100
tweets <- searchTwitter(search.string, n=no.of.tweets,lang="en")
tweets
tweets[1:10]
search.string <- "
no.of.tweets <- 100
tweets <- searchTwitter(search.string, n=no.of.tweets,lang="en")
tweets[1:5]
?searchTwitter
?searchTwitteR
homeTimeline(n=15)
mentions(n=15)
mentions(n=5)
(tweets = userTimeline("10rishav", n=10))
userTimeline("drisha_sinha", n=5)
?userTimeline
tweets = userTimeline("realDonaldTrump", n=100)
tweets[1:5]
n.tweet <- length(tweets)
n.tweet
tweets.df = twListToDF(tweets)
head(tweets.df)
summary(tweets.df)
tweets.df2 <- gsub("http.*","",tweets.df$text)
tweets.df2 <- gsub("https.*","",tweets.df2)
tweets.df2 <- gsub("
tweets.df2 <- gsub("@.*","",tweets.df2)
head(tweets.df2)
library("syuzhet")
word.df <- as.vector(tweets.df2)
word.df
emotion.df <- get_nrc_sentiment(word.df)
emotion.df
word.df[3]
emotion.df2 <- cbind(tweets.df2, emotion.df)
head(emotion.df2)
sent.value <- get_sentiment(word.df)
?get_sentiment
most.positive <- word.df[sent.value == max(sent.value)]
most.positive
most.negative<- word.df[sent.value <= min(sent.value)]
most.negative
sent.value
positive.tweets <- word.df[sent.value > 0]
head(positive.tweets)
negative.tweets <- word.df[sent.value < 0]
head(negative.tweets)
neutral.tweets <- word.df[sent.value == 0]
head(neutral.tweets)
category_senti <- ifelse(sent.value < 0, "Negative", ifelse(sent.value > 0, "Positive", "Neutral"))
head(category_senti)
category_senti2 <- cbind(tweets,category_senti,sent.value)
head(category_senti2)
table(category_senti)
|
product <- function(x, y) {
out <- x*y
out[(x == 0 | y == 0)] <- 0
return (out)
}
|
test_that(desc="Test that multi_model_1 works as intended",
code={
skip_on_oldrel()
set.seed(520)
train_set<-createDataPartition(yields$normal,
p=0.8,
list=FALSE)
valid_set<-yields[-train_set,]
train_set<-yields[train_set,]
ctrl<-trainControl(method="cv",
number=5)
m<-multi_model_1(train_set,"normal",".",
c("knn","rpart"),
"Accuracy",ctrl,
new_data =valid_set)
expect_error(multi_model_1(yields[1:120,],"normal",
".",c("knn","svmRadial"),
"Accuracy",ctrl),
"new_data,metric,method, and control must all be supplied",
fixed=TRUE)
expect_error(multi_model_1(yields[1:120,],
"normal",".",
c("knn","svmRadial"),
metric=NULL,ctrl,
new_data = yields[1:120,]),
"new_data,metric,method, and control must all be supplied",
fixed=TRUE)
expect_error(multi_model_1(yields[1:120,],
"normal",".",method=NULL,
metric="Accuracy",ctrl,
new_data = yields[1:120,]),
"new_data,metric,method, and control must all be supplied",
fixed=TRUE)
expect_false(any(is.null(m$metric),is.null(m$predictions)))
})
|
delScattering2 <-
function(EEM, rep = 0, first = 30, second = 40){
dimMat <- sapply(EEM , dim)
if (sum(!apply(dimMat, 2, function (x) identical(dimMat[,1], x))) > 0){
stop("Dimensions do not match. Please check your data.")
}
Ex <- as.numeric(colnames(EEM[[1]]))
Em <- as.numeric(rownames(EEM[[1]]))
numEx <- length(Ex)
numEm <- length(Em)
Ex_grid <- t(matrix(rep(Ex, numEm), numEx, numEm))
Em_grid <- matrix(rep(Em, numEx), numEm, numEx)
delIndex <- Ex_grid >= Em_grid
for (i in 1:2){
increment <- switch(i, first, second)
plusInd <- i * Ex_grid + increment > Em_grid
minusInd <- i * Ex_grid - increment < Em_grid
tempInd <- plusInd & minusInd
delIndex <- delIndex | tempInd
}
delIndex <- delIndex | (Em_grid >= 2*Ex_grid)
numSamp <- length(EEM)
EEM_delS <- EEM
for (i in 1:numSamp){
EEM_delS[[i]][delIndex] <- rep
}
return(EEM_delS)
}
|
scRNAtools_Gene2exp_1 <-
function(example,types_all,gene1,gene2,n,col_1,col_2,pch,lwd)
{
type=types_all[n,]
example<-as.matrix(example)
gene1<-as.matrix(gene1)
gene2<-as.matrix(gene2)
exp1<-example[which(example[,1]%in%gene1),]
exp2<-example[which(example[,1]%in%gene2),]
exp1<-as.matrix(exp1)
subtype1<-as.matrix(example[1,])
exp11<-cbind(example[1,],exp1)
colnames(exp11)<-exp11[1,]
exp11<-exp11[-1,]
eee1<-as.numeric(exp11[,1])
exp12<-exp11[which(eee1%in%as.numeric(type[,2])),]
num_type<-type[which(type[,2]%in%unique(eee1)),]
geneexp1<-as.numeric(exp12[,2])
exp2<-as.matrix(exp2)
subtype2<-as.matrix(example[1,])
exp21<-cbind(example[1,],exp2)
colnames(exp21)<-exp21[1,]
exp21<-exp21[-1,]
eee2<-as.numeric(exp21[,1])
exp22<-exp21[which(eee2%in%as.numeric(type[,2])),]
num_type<-type[which(type[,2]%in%unique(eee2)),]
geneexp2<-as.numeric(exp22[,2])
pdf(file=file.path(tempdir(), "two-genes expression1.pdf"))
main = paste("Gene expression in",type[,1],"cells")
max_v<-as.numeric(max(geneexp1,geneexp2))
plot(1:nrow(exp12),geneexp1,type="o",main=main,ylim=c(0,max_v),xlab = paste(type[,1],"cells"),ylab="Gene expression",col=col_1,pch=pch,lwd=lwd)
lines(1:nrow(exp22),geneexp2,type="o",ylim=c(0,max_v),xlab = paste(type[,1],"cells"),ylab="Gene expression",col=col_2,pch=pch,lwd=lwd)
dev.off()
}
|
astar_1 <- function(g1, w1, g2, w2){
n <- length(g1)
prod1 <- g1 * w1
c.gw1 <- cumsum(prod1)
c.w1 <- cumsum(w1)
tmp1 <- max(c.gw1 / c.w1)
tmp2 <- matrix(NA, nrow = n, ncol = n)
prod2 <- g2 * w2
c.gw2 <- cumsum(prod2)
c.w2 <- cumsum(w2)
for (tbar in 1:n){tmp2[tbar:n, tbar] <- (c.gw1[tbar:n] + c.gw2[tbar]) / (c.w1[tbar:n] + c.w2[tbar])}
tmp2 <- max(tmp2, na.rm = TRUE)
res <- max(tmp1, tmp2)
return(res)
}
|
cv.vectors <-
function(
x,
y,
weights,
family,
control,
acoefs,
lambda,
phis,
weight,
start,
offset,
L.index, T.index,
indices,
...
)
{
n <- nrow(x)
which.a <- acoefs$which.a
acoefs <- acoefs$A
losses <- matrix(ncol=length(lambda), nrow=1)
losses.sd <- matrix(ncol=length(lambda), nrow=1)
colnames(losses) <- colnames(losses.sd) <- as.character(lambda)
coefs <- matrix(ncol=length(lambda), nrow=nrow(acoefs))
colnames(coefs) <- as.character(lambda)
if (control$tuning.criterion %in% c("GCV", "UBRE")) {
if(control$tuning.criterion == "GCV"){
crit <- function(n, dev, rank, sc=1) {n * dev/(n-rank)^2}
}
if(control$tuning.criterion == "UBRE"){
crit <- function(n, dev, rank, sc=1) {dev/n + 1*rank*sc/n - sc}
}
if(control$cv.refit == FALSE){
evalcv <- function(x, coefficients, control, y, weights, dev, rank) {
output <- list(deviance=dev, rank=rank)
return(output)
}
} else {
evalcv <- function(x, coefficients, control, y, weights, dev, rank){
reductionC <- reduce(coefficients, indices, control$assured.intercept, control$accuracy)$C
x.reduced <- as.matrix(x %*% reductionC)
try(refitted <- glm.fit(x.reduced, y, weights, family=family,
intercept = FALSE))
dev.refitted <- refitted$deviance
rank.refitted <- refitted$rank
output <- list(deviance=dev.refitted, rank=rank.refitted)
return(output)
}
}
for (i in 1:length(lambda)) {
suppressWarnings(model <- gvcmcatfit(x, y, weights=weights, family,
control, acoefs, lambda=lambda[i], phis=phis, weight,
which.a, start = start, offset = offset))
eval.cv <- evalcv(x, model$coefficients, control, y, weights, model$deviance, model$rank)
losses[1,i] <- crit(n, eval.cv$deviance, eval.cv$rank, sc=1)
coefs[,i] <- model$coefficients
}
}
if(control$tuning.criterion %in% c("deviance", "1SE")){
if(family$family == "binomial"){
l <- function(y,mudach,weights=weights){sum((y*log(mudach) + (1-y)*log(1-mudach))*weights + lchoose(weights,y*weights))}
d <- function(y,mudach,weights=weights){e <- matrix(0, nrow=length(y), ncol=1)
rein.binaere <- if (any(y==0) || any(y==1)) c(which(y==0),which(y==1)) else -(1:length(y))
e[rein.binaere,] <- (-2*log(1-abs(y-mudach))*weights)[rein.binaere]
e[-rein.binaere,] <- (weights*(y*log(y/mudach)+(1-y)*log((1-y)/(1-mudach))))[-rein.binaere]
return(e)}
}
if(family$family == "gaussian"){
l <- function(y,mudach,weights=weights){-1/2 * sum(weights*(y - mudach)^2) - n*log(sqrt(2*pi))}
d <- function(y,mudach,weights=weights){weights*(y-mudach)^2}
}
if(family$family == "poisson"){
l <- function(y,mudach,weights=weights){sum(weights*((y*log(mudach)) - mudach - lgamma(y+1)))}
d <- function(y,mudach,weights=weights){e <- matrix(0, nrow=length(y), ncol=1)
e[which(y==0),] <-(2*mudach*weights)[which(y==0)]
e[which(y!=0),] <- (2*weights*((y*log(y/mudach))+mudach-y))[which(y!=0)]
return(e)}
}
if(family$family == "Gamma"){
l <- function(y,mudach,weights=weights){sum(weights*(log(mudach) - y/mudach))}
d <- function(y,mudach,weights=weights){2*(-log(y) + log(mudach) + y/mudach -1)*weights}
}
dev.res <- function(y,mudach,weights) {(y-mudach)/abs(y-mudach) * sqrt(d(y, mudach, weights)) }
dev <- function(y,mudach,weights) {sum(d(y=y,mudach=mudach, weights))}
crit <- dev
if(control$cv.refit == FALSE){
evalcv. <- function(x.tr, x.te, coefficients, control, training.y, training.weights) {
output <- list(coefficients=coefficients, test.x=x.te)
return(output)
}
} else {
evalcv. <- function(x.tr, x.te, coefficients, control, training.y, training.weights){
reductionC <- reduce(coefficients, indices, control$assured.intercept, control$accuracy)$C
x.reduced.tr <- as.matrix(x.tr %*% reductionC)
x.reduced.te <- as.matrix(x.te %*% reductionC)
try(beta.refitted <- glm.fit(x.reduced.tr,training.y, training.weights, family=family,
intercept = FALSE)$coefficients)
output <- list(coefficients=beta.refitted, test.x=x.reduced.te)
return(output)
}
}
for (i in 1:length(lambda)) {
loss <- c()
for (j in 1:control$K){
training.x <- x[L.index[[j]],]
training.y <- y[L.index[[j]]]
training.weights <- weights[L.index[[j]]]
test.x <- x[T.index[[j]],]
test.y <- y[T.index[[j]]]
test.weights <- weights[T.index[[j]]]
if(control$standardize){
if (sum(x[,1])==n || sum(x[,1])==sum(weights)) {
scaling <- c(1, sqrt(colSums(t((t(training.x[,-1]) - colSums(diag(training.weights)%*%training.x[,-1])/sum(training.weights))^2*training.weights))/(sum(training.weights)-1)))
} else {
scaling <- sqrt(colSums(t((t(training.x) - colSums(diag(training.weights)%*%training.x) /sum(training.weights))^2*training.weights))/(sum(training.weights)-1))
}
training.x <- scale(training.x, center = FALSE, scale = scaling)
test.x <- scale(test.x, center = FALSE, scale = scaling)
}
suppressWarnings(model <- gvcmcatfit(training.x, training.y, weights=training.weights, family,
control, acoefs, lambda=lambda[i], phis=phis, weight,
which.a, start = start, offset = offset))
eval.cv <- evalcv.(training.x, test.x, model$coefficients, control, training.y, training.weights)
test.mudach <- family$linkinv(eval.cv$test.x %*% eval.cv$coefficients)
loss <- c(loss, crit(test.y, test.mudach, test.weights))
}
losses[1,i] <- sum(loss) / control$K
losses.sd[1,i] <- sd(loss) * (control$K-1) / control$K
}
coefs <- NA
}
opt <- max(lambda[which(losses==min(losses))])[1]
return(list(
lambda=opt,
lambdas=lambda,
score=losses,
coefs=coefs,
score.sd = losses.sd
))
}
|
module_ui_extract_code_fileconfig <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
shiny::uiOutput(ns("codeconfig")),
shiny::uiOutput(ns("codebuttons")),
shiny::uiOutput(ns("fileRawExportConfig")),
shiny::uiOutput(ns("fileCleanedExportConfig")),
shiny::uiOutput(ns("savebutton"))
)
}
module_server_extract_code_fileconfig <- function(input,
output,
session,
df_label,
is_on_disk,
has_processed) {
ns <- session$ns
output$codeconfig <- shiny::renderUI({
shiny::validate(shiny::need(has_processed(),
message = "Filter or manually select data to set and save outputs."
))
shiny::tagList(
shiny::br(),
shiny::checkboxInput(ns("overwrite"),
label = "Concise code?",
value = TRUE
)
)
})
output$codebuttons <- shiny::renderUI({
shiny::req(has_processed())
shiny::tagList(shiny::fluidRow(
style = "margin-bottom: 20px;",
shiny::column(
width = 6,
align = "left",
shiny::actionButton(
inputId = ns("codebtn"),
label = "Send to RStudio",
class = ifelse(is_on_disk, "btn-secondary", "btn-info"),
icon = shiny::icon("share-square")
)
),
shiny::column(
width = 6,
align = "center",
shiny::actionButton(
inputId = ns("copybtn"),
label = "Copy to clipboard",
class = ifelse(is_on_disk, "btn-secondary", "btn-info"),
icon = shiny::icon("copy")
)
)
))
})
output$fileRawExportConfig <- shiny::renderUI({
shiny::req(is_on_disk)
shiny::req(has_processed())
shiny::tagList(
shiny::h4(shiny::tags$strong("Set Output Locations")),
shiny::fluidRow(
style = "margin-top: 25px;",
shiny::column(5, shinyFiles::shinyDirButton(
id = ns("dirraw"),
"Meta & Recipe",
"Set and/or create a directory for the raw data and the reproducible recipe.",
FALSE,
class = "btn-info",
icon = shiny::icon("folder")
)),
shiny::column(
7,
shiny::checkboxInput(
inputId = ns("dirchooseIdentical"),
label = "Same folder for cleaned data?",
value = TRUE
)
)
)
)
})
output$fileCleanedExportConfig <- shiny::renderUI({
shiny::req(input$dirchooseIdentical == FALSE)
shiny::req(has_processed())
shiny::tagList(
shinyFiles::shinyDirButton(
style = "margin-bottom: 25px;",
id = ns("dirclean"),
"Cleaned Data",
"Set and/or create a directory for the cleaned data.",
FALSE,
class = "btn-info",
icon = shiny::icon("folder")
)
)
})
output$savebutton <- shiny::renderUI({
shiny::req(is_on_disk)
shiny::req(has_processed())
shiny::tagList(
shiny::h4(shiny::tags$strong("Set and Save Outputs")),
shiny::textInput(
inputId = ns("suffixClean"),
label = "Suffix: Cleaned Data",
value = "cleaned"
),
shiny::textInput(
inputId = ns("suffixRawFile"),
label = "Suffix: Filter + Outlier Data",
value = "meta_RAW"
),
shiny::textInput(
inputId = ns("suffixCleaningScript"),
label = "Suffix: Recipe",
value = "cleaning_script"
),
shiny::br(),
shiny::actionButton(
inputId = ns("save"),
label = "Save Recipe & Data",
icon = shiny::icon("save"),
class = "btn-success"
)
)
})
roots <- c(
`Dataset dir` = fs::path_dir(df_label),
`Working dir` = ".",
`Home dir` = Sys.getenv("HOME")
)
shinyFiles::shinyDirChoose(input,
id = "dirraw",
roots = roots
)
shinyFiles::shinyDirChoose(input,
id = "dirclean",
roots = roots
)
outpath <- shiny::reactive({
dirraw <- shinyFiles::parseDirPath(
roots = roots,
input$dirraw
)
dirraw <- ifelse(length(dirraw) == 0,
fs::path_dir(df_label),
dirraw
)
dirclean <- shinyFiles::parseDirPath(
roots = roots,
input$dirclean
)
dirclean <- ifelse(length(dirclean) == 0,
dirraw, dirclean
)
file_out_raw <- make_save_filepath(
save_dir = dirraw,
input_filepath = df_label,
suffix = input$suffixRawFile,
ext = "Rds"
)
file_out_cleaned <- make_save_filepath(
save_dir = dirclean,
input_filepath = df_label,
suffix = input$suffixClean,
ext = "Rds"
)
file_script_cleaning <- make_save_filepath(
save_dir = dirraw,
input_filepath = df_label,
suffix = input$suffixCleaningScript,
ext = "R"
)
return(list(
dirraw = dirraw,
dirclean = dirclean,
file_out_raw = file_out_raw,
file_out_cleaned = file_out_cleaned,
file_script_cleaning = file_script_cleaning
))
})
return(outpath)
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
echo = FALSE,
message = FALSE
)
library(ggip)
knitr::include_graphics("bits_raw.png")
knitr::include_graphics("bits_half_reduced.png")
knitr::include_graphics("bits_reduced.png")
ordinal_suffix <- function(x) {
suffix <- c("st", "nd", "rd", rep("th", 17))
suffix[((x-1) %% 10 + 1) + 10*(((x %% 100) %/% 10) == 1)]
}
plot_curve <- function(curve, curve_order) {
pixel_prefix <- 32L
canvas_prefix <- as.integer(pixel_prefix - (2 * curve_order))
canvas_network <- ip_network(ip_address("0.0.0.0"), canvas_prefix)
n_pixels <- 2^curve_order
ggplot(data.frame(address = seq(canvas_network))) +
geom_path(aes(address$x, address$y)) +
coord_ip(
canvas_network = canvas_network,
pixel_prefix = pixel_prefix,
curve = curve,
expand = TRUE
) +
theme_ip_light() +
labs(title = paste0(
curve_order, ordinal_suffix(curve_order),
" order (", n_pixels, "x", n_pixels, " grid)"
))
}
plot_curve("hilbert", 2)
plot_curve("hilbert", 3)
plot_curve("hilbert", 4)
plot_curve("morton", 2)
plot_curve("morton", 3)
plot_curve("morton", 4)
curve_order <- 2
pixel_prefix <- 2 * curve_order
vertices <- subnets(ip_network("0.0.0.0/0"), new_prefix = pixel_prefix)
data <- data.frame(ip = network_address(vertices), label = as.character(vertices))
nudge <- c(1, 0, 0, 1, 1, 1, 0, 0, 0, 0, -1, -1, -1, 0, 0, -1)
ggplot(data, aes(ip$x, ip$y)) +
geom_path() +
geom_label(aes(label = label), nudge_x = 0.2 * nudge) +
coord_ip(pixel_prefix = pixel_prefix, expand = TRUE) +
theme_ip_light() +
labs(title = paste0("Hilbert curve: ", curve_order, ordinal_suffix(curve_order), " order"))
|
setClass("fibonacci_heap", contains = "heap")
fibonacci_heap <- function(
key.class = c("character", "numeric", "integer")) {
key.class <- match.arg(key.class)
heap <- switch(key.class,
"character" = methods::new(fibonacci_heap_s),
"numeric" = methods::new(fibonacci_heap_d),
"integer" = methods::new(fibonacci_heap_i),
stop("Error defining key class")
)
methods::new("fibonacci_heap",
.key.class = key.class,
.heap = heap
)
}
|
TRAMPsamples <- function(data, info=NULL, warn.factors=TRUE, ...) {
if ( is.null(info) )
info <- data.frame(sample.pk=unique(data$sample.fk))
if ( is.null(info$species) )
info$species <- as.character(NA)
obj <- list(info=defactor(info, warn.factors),
data=defactor(data, warn.factors), ...)
class(obj) <- "TRAMPsamples"
tidy.TRAMPsamples(obj)
}
is.TRAMPsamples <- function(x)
inherits(x, "TRAMPsamples")
valid.TRAMPsamples <- function(x) {
if ( !is.TRAMPsamples(x) )
stop("Not a TRAMPsamples object")
data.cols <- c("sample.fk", "primer", "enzyme", "size", "height")
must.contain.cols(x$info, c("sample.pk", "species"))
must.contain.cols(x$data, data.cols)
if ( any(duplicated(x$info$sample.pk)) )
stop("x$info$sample.pk must be unique")
if ( !(is.numeric(x$info$sample.pk) && all(x$info$sample.pk > 0)) )
stop("Numeric, positive sample.pk required")
if ( any(is.na(x$data[data.cols])) )
stop("NA values are not permitted for columns: ",
paste(data.cols, collapse=", "))
orphan <- setdiff(x$data$sample.fk, x$info$sample.pk)
if ( length(orphan) > 0 )
stop(sprintf("Orphaned data with no info: (sample.fk: %s)",
paste(orphan, collapse=", ")))
invisible(TRUE)
}
print.TRAMPsamples <- function(x, ...)
cat("[TRAMPsamples object]\n")
labels.TRAMPsamples <- function(object, ...) {
valid.TRAMPsamples(object)
sort(object$info$sample.pk)
}
summary.TRAMPsamples <- function(object, include.info=FALSE, ...) {
valid.TRAMPsamples(object)
res <- object$data
res$code <- paste(res$primer, res$enzyme, sep="_")
res <- tapply(res$sample.fk, res[c("sample.fk", "code")], length)
res <- res[match(object$info$sample.pk, rownames(res)),,drop=FALSE]
rownames(res) <- object$info$sample.pk
if ( include.info )
cbind(object$info, res)
else
res
}
plot.TRAMPsamples <- function(x, sample.fk=labels(x), ...)
for ( i in sample.fk )
TRAMPsamples.plotone(x, i, ...)
TRAMPsamples.plotone <- function(x, sample.fk,
all.samples.global=FALSE, col=1:10,
xmax=NULL, mar.default=.5,
mar.labels=8, cex=1) {
sample.data <- x[sample.fk]$data
d.samples <- if (all.samples.global) x$data else sample.data
enzyme.primer <- unique(d.samples[c("enzyme", "primer")])
enzyme.primer <-
enzyme.primer[order(enzyme.primer$enzyme, enzyme.primer$primer),]
n <- nrow(enzyme.primer)
if ( n < 1 ) {
warning("No data for sample: ", sample.fk)
layout(1)
plot(0:1, 0:1, type="n", axes=FALSE, xlab="", ylab="")
text(.5, .5, "(No data)")
title(main=paste("Sample:", sample.fk), outer=TRUE)
}
if ( length(col) < n )
stop(sprintf("Too few colours provided (%d, %d required)",
length(col), n))
sample.data$code <- classify(sample.data, enzyme.primer)
if ( is.null(xmax) )
xmax <- ceiling(max(x$data$size)/100)*100
else if ( is.na(xmax) )
xmax <- ceiling(max(sample.data$size)/100)*100
layout(matrix(1:n, n))
par(oma=c(4, 0, 3, 0) + mar.default, mar=c(.75, mar.labels, 0, 0),
las=1, cex=cex)
for ( i in seq(n) ) {
dsub <- sample.data[sample.data$code == i,]
plot(height ~ size, dsub, type="h", xlim=c(0, xmax),
ylim=range(dsub$height, 0:1), xaxt="n", yaxt="n", bty="l",
xlab="", ylab="", col=col[dsub$code])
axis(1, labels=i == n)
axis(2, mean(par("usr")[3:4]),
with(enzyme.primer[i,], paste(enzyme, primer, sep="/")),
tick=FALSE)
if ( i == n )
title(xlab="Fragment length", xpd=NA)
}
title(main=paste("Sample:", sample.fk), outer=TRUE)
}
combine.TRAMPsamples <- function(x, y, rewrite.sample.pk=FALSE, ...) {
valid.TRAMPsamples(x)
valid.TRAMPsamples(y)
if ( any(labels(y) %in% labels(x)) )
if ( rewrite.sample.pk ) {
y$info$sample.pk <- y$info$sample.pk + max(labels(x))
y$data$sample.fk <- y$data$sample.fk + max(labels(x))
} else {
stop("sample.pk conflict - see ?combine.TRAMPsamples")
}
x$info <- rbind2(x$info, y$info)
x$data <- rbind2(x$data, y$data)
extra <- setdiff(names(y), c("info", "data"))
if ( length(extra) > 0 )
warning("Additional objects in 'y' were ignored: ",
paste(dQuote(extra), collapse=", "))
tidy.TRAMPsamples(x)
}
tidy.TRAMPsamples <- function(x) {
valid.TRAMPsamples(x)
x$info <- x$info[order(x$info$sample.pk),]
x$data <- x$data[do.call(order, x$data),]
rownames(x$info) <- seq(length=nrow(x$info))
rownames(x$data) <- seq(length=nrow(x$data))
x
}
"[.TRAMPsamples" <- function(x, i, na.interp=TRUE, ...) {
if ( is.numeric(i) ) {
if ( !all(i %in% labels(x)) )
stop("Unknown samples: ",
paste(i[!(i %in% labels(x))], collapse=", "))
} else if ( is.logical(i) ) {
if ( length(i) != nrow(x$info) )
stop("Logical index of incorrect length")
i[is.na(i)] <- na.interp
i <- x$info$sample.pk[i]
} else stop("Invalid index type")
x$info <- subset(x$info, x$info$sample.pk %in% i)
x$data <- subset(x$data, x$data$sample.fk %in% i)
tidy.TRAMPsamples(x)
}
|
PlotAM <- function(AMobj=NULL, itnum=1, chr="All", type="Manhattan", interactive=TRUE )
{
if(is.null(AMobj)){
message(" PlotAM function requires AMobj object to be specified. This object is obtained by running AM().")
return(NULL)
}
if(!is.list(AMobj)){
message(" PlotAM function requires AMobj object to be a list object.")
return(NULL)
}
if (!is.integer(itnum)){
if(itnum < 1 || (itnum > length(AMobj$outlierstat) )){
message(" The parameter itnum must have an integer value between ", 1, " and ",
length(AMobj$outlierstat))
return(NULL)
}
}
if (!(chr=="All") && !any(chr %in% unique(AMobj$map[,2])) ) {
message(" The parameter chr does not match any of the chromosome labels. ")
message(" The allowable chromosome labels are ", c("All", cat(unique(AMobj$map[,2]))))
return(NULL)
}
xindx <- 1:length( AMobj$outlierstat[[itnum]] )
xvals <- xindx
yvals <- AMobj$outlierstat[[itnum]]
isit <- IsItBigger(vals=AMobj$outlierstat, itnum=itnum )
bigger <- isit$bigger
chrm <- rep(1, length(xindx))
pos <- xvals
if(!is.null(AMobj$map)){
oindx <- order(AMobj$map[,2], AMobj$map[, ncol(AMobj$map)])
yvals <- AMobj$outlierstat[[as.numeric(itnum)]][oindx]
mapordered <- AMobj$map[oindx,]
chrm <- mapordered[,2]
pos <- rep(NA, nrow(mapordered))
t <- 0
for(ii in 1:nrow(mapordered)){
t <- t + mapordered[ii,ncol(mapordered)]
pos[ii] <- t
}
if(length(AMobj$Indx) > 1){
Indx <- rep(NA, length(AMobj$Mrk))
NewMrkPos <- rep(NA, length(AMobj$Mrk))
for(ii in 2:length(AMobj$Mrk)){
Indx[ii] <- which(mapordered[,1]==AMobj$Mrk[ii])
NewMrkPos[ii] <- pos[Indx[ii]]
}
Indx <- Indx[!is.na(Indx)]
NewMrkPos <- NewMrkPos[!is.na(NewMrkPos)]
}
if( as.numeric(itnum) > 1){
bigger <- rep("" , length(yvals) )
percentagechange <- rep(0, length(yvals) )
a <- AMobj$outlierstat[[as.numeric(itnum)]][oindx]
b <- AMobj$outlierstat[[as.numeric(itnum) - 1 ]][oindx]
indx <- which( a > b )
bigger[indx] <- "Increased value"
percentagechange[indx] <- (( b - a)) [indx]
indx <- which( a <= b )
bigger[indx] <- "Decreased value"
percentagechange[indx] <- (( a - b)) [indx]
}
}
xlabel <- "Map Position (bp)"
if(is.null(AMobj$map ))
xlabel <- "Column Position of SNP"
ylabel <- "Score Statistic"
if(type=="Manhattan")
ylabel <- "-log10(p value)"
if(type=="Manhattan"){
yvals[is.nan(yvals)] <- 0
yvals[yvals < 0] <- 0
ts <- sqrt(yvals)
pval <- 1 - pnorm(ts)
logp <- -1*log10(pval)
yvals <- logp
}
df <- data.frame(xvals=pos, yvals=yvals, chrm=chrm )
if(chr!="All"){
indx <- which(df$chrm==chr)
df <- df[indx,]
if (itnum >1){
bigger <- bigger[indx]
percentagechange <- percentagechange[indx]
}
}
geomX <- NULL
if(length(AMobj$Indx) > 1){
Labels <- 1:length(Indx)
indx <- which( NewMrkPos %in% df$xvals )
if (length(indx) > 0 ){
geomX <- NewMrkPos[indx]
geomLabels <- Labels[indx ]
}
}
if(itnum==1){
p <- ggplot(data=df, aes(x=xvals, y=yvals )) + geom_point()
} else {
percentagechange <- abs(percentagechange)
sd <- sqrt(var(percentagechange))
indx <- which( 2.0 *sd < percentagechange)
percentagechange[indx] <- 2.0*sd
p <- ggplot(data=df, aes(x=xvals, y=yvals , color=bigger, size=percentagechange ) ) +
geom_point() + scale_color_manual(values=c("
p <- p + scale_size(percentagechange, range=c(0.4 ,2 ), guide="none")
}
p <- p + theme_hc()
p <- p + ylab(ylabel) + xlab(xlabel)
p <- p + theme(legend.title=element_blank())
p <- p + theme(legend.position="right")
if(!is.null(geomX)){
if (itnum >1){
for(ii in geomLabels) {
if (ii < itnum){
yadj <- sample(seq(0.5,0.9,0.1), 1)
p <- p + geom_vline(xintercept = geomX[which(ii==geomLabels)],
linetype="solid", color="
p <- p + annotate("text", size=6, label=ii,
x=(geomX[which(ii==geomLabels)] - ( diff(range(df$xvals))*0.00) ) ,
y = max(df$yvals)*yadj )
}
if (ii == itnum){
p <- p + geom_vline(xintercept = geomX[which(ii==geomLabels)] ,
linetype="solid", color="red", size=0.75)
}
}
} else {
ii <- 1
p <- p + geom_vline(xintercept = geomX[which(ii==geomLabels)],
linetype="solid", color="red", size=0.75)
}
}
p <- p + theme( axis.text.x = element_text(size=16), axis.text.y = element_text(size=16),
axis.title.x=element_text(size=16), axis.title.y=element_text(size=16),
legend.text=element_text(size=14) )
p <- p + guides(colour = guide_legend(override.aes = list(size=8)))
p <- p + theme(legend.position = 'bottom', legend.spacing.x = unit(0.5, 'cm'))
if(chr=="All"){
txt2 <- "across all chromosomes"
if(type=="Manhattan"){
txt1 <- " -log p value of the score statistic"
txt3 <- "-log p value"
} else {
txt1 <- "score statistic"
txt3 <- txt1
}
} else{
txt2 <- paste("on chromosome", chr)
if(type=="Manhattan"){
txt1 <- " -log p value of the score statistic"
txt3 <- "-log p value"
} else {
txt1 <- "score statistic"
txt3 <- txt1
}
}
p <- p + ylim(0, (max(df$yvals)*1.2) )
p <- p + guides(colour = guide_legend(override.aes = list(size=5)))
if(interactive){
ggplotly(p) %>% layout(legend = list( orientation = "h", x=0, y=-0.4, itemsizing="constant" ))
} else {
return(p)
}
}
IsItBigger <- function(vals, itnum, xindx=NULL){
bigger <- NULL
percentagechange <- NULL
if(as.numeric(itnum) > 1){
bigger <- rep("" , length(vals[[as.numeric(itnum)]]) )
percentagechange <- rep(0, length(vals[[as.numeric(itnum)]]) )
a <- vals[[as.numeric(itnum)]]
b <- vals[[as.numeric(itnum) - 1 ]]
indx <- which( a > b )
bigger[indx] <- "Increased value"
percentagechange[indx] <- ( (a - b ) )[indx]
indx <- which( a <= b )
bigger[indx] <- "Decreased value"
percentagechange[indx] <- ( (b - a ) )[indx]
if(!is.null(xindx)){
bigger <- bigger[xindx]
percentagechange <- percentagechange[xindx]
}
}
res <- list(bigger=bigger, percentagechange=percentagechange)
return(res)
}
|
require(geometa, quietly = TRUE)
require(testthat)
context("ISOMemberName")
test_that("encoding",{
testthat::skip_on_cran()
md <- ISOMemberName$new(aName = "name", attributeType = "type")
expect_is(md, "ISOMemberName")
xml <- md$encode()
expect_is(xml, "XMLInternalNode")
md2 <- ISOMemberName$new(xml = xml)
xml2 <- md2$encode()
expect_true(ISOAbstractObject$compare(md, md2))
})
test_that("encoding - i18n",{
testthat::skip_on_cran()
md <- ISOMemberName$new()
md$setName(
"name",
locales = list(
EN = "name in english",
FR = "nom en français",
ES = "Nombre en español",
AR = "الاسم باللغة العربية",
RU = "имя на русском",
ZH = "中文名"
))
md$setAttributeType("type")
expect_is(md, "ISOMemberName")
xml <- md$encode()
expect_is(xml, "XMLInternalNode")
md2 <- ISOMemberName$new(xml = xml)
xml2 <- md2$encode()
expect_true(ISOAbstractObject$compare(md, md2))
})
|
faces<-function(xy,which.row,fill=FALSE,face.type=1,
nrow.plot,ncol.plot,scale=TRUE,byrow=FALSE,main,
labels,print.info = TRUE,na.rm = FALSE,
ncolors=20,
col.nose=rainbow(ncolors),
col.eyes=rainbow(ncolors,start=0.6,end=0.85),
col.hair=terrain.colors(ncolors),
col.face=heat.colors(ncolors),
col.lips=rainbow(ncolors,start=0.0,end=0.2),
col.ears=rainbow(ncolors,start=0.0,end=0.2),
plot.faces=TRUE, cex = 2){
if((demo<-missing(xy))){
xy<-rbind(
c(1,3,5),c(3,5,7),
c(1,5,3),c(3,7,5),
c(3,1,5),c(5,3,7),
c(3,5,1),c(5,7,3),
c(5,1,3),c(7,3,5),
c(5,3,1),c(7,5,3),
c(1,1,1),c(4,4,4),c(7,7,7)
)
labels<-apply(xy,1,function(x) paste(x,collapse="-"))
}
spline<-function(a,y,m=200,plot=FALSE){
n<-length(a)
h<-diff(a)
dy<-diff(y)
sigma<-dy/h
lambda<-h[-1]/(hh<-h[-1]+h[-length(h)])
mu<-1-lambda
d<-6*diff(sigma)/hh
tri.mat<-2*diag(n-2)
tri.mat[2+ (0:(n-4))*(n-1)] <-mu[-1]
tri.mat[ (1:(n-3))*(n-1)] <-lambda[-(n-2)]
M<-c(0,solve(tri.mat)%*%d,0)
x<-seq(from=a[1],to=a[n],length=m)
anz.kl <- hist(x,breaks=a,plot=FALSE)$counts
adj<-function(i) i-1
i<-rep(1:(n-1),anz.kl)+1
S.x<- M[i-1]*(a[i]-x )^3 / (6*h[adj(i)]) +
M[i] *(x -a[i-1])^3 / (6*h[adj(i)]) +
(y[i-1] - M[i-1]*h[adj(i)]^2 /6) * (a[i]-x)/ h[adj(i)] +
(y[i] - M[i] *h[adj(i)]^2 /6) * (x-a[i-1]) / h[adj(i)]
if(plot){ plot(x,S.x,type="l"); points(a,y) }
return(cbind(x,S.x))
}
n.char<-15
xy<-rbind(xy)
if(byrow) xy<-t(xy)
if(any(is.na(xy))){
if(na.rm){
xy<-xy[!apply(is.na(xy),1,any),,drop=FALSE]
if(nrow(xy)<3) {print("not enough data points"); return()}
print("Warning: NA elements have been removed!!")
}else{
xy.means<-colMeans(xy,na.rm=TRUE)
for(j in 1:length(xy[1,])) xy[is.na(xy[,j]),j]<-xy.means[j]
print("Warning: NA elements have been exchanged by mean values!!")
}
}
if(!missing(which.row)&& all( !is.na(match(which.row,1:dim(xy)[2])) ))
xy<-xy[,which.row,drop=FALSE]
mm<-dim(xy)[2]; n<-dim(xy)[1]
xnames<-dimnames(xy)[[1]]
if(is.null(xnames)) xnames<-as.character(1:n)
if(!missing(labels)) xnames<-labels
if(scale){
xy<-apply(xy,2,function(x){
x<-x-min(x); x<-if(max(x)>0) 2*x/max(x)-1 else x })
} else xy[]<-pmin(pmax(-1,xy),1)
xy<-rbind(xy);n.c<-dim(xy)[2]
xy<-xy[,(rows.orig<-h<-rep(1:mm,ceiling(n.char/mm))),drop=FALSE]
if(fill) xy[,-(1:n.c)]<-0
face.orig<-list(
eye =rbind(c(12,0),c(19,8),c(30,8),c(37,0),c(30,-8),c(19,-8),c(12,0))
,iris =rbind(c(20,0),c(24,4),c(29,0),c(24,-5),c(20,0))
,lipso=rbind(c(0,-47),c( 7,-49),lipsiend=c( 16,-53),c( 7,-60),c(0,-62))
,lipsi=rbind(c(7,-54),c(0,-54))
,nose =rbind(c(0,-6),c(3,-16),c(6,-30),c(0,-31))
,shape =rbind(c(0,44),c(29,40),c(51,22),hairend=c(54,11),earsta=c(52,-4),
earend=c(46,-36),c(38,-61),c(25,-83),c(0,-89))
,ear =rbind(c(60,-11),c(57,-30))
,hair =rbind(hair1=c(72,12),hair2=c(64,50),c(36,74),c(0,79))
)
lipso.refl.ind<-4:1
lipsi.refl.ind<-1
nose.refl.ind<-3:1
hair.refl.ind<-3:1
shape.refl.ind<-8:1
shape.xnotnull<-2:8
nose.xnotnull<-2:3
nr<-n^0.5; nc<-n^0.5
if(!missing(nrow.plot)) nr<-nrow.plot
if(!missing(ncol.plot)) nc<-ncol.plot
if(plot.faces){
opar<-par(mfrow=c(ceiling(c(nr,nc))),oma=rep(6,4), mar=rep(.7,4))
on.exit(par(opar))
}
face.list<-list()
for(ind in 1:n){
factors<-xy[ind,]
face<-face.orig
m<-mean(face$lipso[,2])
face$lipso[,2]<-m+(face$lipso[,2]-m)*(1+0.7*factors[4])
face$lipsi[,2]<-m+(face$lipsi[,2]-m)*(1+0.7*factors[4])
face$lipso[,1]<-face$lipso[,1]*(1+0.7*factors[5])
face$lipsi[,1]<-face$lipsi[,1]*(1+0.7*factors[5])
face$lipso["lipsiend",2]<-face$lipso["lipsiend",2]+20*factors[6]
m<-mean(face$eye[,2])
face$eye[,2] <-m+(face$eye[,2] -m)*(1+0.7*factors[7])
face$iris[,2]<-m+(face$iris[,2]-m)*(1+0.7*factors[7])
m<-mean(face$eye[,1])
face$eye[,1] <-m+(face$eye[,1] -m)*(1+0.7*factors[8])
face$iris[,1]<-m+(face$iris[,1]-m)*(1+0.7*factors[8])
m<-min(face$hair[,2])
face$hair[,2]<-m+(face$hair[,2]-m)*(1+0.2*factors[9])
m<-0
face$hair[,1]<-m+(face$hair[,1]-m)*(1+0.2*factors[10])
m<-0
face$hair[c("hair1","hair2"),2]<-face$hair[c("hair1","hair2"),2]+50*factors[11]
m<-mean(face$nose[,2])
face$nose[,2]<-m+(face$nose[,2]-m)*(1+0.7*factors[12])
face$nose[nose.xnotnull,1]<-face$nose[nose.xnotnull,1]*(1+factors[13])
m<-mean(face$shape[c("earsta","earend"),1])
face$ear[,1]<-m+(face$ear[,1]-m)* (1+0.7*factors[14])
m<-min(face$ear[,2])
face$ear[,2]<-m+(face$ear[,2]-m)* (1+0.7*factors[15])
face<-lapply(face,function(x){ x[,2]<-x[,2]*(1+0.2*factors[1]);x})
face<-lapply(face,function(x){ x[,1]<-x[,1]*(1+0.2*factors[2]);x})
face<-lapply(face,function(x){ x[,1]<-ifelse(x[,1]>0,
ifelse(x[,2] > -30, x[,1],
pmax(0,x[,1]+(x[,2]+50)*0.2*sin(1.5*(-factors[3])))),0);x})
invert<-function(x) cbind(-x[,1],x[,2])
face.obj<-list(
eyer=face$eye
,eyel=invert(face$eye)
,irisr=face$iris
,irisl=invert(face$iris)
,lipso=rbind(face$lipso,invert(face$lipso[lipso.refl.ind,]))
,lipsi=rbind(face$lipso["lipsiend",],face$lipsi,
invert(face$lipsi[lipsi.refl.ind,,drop=FALSE]),
invert(face$lipso["lipsiend",,drop=FALSE]))
,earr=rbind(face$shape["earsta",],face$ear,face$shape["earend",])
,earl=invert(rbind(face$shape["earsta",],face$ear,face$shape["earend",]))
,nose=rbind(face$nose,invert(face$nose[nose.refl.ind,]))
,hair=rbind(face$shape["hairend",],face$hair,invert(face$hair[hair.refl.ind,]),
invert(face$shape["hairend",,drop=FALSE]))
,shape=rbind(face$shape,invert(face$shape[shape.refl.ind,]))
)
face.list<-c(face.list,list(face.obj))
if(plot.faces){
plot(1,type="n",xlim=c(-105,105)*1.1, axes=FALSE,
ylab="",ylim=c(-105,105)*1.3)
title(xnames[ind], cex.main = cex, xpd = NA)
f<-1+(ncolors-1)*(factors+1)/2
xtrans<-function(x){x}; ytrans<-function(y){y}
for(obj.ind in seq(face.obj)[c(10:11,1:9)]) {
x <-face.obj[[obj.ind]][,1]; y<-face.obj[[obj.ind]][,2]
xx<-spline(1:length(x),x,40,FALSE)[,2]
yy<-spline(1:length(y),y,40,FALSE)[,2]
if(plot.faces){
lines(xx,yy)
if(face.type>0){
if(obj.ind==10)
polygon(xtrans(xx),ytrans(yy),col=col.hair[ceiling(mean(f[9:11]))],xpd=NA)
if(obj.ind==11){
polygon(xtrans(xx),ytrans(yy),col=col.face[ceiling(mean(f[1:2 ]))],xpd=NA)
if(face.type==2){
for(zzz in seq(hhh<-max(face.obj[[8]][,1]),-hhh,length=30)){
hrx<-rnorm(8,zzz,2); hry<-0:7*-3*rnorm(1,3)+abs(hrx)^2/150
hry<-min(face.obj[[9]][,2])+hry
lines(xtrans(hrx),ytrans(hry),lwd=5,col="
}
ind<-which.max(xx); wx<-xx[ind]; ind<-which.max(yy); wy<-yy[ind]
wxh<-wx<-seq(-wx,wx,length=20); wyh<-wy<-wy-(wx-mean(wx))^2/250+runif(20)*3
lines(xtrans(wxh),ytrans(wyh)); wx<-c(wx,rev(wx)); wy<-c(wy-10,rev(wy)+20)
wmxy1<-wmxy0<-c(min(wx),min(wy)+20)
wmxy2<-wmxy3<-c(runif(1,wmxy0[1],-wmxy0[1]), wy[1]+100)
wmxy1[2]<-0.5*(wmxy0[2]+wmxy3[2]); wmxy2[1]<-0.5*(wmxy2[1]+wmxy0[1])
npxy<-20; pxy<-seq(0,1,length=npxy)
gew<-outer(pxy,0:3,"^")*outer(1-pxy,3:0,"^")*
matrix(c(1,3,3,1),npxy,4,byrow=TRUE)
wxl<-wmxy0[1]*gew[,1]+wmxy1[1]*gew[,2]+wmxy2[1]*gew[,3]+wmxy3[1]*gew[,4]
wyl<-wmxy0[2]*gew[,1]+wmxy1[2]*gew[,2]+wmxy2[2]*gew[,3]+wmxy3[2]*gew[,4]
lines(xtrans(wxl),ytrans(wyl),col="green")
wmxy1[1]<- wmxy0[1]<- -wmxy0[1]
wmxy1[2]<-0.5*(wmxy0[2]+wmxy3[2]); wmxy2[1]<-0.5*(wmxy2[1]+wmxy0[1])
wxr<-wmxy0[1]*gew[,1]+wmxy1[1]*gew[,2]+wmxy2[1]*gew[,3]+wmxy3[1]*gew[,4]
wyr<-wmxy0[2]*gew[,1]+wmxy1[2]*gew[,2]+wmxy2[2]*gew[,3]+wmxy3[2]*gew[,4]
points(xtrans(wmxy3[1]),ytrans(wmxy3[2]),pch=19,cex=2,col="
points(xtrans(wmxy3[1]),ytrans(wmxy3[2]),pch=11,cex=2.53,col="red",xpd=NA)
polygon(xtrans(c(wxl,rev(wxr))),ytrans(c(wyl,rev(wyr))),col="red",xpd=NA)
polygon(xtrans(wx),ytrans(wy),col="
}
}
xx<-xtrans(xx); yy<-ytrans(yy)
if(obj.ind %in% 1:2) polygon(xx,yy,col="
if(obj.ind %in% 3:4) polygon(xx,yy,col=col.eyes[ceiling(mean(f[7:8 ]))],xpd=NA)
if(obj.ind %in% 9) polygon(xx,yy,col=col.nose[ceiling(mean(f[12:13]))],xpd=NA)
if(obj.ind %in% 5:6) polygon(xx,yy,col=col.lips[ceiling(mean(f[1:3]))],xpd=NA)
if(obj.ind %in% 7:8) polygon(xx,yy,col=col.ears[ceiling(mean(f[14:15]))],xpd=NA)
}
}
}
}
}
if(plot.faces&&!missing(main)){
par(opar);par(mfrow=c(1,1))
mtext(main, 3, 3, TRUE, 0.5)
title(main)
}
info<-c(
"var1"="height of face ",
"var2"="width of face ",
"var3"="structure of face",
"var4"="height of mouth ",
"var5"="width of mouth ",
"var6"="smiling ",
"var7"="height of eyes ",
"var8"="width of eyes ",
"var9"="height of hair ",
"var10"="width of hair ",
"var11"="style of hair ",
"var12"="height of nose ",
"var13"="width of nose ",
"var14"="width of ear ",
"var15"="height of ear ")
var.names<-dimnames(xy)[[2]]
if(0==length(var.names)) var.names<-paste("Var",rows.orig,sep="")
info<-cbind("modified item"=info,"Var"=var.names[1:length(info)])
rownames(info)<-rep("",15)
if(print.info){
cat("effect of variables:\n")
print(info)
}
if(demo&&plot.faces) {
plot(1:15,1:15,type="n",axes=FALSE,bty="n")
text(rep(1,15),15:1,adj=0,apply(info,1,function(x)
paste(x,collapse=" - ")),cex=0.7)
}
names(face.list)<-xnames
out<-list(faces=face.list,info=info,xy=t(xy))
class(out)<-"faces"
invisible(out)
}
|
frenchdata <- new.env()
NULL
print.french_data_list <- function(x, ...) {
cli::cli_h3("Kenneth's French data library")
cli::cli_alert_info(x$info)
cli::cli_text("")
cli::cli_h3("Files list")
print(x$files_list, ...)
}
browse_french_site <- function() {
utils::browseURL("https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html")
}
get_french_data_list <- function(max_tries = 3,
refresh = FALSE) {
assertthat::assert_that(is.numeric(max_tries),
length(max_tries) == 1)
assertthat::assert_that(assertthat::is.flag(refresh))
if ((refresh == TRUE) || (!exists("french_data_files_list",
envir = frenchdata)))
{
base_url <-
"https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html"
trial <- 1
success <- FALSE
while (trial <= as.integer(max_tries)) {
request <-
httr::GET(base_url)
if (httr::status_code(request) == 200) {
success <- TRUE
page <- httr::content(request, encoding = "UTF-8")
links <- get_info(page)
break()
} else {
trial <- trial + 1
cli::cli_h3("Error reading the page")
cli::cli_alert_danger(httr::http_status(request)$message)
cli::cli_alert_info("Trying again in 5 seconds. Please wait...")
Sys.sleep(5)
}
}
if (success == FALSE) {
cli::cli_h3("Unable to get the file list")
cli::cli_alert_danger("Max trials reached!")
cli::cli_alert(
"Check your internet connection; please check if you can visit the site <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html> on a browser."
)
cli::cli_alert(
"Try again in a couple of minutes and if the problem persists please open a ticket on the package github site."
)
files_list <- NULL
} else {
files_list <-
structure(list(
info = paste(
"Information collected from:",
base_url,
"on",
format(Sys.time(), "%a %b %d %H:%M:%S %Y")
),
files_list = links
),
class = "french_data_list")
assign("french_data_files_list", files_list, envir = frenchdata)
}
} else {
files_list <- get("french_data_files_list", envir = frenchdata)
}
return(files_list)
}
get_info <- function(page) {
links <- tibble::tibble(file_url = page %>%
rvest::html_elements("a") %>%
rvest::html_attr("href")) %>%
dplyr::filter(stringr::str_detect(.data$file_url, "_CSV.zip")) %>%
dplyr::mutate(
name = purrr::map(.data$file_url,
find_file_description,
page),
details_url = purrr::map(.data$file_url,
find_details,
page)
) %>%
dplyr::select(.data$name, .data$file_url, .data$details_url) %>%
tidyr::unnest(cols = c(.data$name, .data$details_url))
return(links)
}
find_file_description <- function(url, page) {
page %>%
rvest::html_elements(xpath =
paste0("//a[contains(@href,'", url,
"')]/preceding::b[2]")) %>%
rvest::html_text()
}
find_details <- function(url, page) {
page %>%
rvest::html_elements(xpath =
paste0("//a[contains(@href,'", url,
"')]/following::a[1]")) %>%
rvest::html_attr("href")
}
|
vt_create_node <- function (total_lab = "Total") {
stopifnot(is_scalar_character(total_lab))
node <- Node$new(total_lab)
node
}
vt_add_nodes <- function(node, refnode, node_names, colors=NULL, weights=NULL, codes=NULL) {
cur_node <- FindNode(node, refnode)
if (is.null(cur_node)) {
return(NULL)
}
stopifnot(is.character(node_names))
if (!is.null(colors)) {
stopifnot(is.character(colors), length(colors)==length(node_names))
}
if (!is.null(weights)) {
stopifnot(is.numeric(weights), length(weights)==length(node_names))
}
if (!is.null(codes)) {
stopifnot(is.character(codes), length(codes)==length(node_names))
}
col <- ww <- cc <- NULL
for (i in seq_along(node_names)) {
lab <- node_names[i]
if (!is.null(FindNode(cur_node, lab))) {
cat("Node", lab, "already exists under", shQuote(refnode), "--> skipping\n")
}
else {
if(!is.null(weights)) {
ww <- weights[i]
}
if(!is.null(colors)) {
col <- colors[i]
}
if(!is.null(codes)) {
cc <- codes[i]
}
cur_node$AddChild(lab, color=col, weight=ww, code=cc)
}
}
return(node)
}
|
rplotsClass <- R6::R6Class(
"rplotsClass",
inherit = rplotsBase,
private = list(
.run = function() {
vars <- self$options$vars
factor <- self$options$splitBy
for (var in vars) {
image <- self$results$plots$get(key=var)
v <- jmvcore::toNumeric(self$data[[var]])
df <- data.frame(v=v)
if ( ! is.null(self$options$splitBy))
df$f <- factor(self$data[[factor]])
else
df$f <- factor(rep('var', length(v)))
df <- jmvcore::naOmit(df)
image$setState(df)
}
},
.plot = function(image, ggtheme, theme, ...) {
if (is.null(image$state))
return(FALSE)
factor <- self$options$splitBy
p <- ggplot2::ggplot(data=image$state, ggplot2::aes(x = f, y = v)) +
ggtheme + ggplot2::theme(legend.position = "none") +
ggplot2::labs(x=factor, y=image$key)
if (self$options$violin)
p <- p + ggplot2::geom_violin(fill=theme$fill[1], color=theme$color[1])
if (self$options$dot) {
if (self$options$dotType == 'jitter')
p <- p + ggplot2::geom_jitter(color=theme$color[1], width=0.1, alpha=0.4)
else
p <- p + ggplot2::geom_dotplot(binaxis = "y", stackdir = "center", color=theme$color[1],
alpha=0.4, stackratio=0.9, dotsize=0.7)
}
if (self$options$boxplot)
p <- p + ggplot2::geom_boxplot(color=theme$color[1], width=0.2, alpha=0.9, fill=theme$fill[2],
outlier.colour=theme$color[1])
if (is.null(self$options$splitBy)) {
p <- p + ggplot2::theme(axis.text.x = ggplot2::element_blank(),
axis.ticks.x = ggplot2::element_blank(),
axis.title.x = ggplot2::element_blank())
}
suppressWarnings({
suppressMessages({
print(p)
})
})
TRUE
})
)
|
SS_readdat_3.00 <- function(file,verbose=TRUE,echoall=FALSE,section=NULL){
if(verbose) cat("running SS_readdat_3.00\n")
dat <- readLines(file,warn=FALSE)
if(!is.null(section)){
Nsections <- as.numeric(substring(dat[grep("Number_of_datafiles",dat)],24))
if(!section %in% 1:Nsections) stop("The 'section' input should be within the 'Number_of_datafiles' in a data.ss_new file.\n")
if(section==1){
end <- grep("
if (length(end) == 0) end <- length(dat)
dat <- dat[grep("
}
if(section==2){
end <- grep("
if (length(end) == 0) end <- length(dat)
dat <- dat[grep("
}
if(section>=3){
start <- grep(paste("
end <- grep(paste("
if(length(end)==0) end <- length(dat)
dat <- dat[start:end]
}
}
temp <- strsplit(dat[2]," ")[[1]][1]
if(!is.na(temp) && temp=="Start_time:") dat <- dat[-(1:2)]
allnums <- NULL
for(i in 1:length(dat)){
mysplit <- strsplit(dat[i],split="[[:blank:]]+")[[1]]
mysplit <- mysplit[mysplit!=""]
nvals <- length(mysplit)
if(nvals>0) mysplit[nvals] <- strsplit(mysplit[nvals],"
nums <- suppressWarnings(as.numeric(mysplit))
if(sum(is.na(nums)) > 0) maxcol <- min((1:length(nums))[is.na(nums)])-1
else maxcol <- length(nums)
if(maxcol > 0){
nums <- nums[1:maxcol]
allnums <- c(allnums, nums)
}
}
i <- 1
datlist <- list()
datlist$eof <- FALSE
datlist$sourcefile <- file
datlist$type <- "Stock_Synthesis_data_file"
datlist$ReadVersion <- "3.00"
if (verbose){
message("SS_readdat_3.00 - SS version = ", datlist$ReadVersion)
}
datlist$styr <- allnums[i]; i <- i+1
datlist$endyr <- allnums[i]; i <- i+1
datlist$nseas <- nseas <- allnums[i]; i <- i+1
datlist$months_per_seas <- allnums[i:(i+nseas-1)]; i <- i+nseas
datlist$spawn_seas <- allnums[i]; i <- i+1
datlist$Nfleet <- Nfleet <- allnums[i]; i <- i+1
datlist$Nsurveys <- Nsurveys <- allnums[i]; i <- i+1
Ntypes <- Nfleet+Nsurveys
datlist$N_areas <- allnums[i]; i <- i+1
fleetnames.good <- NULL
if(Ntypes>1){
percentlines <- grep('%',dat)
for(iline in percentlines){
fleetnames <- dat[iline]
fleetnames <- strsplit(fleetnames,'%')[[1]]
fleetnames[length(fleetnames)] <- strsplit(fleetnames[length(fleetnames)],"[[:blank:]]+")[[1]][1]
if(length(fleetnames)==Ntypes) fleetnames.good <- fleetnames
}
fleetnames <- fleetnames.good
if(is.null(fleetnames))
fleetnames <- c(paste("fishery",1:Nfleet),paste("survey",1:Nsurveys))
}else{
fleetnames <- "fleet1"
}
datlist$fleetnames <- fleetnames
datlist$surveytiming <- surveytiming <- allnums[i:(i+Ntypes-1)]; i <- i+Ntypes
datlist$areas <- areas <- allnums[i:(i+Ntypes-1)]; i <- i+Ntypes
if(verbose){
cat("areas:",areas,'\n')
cat("fleet info:\n")
print(data.frame(fleet = 1:Ntypes,
name = fleetnames,
area = areas,
timing = surveytiming,
type = c(rep("FISHERY",Nfleet), rep("SURVEY",Nsurveys))))
}
fleetinfo1 <- data.frame(rbind(surveytiming,areas))
names(fleetinfo1) <- fleetnames
fleetinfo1$input <- c("
datlist$fleetinfo1 <- fleetinfo1
datlist$units_of_catch <- units_of_catch <- allnums[i:(i+Nfleet-1)]; i <- i+Nfleet
datlist$se_log_catch <- se_log_catch <- allnums[i:(i+Nfleet-1)]; i <- i+Nfleet
fleetinfo2 <- data.frame(rbind(units_of_catch,se_log_catch))
names(fleetinfo2) <- fleetnames[1:Nfleet]
fleetinfo2$input <- c("
datlist$fleetinfo2 <- fleetinfo2
datlist$Ngenders <- Ngenders <- allnums[i]; i <- i+1
datlist$Nages <- Nages <- allnums[i]; i <- i+1
datlist$init_equil <- allnums[i:(i+Nfleet-1)]; i <- i+Nfleet
datlist$N_catch <- N_catch <- allnums[i]; i <- i+1
if(verbose) cat("N_catch =",N_catch,"\n")
Nvals <- N_catch*(Nfleet+2)
catch <- data.frame(matrix(allnums[i:(i+Nvals-1)],
nrow=N_catch,ncol=(Nfleet+2),byrow=TRUE))
names(catch) <- c(fleetnames[1:Nfleet],"year","seas")
datlist$catch <- catch
i <- i+Nvals
if(echoall) print(catch)
datlist$N_cpue <- N_cpue <- allnums[i]; i <- i+1
if(verbose) cat("N_cpue =",N_cpue,"\n")
if(N_cpue > 0){
CPUEinfo <- data.frame(matrix(c(1:Ntypes,rep(1,Ntypes),rep(0,Ntypes)),
nrow=Ntypes,ncol=3,byrow=FALSE))
names(CPUEinfo) <- c("Fleet","Units","Errtype")
CPUE <- data.frame(matrix(
allnums[i:(i+N_cpue*5-1)],nrow=N_cpue,ncol=5,byrow=TRUE))
i <- i+N_cpue*5
names(CPUE) <- c('year','seas','index','obs','se_log')
CPUE<-CPUE[which(CPUE$obs>=0),]
}else{
CPUEinfo <- NULL
CPUE <- NULL
}
datlist$CPUEinfo <- CPUEinfo
datlist$CPUE <- CPUE
if(echoall){
print(CPUEinfo)
print(CPUE)
}
Dis_type <- allnums[i]; i <- i+1
datlist$N_discard <- N_discard <- allnums[i]; i <- i+1
if(verbose) cat("N_discard =",N_discard,"\n")
if(N_discard > 0){
Ncols <- 5
discard_data <- data.frame(matrix(
allnums[i:(i+N_discard*Ncols-1)],nrow=N_discard,ncol=Ncols,byrow=TRUE))
i <- i+N_discard*Ncols
names(discard_data) <- c('Yr','Seas','Flt','Discard','Std_in')
datlist$discard_data <- discard_data
datlist$N_discard_fleets <- N_discard_fleets <- length(unique(discard_data$Flt))
datlist$discard_fleet_info <- data.frame(matrix(c(unique(discard_data$Flt),
rep(Dis_type,N_discard_fleets),rep(0,N_discard_fleets)),
nrow=N_discard_fleets,ncol=3,byrow=FALSE))
names(datlist$discard_fleet_info) <- c("Fleet","units","errtype")
}else{
datlist$N_discard_fleets <- 0
datlist$discard_data <- NULL
datlist$discard_fleet_info <- NULL
}
datlist$N_meanbodywt <- N_meanbodywt <- allnums[i]; i <- i+1
if(verbose) cat("N_meanbodywt =",N_meanbodywt,"\n")
if(N_meanbodywt > 0){
Ncols <- 6
meanbodywt <- data.frame(matrix(
allnums[i:(i+N_meanbodywt*Ncols-1)],nrow=N_meanbodywt,ncol=Ncols,byrow=TRUE))
i <- i+N_meanbodywt*Ncols
names(meanbodywt) <- c('Year','Seas','Type','Partition','Value','CV')
datlist$DF_for_meanbodywt <- NULL
}else{
datlist$DF_for_meanbodywt <- NULL
meanbodywt <- NULL
}
datlist$meanbodywt <- meanbodywt
if(echoall) print(meanbodywt)
datlist$lbin_method <- lbin_method <- allnums[i]; i <- i+1
if(echoall) cat("lbin_method =",lbin_method,"\n")
if(lbin_method==2){
datlist$binwidth <- allnums[i]; i <- i+1
datlist$minimum_size <- allnums[i]; i <- i+1
datlist$maximum_size <- allnums[i]; i <- i+1
if(echoall) cat("bin width, min, max =",datlist$binwidth,", ",datlist$minimum_size,", ",datlist$maximum_size,"\n")
}else{
datlist$binwidth <- NA
datlist$minimum_size <- NA
datlist$maximum_size <- NA
}
if(lbin_method==3){
datlist$N_lbinspop <- N_lbinspop <- allnums[i]; i <- i+1
datlist$lbin_vector_pop <- allnums[i:(i+N_lbinspop-1)]; i <- i+N_lbinspop
if(echoall) cat("N_lbinspop =",N_lbinspop,"\nlbin_vector_pop:\n")
}else{
datlist$N_lbinspop <- NA
datlist$lbin_vector_pop <- NA
}
datlist$comp_tail_compression <- allnums[i]; i <- i+1
datlist$add_to_comp <- allnums[i]; i <- i+1
datlist$max_combined_age <- allnums[i]; i <- i+1
datlist$N_lbins <- N_lbins <- allnums[i]; i <- i+1
datlist$lbin_vector <- lbin_vector <- allnums[i:(i+N_lbins-1)]; i <- i+N_lbins
if(echoall) print(lbin_vector)
datlist$N_lencomp <- N_lencomp <- allnums[i]; i <- i+1
if(verbose) cat("N_lencomp =",N_lencomp,"\n")
if(N_lencomp > 0){
Ncols <- N_lbins*Ngenders+6
lencomp <- data.frame(matrix(
allnums[i:(i+N_lencomp*Ncols-1)],nrow=N_lencomp,ncol=Ncols,byrow=TRUE))
i <- i+N_lencomp*Ncols
names(lencomp) <- c("Yr","Seas","FltSvy","Gender","Part","Nsamp",
if(Ngenders==1){paste("l",lbin_vector,sep="")}else{NULL},
if(Ngenders>1){ c(paste("f",lbin_vector,sep=""),paste("m",lbin_vector,sep="")) }else{ NULL } )
}else{
lencomp <- NULL
}
datlist$lencomp <- lencomp
datlist$N_agebins <- N_agebins <- allnums[i]; i <- i+1
if(verbose) cat("N_agebins =",N_agebins,"\n")
if(N_agebins > 0){
agebin_vector <- allnums[i:(i+N_agebins-1)]; i <- i+N_agebins
}else{
agebin_vector <- NULL
}
datlist$agebin_vector <- agebin_vector
if(echoall) print(agebin_vector)
datlist$N_ageerror_definitions <- N_ageerror_definitions <- allnums[i]; i <- i+1
if(N_ageerror_definitions > 0){
Ncols <- Nages+1
ageerror <- data.frame(matrix(
allnums[i:(i+2*N_ageerror_definitions*Ncols-1)],
nrow=2*N_ageerror_definitions,ncol=Ncols,byrow=TRUE))
i <- i+2*N_ageerror_definitions*Ncols
names(ageerror) <- paste("age",0:Nages,sep="")
}else{
ageerror <- NULL
}
datlist$ageerror <- ageerror
datlist$N_agecomp <- N_agecomp <- allnums[i]; i <- i+1
if(verbose) cat("N_agecomp =",N_agecomp,"\n")
datlist$Lbin_method <- allnums[i]; i <- i+1
datlist$max_combined_lbin <- allnums[i]; i <- i+1
if(N_agecomp > 0){
if(N_agebins==0) stop("N_agecomp =",N_agecomp," but N_agebins = 0")
Ncols <- N_agebins*Ngenders+9
agecomp <- data.frame(matrix(allnums[i:(i+N_agecomp*Ncols-1)],
nrow=N_agecomp,ncol=Ncols,byrow=TRUE))
i <- i+N_agecomp*Ncols
names(agecomp) <- c("Yr","Seas","FltSvy","Gender","Part","Ageerr","Lbin_lo","Lbin_hi","Nsamp",
if(Ngenders==1){paste("a",agebin_vector,sep="")}else{NULL},
if(Ngenders>1){ c(paste("f",agebin_vector,sep=""),paste("m",agebin_vector,sep="")) }else{ NULL } )
}else{
agecomp <- NULL
}
datlist$agecomp <- agecomp
datlist$N_MeanSize_at_Age_obs <- N_MeanSize_at_Age_obs <- allnums[i]; i <- i+1
if(verbose) cat("N_MeanSize_at_Age_obs =",N_MeanSize_at_Age_obs,"\n")
if(N_MeanSize_at_Age_obs > 0){
Ncols <- 2*N_agebins*Ngenders + 7
MeanSize_at_Age_obs <- data.frame(matrix(
allnums[i:(i+N_MeanSize_at_Age_obs*Ncols-1)],nrow=N_MeanSize_at_Age_obs,ncol=Ncols,byrow=TRUE))
i <- i+N_MeanSize_at_Age_obs*Ncols
names(MeanSize_at_Age_obs) <- c('Yr','Seas','FltSvy','Gender','Part','AgeErr','Ignore',
if(Ngenders==1){paste("a",agebin_vector,sep="")}else{NULL},
if(Ngenders>1){ c(paste("f",agebin_vector,sep=""),paste("m",agebin_vector,sep="")) }else{ NULL },
if(Ngenders==1){paste("N_a",agebin_vector,sep="")}else{NULL},
if(Ngenders>1){ c(paste("N_f",agebin_vector,sep=""),paste("N_m",agebin_vector,sep="")) }else{ NULL } )
}else{
MeanSize_at_Age_obs <- NULL
}
datlist$MeanSize_at_Age_obs <- MeanSize_at_Age_obs
datlist$N_environ_variables <- N_environ_variables <- allnums[i]; i <- i+1
datlist$N_environ_obs <- N_environ_obs <- allnums[i]; i <- i+1
if(N_environ_obs > 0){
Ncols <- 3
envdat <- data.frame(matrix(
allnums[i:(i+Ncols*N_environ_obs-1)],nrow=N_environ_obs,ncol=Ncols,byrow=TRUE))
i <- i+N_environ_obs*Ncols
names(envdat) <- c("Yr","Variable","Value")
}else{
envdat <- NULL
}
datlist$envdat <- envdat
datlist$N_sizefreq_methods <- N_sizefreq_methods <- allnums[i]; i <- i+1
if(verbose) cat("N_sizefreq_methods =",N_sizefreq_methods,"\n")
if(N_sizefreq_methods > 0){
datlist$nbins_per_method <- nbins_per_method <- allnums[i:(i+N_sizefreq_methods-1)]
i <- i+N_sizefreq_methods
datlist$units_per_method <- units_per_method <- allnums[i:(i+N_sizefreq_methods-1)]
i <- i+N_sizefreq_methods
datlist$scale_per_method <- scale_per_method <- allnums[i:(i+N_sizefreq_methods-1)]
i <- i+N_sizefreq_methods
datlist$mincomp_per_method <- mincomp_per_method <- allnums[i:(i+N_sizefreq_methods-1)]
i <- i+N_sizefreq_methods
datlist$Nobs_per_method <- Nobs_per_method <- allnums[i:(i+N_sizefreq_methods-1)]
i <- i+N_sizefreq_methods
if(verbose){
cat("details of generalized size frequency methods:\n")
print(data.frame(method = 1:N_sizefreq_methods,
nbins = nbins_per_method,
units = units_per_method,
scale = scale_per_method,
mincomp = mincomp_per_method,
nobs = Nobs_per_method))
}
sizefreq_bins_list <- list()
for(imethod in 1:N_sizefreq_methods){
sizefreq_bins_list[[imethod]] <- allnums[i:(i+nbins_per_method[imethod]-1)]
i <- i+nbins_per_method[imethod]
}
datlist$sizefreq_bins_list <- sizefreq_bins_list
sizefreq_data_list <- list()
for(imethod in 1:N_sizefreq_methods){
Ncols <- 7+Ngenders*nbins_per_method[imethod]
Nrows <- Nobs_per_method[imethod]
sizefreq_data_tmp <- data.frame(matrix(allnums[i:(i+Nrows*Ncols-1)],
nrow=Nrows,ncol=Ncols,byrow=TRUE))
names(sizefreq_data_tmp) <-
c("Method","Yr","Seas","FltSvy","Gender","Part","Nsamp",
if(Ngenders==1){
paste("a",sizefreq_bins_list[[imethod]],sep="")
}else{NULL},
if(Ngenders>1){
c(paste("f",sizefreq_bins_list[[imethod]],sep=""),
paste("m",sizefreq_bins_list[[imethod]],sep=""))
}else{NULL})
if(verbose){
cat("Method =",imethod," (first two rows, ten columns):\n")
print(sizefreq_data_tmp[1:min(Nrows,2),1:min(Ncols,10)])
}
if(any(sizefreq_data_tmp$Method!=imethod))
stop("Problem with method in size frequency data:\n",
"Expecting method: ",imethod,"\n",
"Read method(s): ",paste(unique(sizefreq_data_tmp$Method),collapse=", "))
sizefreq_data_list[[imethod]] <- sizefreq_data_tmp
i <- i+Nrows*Ncols
}
datlist$sizefreq_data_list <- sizefreq_data_list
}else{
datlist$nbins_per_method <- NULL
datlist$units_per_method <- NULL
datlist$scale_per_method <- NULL
datlist$mincomp_per_method <- NULL
datlist$Nobs_per_method <- NULL
datlist$sizefreq_bins_list <- NULL
datlist$sizefreq_data_list <- NULL
}
datlist$do_tags <- do_tags <- allnums[i]; i <- i+1
if(verbose) cat("do_tags =",do_tags,"\n")
if(do_tags != 0){
datlist$N_tag_groups <- N_tag_groups <- allnums[i]; i <- i+1
datlist$N_recap_events <- N_recap_events <- allnums[i]; i <- i+1
datlist$mixing_latency_period <- mixing_latency_period <- allnums[i]; i <- i+1
datlist$max_periods <- max_periods <- allnums[i]; i <- i+1
if(N_tag_groups > 0){
Ncols <- 8
tag_releases <- data.frame(matrix(allnums[i:(i+N_tag_groups*Ncols-1)],nrow=N_tag_groups,ncol=Ncols,byrow=TRUE))
i <- i+N_tag_groups*Ncols
names(tag_releases) <- c('TG', 'Area', 'Yr', 'Season', 'tfill', 'Gender', 'Age', 'Nrelease')
if(verbose){
cat("Head of tag release data:\n")
print(head(tag_releases))
}
}else{
tag_releases <- NULL
}
datlist$tag_releases <- tag_releases
if(N_recap_events > 0){
Ncols <- 5
tag_recaps <- data.frame(matrix(allnums[i:(i+N_recap_events*Ncols-1)],nrow=N_recap_events,ncol=Ncols,byrow=TRUE))
i <- i+N_recap_events*Ncols
names(tag_recaps) <- c('TG', 'Yr', 'Season', 'Fleet', 'Nrecap')
if(verbose){
cat("Head of tag recapture data:\n")
print(head(tag_recaps))
}
}else{
tag_recaps <- NULL
}
datlist$tag_recaps <- tag_recaps
}
datlist$morphcomp_data <- do_morphcomps <- allnums[i]; i <- i+1
if(verbose) cat("do_morphcomps =",do_morphcomps,"\n")
if(allnums[i]==999){
if(verbose) cat("read of data file 3.00 complete (final value = 999)\n")
datlist$eof <- TRUE
}else{
cat("Error: final value is", allnums[i]," but should be 999\n")
datlist$eof <- FALSE
}
return(datlist)
}
|
`ltrend.test` <-
function (y,
group,
score = NULL,
location = c("median", "mean", "trim.mean"),
tail = c("right", "left", "both"),
trim.alpha = 0.25,
bootstrap = FALSE,
num.bootstrap = 1000,
correction.method = c("none",
"correction.factor",
"zero.removal",
"zero.correction"),
correlation.method = c("pearson", "kendall", "spearman"))
{
if (is.null(score))
{
score <- group
}
if (length(y) != length(group))
{
stop("the length of the data (y) does not match the length of the group")
}
location <- match.arg(location)
tail <- match.arg(tail)
correlation.method <- match.arg(correlation.method)
correction.method <- match.arg(correction.method)
DNAME <- deparse(substitute(y))
y <- y[!is.na(y)]
score <- score[!is.na(y)]
group <- group[!is.na(y)]
if ((location == "trim.mean") & (trim.alpha > 0.5))
{
stop("trim.alpha value of 0 to 0.5 should be provided for the trim.mean location")
}
reorder <- order(group)
group <- group[reorder]
y <- y[reorder]
score <- score[reorder]
gr <- score
group <- as.factor(group)
if (location == "mean")
{
means <- tapply(y, group, mean)
METHOD <-
"ltrend test based on classical Levene's procedure using the group means"
}
else if (location == "median")
{
means <- tapply(y, group, median)
METHOD <-
"ltrend test based on the modified Brown-Forsythe Levene-type procedure using the group medians"
} else {
location <- "trim.mean"
means <- tapply(y, group, mean, trim = trim.alpha)
METHOD <-
"ltrend test based on the modified Brown-Forsythe Levene-type procedure using the group trimmed means"
}
n <- tapply(y, group, length)
ngroup <- n[group]
resp.mean <- abs(y - means[group])
if (location != "median" &&
correction.method != "correction.factor")
{
METHOD <-
paste(
METHOD,
"(",
correction.method,
"not applied because the location is not set to median",
")"
)
correction.method <- "none"
}
if (correction.method == "correction.factor")
{
METHOD <- paste(METHOD, "with correction factor applied")
correction <- 1 / sqrt(1 - 1 / ngroup)
resp.mean <- resp.mean * correction
}
if (correction.method == "zero.removal" ||
correction.method == "zero.correction")
{
if (correction.method == "zero.removal")
{
METHOD <-
paste(METHOD,
"with Hines-Hines structural zero removal method")
}
if (correction.method == "zero.correction")
{
METHOD <-
paste(
METHOD,
"with modified structural zero removal method and correction factor"
)
}
resp.mean <- y - means[group]
k <- length(n)
temp <- double()
endpos <- double()
startpos <- double()
for (i in 1:k)
{
group.size <- n[i]
j <- i - 1
if (i == 1)
start <- 1
else
start <- sum(n[1:j]) + 1
startpos <- c(startpos, start)
end <- sum(n[1:i])
endpos <- c(endpos, end)
sub.resp.mean <- resp.mean[start:end]
sub.resp.mean <- sub.resp.mean[order(sub.resp.mean)]
if (group.size %% 2 == 1)
{
mid <- (group.size + 1) / 2
temp2 <- sub.resp.mean[-mid]
if (correction.method == "zero.correction")
{
ntemp <- length(temp2) + 1
correction <- sqrt((ntemp - 1) / ntemp)
temp2 <- correction * temp2
}
}
if (group.size %% 2 == 0)
{
mid <- group.size / 2
if (correction.method == "zero.removal")
{
denom <- sqrt(2)
}
else
{
denom <- 1
}
replace1 <- (sub.resp.mean[mid + 1] - sub.resp.mean[mid]) / denom
temp2 <- sub.resp.mean[c(-mid, -mid - 1)]
temp2 <- c(temp2, replace1)
if (correction.method == "zero.correction")
{
ntemp <- length(temp2) + 1
correction <- sqrt((ntemp - 1) / ntemp)
temp2 <- correction * temp2
}
}
temp <- c(temp, temp2)
}
ngroup2 <- ngroup[-endpos] - 1
resp.mean <- abs(temp)
zero.removal.gr <- gr[-endpos]
}
else
{
correction.method = "none"
}
mu <- mean(resp.mean)
z <- as.vector(resp.mean - mu)
if (correction.method == "zero.removal" ||
correction.method == "zero.correction")
{
d <- as.numeric(zero.removal.gr)
}
else
{
d <- as.numeric(gr)
}
t.statistic <- summary(lm(z ~ d))$coefficients[2, 3]
df <- summary(lm(z ~ d))$df[2]
if (correlation.method == "pearson")
{
correlation <- cor(d, z, method = "pearson")
if (tail == "left")
{
METHOD <-
paste(METHOD,
"(left-tailed with Pearson correlation coefficient)")
p.value <- pt(t.statistic, df, lower.tail = TRUE)
log.p.value <- pt(t.statistic,
df,
lower.tail = TRUE,
log.p = TRUE)
log.q.value <- pt(t.statistic,
df,
lower.tail = FALSE,
log.p = TRUE)
}
else if (tail == "right")
{
METHOD <-
paste(METHOD,
"(right-tailed with Pearson correlation coefficient)")
p.value <- pt(t.statistic, df, lower.tail = FALSE)
log.p.value <- pt(t.statistic,
df,
lower.tail = FALSE,
log.p = TRUE)
log.q.value <- pt(t.statistic,
df,
lower.tail = TRUE,
log.p = TRUE)
}
else
{
tail <- "both"
METHOD <-
paste(METHOD,
"(two-tailed with Pearson correlation coefficient)")
p.value <- pt(t.statistic, df, lower.tail = TRUE)
log.p.value <- pt(t.statistic,
df,
lower.tail = TRUE,
log.p = TRUE)
log.q.value <- pt(t.statistic,
df,
lower.tail = FALSE,
log.p = TRUE)
if (p.value >= 0.5)
{
p.value <- pt(t.statistic, df, lower.tail = FALSE)
log.p.value <- pt(t.statistic,
df,
lower.tail = FALSE,
log.p = TRUE)
log.q.value <- pt(t.statistic,
df,
lower.tail = TRUE,
log.p = TRUE)
}
p.value <- p.value * 2
log.p.value <- log.p.value + log(2)
log.q.value <- log(1 - p.value)
}
}
else if (correlation.method == "kendall")
{
correlation <- cor(d, z, method = "kendall")
if (tail == "left")
{
METHOD <-
paste(METHOD,
"(left-tailed with Kendall correlation coefficient)")
p.value.temp <- Kendall(d, z)$sl
if (correlation < 0)
{
p.value <- p.value.temp / 2
}
else
{
p.value <- 1 - p.value.temp / 2
}
q.value <- 1 - p.value
log.p.value <- log(p.value)
log.q.value <- log(q.value)
}
if (tail == "right")
{
METHOD <-
paste(METHOD,
"(right-tailed with Kendall correlation coefficient)")
p.value.temp <- Kendall(d, z)$sl
if (correlation > 0)
{
p.value <- p.value.temp / 2
}
else
{
p.value <- 1 - p.value.temp / 2
}
q.value <- 1 - p.value
log.p.value <- log(p.value)
log.q.value <- log(q.value)
}
if (tail == "both")
{
METHOD <-
paste(METHOD,
"(two-tailed with Kendall correlation coefficient)")
p.value <- Kendall(d, z)$sl
q.value <- 1 - p.value
log.p.value <- log(p.value)
log.q.value <- log(q.value)
}
}
else
{
correlation <- cor(d, z, method = "spearman")
if (tail == "left")
{
METHOD <-
paste(METHOD,
"(left-tailed with Spearman correlation coefficient)")
p.value.temp <- cor.test(d, z, method = "spearman")$p.value
if (correlation < 0)
{
p.value <- p.value.temp / 2
}
else
{
p.value <- 1 - p.value.temp / 2
}
q.value <- 1 - p.value
log.p.value <- log(p.value)
log.q.value <- log(q.value)
}
if (tail == "right")
{
METHOD <-
paste(METHOD,
"(right-tailed with Spearman correlation coefficient)")
p.value.temp <- cor.test(d, z, method = "spearman")$p.value
if (correlation > 0)
{
p.value <- p.value.temp / 2
}
else
{
p.value <- 1 - p.value.temp / 2
}
q.value <- 1 - p.value
log.p.value <- log(p.value)
log.q.value <- log(q.value)
}
if (tail == "both")
{
METHOD <-
paste(METHOD,
"(two-tailed with Spearman correlation coefficient)")
p.value <- cor.test(d, z, method = "spearman")$p.value
q.value <- 1 - p.value
log.p.value <- log(p.value)
log.q.value <- log(q.value)
}
}
non.bootstrap.p.value <- p.value
if (bootstrap == TRUE)
{
METHOD = paste("bootstrap", METHOD)
R <- 0
N <- length(y)
frac.trim.alpha = 0.2
b.trimmed.mean <- function(y)
{
nn <- length(y)
wt <- rep(0, nn)
y2 <- y[order(y)]
lower <- ceiling(nn * frac.trim.alpha) + 1
upper <- floor(nn * (1 - frac.trim.alpha))
if (lower > upper)
stop("frac.trim.alpha value is too large")
m <- upper - lower + 1
frac <- (nn * (1 - 2 * frac.trim.alpha) - m) / 2
wt[lower - 1] <- frac
wt[upper + 1] <- frac
wt[lower:upper] <- 1
return(weighted.mean(y2, wt))
}
b.trim.means <- tapply(y, group, b.trimmed.mean)
rm <- y - b.trim.means[group]
for (j in 1:num.bootstrap)
{
sam <- sample(rm, replace = TRUE)
boot.sample <- sam
if (min(n) < 10)
{
U <- runif(1) - 0.5
means <- tapply(y, group, mean)
v <- sqrt(sum((y - means[group]) ^ 2) / N)
boot.sample <- ((12 / 13) ^ (0.5)) * (sam + v * U)
}
if (location == "mean") {
boot.means <- tapply(boot.sample, group, mean)
} else if (location == "median") {
boot.means <- tapply(boot.sample, group, median)
} else {
location <- "trim.mean"
boot.means <- tapply(boot.sample, group, mean, trim = trim.alpha)
}
resp.boot.mean <- abs(boot.sample - boot.means[group])
if (correction.method == "correction.factor")
{
correction <- 1 / sqrt(1 - 1 / ngroup)
resp.boot.mean <- resp.boot.mean * correction
}
if (correction.method == "zero.removal" ||
correction.method == "zero.correction")
{
resp.mean <- boot.sample - boot.means[group]
k <- length(n)
temp <- double()
endpos <- double()
startpos <- double()
for (i in 1:k)
{
group.size <- n[i]
j <- i - 1
if (i == 1)
start <- 1
else
start <- sum(n[1:j]) + 1
startpos <- c(startpos, start)
end <- sum(n[1:i])
endpos <- c(endpos, end)
sub.resp.mean <- resp.mean[start:end]
sub.resp.mean <- sub.resp.mean[order(sub.resp.mean)]
if (group.size %% 2 == 1)
{
mid <- (group.size + 1) / 2
temp2 <- sub.resp.mean[-mid]
if (correction.method == "zero.correction")
{
ntemp <- length(temp2) + 1
correction <- sqrt((ntemp - 1) / ntemp)
temp2 <- correction * temp2
}
}
if (group.size %% 2 == 0)
{
mid <- group.size / 2
if (correction.method == "zero.removal")
{
denom <- sqrt(2)
}
else
{
denom <- 1
}
replace1 <- (sub.resp.mean[mid + 1] - sub.resp.mean[mid]) / denom
temp2 <- sub.resp.mean[c(-mid, -mid - 1)]
temp2 <- c(temp2, replace1)
if (correction.method == "zero.correction")
{
ntemp <- length(temp2) + 1
correction <- sqrt((ntemp - 1) / ntemp)
temp2 <- correction * temp2
}
}
temp <- c(temp, temp2)
}
ngroup2 <- ngroup[-endpos] - 1
resp.boot.mean <- abs(temp)
zero.removal.gr <- gr[-endpos]
}
if (correction.method == "zero.removal" ||
correction.method == "zero.correction")
{
d <- as.numeric(zero.removal.gr)
}
else
{
d <- as.numeric(gr)
}
boot.mu <- mean(resp.boot.mean)
boot.z <- as.vector(resp.boot.mean - boot.mu)
correlation2 <- cor(boot.z, d, method = correlation.method)
if (tail == "right")
{
if (correlation2 > correlation)
R <- R + 1
}
else if (tail == "left")
{
if (correlation2 < correlation)
R <- R + 1
}
else
{
tail = "both"
if (abs(correlation2) > abs(correlation))
R <- R + 1
}
}
p.value <- R / num.bootstrap
}
STATISTIC = correlation
names(STATISTIC) = "Test Statistic (Correlation)"
structure(
list(
statistic = STATISTIC,
p.value = p.value,
method = METHOD,
data.name = DNAME,
t.statistic = t.statistic,
non.bootstrap.p.value = non.bootstrap.p.value,
log.p.value = log.p.value,
log.q.value = log.q.value
),
class = "htest"
)
}
|
parallelPermFun = function(offsets, lefttemp, rghttemp, obs_zscr){
if( is.character(lefttemp) ) {
leftSets = readRDS(file = lefttemp)
} else {
leftSets = lefttemp;
}
if( is.character(rghttemp) ) {
rghtSets = readRDS(file = rghttemp)
} else {
rghtSets = rghttemp;
}
obs_cntE = matrix(NA_real_, length(leftSets), length(rghtSets));
obs_cntD = matrix(NA_real_, length(leftSets), length(rghtSets));
obs_cntO = matrix(NA_real_, length(leftSets), length(rghtSets));
all_zmin = Inf;
all_zmax = -Inf;
for(i in seq_along(leftSets)){
for(j in seq_along(rghtSets)){
z = shiftrPermBinary(
left = leftSets[[i]],
right = rghtSets[[j]],
offsets = offsets,
alsoDoFisher = FALSE,
returnPermOverlaps = TRUE);
all_z = cramerV(z$overlapsPerm,
z$lfeatures,
z$rfeatures,
z$nfeatures);
obs_cntE[i, j] = sum(all_z >= obs_zscr[i,j]);
obs_cntD[i, j] = sum(all_z <= obs_zscr[i,j]);
obs_cntO[i, j] = sum(abs(all_z) >= abs(obs_zscr[i,j]));
all_zmin = pmin.int(all_zmin, all_z);
all_zmax = pmax.int(all_zmax, all_z);
rm(z, all_z);
}
}
obs_zmax = max(obs_zscr);
obs_zmin = min(obs_zscr);
all_cntE = sum(all_zmax >= obs_zmax);
all_cntD = sum(all_zmin <= obs_zmin);
all_cntO = sum(pmax(all_zmax, -all_zmin) >= max(obs_zmax, -obs_zmin));
result = list(
npermute = length(offsets),
obs_cntE = obs_cntE,
obs_cntD = obs_cntD,
obs_cntO = obs_cntO,
all_cntE = all_cntE,
all_cntD = all_cntD,
all_cntO = all_cntO);
return(result);
}
enrichmentAnalysis = function(
pvstats1,
pvstats2,
percentiles1 = NULL,
percentiles2 = NULL,
npermute,
margin = 0.05,
threads = 1){
stopifnot( length(pvstats1) == length(pvstats2) );
n = length(pvstats1);
if(margin > 1)
margin = margin / length(pvstats1);
maxperm = getNOffsetsMax(n = n, margin = margin);
if(npermute >= maxperm) {
npermute = maxperm;
offsets = getOffsetsAll(n = n, margin = margin);
} else {
offsets = getOffsetsRandom(n = n, npermute = npermute, margin = margin);
}
if(is.null(threads))
threads = TRUE;
if(is.logical(threads)){
if(threads){
threads = detectCores();
} else {
threads = 1L;
}
}
if(sum(!duplicated(pvstats1)) > 2){
thresholds1 = quantile(
x = pvstats1,
probs = percentiles1,
na.rm = TRUE,
names = FALSE);
} else {
thresholds1 = min(pvstats1);
}
if(sum(!duplicated(pvstats2)) > 2){
thresholds2 = quantile(
x = pvstats2,
probs = percentiles2,
na.rm = TRUE,
names = FALSE);
} else {
thresholds2 = min(pvstats2);
}
leftSets = vector('list', length(thresholds1));
for(i in seq_along(thresholds1)){
bool1 = (pvstats1 <= thresholds1[i]);
if((!any(bool1)) || all(bool1))
stop("No variaton in primary data after mapping and thresholding");
leftSets[[i]] = shiftrPrepareLeft(bool1);
rm(bool1);
}
rghtSets = vector('list', length(thresholds2));
for(j in seq_along(thresholds2)){
bool2 = (pvstats2 <= thresholds2[j]);
if((!any(bool2)) || all(bool2))
stop("No variaton in enrichment data after mapping and thresholding");
rghtSets[[j]] = shiftrPrepareRight(bool2);
rm(bool2);
}
obs_zscr = matrix(NA_real_, length(thresholds1), length(thresholds2));
for(i in seq_along(thresholds1)){
for(j in seq_along(thresholds2)){
z = shiftrPermBinary(
left = leftSets[[i]],
right = rghtSets[[j]],
offsets = c(),
alsoDoFisher = FALSE,
returnPermOverlaps = FALSE);
obs_zscr[i, j] = cramerV(
z$overlap,
z$lfeatures,
z$rfeatures,
z$nfeatures);
rm(z);
}
}
if( threads > 1){
lefttemp = tempfile();
rghttemp = tempfile();
saveRDS(file = lefttemp, leftSets, compress = FALSE)
saveRDS(file = rghttemp, rghtSets, compress = FALSE)
cl = makeCluster(threads);
clres = clusterApplyLB(
cl,
clusterSplit(cl, offsets),
parallelPermFun,
lefttemp = lefttemp,
rghttemp = rghttemp,
obs_zscr = obs_zscr);
stopCluster(cl);
file.remove(lefttemp);
file.remove(rghttemp);
sumlist = lapply(names(clres[[1]]),
function(nm){ Reduce('+',lapply(clres,`[[`,nm)) });
names(sumlist) = names(clres[[1]]);
} else {
sumlist = parallelPermFun(
offsets = offsets,
lefttemp = leftSets,
rghttemp = rghtSets,
obs_zscr = obs_zscr);
}
stopifnot(npermute == sumlist$npermute)
result = list(
overallPV = c(
TwoSided = sumlist$all_cntO / npermute,
Enrichment = sumlist$all_cntE / npermute,
Depletion = sumlist$all_cntD / npermute),
byThresholdPV = list(
TwoSided = sumlist$obs_cntO / npermute,
Enrichment = sumlist$obs_cntE / npermute,
Depletion = sumlist$obs_cntD / npermute)
);
return(result);
}
|
asym2sym <- function(foodweb, problem, name, single) {
if (any(duplicated(t(foodweb[1,-(1)]))) || any(duplicated(foodweb[-(1),1]))) {
if (single==TRUE) {
print("Your matrix contains duplicate species names. The first row and column of the matrix must be species names.")} else {
write.table(cbind(name, "Duplicated species names"), file = problem, append=TRUE, quote=FALSE, sep=",",
col.names=FALSE, row.names=FALSE)}
} else {
if (length(setdiff(foodweb[1,], foodweb[,1]))+length(setdiff(foodweb[,1], foodweb[1,]))==0){} else {
foodweb[1,1] <- 9999
colnames(foodweb) <- foodweb[1,]
row.names(foodweb) <- foodweb[,1]
non.basal.sp <- ncol(foodweb)
no.col <- as.vector(setdiff(row.names(foodweb), colnames(foodweb)))
for (i in no.col) {
foodweb <- cbind(foodweb, as.numeric(c(i,rep(0, times=nrow(foodweb)-1))))
colnames(foodweb)[(which(no.col==i) + non.basal.sp)] <- i
}
no.row <- as.vector(setdiff(colnames(foodweb), row.names(foodweb)))
for (i in no.row) {
foodweb <- rbind(foodweb, as.numeric(c(i,rep(0, times=ncol(foodweb)-1))))
row.names(foodweb)[nrow(foodweb)] <- i
}
foodweb <- foodweb[-(1),-(1)]
foodweb <- foodweb[,order(as.numeric(colnames(foodweb)))]
foodweb <<- foodweb[order(as.numeric(row.names(foodweb))),]
}
}
}
|
.getstructure <- function(fid, strgp){
gid <- rhdf5::H5Gopen(fid, strgp)
data <- rhdf5::h5dump(gid)
rhdf5::H5Gclose(gid)
if(length(which(data$reCalcVar!="")) > 0)
{
data$reCalcVar <- data$reCalcVar[which(data$reCalcVar!="")]
data$variable <- c(data$variable, data$reCalcVar)
data$reCalcVar <- NULL
}
data
}
.tryCloseH5 <- function(){
try(rhdf5::H5close(), silent = TRUE)
}
|
exptab <- function(tab, file, dids = names(tab),
aggiungi = FALSE, ...)
{
for (i in seq_along(tab)){
write(dids[[i]],
file,
append = ifelse(i == 1, aggiungi, TRUE))
write.table(tab[[i]],
file,
dec = ",",
sep = ";",
na = "",
row.names = ifelse(length(dimnames(tab[[i]]))==1,
FALSE, TRUE),
col.names = ifelse(length(dimnames(tab[[i]]))==1,
TRUE, NA),
append = TRUE,
...)
write(" ",
file,
append = TRUE)
}
}
|
ge_factanal <- function(.data, env, gen, rep, resp, mineval = 1,
verbose = TRUE) {
factors <-
.data %>%
select({{env}}, {{gen}}, {{rep}}) %>%
mutate(across(everything(), as.factor))
vars <- .data %>% select({{resp}}, -names(factors))
vars %<>% select_numeric_cols()
factors %<>% set_names("ENV", "GEN", "REP")
listres <- list()
nvar <- ncol(vars)
for (var in 1:nvar) {
data <- factors %>%
mutate(Y = vars[[var]])
if(has_na(data)){
data <- remove_rows_na(data)
has_text_in_num(data)
}
means <- make_mat(data, GEN, ENV, Y)
cor.means <- cor(means)
eigen.decomposition <- eigen(cor.means)
eigen.values <- eigen.decomposition$values
eigen.vectors <- eigen.decomposition$vectors
colnames(eigen.vectors) <- paste("PC", 1:ncol(cor.means), sep = "")
rownames(eigen.vectors) <- colnames(means)
if (length(eigen.values[eigen.values >= mineval]) == 1) {
eigen.values.factors <- as.vector(c(as.matrix(sqrt(eigen.values[eigen.values >= mineval]))))
initial.loadings <- cbind(eigen.vectors[, eigen.values >= mineval] * eigen.values.factors)
A <- initial.loadings
} else {
eigen.values.factors <- t(replicate(ncol(cor.means), c(as.matrix(sqrt(eigen.values[eigen.values >= mineval])))))
initial.loadings <- eigen.vectors[, eigen.values >= mineval] * eigen.values.factors
A <- varimax(initial.loadings)[[1]][]
}
partial <- solve_svd(cor.means)
k <- ncol(means)
seq_k <- seq_len(ncol(means))
for (j in seq_k) {
for (i in seq_k) {
if (i == j) {
next
} else {
partial[i, j] <- -partial[i, j]/sqrt(partial[i,
i] * partial[j, j])
}
}
}
KMO <- sum((cor.means[!diag(k)])^2)/(sum((cor.means[!diag(k)])^2) +
sum((partial[!diag(k)])^2))
MSA <- unlist(lapply(seq_k, function(i) {
sum((cor.means[i, -i])^2)/(sum((cor.means[i, -i])^2) +
sum((partial[i, -i])^2))
}))
names(MSA) <- colnames(means)
colnames(A) <- paste("FA", 1:ncol(initial.loadings), sep = "")
variance <- (eigen.values/sum(eigen.values)) * 100
cumulative.var <- cumsum(eigen.values/sum(eigen.values)) *
100
pca <- data.frame(PCA = paste("PC", 1:ncol(means), sep = ""),
Eigenvalues = eigen.values, Variance = variance,
Cumul_var = cumulative.var)
Communality <- diag(A %*% t(A))
Uniquenesses <- 1 - Communality
fa <- data.frame(Env = names(means), A, Communality,
Uniquenesses)
z <- scale(means, center = FALSE, scale = apply(means, 2,
sd))
canonical.loadings <- t(t(A) %*% solve_svd(cor.means))
scores <- z %*% canonical.loadings
colnames(scores) <- paste("FA", 1:ncol(scores), sep = "")
rownames(scores) <- rownames(means)
pos.var.factor <- which(abs(A) == apply(abs(A), 1, max),
arr.ind = TRUE)
var.factor <- lapply(1:ncol(A), function(i) {
rownames(pos.var.factor)[pos.var.factor[, 2] == i]
})
names(var.factor) <- paste("FA", 1:ncol(A), sep = "")
names.pos.var.factor <- rownames(pos.var.factor)
means.factor <- means[, names.pos.var.factor]
genv <- data.frame(Env = names(means.factor),
Factor = paste("FA", pos.var.factor[, 2], sep = ""),
Mean = colMeans(means.factor),
Min = apply(means.factor, 2, min),
Max = apply(means.factor, 2, max),
CV = (apply(means.factor, 2, sd)/apply(means.factor, 2, mean)) * 100)
colnames(initial.loadings) <- paste("FA", 1:ncol(initial.loadings), sep = "")
if(ncol(scores) < 2){
warning("The number of retained factors is ",ncol(scores),
".\nA plot with the scores cannot be obtained.\nUse 'mineval' to increase the number of factors retained", call. = FALSE)
}
temp <- (structure(list(data = as_tibble(data),
cormat = as.matrix(cor.means),
PCA = as_tibble(pca),
FA = as_tibble(fa),
env_strat = as_tibble(genv),
KMO = KMO,
MSA = MSA,
communalities = Communality,
communalities.mean = mean(Communality),
initial.loadings = as_tibble(cbind(Env = names(means), as_tibble(initial.loadings))),
finish.loadings = as_tibble(cbind(Env = names(means), as_tibble(A))),
canonical.loadings = as_tibble(cbind(Env = names(means), as_tibble(canonical.loadings))),
scores.gen = as_tibble(cbind(Gen = rownames(means), as_tibble(scores)))), class = "ge_factanal"))
listres[[paste(names(vars[var]))]] <- temp
}
return(structure(listres, class = "ge_factanal"))
}
plot.ge_factanal <- function(x, var = 1, plot_theme = theme_metan(), x.lim = NULL, x.breaks = waiver(),
x.lab = NULL, y.lim = NULL, y.breaks = waiver(), y.lab = NULL,
shape = 21, col.shape = "gray30", col.alpha = 1, size.shape = 2.2,
size.bor.tick = 0.3, size.tex.lab = 12, size.tex.pa = 3.5,
force.repel = 1, line.type = "dashed", line.alpha = 1,
col.line = "black", size.line = 0.5, ...) {
x <- x[[var]]
if (!class(x) == "ge_factanal") {
stop("The object 'x' is not of class 'ge_factanal'")
}
data <- data.frame(x$scores.gen)
if(ncol(data) == 2){
stop("A plot cannot be generated with only one factor. \nUse 'mineval' argument in 'ge_factanal()' to increase the number of factors retained.", call. = FALSE)
}
if (is.null(y.lab) == FALSE) {
y.lab <- y.lab
} else {
y.lab <- paste("Factor 2 (",round(x$PCA$Variance[[2]],2), "%)", sep = "")
}
if (is.null(x.lab) == FALSE) {
x.lab <- x.lab
} else {
x.lab <- paste("Factor 1 (",round(x$PCA$Variance[[1]],2), "%)", sep = "")
}
p <- ggplot(data = data, aes(x = FA1, y = FA2)) +
geom_hline(yintercept = mean(data[,3]), linetype = line.type, color = col.line, size = size.line, alpha = line.alpha)+
geom_vline(xintercept = mean(data[,2]), linetype = line.type, color = col.line, size = size.line, alpha = line.alpha)+
geom_point(shape = shape, size = size.shape, fill = col.shape, stroke = size.bor.tick, alpha = col.alpha)+
labs(x = x.lab, y = y.lab)+
geom_text_repel(aes(label = Gen), size = size.tex.pa, force = force.repel)+
scale_x_continuous(limits = x.lim, breaks = x.breaks) +
scale_y_continuous(limits = y.lim, breaks = y.breaks) +
plot_theme %+replace%
theme(aspect.ratio = 1,
axis.text = element_text(size = size.tex.lab, color = "black"),
axis.title = element_text(size = size.tex.lab, color = "black"),
axis.ticks = element_line(color = "black"))
return(p)
}
print.ge_factanal <- function(x, export = FALSE, file.name = NULL, digits = 4, ...) {
if (!class(x) == "ge_factanal") {
stop("The object must be of class 'ge_factanal'")
}
opar <- options(pillar.sigfig = digits)
on.exit(options(opar))
if (export == TRUE) {
file.name <- ifelse(is.null(file.name) == TRUE, "ge_factanal print", file.name)
sink(paste0(file.name, ".txt"))
}
for (i in 1:length(x)) {
var <- x[[i]]
cat("Variable", names(x)[i], "\n")
cat("------------------------------------------------------------------------------------\n")
cat("Correlation matrix among environments\n")
cat("------------------------------------------------------------------------------------\n")
print(as_tibble(var$cormat, rownames = "ENV"))
cat("------------------------------------------------------------------------------------\n")
cat("Eigenvalues and explained variance\n")
cat("------------------------------------------------------------------------------------\n")
print(var$PCA)
cat("------------------------------------------------------------------------------------\n")
cat("Initial loadings\n")
cat("------------------------------------------------------------------------------------\n")
print(var$initial.loadings)
cat("------------------------------------------------------------------------------------\n")
cat("Loadings after varimax rotation and commonalities\n")
cat("------------------------------------------------------------------------------------\n")
print(var$FA)
cat("------------------------------------------------------------------------------------\n")
cat("Environmental stratification based on factor analysis\n")
cat("------------------------------------------------------------------------------------\n")
print(var$env_strat)
cat("------------------------------------------------------------------------------------\n")
cat("Mean = mean; Min = minimum; Max = maximum; CV = coefficient of variation (%)\n")
cat("------------------------------------------------------------------------------------\n")
cat("\n\n\n")
}
if (export == TRUE) {
sink()
}
}
|
board_blob <- board_azure_test(path = "", type = "blob")
test_api_basic(board_blob)
test_api_versioning(board_blob)
test_api_meta(board_blob)
board_blob2 <- board_azure_test(path = "test/path", type = "blob")
test_api_basic(board_blob2)
test_api_versioning(board_blob2)
test_api_meta(board_blob2)
test_that("can deparse", {
board <- board_azure_test(path = "test/path", type = "blob")
expect_snapshot(board_deparse(board))
})
|
context("Tidy dataframe with scriptures")
suppressPackageStartupMessages(library(dplyr))
test_that("tidy frame for LDS scriptures books is right", {
scriptures <- lds_scriptures()
expect_equal(nrow(scriptures), 41995)
expect_equal(ncol(scriptures), 19)
scriptures_test <- scriptures %>%
group_by(volume_title) %>%
summarise(total_verses = n())
expect_equal(nrow(scriptures_test), 5)
expect_equal(ncol(scriptures_test), 2)
})
|
wilcoxtestClust <- function(x, ...) {
UseMethod("wilcoxtestClust")
}
wilcoxtestClust.default <- function (x, y = NULL, idx, idy=NULL,
alternative = c("two.sided", "less", "greater"),
mu = 0, paired = FALSE, method = c("cluster", "group"), ...)
{
meth <- match.arg(method)
alternative <- match.arg(alternative)
if (!missing(mu) && ((length(mu) > 1L) || !is.finite(mu)))
stop("'mu' must be a single number")
if (!is.numeric(x))
stop("'x' must be numeric")
if (!is.null(y)) {
if (!is.numeric(y))
stop("'y' must be numeric")
DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(y)))
if (paired) {
if (length(x) != length(y))
stop("'x' and 'y' must have the same length")
OK <- stats::complete.cases(x, y, idx)
x <- x[OK] - y[OK]
idx <- idx[OK]
y <- idy <- NULL
m <- length(unique(idx))
METHOD <- "Paired cluster-weighted signed rank test"
}
else {
xok <- stats::complete.cases(x, idx)
yok <- stats::complete.cases(y, idy)
x <- x[xok]
idx <- factor(as.factor(idx[xok]), levels=unique(as.factor(idx[xok])))
y <- y[yok]
idy <- factor(as.factor(idy[yok]), levels=unique(as.factor(idy[yok])))
xdat <- data.frame(idx, x, rep(0,length(x)))
ydat <- data.frame(idy, y, rep(1,length(y)))
colnames(xdat) <- c("ID", "X", "grp")
colnames(ydat) <- c("ID", "X", "grp")
dat <- rbind(xdat, ydat)
dat[,1] <- as.numeric(dat[,1])
dat <- dat[with(dat, order(ID)),]
}
}
else {
DNAME <- deparse(substitute(x))
if (paired)
stop("'y' is missing for paired test")
xok <- stats::complete.cases(x, idx)
yok <- NULL
x <- x[xok]
idx <- idx[xok]
m <- length(unique(idx))
METHOD <- "One sample cluster-weighted signed rank test"
}
if (length(x) < 1L)
stop("not enough (finite) 'x' observations")
if (is.null(y)) {
x <- x - mu
datx <- cbind.data.frame(idx, x)
datx <- datx[with(datx, order(idx)),]
x <- datx$x
idx <- factor(as.factor(datx$idx), levels=unique(as.factor(datx$idx)))
Fi <- function(x,i) { Xi <- Xij[(cni[i]+1):(cni[i+1])];
(sum(abs(Xi)<=x)+sum(abs(Xi)<x))/(2*ni[i])}
Ftot <- function(x) { st <- 0;
for (i in 1:g) st <- st + Fi(x,i);
return(st)}
Fcom <- function(x) { st <- 0;
for (i in 1:g) st <- st + Fi(x,i)*ni[i];
return(st/n)}
Xij <- x
ni <- as.vector(table(idx))
g <- length(ni)
n <- sum(ni)
cni <- c(0, cumsum(ni))
TS <- VTS <- 0
for (i in 1:g) {
Xi <- Xij[(cni[i]+1):(cni[i+1])]
first <- (sum(Xi>0)-sum(Xi<0))/length(Xi)
second <- 0
third <- 0
for (x in Xi) { second <- second + sign(x)*(Ftot(abs(x))-Fi(abs(x),i));
third <- third + sign(x)*Fcom(abs(x))}
TS <- TS + first+second/length(Xi)
VTS <- VTS + (first+ (g-1)*third/length(Xi))^2
}
Z <- TS/sqrt(VTS)
PVAL <- switch(alternative, less = stats::pnorm(Z), greater = stats::pnorm(Z,
lower.tail = FALSE), two.sided = 2*(1-stats::pnorm(abs(Z))))
}
else {
mu <- 0
m <- length(unique(dat[,1]))
if (meth=="cluster") {
METHOD <- "Cluster-weighted rank sum test"
clus.rank.sum<-function(Cluster,X,grp) {
if (length(unique(Cluster[grp==1]))!=length(unique(Cluster[grp==0])))
stop ("Incomplete intra-cluster group structure: can not apply cluster-weighted rank sum test")
n<-length(X)
F.hat<-numeric(n)
for (i in 1:n){
F.hat[i]<-(sum(X<=X[i])+sum(X<X[i]))/(2*n)
}
M<-length(unique(Cluster))
n.i<-table(Cluster)
F.prop<-numeric(n)
for(ii in 1:n){
F.j<-numeric(M)
for (i in 1:M){
F.j[i]<-(sum(X[Cluster==i]<X[ii])+0.5*sum(X[Cluster==i]==X[ii]))/(n.i[i])
}
F.prop[ii]<-sum(F.j[-Cluster[ii]])
}
a<-numeric(M)
b<-1+F.prop
for (i in 1:M){
a[i]<-sum((grp[Cluster==i]*b[Cluster==i])/(n.i[i]))
}
c<-1/(M+1)
S<-c*sum(a)
n.i1 <- table(Cluster, grp)[,2]
d<-n.i1/n.i
E.S<-(1/2)*sum(d)
W.hat<-numeric(M)
a<-n.i1/n.i
for (i in 1:M){
b<-1/(n.i[i]*(M+1))
c<-(grp[Cluster==i])*(M-1)
d<-sum(a[-i])
W.hat[i]<-b*sum((c-d)*F.hat[Cluster==i])
}
a<-n.i1/n.i
E.W<-(M/(2*(M+1)))*(a-sum(a)/M)
var.s<-sum((W.hat-E.W)^2)
stat<-(S-E.S)/sqrt(var.s)
stat
}
Z <- clus.rank.sum(dat$ID, dat$X, dat$grp)
PVAL <- switch(alternative, less = stats::pnorm(Z), greater = stats::pnorm(Z, lower.tail = FALSE),
two.sided = 2*(1-stats::pnorm(abs(Z))))
}
else {
METHOD <- "Group-weighted rank sum test"
rn<-function(dv){
ik=dv[1]
x=dv[2]
ds1=dat[dat[,3]==1,]
vs1=(kh==2)*(ds1[,2]<x)+(kh==1)*(ds1[,2]<=x)
ic1 <- subset(unique(dat[,1]), !(unique(dat[,1]) %in% unique(ds1[,1])))
if (length(ic1)==0) {
sl1=stats::aggregate(vs1,list(ds1[,1]),mean)[,2]
}
else {
cmp1 <- stats::aggregate(vs1,list(ds1[,1]),mean)
incp1 <- data.frame(cbind(ic1, rep(0, length(ic1))))
colnames(incp1) <- colnames(cmp1)
tmp1 <- rbind(cmp1, incp1)
sl1 <- tmp1[with(tmp1, order(tmp1[,1])), 2]
}
ds2=dat[dat[,3]==0,]
vs2=(kh==2)*(ds2[,2]<x)+(kh==1)*(ds2[,2]<=x)
ic2 <- subset(unique(dat[,1]), !(unique(dat[,1]) %in% unique(ds2[,1])))
if (length(ic2)==0) {
sl2=stats::aggregate(vs2,list(ds2[,1]),mean)[,2]
}
else {
cmp2 <- stats::aggregate(vs2,list(ds2[,1]),mean)
incp2 <- data.frame(cbind(ic2, rep(0, length(ic2))))
colnames(incp2) <- colnames(cmp2)
tmp2 <- rbind(cmp2, incp2)
sl2 <- tmp2[with(tmp2, order(tmp2[,1])), 2]
}
Fwt <- 1*unique(dat[,1])%in%c(ic1,ic2) + 2*(1-1*unique(dat[,1])%in%c(ic1,ic2))
fg=(sl1+sl2)/Fwt
fg[ik]=0
return(fg)
}
rst <- function(il){
ly=sum(mat[-which(dw[,1]==il),-il])
return(ly)
}
m <- g <- length(unique(dat[,1]))
dw <- dat[(dat[,3]==1),]
ns <- (dw[,1])
incc1 <- subset(unique(dat[,1]), !(unique(dat[,1]) %in% unique(dat[(dat[,3]==0),][,1])))
incc0 <- subset(unique(dat[,1]), !(unique(dat[,1]) %in% unique(dat[(dat[,3]==1),][,1])))
nv <- 4*(1-1*(ns%in%incc1))*as.vector(table(ns)[match(ns,names(table(ns)))]) + 2*(1*(ns%in%incc1))
kh <- 1
mat <- t(apply(cbind(dw[,1:2]),1,rn))/nv
vf1 <- apply(cbind(seq(1,m)),1,rst)
sFs1 <- sum(mat)
kh <- 2
mat <- t(apply(cbind(dw[,1:2]),1,rn))/nv
vf2 <- apply(cbind(seq(1,m)),1,rst)
sFs2 <- sum(mat)
I <- sum(1*unique(dat[,1])%in%c(incc1, incc0))
C <- sum(1-1*unique(dat[,1])%in%c(incc1, incc0))
v1=(sFs1+sFs2)+(C+2*I)/2
vd= (vf1+vf2)+((C+2*I)-1)/2
h=1
TS <- v1
E.T<- 0.25*m*(m+1)
test=(m/m^h)*v1-((m-1)/(m-1)^h)*vd
v.test=stats::var(test)
v_hat=(((m^h)^2)/(m-1))*v.test
v.hat=ifelse(v_hat==0,0.00000001,v_hat)
Z <- (TS-E.T)/sqrt(v.hat)
PVAL <- switch(alternative, less = stats::pnorm(Z), greater = stats::pnorm(Z, lower.tail = FALSE),
two.sided = 2*(1-stats::pnorm(abs(Z))))
}
}
names(Z) <- "z"
DNAME <- paste0(paste0(DNAME, ", M = "), as.character(m))
names(mu) <- if (paired || !is.null(y))
"location shift"
else "location"
rval <- list(statistic=Z, p.value=PVAL, null.value = mu, data.name=DNAME, method=METHOD,
alternative=alternative, M = m)
class(rval) <- "htest"
if (m < 30)
warning('Number of clusters < 30. Normal approximation may be incorrect')
return(rval)
}
wilcoxtestClust.formula <- function (formula, id, data, subset, na.action, ...)
{
if (missing(formula) || (length(formula) != 3L) || (length(attr(stats::terms(formula[-2L]),
"term.labels")) != 1L))
stop("'formula' missing or incorrect")
m <- match.call(expand.dots = FALSE)
if (is.matrix(eval(m$data, parent.frame())))
m$data <- as.data.frame(data)
m[[1L]] <- quote(stats::model.frame)
m$... <- NULL
mf <- eval(m, parent.frame())
DNAME <- paste(names(mf)[1:2], collapse = " by ")
names(mf) <- c("r", "group", "id")
g <- factor(mf$group)
if (nlevels(g) != 2L)
stop("grouping factor must have exactly 2 levels")
DATA <- stats::setNames(split(mf[,-2], g), c("x", "y"))
y <- do.call("wilcoxtestClust", args=c(list(DATA$x$r, DATA$y$r, DATA$x$id, DATA$y$id,...)))
y$data.name <- paste0(paste0(DNAME, ", M = "), as.character(length(unique(mf$id))))
y
}
|
ckmeans <-
function(data, k, mustLink, cantLink, maxIter = 100) {
dist <- function(x, y) {
tmp <- x - y
sum(tmp * tmp)
}
violate <- function(i, j) {
for (u in mlw[[i]]) {
if (label[u] != 0 && label[u] != j)
return(1);
}
for (u in clw[[i]]) {
if (label[u] == j)
return(1);
}
0
}
findMustLink <- function(i) {
tmp = c()
for (j in 1:n) {
if (M[i, j] == 1)
tmp = c(tmp, j)
}
tmp
}
findCantLink <- function(i) {
tmp = c()
for (j in 1:n) {
if (C[i, j] == 1)
tmp = c(tmp, j)
}
tmp
}
data = as.matrix(data)
n <- nrow(data)
d <- ncol(data)
nm <- nrow(mustLink)
nc <- nrow(cantLink)
M = matrix(0, nrow = n, ncol = n)
for (i in 1:nm) {
if (i > nm)
break;
u = mustLink[i, 1]
v = mustLink[i, 2]
M[u, v] = 1
M[v, u] = 1
}
for (u in 1:n) {
for (i in 1:n) {
for (j in 1:n) {
if (M[i, u] == 1 && M[u, j] == 1)
M[i, j] = 1
}
}
}
tp = rep(0, n)
ntp = 0
for (i in 1:n) {
if (tp[i] == 0) {
ntp = ntp + 1
tp[i] = ntp
j = i + 1
while (j <= n) {
if (tp[j] == 0 && M[i, j] == 1)
tp[j] = ntp
j = j + 1
}
}
}
findMember <- function(v) {
tmp = c()
for (u in 1:n) {
if (tp[u] == v)
tmp = c(tmp, u)
}
tmp
}
tmpPi = lapply(1:ntp, findMember)
C = matrix(0, nrow = n, ncol = n)
for (i in 1:nc) {
if (i > nc)
break;
u = cantLink[i, 1]
v = cantLink[i, 2]
x = tp[u]
y = tp[v]
if (x != y) {
for (p in tmpPi[[x]]) {
for (q in tmpPi[[y]]) {
C[p, q] = 1
C[q, p] = 1
}
}
}
}
mlw <- lapply(1:n, findMustLink)
clw <- lapply(1:n, findCantLink)
tmp <- sample(1:n, k)
C <- matrix(nrow = k, ncol = d)
for (i in 1:k) {
C[i,] = data[tmp[i],]
}
for (iter in 1:maxIter) {
label <- rep(0, n)
for (i in 1:n) {
dd <- rep(1e15, k)
best <- -1
for (j in 1:k) {
if (violate(i, j) == 0) {
dd[j] <- dist(data[i,], C[j,])
if (best == -1 || dd[j] < dd[best]) {
best = j
}
}
}
if (best == -1)
return(0)
label[i] <- best
}
if (iter == maxIter)
return(label)
C2 <- matrix(0, nrow = k, ncol = d)
dem <- rep(0, k)
for (i in 1:n) {
j = label[i]
C2[j,] = C2[j,] + data[i,]
dem[j] = dem[j] + 1
}
for (i in 1:k) {
if (dem[i] > 0)
C[i,] = 1.0 * C2[i,] / dem[i]
}
}
}
|
tidy_feature_matrix <- function(
.data,
remove_nzv = FALSE,
nan_is_na = FALSE,
clean_names = FALSE
) {
to_r <- tibble::as_tibble(.data[[1]])
nondupe <- to_r[, !duplicated(names(to_r))]
if(remove_nzv) {
nzvs <- purrr::map_dfr(
lapply(
X = names(nondupe),
FUN = function(colname) {
t <- caret::nearZeroVar(nondupe[, colname], saveMetrics = TRUE)
t$variable <- colname
return(t)
}
), c)
nondupe <- nondupe[, !nzvs$nzv]
}
if(nan_is_na) {
for (colname in names(nondupe)) {
nondupe[, colname][[1]][is.nan(nondupe[, colname][[1]])] <- NA
}
}
if(clean_names) {
n <- tolower(names(nondupe))
tn <- gsub("[^A-z0-9]", "_", n)
tn <- gsub("(_+?$)|(__+?)", "", tn)
names(nondupe) <- tn
}
result <- as.data.frame(nondupe)
return(result)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.