code
stringlengths
1
13.8M
LTRCART <- function(formula, data, weights=NULL, subset = NULL, no.SE = 0, control = rpart::rpart.control(cp = 0.001)){ if(missing(data)){ y <- eval(formula[[2]]) predictors <- formula[[3]] if (!inherits(y, "Surv") | length(as.list(formula[[2]]))!=4){ stop(" Response must be a 'survival' object with 'Surv(time1, time2, event)' ") } Status <- y[,3L] Times <- y[,2L] unique.times <- sort(unique(Times[Status == 1])) temp <- survival::coxph(y ~ 1) cumhaz.table <- survival::basehaz(temp) if(sum(is.infinite(cumhaz.table$hazard))!=0){ cumhaz.table <- cumhaz.table[cumhaz.table$hazard != Inf,] } cumhaz.table2 <- cumhaz.table[cumhaz.table$time %in% unique.times,] cumhaz.times <- c(0, cumhaz.table2$time[-length(cumhaz.table2$time)], max(Times)) cumhaz <- c(0, cumhaz.table2$hazard) Start.cumhaz <- stats::approx(cumhaz.times, cumhaz, y[,1L])$y End.cumhaz <- stats::approx(cumhaz.times, cumhaz, y[,2L])$y Newtime <- End.cumhaz - Start.cumhaz Formula = formula(paste(c( paste("cbind(Newtime,","Status)",sep = ""), predictors), collapse = "~")) Fit.tree <- rpart::rpart(formula = Formula, method = "poisson", weights = weights, subset = subset, control = control) if( length(unique(Fit.tree$where))!=1 ){ cventry <- which.min(Fit.tree$cptable[, "xerror"]) if(no.SE == 0){ cpcv <- Fit.tree$cptable[cventry, "CP"] Fit.tree <- rpart::prune(Fit.tree,cp=cpcv) }else{ xerrorcv <- Fit.tree$cptable[cventry, "xerror"] sexerrorcv <- xerrorcv + Fit.tree$cptable[cventry,"xstd"] * no.SE cpcvse <- Fit.tree$cptable[which.max(Fit.tree$cptable[, "xerror"] <= sexerrorcv), "CP"] Fit.tree <- rpart::prune(Fit.tree, cp = cpcvse) } } return(Fit.tree) }else{ Data <- data Response <- formula[[2]] predictors <- formula[[3]] if(length(as.list(Response))!=4){ stop(" Response must be a 'survival' object with 'Surv(time1, time2, event)' ") } y.names <- c(as.character(as.list(Response)[[2]]),as.character(as.list(Response)[[3]]),as.character(as.list(Response)[[4]])) y.IDs <- match(y.names, names(Data)) y <- survival::Surv(Data[,y.IDs[1]],Data[,y.IDs[2]],Data[,y.IDs[3]]) Status <- y[,3L] Times <- y[,2L] unique.times <- sort(unique(Times[Status == 1])) temp <- survival::coxph(y ~ 1) cumhaz.table <- survival::basehaz(temp) if(sum(is.infinite(cumhaz.table$hazard))!=0){ cumhaz.table <- cumhaz.table[cumhaz.table$hazard != Inf,] } cumhaz.table2 <- cumhaz.table[cumhaz.table$time %in% unique.times,] cumhaz.times <- c(0, cumhaz.table2$time[-length(cumhaz.table2$time)], max(Times)) cumhaz <- c(0, cumhaz.table2$hazard) Start.cumhaz <- stats::approx(cumhaz.times, cumhaz, y[,1L])$y End.cumhaz <- stats::approx(cumhaz.times, cumhaz, y[,2L])$y Data$Newtime <- End.cumhaz - Start.cumhaz Formula = formula(paste(c( paste("cbind(Newtime,",y.names[3],")",sep = ""), predictors), collapse = "~")) DATA = Data[,-y.IDs[1:2]] Fit.tree <- rpart::rpart(formula = Formula, data = DATA, method = "poisson", weights = weights, subset = subset, control = control) if( length(unique(Fit.tree$where))!=1 ){ cventry <- which.min(Fit.tree$cptable[, "xerror"]) if(no.SE == 0){ cpcv <- Fit.tree$cptable[cventry, "CP"] Fit.tree <- rpart::prune(Fit.tree,cp=cpcv) }else{ xerrorcv <- Fit.tree$cptable[cventry, "xerror"] sexerrorcv <- xerrorcv + Fit.tree$cptable[cventry,"xstd"] * no.SE cpcvse <- Fit.tree$cptable[which.max(Fit.tree$cptable[, "xerror"] <= sexerrorcv), "CP"] Fit.tree <- rpart::prune(Fit.tree, cp = cpcvse) } } return(Fit.tree) } }
CAM <-function(x){ if (class(x) == "mdf"){ y <- x$MUDFOLD_INFO$second_step$CAM class(y) <- "cam.mdf" return(y) }else{ J <- colnames(x) K <- ncol(x) CADJ.mat<-matrix(0,nrow=K,ncol=K,dimnames=list(J,J)) for (i in 1:K) for(j in 1:K) CADJ.mat[i,j] <- sum(x[,i]*x[,j]) / sum(x[,j]) diag(CADJ.mat) <- NA class(CADJ.mat) <- "cam.mdf" return(CADJ.mat) } }
context("fixed_species") library(dplyr) testdata <- data.frame("1" = c(0,0,0,1,0,0), "2" = c(0,0,1,0,0,0), "3" = c(1,0,0,0,1,0), "4" = c(0,0,1,0,0,1), "5" = c(1,1,1,1,1,0)) partial_solution <- data.frame("1" = c(0,0,0,0,0,0), "2" = c(0,0,0,0,0,0), "3" = c(0,0,0,0,0,0), "4" = c(0,0,0,0,0,0), "5" = c(1,1,1,1,1,1)) %>% as.matrix() fixed_species <- data.frame("1" = c(1,1,1,1,1,1), "2" = c(0,0,1,0,0,0), "3" = c(1,0,0,0,1,0), "4" = c(0,0,1,0,0,1), "5" = c(1,1,1,1,1,1)) %>% as.matrix() alpha_list_test <- testdata %>% summarise_all(sum) %>% as.numeric() total_gamma_test <- testdata %>% filter_all(any_vars(sum(.) != 0)) %>% nrow() target_matrix_test <- testdata %>% as.matrix() %>% spectre:::calculate_solution_commonness_rcpp() res_sim <- run_optimization_min_conf(alpha_list = alpha_list_test, total_gamma = total_gamma_test, target = target_matrix_test, fixed_species = fixed_species, partial_solution = partial_solution, max_iterations = 200, verbose = FALSE) resultdata <- res_sim$optimized_grid %>% as.data.frame() alpha_list_result <- resultdata %>% summarise_all(sum) %>% as.numeric() total_gamma_result <- resultdata %>% filter_all(any_vars(sum(.) != 0)) %>% nrow() target_matrix_result <- spectre:::calculate_solution_commonness_rcpp(res_sim$optimized_grid) resultdata <- resultdata %>% as.matrix() expect_equal(alpha_list_result[5], 6L) expect_equal(alpha_list_result[1], 0L) expect_equal(total_gamma_test, total_gamma_result) expect_true(resultdata[1,3] == 0L) expect_true(resultdata[3,2] == 0L) expect_true(resultdata[3,4] == 0L) expect_true(resultdata[5,3] == 0L) expect_true(resultdata[6,4] == 0L) expect_setequal(resultdata[1:6,5], rep(1L, times = 6))
"pwrFDR" <- function(effect.size, n.sample, r.1, alpha, delta=NULL, groups=2, N.tests, average.power, tp.power, lambda, type=c("paired","balanced","unbalanced"), grpj.per.grp1=NULL, FDP.control.method=c("BHFDR","BHCLT","Romano","Auto","both"), method=c("FixedPoint", "simulation"), n.sim=1000, temp.file, control=list(tol=1e-8, max.iter=c(1000,20), distopt=1, CS=list(NULL), sim.level=2, low.power.stop=TRUE, FDP.meth.thresh=FDP.cntl.mth.thrsh.def, verb=FALSE, ast.le.a=TRUE)) { .call. <- m <- match.call() pfx <- as.character(m[[1]]) frmls <- names(formals(pwrFDR)) sppld <- names(m)[-1] m <- evald.call <- args.def.err.chk(m, sppld, frmls) err.msg <- attr(m, "err.msg") if(!is.null(err.msg)) stop(err.msg) m[[1]] <- as.name(pfx %,% "." %,% pwrfdrmthd.sfx[m$method]) m$method <- m$temp.file <- NULL args.full <- evald.call args.full[[1]] <- as.name("list") args.full <- eval(args.full) args.full$call <- evald.call out <- eval(m) class(out) <- "pwr" attr(out, "arg.vals") <- args.full out$call <- .call. out } "pwrFDR.grid" <- function(effect.size, n.sample, r.1, alpha, delta, groups, N.tests, average.power, tp.power, lambda, type, grpj.per.grp1, FDP.control.method, control) { .call. <- m <- fd <- match.call() pfx <- as.character(m[[1]]) frmls <- names(formals(pwrFDR.grid)) sppld <- names(m)[-1] n.sppld <- length(sppld) is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls msng.nms <- names(is.msng)[is.msng] eval.env <- sys.parent for (k in 1:n.sppld) { m[[sppld[k]]] <- eval(m[[sppld[k]]], eval.env()) fd[[sppld[k]]] <- length(m[[sppld[k]]]) } is.pwr <- (!is.msng["average.power"]) || (!is.msng["tp.power"]) nera <- c("n.sample", "effect.size", "r.1", "alpha") pwr.spcfd <- !is.msng["average.power"]||!is.msng["tp.power"] use.L.pwr <- !is.msng["tp.power"] pwr.nm <- c("average.power", "tp.power")[1+use.L.pwr] msng.nera <- nera[which(is.msng[nera])] fd[[1]] <- as.name("factorial.design") fd <- as.data.frame(eval(fd)) n.conds <- nrow(fd) pwrFDR.call <- as.call(expression(pwrFDR)) names(fd) <- sppld rslts <- list() cnds <- NULL for(j in 1:n.conds) { cnds.j <- NULL for(k in 1:n.sppld) { cnds.j <- c(cnds.j, m[[sppld[k]]][fd[j,k]]) pwrFDR.call[[sppld[k]]] <- m[[sppld[k]]][fd[j,k]] } cnds <- rbind(cnds, cnds.j) rslts[[j]] <- try(eval(pwrFDR.call, eval.env()), silent=TRUE) } dimnames(cnds)[[1]] <- NULL cnds <- as.data.frame(cnds) names(cnds) <- sppld list(conditions=cnds, results=rslts) } "pwrFDR.FP" <- function(effect.size, n.sample, r.1, alpha, delta, groups, N.tests, average.power, tp.power, lambda, type, grpj.per.grp1, FDP.control.method, method, n.sim, temp.file, control) { .call. <- m.sv <- m <- match.call() ee <- function(x)exp(exp(x))-1 ll <- function(x)log(log(1 + x)) ijumps <- FALSE Auto <- "" is.msng <- control$is.msng pfx <- as.character(m[[1]]) is.N <- !is.msng["N.tests"] pwr.spcfd <- !is.msng["average.power"]||!is.msng["tp.power"] if(!pwr.spcfd) { m[[1]] <- as.name(as.character(m[[1]]) %,% ".1X") m$average.power <- m$tp.power <- NULL out <- eval(m) } if(pwr.spcfd) { use.L.pwr <- !is.msng["tp.power"] pwr.nm <- c("average.power", "tp.power")[1+use.L.pwr] msng.nera <- nera[which(is.msng[nera])] psi.inv <- list(n.sample=ee, effect.size=ee, r.1=logit.inv.r, alpha=logit.inv.r)[[msng.nera]] psi <- list(n.sample=ll, effect.size=ll, r.1=logit, alpha=logit)[[msng.nera]] OBJ <- function(x, m, misc, p=c(2, 1.25)) { rslt.call <- m rslt.call[[1]] <- as.name(pfx %,% ".1X") rslt.call[[misc$msng.nera]] <- misc$psi.inv(x) rslt.call$average.power <- rslt.call$tp.power <- NULL rslt <- suppressWarnings(eval(rslt.call)) if(!use.L.pwr) { pwr <- rslt$pwr <- rslt$average.power pwr. <- max(min(pwr, 1-1e-16),1e-16) out <- out.n <- ((logit(pwr.) - logit(average.power))^p[1])^(1/p[2]) } if(use.L.pwr) { pwr <- rslt$pwr <- rslt$tp.power pwr. <- min(max(pwr, 1e-16), 1-1e-16) out <- out.n <- ((logit(pwr.) - logit(tp.power))^p[1])^(1/p[2]) } attr(out, "detail") <- rslt if(control$verb>0) cat(sprintf("(obj, %s, %s)=(%g, %g, %g)\n", misc$msng.nera, misc$pwr.nm, out, misc$psi.inv(x), pwr.)) if(control$verb>0 && is.na(out)) browser() out } idistopt <- control$distopt is.pos <- (dists$minv[[1+idistopt]]==0) if(use.L.pwr) pwr <- tp.power if(!use.L.pwr) pwr <- average.power l.nera <- c(n.sample=5, effect.size=0.01, r.1=0.00001, alpha=0.00001) u.nera <- c(n.sample=Inf, effect.size=2, r.1=0.99999, alpha=0.99999) l.x <- psi(l.nera[msng.nera]) u.x <- psi(u.nera[msng.nera]) if(msng.nera=="n.sample") { grps <- groups r.0 <- 1 - r.1 alpha.0 <- r.0*alpha if(use.L.pwr) pwr <- tp.power if(!use.L.pwr) pwr <- average.power gma <- r.1*pwr/(1-alpha.0) ftest.ss <- f.power(power=pwr, groups=grps, effect.size=effect.size, e.I=gma*alpha) u.x <- psi(10*ftest.ss$n.sample) done <- FALSE while(!done) { obj.ux <-OBJ(u.x,m=m.sv, misc=list(msng.nera=msng.nera, pwr.nm=pwr.nm, psi.inv=psi.inv), p=c(1,1)) done <- !is.na(obj.ux) if(!done) u.x <- psi(psi.inv(u.x) -1) } lu.k <- c(l.x, u.x) err <- 1 x <- u.x iter <- 0 while(err > 1e-3) { while(err > 1e-3 && iter < 20) { obj <- OBJ(x, m=m.sv, misc=list(msng.nera=msng.nera, pwr.nm=pwr.nm, psi.inv=psi.inv), p=c(1,1)) pos <- obj > 0 err <- abs(obj) if(control$verb > 0) cat(sprintf("n: %d, x: %g, lu.k[1]: %g, lu.k[2]: %g, obj: %g, err: %g\n", ceiling(psi.inv(x)), x, lu.k[1], lu.k[2], obj, err)) lu.k <- pos*c(lu.k[1], x) + (1-pos)*c(x, lu.k[2]) x <- mean(lu.k) iter <- iter + 1 } if(err > 1e-3) { lu.k <- lu.k <- c(l.x, u.x) if(m.sv$FDP.control.method %in% c("BHCLT","Auto")) m.sv$FDP.control.method <- Auto <- "Romano" ijumps <- TRUE iter <- 0 } } ans <- list(objective=obj) y <- ceiling(psi.inv(x)) } if(msng.nera!="n.sample") { ans <- optimize(f=OBJ, lower=l.x, upper=u.x, m=m.sv, tol=.Machine$double.eps^0.35, misc=list(msng.nera=msng.nera, pwr.nm=pwr.nm, psi.inv=psi.inv)) obj <- ans$objective if(abs(obj)>1e-3) stop("No Solution, " %,% msng.nera %,% " too close to " %,% l.nera[msng.nera] %,% " or " %,% u.nera[msng.nera] %,% " and " %,% pwr.nm %,% " is " %,% signif(attr(obj,"detail")$pwr,3)) y <- psi.inv(ans$minimum) } assign(msng.nera, y) nii.sample <- n.sample if(groups>=2 && type==3) nii.sample <- n.sample*grpj.per.grp1 .DF. <- eval(DF[type]) .NCP. <- eval(NCP[type]) pars0 <- eval(dists$pars0[[1+idistopt]]) pars1 <- eval(dists$pars1[[1+idistopt]]) r.0 <- 1 - r.1 alpha.0 <- r.0*alpha gma <- r.1*ans$average.power/(1-alpha.0) c.g <- dists$qdist[[1+idistopt]](1 - gma*alpha/2^(!is.pos), pars0) eIII <- dists$pdist[[1+idistopt]](-c.g, pars1) dtl <- attr(ans$objective, "detail") dtl$pwr <- NULL out <- numeric(0) out[msng.nera] <- get(msng.nera) if(ijumps) dtl$Auto <- Auto out <- c(out, dtl) } out } "pwrFDR.FP.1X" <- function(effect.size, n.sample, r.1, alpha, delta, groups, N.tests, average.power, tp.power, lambda, type, grpj.per.grp1, FDP.control.method, method, n.sim, temp.file, control) { .call. <- m <- m.sv <- match.call() is.msng <- control$is.msng ast.le.a <- control$ast.le.a if(is.msng["alpha"]) .call.$delta <- m$delta <- m.sv$delta <- m$alpha is.N <- !missing(N.tests) idistopt <- control$distopt nii.sample <- n.sample if(groups>=2 && type==3) nii.sample <- n.sample*grpj.per.grp1 .DF. <- eval(DF[type]) .NCP. <- eval(NCP[type]) pars0 <- eval(dists$pars0[[1+idistopt]]) pars1 <- eval(dists$pars1[[1+idistopt]]) is.pos <- (dists$minv[[1+idistopt]]==0) Auto <- se.by.a <- gma.Ntsts <- NULL n <- n.sample r.0 <- 1 - r.1 alpha.0 <- r.0*alpha alpha.st <- NULL do.tp.power <- !missing(lambda) if(FDP.control.method == "Auto") { m.fxd.pt <- m m.fxd.pt[[1]] <- as.name("CDF.Pval.ua.eq.u") m.fxd.pt$N.tests <- m.fxd.pt$lambda <- m.fxd.pt$FDP.control.method <- m.fxd.pt$delta <- NULL gma <- eval(m.fxd.pt, sys.parent())$gamma se.VoR <- (r.0*alpha*(1-r.0*alpha*gma)/(N.tests*gma))^0.5 FDP.meth.thresh <- control$FDP.meth.thresh se.by.a <- se.VoR/alpha do.bhfdr <- (se.by.a < FDP.meth.thresh[1]) do.bhclt <- ((se.by.a >= FDP.meth.thresh[1]) && (N.tests >= FDP.meth.thresh[2])) do.romano <- !do.bhfdr && !do.bhclt mthd.chc <- 1*do.romano + 2*do.bhclt + 3*do.bhfdr FDP.control.method <- c("Romano", "BHCLT", "BHFDR")[mthd.chc] Auto <- FDP.control.method } if(FDP.control.method == "BHFDR") { m.fxd.pt <- m m.fxd.pt[[1]] <- as.name("CDF.Pval.ua.eq.u") m.fxd.pt$N.tests <- m.fxd.pt$lambda <- m.fxd.pt$FDP.control.method <- m.fxd.pt$delta <- NULL gma <- gma.st <- eval(m.fxd.pt, sys.parent())$gamma c.g <- qdist(1 - gma*alpha/2^(!is.pos), pars0) G1.pr <- r.1*(ddist(c.g, pars1) + (!is.pos)*ddist(-c.g, pars1))/(ddist(c.g, pars0) + (!is.pos)*ddist(-c.g, pars0)) G.pr <- r.0 + G1.pr average.power <- pi.1 <- 1 - pdist(c.g, pars1) + (!is.pos) * pdist(-c.g, pars1) sigma.rtm.VoR <- (r.0*alpha*(1-r.0*alpha*gma)/gma)^0.5 tau2 <- gma*(1-gma)/(1-alpha*G.pr)^2 v.W1 <- r.1*pi.1 - r.1^2*pi.1^2 c.W0.W1 <- - r.0*alpha*gma*r.1*pi.1 v.top <- v.W1 + alpha^2*G1.pr^2*tau2 + 2*alpha*G1.pr*(v.W1 + c.W0.W1)/ (1-alpha*G.pr) v.bot <- r.0*r.1 c.top.bot <- r.0*r.1*(pi.1 + alpha*G1.pr/(1-alpha*G.pr)*(pi.1 - alpha*gma)) sigma.rtm.ToM <- (v.top - 2*pi.1*c.top.bot + pi.1^2*v.bot)^0.5/r.1 } if(FDP.control.method == "BHCLT") { m.cntlfdp <- m m.cntlfdp[[1]] <- as.name("controlFDP") m.cntlfdp$lambda <- m.cntlfdp$FDP.control.method <- NULL alpha.st <- eval(m.cntlfdp, sys.parent())$alpha.star if(ast.le.a) alpha.st <- min(alpha.st, alpha) if(is.na(alpha.st)) FDP.control.method <- Auto <- "Romano" if(!is.na(alpha.st)) { m.fxd.pt <- m m.fxd.pt[[1]] <- as.name("CDF.Pval.ua.eq.u") m.fxd.pt$N.tests <- m.fxd.pt$lambda <- m.fxd.pt$FDP.control.method <- m.fxd.pt$delta <- NULL m.fxd.pt$alpha <- alpha.st gma <- gma.st <- eval(m.fxd.pt, sys.parent())$gamma c.g <- qdist(1 - gma.st*alpha.st/2^(!is.pos), pars0) G1.pr <- r.1*(ddist(c.g, pars1) + (!is.pos)*ddist(-c.g, pars1))/(ddist(c.g, pars0) + (!is.pos)*ddist(-c.g, pars0)) G.pr <- r.0 + G1.pr average.power <- pi.1 <- 1 - pdist(c.g, pars1) + (!is.pos) * pdist(-c.g, pars1) sigma.rtm.VoR <- (r.0*alpha.st*(1-r.0*gma.st*alpha.st)/gma.st)^0.5 tau2 <- gma.st*(1-gma.st)/(1-alpha.st*G.pr)^2 v.W1 <- r.1*pi.1 - r.1^2*pi.1^2 c.W0.W1 <- - r.0*alpha.st*gma.st*r.1*pi.1 v.top <- v.W1 + alpha.st^2*G1.pr^2*tau2 + 2*alpha.st*G1.pr*(v.W1 + c.W0.W1)/ (1-alpha.st*G.pr) v.bot <- r.0*r.1 c.top.bot <- r.0*r.1*(pi.1 + alpha.st*G1.pr/(1-alpha.st*G.pr)*(pi.1 - alpha.st*gma.st)) sigma.rtm.ToM <- (v.top - 2*pi.1*c.top.bot + pi.1^2*v.bot)^0.5/r.1 } } if(FDP.control.method == "Romano") { m.fxd.pt <- m m.fxd.pt[[1]] <- as.name("CDF.Pval.ar.eq.u") m.fxd.pt$N.tests <- m.fxd.pt$lambda <- m.fxd.pt$FDP.control.method <- NULL gma <- gma.R <- eval(m.fxd.pt, sys.parent())$gamma psi. <- gma.R*delta/(1-(1-delta)*gma.R) psi.pr <- delta/(1-(1-delta)*gma.R)^2 u <- psi.*alpha c.g <- qdist(1 - u/2^(!is.pos), pars0) G1.pr <- r.1*(ddist(c.g, pars1) + (!is.pos)*ddist(-c.g, pars1))/(ddist(c.g, pars0) + (!is.pos)*ddist(-c.g, pars0)) G.pr <- r.0 + G1.pr average.power <- pi.1 <- 1 - pdist(c.g, pars1) + (!is.pos)*pdist(-c.g, pars1) tau2 <- gma.R*(1-gma.R)/(1-alpha*psi.pr*G.pr)^2 sigma.rtm.VoR <- ((1+r.0*alpha*(psi.pr-psi./gma.R)/(1-alpha*psi.pr*G.pr))^2*r.0*alpha*psi.*(1-r.0*alpha*psi.) +(r.0*alpha*(psi.pr-psi./gma.R)/(1-alpha*psi.pr*G.pr))^2*r.1*pi.1*(1-r.1*pi.1) -2*(1+r.0*alpha*(psi.pr-psi./gma.R)/(1-alpha*psi.pr*G.pr))* (r.0*alpha*(psi.pr-psi./gma.R)/(1-alpha*psi.pr*G.pr))*r.0*alpha*psi.*r.1*pi.1)^0.5/gma.R v.W1 <- r.1*pi.1 - r.1^2*pi.1^2 c.W0.W1 <- - r.0*alpha*psi.*r.1*pi.1 v.top <- v.W1 + alpha^2*psi.pr^2*G1.pr^2*tau2 + 2*alpha*psi.pr*G1.pr*(v.W1 + c.W0.W1)/ (1-alpha*psi.pr*G.pr) v.bot <- r.0*r.1 c.top.bot <- r.0*r.1*(pi.1 + alpha*psi.pr*G1.pr/(1-alpha*psi.pr*G.pr)*(pi.1 - alpha*psi.)) sigma.rtm.ToM <- (v.top - 2*pi.1*c.top.bot + pi.1^2*v.bot)^0.5/r.1 } eIII <- dists$pdist[[1+idistopt]](-c.g, pars1) out <- list(average.power = average.power, c.g = c.g, gamma = gma, err.III=eIII) if(!is.N) { out$sigma.rtm.Rom <- max(tau2^0.5, 1e-10) out$sigma.rtm.VoR <- max(sigma.rtm.VoR, 1e-10) out$sigma.rtm.ToM <- max(sigma.rtm.ToM, 1e-10) } if(is.N) { out$se.Rom <- max((tau2/N.tests)^0.5, 1e-10) out$se.VoR <- max(sigma.rtm.VoR/N.tests^0.5, 1e-10) out$se.ToM <- max(sigma.rtm.ToM/N.tests^0.5, 1e-10) } if(!is.null(Auto)) out$Auto <- Auto if(!is.null(alpha.st)&&!is.na(alpha.st)) out$alpha.star <- alpha.st if(do.tp.power) { se.ToM <- sigma.rtm.ToM/N.tests^0.5 tp.power <- pnorm((average.power - lambda)/se.ToM) L.eq <- average.power - se.ToM * qnorm(average.power) out$tp.power <- tp.power out$L.eq <- L.eq } attr(out, "pars") <- rbind(pars0=pars0,pars1=pars1) out } "pwrFDR.sim" <- function(groups, effect.size, n.sample, r.1, alpha, N.tests, control, lambda, FDP.control.method, type, grpj.per.grp1, n.sim=1000, delta) { .call. <- m <- match.call() m.FP.1X <- m m.FP.1X$n.sim <- NULL m.FP.1X$do.Romano <- NULL m.FP.1X[[1]] <- as.name("pwrFDR.FP.1X") m.FP.1X$FDP.control.method <- "BHFDR" rslt.FP.1X <- eval(m.FP.1X, sys.parent()) low.power.stop <- control$low.power.stop if(is.null(control$low.power.stop)) low.power.stop <- TRUE if(rslt.FP.1X$average.power < 0.50 && low.power.stop) stop("You don't want to run a simulation on a set of inputs with average power < 0.50") verb <- control$verb idistopt <- control$distopt ast.le.a <- control$ast.le.a nii.sample <- n.sample if(groups>=2 && type==3) nii.sample <- n.sample*grpj.per.grp1 .DF. <- eval(DF[type]) .NCP. <- eval(NCP[type]) pars0 <- eval(dists$pars0[[1+idistopt]]) pars1 <- eval(dists$pars1[[1+idistopt]]) is.pos <- (dists$minv[[1+idistopt]]==0) nsim <- n.sim do.tp.power <- !missing(lambda) alpha.st <- alpha BHCLT.lvl <- control$sim.level*(FDP.control.method=="BHCLT" || FDP.control.method=="both") Rmno <- (FDP.control.method=="Romano" || FDP.control.method=="both") if(BHCLT.lvl>=1) { m.cntlFDP <- m m.cntlFDP$n.sim <- m.cntlFDP$lambda <- m.cntlFDP$FDP.control.method <- m.cntlFDP$do.Romano <- NULL m.cntlFDP[[1]] <- as.name("controlFDP") alpha.st <- eval(m.cntlFDP, sys.parent())$alpha.star alpha.st <- ifelse(!is.na(alpha.st), alpha.st, -1) if(ast.le.a) alpha.st <- min(alpha.st, alpha) BHCLT.lvl <- ifelse(alpha.st > 0, BHCLT.lvl, 0) } is.CS <- !is.null(control$CS[[1]]) if(!is.CS) { if(verb) { cat(sprintf("nsim=%d, alpha=%g, N.tests=%d, r.1=%g, n.sample=%d, effect.size=%g\n", nsim, alpha, N.tests, r.1, n.sample, effect.size)) } rslt <- .C("pwrFDRsim", nsim = as.integer(nsim), alpha = as.double(alpha), BHCLT = as.integer(BHCLT.lvl), do.Rmno = as.integer(Rmno), alpha.star = as.double(alpha.st), Ng = as.integer(N.tests), r1 = as.double(r.1), n = as.integer(n.sample), theta = as.double(effect.size), distopt = as.integer(control$distopt), groups = as.double(groups), delta = as.double(delta), verb = as.integer(verb), M1 = integer(nsim), R = integer(nsim), T = integer(nsim), R.st = integer(nsim), T.st = integer(nsim), p0.ht = double(nsim), R.R = integer(nsim), T.R = integer(nsim), X.i = double(N.tests), M.i = integer(1), PACKAGE = "pwrFDR") } if(is.CS) { CS <- control$CS bad <- is.null(CS$rho)||is.null(CS$n.WC) if(!bad) { rho <- control$CS$rho n.WC <- control$CS$n.WC bad <- (rho <= -1 || rho >= 1 || n.WC <= 0) if(!bad) bad <- (N.tests %% n.WC) != 0 if(bad) stop("list argument 'control' must contain a component, 'CS', of type list, " %,% "with components 'rho' and 'n.WC', which must satisfy -1 < rho < 1 " %,% "and 'n.WC' divides 'N.tests' evenly") } if(verb) { cat(sprintf("nsim=%d, alpha=%g, N.tests=%d, r.1=%g, n.sample=%d, effect.size=%g, rho=%g, n.WC=%d\n", nsim, alpha, N.tests, r.1, n.sample, effect.size, rho, n.WC)) } rslt <- .C("pwrFDRsimCS", nsim = as.integer(nsim), alpha = as.double(alpha), BHCLT = as.integer(BHCLT.lvl), do.Rmno = as.integer(Rmno), alpha.star = as.double(alpha.st), Ng = as.integer(N.tests), r1 = as.double(r.1), n = as.integer(n.sample), theta = as.double(effect.size), rho = as.double(rho), n.WC = as.integer(n.WC), delta = as.double(delta), pverb = as.integer(verb), M1 = integer(nsim), R = integer(nsim), T = integer(nsim), R.st = integer(nsim), T.st = integer(nsim), p0.ht = double(nsim), R.R = integer(nsim), T.R = integer(nsim), X.i = double(N.tests), M.i = integer(1), PACKAGE = "pwrFDR") } reps <- data.frame(M1=rslt$M1, R=rslt$R, T=rslt$T) average.power <- with(reps, mean(T %over% M1)) gamma <- with(reps, mean(R)/N.tests) se.Rom <- with(reps, var(R/N.tests)^0.5) se.VoR <- with(reps, var((R - T) %over% R)^0.5) se.ToM <- with(reps, var(T %over% M1)^0.5) out <- list(average.power=average.power, gamma=gamma, se.Rom=se.Rom, se.VoR=se.VoR, se.ToM=se.ToM) if(do.tp.power) { tp.power <- with(reps, mean(T %over% M1 >= lambda)) out$tp.power <- tp.power } se.VoR.st <- se.ToM.st <- se.VoR.st.ht <- se.ToM.st.ht <- se.VoR.R <- se.ToM.R <- NULL if(BHCLT.lvl >= 1) { reps <- cbind(reps, R.st=rslt$R.st, T.st=rslt$T.st) average.power.st <- with(reps, mean(T.st %over% M1)) P.st <- with(reps, mean((R.st - T.st) %over% R.st > alpha)) se.Rom.st <- with(reps, var(R.st/N.tests)^0.5) se.VoR.st <- with(reps, var((R.st - T.st) %over% R.st)^0.5) se.ToM.st <- with(reps, var(T.st %over% M1)^0.5) gamma.st <- with(reps, mean(R.st)/N.tests) out <- c(out, average.power.st=average.power.st, gamma.st=gamma.st, se.Rom.st=se.Rom.st, se.VoR.st=se.VoR.st, se.ToM.st=se.ToM.st, alpha.star=alpha.st) if(do.tp.power) { tp.power.st <- with(reps, mean(T.st %over% M1 >= lambda)) out$tp.power.st <- tp.power.st } } if(BHCLT.lvl == 2) { reps <- cbind(reps, p0.ht=pmin(rslt$p0.ht,1)) out <- c(out, p0.ht.avg=mean(rslt$p0.ht), sd.p0.ht=var(rslt$p0.ht)^0.5) } if(Rmno) { reps <- cbind(reps, R.R=rslt$R.R, T.R=rslt$T.R) average.power.R <- with(reps, mean(T.R %over% M1)) P.R <- with(reps, mean((R.R - T.R) %over% R.R > alpha)) se.Rom.R <- with(reps, var(R.R/N.tests)^0.5) se.VoR.R <- with(reps, var((R.R - T.R) %over% R.R)^0.5) se.ToM.R <- with(reps, var(T.R %over% M1)^0.5) gamma.R <- with(reps, mean(R.R)/N.tests) out <- c(out, average.power.R=average.power.R, gamma.R=gamma.R, se.Rom.R=se.Rom.R, se.VoR.R=se.VoR.R, se.ToM.R=se.ToM.R) if(do.tp.power) { tp.power.R <- with(reps, mean(T.R %over% M1 >= lambda)) out$tp.power.R <- tp.power.R } } dtl <- list(reps=reps) X.i <- rslt$X.i M.i <- rslt$M.i rep.i <- cbind(X=X.i, xi=c(rep(1, M.i), rep(0, N.tests - M.i))) rep.i <- as.data.frame(cbind(rep.i, pval=2^(!is.pos)*(1-dists$pdist[[1+idistopt]](abs(X.i), pars0)))) rep.i <- rep.i[order(rep.i$pval), ] rep.i$BHFDRcrit <- alpha*(1:N.tests)/N.tests rep.i$Rmnocrit <- (floor(alpha*(1:N.tests)) + 1)*alpha/(N.tests + floor(alpha*(1:N.tests)) + 1 -(1:N.tests)) dtl$X <- rep.i attr(out, "detail") <- dtl attr(out, "pars") <- rbind(pars0=pars0,pars1=pars1) out$call <- .call. class(out) <- "pwr" out } "criterion" <- function(alpha, delta, N.tests, FDP.control.method=c("BHFDR","Romano")) { .call. <- m <- match.call() frmls <- names(formals(criterion)) sppld <- names(m)[-1] is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls err.msng <- any(c("alpha", "N.tests", "FDP.control.method") %in% names(is.msng[is.msng])) if(err.msng) stop("Arguments 'alpha', 'N.tests' and 'FDP.control.method' are required") if(is.msng["delta"]) delta <- alpha errs <- list(alpha=(alpha <= 0 || alpha >= 1), delta=(delta <= 0 || delta >= 1), N.tests=(!is.int(N.tests) || N.tests <= 0), FDP.control.method=!(FDP.control.method %in% c("BHFDR", "Romano"))) msgs <- list(alpha="Argument, 'alpha' must be between 0 and 1\n", delta="Argument, 'delta' must be between 0 and 1\n", N.tests="Argument, 'N.tests' must be integral and positive\n", FDP.control.method="Argument, 'FDP.control.method' must be either 'BHFDR' or 'Romano'\n") err <- any(unlist(errs)) msg <- paste(msgs[names(which(unlist(errs)))], collapse="") if(err) stop(msg) ii <- 1:m$N.tests if(FDP.control.method=="BHFDR") crit <- m$alpha*ii/m$N.tests if(FDP.control.method=="Romano") crit <- (floor(delta*ii) + 1)*alpha/(N.tests + floor(delta*ii) + 1 - ii) crit } "es.ROC" <- function(FPR0, FPR1=NULL, TPR0, TPR1=NULL, b=NULL) { m <- match.call() fn.nm <- as.character(m[[1]]) is.FPR1 <- !missing(FPR1) is.TPR1 <- !missing(TPR1) if(!is.FPR1&!is.TPR1) stop("You must specify exactly one of the arguments 'FPR1' and 'TPR1'") if(is.TPR1) fn.nm <- fn.nm %,% ".fxFPR" if(is.FPR1) fn.nm <- fn.nm %,% ".fxTPR" m[[1]] <- as.name(fn.nm) eval(m) } "cc.ROC" <- function(FPR0, FPR1=NULL, TPR0, TPR1=NULL, b=NULL) { m <- match.call() fn.nm <- as.character(m[[1]]) is.FPR1 <- !missing(FPR1) is.TPR1 <- !missing(TPR1) if(!is.FPR1&!is.TPR1) stop("You must specify exactly one of the arguments 'FPR1' and 'TPR1'") if(is.TPR1) fn.nm <- fn.nm %,% ".fxFPR" if(is.FPR1) fn.nm <- fn.nm %,% ".fxTPR" m[[1]] <- as.name(fn.nm) eval(m) } "es.ROC.fxTPR" <- function(FPR0, FPR1, TPR0, b=NULL) { if(missing(b)) b <- 1 v.tpr0 <- TPR0*(1-TPR0) v.fpr1 <- FPR1*(1-FPR1) r <- b*dnorm(qnorm(1-TPR0))/dnorm(qnorm(1-FPR1)) k <- (v.fpr1/v.tpr0)^0.5/r nu <- (FPR1-FPR0)/(v.fpr1 + r^2/k*v.tpr0)^0.5 abs(nu) } "cc.ROC.fxTPR" <- function(FPR0, FPR1, TPR0, b=NULL) { if(missing(b)) b <- 1 v.tpr0 <- TPR0*(1-TPR0) v.fpr1 <- FPR1*(1-FPR1) r <- b*dnorm(qnorm(1-TPR0))/dnorm(qnorm(1-FPR1)) k <- (v.fpr1/v.tpr0)^0.5/r k } "es.ROC.fxFPR" <- function(FPR0, TPR0, TPR1, b=NULL) { if(missing(b)) b <- 1 v.fpr0 <- FPR0*(1-FPR0) v.tpr1 <- TPR1*(1-TPR1) r <- b*dnorm(qnorm(TPR1))/dnorm(qnorm(FPR0)) k <- (v.tpr1/v.fpr0)^0.5/r nu <- (TPR1-TPR0)/(v.tpr1 + k*r^2*v.fpr0)^0.5 abs(nu) } "cc.ROC.fxFPR" <- function(FPR0, TPR0, TPR1, b=NULL) { if(missing(b)) b <- 1 v.fpr0 <- FPR0*(1-FPR0) v.tpr1 <- TPR1*(1-TPR1) r <- b*dnorm(qnorm(TPR1))/dnorm(qnorm(FPR0)) k <- (v.tpr1/v.fpr0)^0.5/r k } "CDF.Pval" <- function(u, effect.size, n.sample, r.1, groups=2, type="balanced", grpj.per.grp1=1, control) { .call. <- m <- match.call() pfx <- as.character(m[[1]]) frmls <- names(formals(CDF.Pval)) sppld <- names(m)[-1] m <- evald.call <- args.def.err.chk(m, sppld, frmls, other.rules=FALSE) err.msg <- attr(m, "err.msg") if(!is.null(err.msg)) stop(err.msg) u <- m$u groups <- m$groups r.1 <- m$r.1 effect.size <- m$effect.size n.sample <- m$n.sample type <- m$type grpj.per.grp1 <- m$grpj.per.grp1 control <- m$control nii.sample <- n.sample if(groups>=2 && type==3) nii.sample <- n.sample*grpj.per.grp1 idistopt <- control$distopt .DF. <- eval(DF[type]) .NCP. <- eval(NCP[type]) pars0 <- eval(dists$pars0[[1+idistopt]]) pars1 <- eval(dists$pars1[[1+idistopt]]) u <- abs(u) is.pos <- (dists$minv[[1+idistopt]]==0) c.g <- dists$qdist[[1+idistopt]](1-u/2^(!is.pos), pars0) ans <- (1-r.1)*u + r.1*(1-dists$pdist[[1+idistopt]](c.g, pars1) + (!is.pos)*dists$pdist[[1+idistopt]](-c.g, pars1)) df <- as.data.frame(list(u=u, CDF.Pval=ans)) out <- list(CDF.Pval=df, call=.call.) attr(out, "pars") <- rbind(pars0=pars0,pars1=pars1) class(out) <- "cdf" out } "CDF.Pval.HA" <- function(u, effect.size, n.sample, r.1, groups=2, type="balanced", grpj.per.grp1=1, control) { .call. <- m <- match.call() pfx <- as.character(m[[1]]) frmls <- names(formals(CDF.Pval.HA)) sppld <- names(m)[-1] m <- evald.call <- args.def.err.chk(m, sppld, frmls, other.rules=FALSE) err.msg <- attr(m, "err.msg") if(!is.null(err.msg)) stop(err.msg) u <- m$u groups <- m$groups r.1 <- m$r.1 effect.size <- m$effect.size n.sample <- m$n.sample type <- m$type grpj.per.grp1 <- m$grpj.per.grp1 control <- m$control nii.sample <- n.sample if(groups>=2 && type==3) nii.sample <- n.sample*grpj.per.grp1 idistopt <- control$distopt .DF. <- eval(DF[type]) .NCP. <- eval(NCP[type]) pars0 <- eval(dists$pars0[[1+idistopt]]) pars1 <- eval(dists$pars1[[1+idistopt]]) u <- abs(u) is.pos <- (dists$minv[[1+idistopt]]==0) c.g <- dists$qdist[[1+idistopt]](1-u/2^(!is.pos), pars0) ans <- 1-dists$pdist[[1+idistopt]](c.g, pars1) + (!is.pos)*dists$pdist[[1+idistopt]](-c.g, pars1) df <- as.data.frame(list(u=u, CDF.Pval.HA=ans)) out <- list(CDF.Pval.HA=df, call=.call.) attr(out, "pars") <- rbind(pars0=pars0,pars1=pars1) class(out) <- "cdf" out } "CDF.Pval.ua.eq.u" <- function(effect.size, n.sample, r.1, alpha, groups, type, grpj.per.grp1, control) { calling.env <- sys.parent() eval.env <- ifelse(calling.env==0, topenv, sys.parent) m <- .call. <- match.call() n.args <- length(m)-1 arg.nms <- names(m)[-1] is.rqd <- all(nera %in% arg.nms) if(!is.rqd) stop(list.a(nera, "Arguments ", " are required by CDF.Pval.ua.eq.u")) if(missing(groups)) m$groups <- 2 if(missing(type)) m$type <- 2 if(missing(grpj.per.grp1)) m$grpj.per.grp1 <- 1 if(missing(control)) m$control <- list(distopt=1, tol=1e-8) alpha <- eval(m$alpha, eval.env()) groups <- eval(m$groups, eval.env()) r.1 <- eval(m$r.1, eval.env()) effect.size <- eval(m$effect.size, eval.env()) n.sample <- eval(m$n.sample, eval.env()) type <- eval(m$type, eval.env()) grpj.per.grp1 <- eval(m$grpj.per.grp1, eval.env()) control <- eval(m$control, eval.env()) idistopt <- control$distopt nii.sample <- n.sample if(groups>=2 && type==3) nii.sample <- n.sample*grpj.per.grp1 .DF. <- eval(DF[type]) .NCP. <- eval(NCP[type]) pars0 <- eval(dists$pars0[[1+idistopt]]) pars1 <- eval(dists$pars1[[1+idistopt]]) is.pos <- (dists$minv[[1+idistopt]]==0) conv <- is.na(alpha) gma.old <- r.1 gma.new <- 1 while(!conv) { u <- gma.old*alpha c.g <- dists$qdist[[1+idistopt]](1-u/2^(!is.pos), pars0) gma.new <- (1-r.1)*u + r.1*(1-dists$pdist[[1+idistopt]](c.g, pars1) + (!is.pos)*dists$pdist[[1+idistopt]](-c.g, pars1)) obj <- abs(gma.new-gma.old) conv <- (obj < control$tol) gma.old <- gma.new } gamma <- gma.new out <- list(gamma=gamma, call=.call.) attr(out, "pars") <- rbind(pars0=pars0,pars1=pars1) class(out) <- "cdf" out } "CDF.Pval.ar.eq.u" <- function(effect.size, n.sample, r.1, alpha, delta, groups, type, grpj.per.grp1, control) { calling.env <- sys.parent() eval.env <- ifelse(calling.env==0, topenv, sys.parent) m <- .call. <- match.call() n.args <- length(m)-1 arg.nms <- names(m)[-1] is.rqd <- all(nera %in% arg.nms) if(!is.rqd) stop(list.a(nera, "Arguments ", " are required by CDF.Pval.ua.eq.u")) if(missing(groups)) m$groups <- 2 if(missing(delta)) m$delta <- alpha if(missing(type)) m$type <- 2 if(missing(grpj.per.grp1)) m$grpj.per.grp1 <- 1 if(missing(control)) m$control <- list(distopt=1, tol=1e-8) alpha <- eval(m$alpha, eval.env()) delta <- eval(m$delta, eval.env()) groups <- eval(m$groups, eval.env()) r.1 <- eval(m$r.1, eval.env()) effect.size <- eval(m$effect.size, eval.env()) n.sample <- eval(m$n.sample, eval.env()) type <- eval(m$type, eval.env()) grpj.per.grp1 <- eval(m$grpj.per.grp1, eval.env()) control <- eval(m$control, eval.env()) idistopt <- control$distopt nii.sample <- n.sample if(groups>=2 && type==3) nii.sample <- n.sample*grpj.per.grp1 .DF. <- eval(DF[type]) .NCP. <- eval(NCP[type]) pars0 <- eval(dists$pars0[[1+idistopt]]) pars1 <- eval(dists$pars1[[1+idistopt]]) is.pos <- (dists$minv[[1+idistopt]]==0) conv <- is.na(alpha) gma.old <- r.1 gma.new <- 1 psi <- function(gma,a)gma*a/(1-(1-a)*gma) while(!conv) { u <- psi(gma.old, delta)*alpha c.g <- dists$qdist[[1+idistopt]](1-u/2^(!is.pos), pars0) gma.new <- (1-r.1)*u + r.1*(1-dists$pdist[[1+idistopt]](c.g, pars1) + (!is.pos)*dists$pdist[[1+idistopt]](-c.g, pars1)) obj <- abs(gma.new-gma.old) conv <- (obj < control$tol) gma.old <- gma.new } gamma <- gma.new out <- list(gamma=gamma, call=.call.) attr(out, "pars") <- rbind(pars0=pars0,pars1=pars1) class(out) <- "cdf" out } "sd.rtm.Rom" <- function(object) { fn.nm <- as.character(object$call[[1]]) frml.vals <- formals(get(fn.nm)) frmls <- names(frml.vals) sppld <- names(object$call)[-1] is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls if(is.msng["method"]) object$call$method <- "FixedPoint" method <- match.arg(object$call$method, eval(frml.vals$method)) sfx <- NULL if(method=="simulation") { fdpsfx <- c(`BHFDR`="",`BHCLT`=".st", `Romano`=".R") if(is.msng["FDP.control.method"]) object$call$FDP.control.method <- "BHFDR" sfx <- fdpsfx[object$call$FDP.control.method] } if(!is.msng["N.tests"]) ans <- object[["se.Rom" %,% sfx]]*eval(object$call$N.tests)^0.5 if(is.msng["N.tests"]) ans <- object[["sigma.rtm.Rom" %,% sfx]] ans } "sd.rtm.VoR" <- function(object) { fn.nm <- as.character(object$call[[1]]) frml.vals <- formals(get(fn.nm)) frmls <- names(frml.vals) sppld <- names(object$call)[-1] is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls if(is.msng["method"]) object$call$method <- "FixedPoint" method <- match.arg(object$call$method, eval(frml.vals$method)) sfx <- NULL if(method=="simulation") { fdpsfx <- c(`BHFDR`="",`BHCLT`=".st", `Romano`=".R") if(is.msng["FDP.control.method"]) object$call$FDP.control.method <- "BHFDR" sfx <- fdpsfx[object$call$FDP.control.method] } if(!is.msng["N.tests"]) ans <- object[["se.VoR" %,% sfx]]*eval(object$call$N.tests)^0.5 if(is.msng["N.tests"]) ans <- object[["sigma.rtm.VoR" %,% sfx]] ans } "sd.rtm.ToM" <- function(object) { fn.nm <- as.character(object$call[[1]]) frml.vals <- formals(get(fn.nm)) frmls <- names(frml.vals) sppld <- names(object$call)[-1] is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls if(is.msng["method"]) object$call$method <- "FixedPoint" method <- match.arg(object$call$method, eval(frml.vals$method)) sfx <- NULL if(method=="simulation") { fdpsfx <- c(`BHFDR`="",`BHCLT`=".st", `Romano`=".R") if(is.msng["FDP.control.method"]) object$call$FDP.control.method <- "BHFDR" sfx <- fdpsfx[object$call$FDP.control.method] } if(!is.msng["N.tests"]) ans <- object[["se.ToM" %,% sfx]]*eval(object$call$N.tests)^0.5 if(is.msng["N.tests"]) ans <- object[["sigma.rtm.ToM" %,% sfx]] ans } "controlFDP" <- function(effect.size, n.sample, r.1, alpha, delta, groups=2, N.tests, type, grpj.per.grp1, control, formula, data) { calling.env <- sys.parent() eval.env <- ifelse(calling.env==0, topenv, sys.parent) m <- .call. <- match.call() m.sv <- m n.args <- length(m)-1 arg.nms <- names(m)[-1] is.form <- !missing(formula) if(is.form) { m[[1]] <- as.name("controlFDP.formula") dfa <- c("data","formula","alpha") is.rqd <- all(dfa %in% arg.nms) if(!is.rqd) stop(list.a(dfa, "Aguments ", " are required by the formula " %,% "'controlFDP' method ")) if(missing(delta)) m$delta <- alpha if(missing(control)) m$control <- list(distopt=1, verb=0, tol=1e-8) } if(!is.form) { m[[1]] <- as.name("controlFDP.theoret") is.rqd <- all(Nnera %in% arg.nms) if(!is.rqd) stop(list.a(Nnera, "Arguments ", " are required by the asymptotic " %,% "'controlFDP' method")) if(missing(delta)) m$delta <- alpha if(missing(groups)) m$groups <- 2 if(missing(type)) m$type <- 2 if(missing(grpj.per.grp1)) m$grpj.per.grp1 <- 1 if(missing(control)) m$control <- list(distopt=1, verb=0, tol=1e-8) } out <- eval(m) out$call <- .call. class(out) <- "vvv" out } "controlFDP.formula" <- function(effect.size, n.sample, r.1, alpha, delta, groups=2, N.tests, type, grpj.per.grp1, control, formula, data) { .call. <- m <- match.call() calling.env <- sys.parent() eval.env <- ifelse(calling.env==0, topenv, sys.parent) mf <- as.call(expression(model.frame)) mf$groups <- mf$effect.size <- mf$n.sample <- mf$r.1 <- mf$N.tests <- mf$control <- mf$delta <- NULL mf$formula <- formula mf$data <- data mf <- eval(mf, eval.env()) pval <- model.extract(mf, "response") N.tests <- length(pval) pvalgthlf <- 1*(pval > 0.5) r.0 <- 2*mean(pvalgthlf) r.1 <- 1-r.0 conv <- neg <- FALSE msg <- NULL ast.old <- alpha a.star <- gma.st <- obj <- sqrt.v <- P.star <- NA while(!(conv||neg)) { gma <- max(which(pval <= (1:N.tests)/N.tests*ast.old))/N.tests v <- r.0*ast.old*(1-r.0*ast.old*gma)/(N.tests*gma) ast.new <- (delta - v^0.5*qnorm(1-alpha))/r.0 neg <- ast.new < 0 if(control$verb>1) cat(sprintf("ast.new=%f\n", ast.new)) obj <- abs(ast.new-ast.old) conv <- (obj < 1e-4*alpha) ast.old <- ast.new } if(neg) { a.star <- gma.st <- obj <- sqrt.v <- P.star <- NA msg <- "Solution not attainable." } if(!neg) { a.star <- ast.new gma.st <- max(which(pval <= (1:N.tests)/N.tests*ast.old))/N.tests v <- r.0*a.star*(1-r.0*a.star*gma.st)/(N.tests*gma.st) sqrt.v <- v^0.5 P.star <- 1-pnorm((delta - r.0*a.star)/sqrt.v) } out <- list(alpha.star = a.star, gamma=gma.st, obj = obj, se.FDF=sqrt.v, P.star = P.star) if(!is.null(msg)) out$note <- msg out } "controlFDP.theoret" <- function(effect.size, n.sample, r.1, alpha, delta, groups=2, N.tests, type, grpj.per.grp1, control, formula, data) { .call. <- m <- match.call() calling.env <- sys.parent() eval.env <- ifelse(calling.env==0, topenv, sys.parent) ast.old <- alpha conv <- neg <- FALSE msg <- NULL a.star <- gma.st <- obj <- sqrt.v <- P.star <- NA gma.call <- match.call() gma.call[[1]] <- as.name("CDF.Pval.ua.eq.u") gma.call$formula <- gma.call$data <- gma.call$N.tests <- gma.call$delta <- NULL gma0 <- eval(gma.call) r.0 <- 1-r.1 while(!(conv || neg)) { gma.st <- update(gma0, alpha=ast.old)$gamma v <- r.0*ast.old*(1-r.0*ast.old*gma.st)/(N.tests*gma.st) ast.new <- (delta - v^0.5*qnorm(1 - alpha))/r.0 neg <- ast.new < 0 if(control$verb>1) cat(sprintf("ast.new=%f\n", ast.new)) obj <- abs(ast.new-ast.old) conv <- (obj < 1e-4*alpha) ast.old <- ast.new } if(neg) { a.star <- gma.st <- obj <- sqrt.v <- P.star <- NA msg <- "Solution not attainable." } if(!neg) { a.star <- ast.new gma.st <- update(gma0, alpha=a.star)$gamma v <- r.0*a.star*(1-r.0*a.star*gma.st)/(N.tests*gma.st) sqrt.v <- v^0.5 P.star <- 1-pnorm((delta - r.0*a.star)/sqrt.v) } out <- list(alpha.star = a.star, gamma=gma.st, obj = obj, se.FDF=sqrt.v, P.star = P.star) if(!is.null(msg)) out$note <- msg out } "cCDF.Rom" <- function(u, effect.size, n.sample, r.1, alpha, delta, groups=2, N.tests, type=c("paired","balanced","unbalanced"), grpj.per.grp1=NULL, FDP.control.method="BHFDR", control=list(tol=1e-8, max.iter=c(1000,20), distopt=1, CS=list(NULL), sim.level=2, low.power.stop=TRUE, FDP.meth.thresh=FDP.cntl.mth.thrsh.def, verb=FALSE)) { m <- .call. <- match.call() m[[1]] <- as.name("pwrFDR") m$u <- NULL avgpwr <- eval(m, sys.parent()) gma <- avgpwr$gamma sdrtmRom <- sd.rtm.Rom(avgpwr) ans <- 1-pnorm(N.tests^0.5*(u - gma)/sdrtmRom) df <- as.data.frame(list(u=u, cCDF.Rom=ans)) out <- list(cCDF.Rom=df, call=.call.) class(out) <- "cdf" out } "cCDF.ToM" <- function(u, effect.size, n.sample, r.1, alpha, delta, groups=2, N.tests, type=c("paired","balanced","unbalanced"), grpj.per.grp1=NULL, FDP.control.method="BHFDR", control=list(tol=1e-8, max.iter=c(1000,20), distopt=1, CS=list(NULL), sim.level=2, low.power.stop=TRUE, FDP.meth.thresh=FDP.cntl.mth.thrsh.def, verb=FALSE)) { m <- .call. <- match.call() m[[1]] <- as.name("pwrFDR") m$u <- NULL avgpwr <- eval(m, sys.parent()) pi <- avgpwr$average.power sdrtmToM <- sd.rtm.ToM(avgpwr) ans <- 1-pnorm(N.tests^0.5*(u - pi)/sdrtmToM) df <- as.data.frame(list(lambda=u, cCDF.ToM=ans)) out <- list(cCDF.ToM=df, call=.call.) class(out) <- "cdf" out } "cCDF.VoR" <- function(u, effect.size, n.sample, r.1, alpha, delta, groups=2, N.tests, type=c("paired","balanced","unbalanced"), grpj.per.grp1=NULL, FDP.control.method="BHFDR", control=list(tol=1e-8, max.iter=c(1000,20), distopt=1, CS=list(NULL), sim.level=2, low.power.stop=TRUE, FDP.meth.thresh=FDP.cntl.mth.thrsh.def, verb=FALSE)) { m <- .call. <- match.call() m[[1]] <- as.name("pwrFDR") m$u <- NULL avgpwr <- eval(m, sys.parent()) sdrtmVoR <- sd.rtm.VoR(avgpwr) r.0 <- 1-r.1 do.bhclt <- do.R <- FALSE if(FDP.control.method=="BHCLT") do.bhclt <- TRUE if(FDP.control.method=="Romano") do.R <- TRUE if(FDP.control.method=="Auto") { if(avgpwr$Auto=="BHCLT") do.bhclt <- TRUE if(avgpwr$Auto=="Romano") do.R <- TRUE } alpha. <- alpha psi.o.gma <- 1 if((do.bhclt || do.R) && missing(delta)) delta <- attr(avgpwr, "arg.vals")$delta if(do.bhclt) alpha. <- avgpwr$alpha.star if(do.R) { psi <- function(gma,a)gma*a/(1-(1-a)*gma) gma <- avgpwr$gamma .psi. <- psi(gma, delta) psi.o.gma <- .psi./gma } ans <- 1-pnorm(N.tests^0.5*(u - r.0*psi.o.gma*alpha.)/sdrtmVoR) df <- as.data.frame(list(delta=u, cCDF.VoR=ans)) out <- list(cCDF.VoR=df, call=.call.) class(out) <- "cdf" out } "detail" <- function(obj) { attr(obj, "detail") } "%,%" <- function(x,y)paste(x,y,sep="") "DX" <- function(x)c(x[1],diff(x)) "ddist" <- function(x, pars) { idistopt <- pars[1] dists$ddist[[1+idistopt]](x, pars) } "pdist" <- function(x, pars) { idistopt <- pars[1] dists$pdist[[1+idistopt]](x, pars) } "qdist" <- function(x, pars) { idistopt <- pars[1] dists$qdist[[1+idistopt]](x, pars) } "gentempfilenm" <- function(prfx="temp", sfx=".txt") { alphanum <- c(letters, toupper(letters), 0:9) n <- length(alphanum) prfx %,% paste(alphanum[sample(n, 5)], collapse="") %,% sfx } "print.pwr" <- function (x, ...) { y <- x cat("Call:\n") print(x$call) class(x) <- NULL x$call <- NULL x <- as.data.frame(x) dimnames(x)[[1]] <- " " out <- t(format(x)) print(out, quote=FALSE) invisible(x) } "print.vvv" <- function (x, ...) { y <- x cat("Call:\n") print(x$call) class(x) <- NULL x$call <- NULL x <- as.data.frame(x) dimnames(x)[[1]] <- " " print(x) invisible(x) } "print.cdf" <- function(x, ...) { y <- x cat("Call:\n") print(x$call) class(x) <- NULL x$call <- NULL print(x[[1]]) invisible(x) } "is.int" <- function(x) { abs(x - floor(x)) < 1e-10 } `+.pwr` <- function(x,y) { xpwr <- x ypwr <- y if(is(x,"pwr")) xpwr <- ifelse(!is.null(x$call$lambda), x$tp.power, x$average.power) if(is(y,"pwr")) ypwr <- ifelse(!is.null(y$call$lambda), y$tp.power, y$average.power) xpwr + ypwr } `-.pwr` <- function(x,y) { xpwr <- x ypwr <- y if(is(x,"pwr")) xpwr <- ifelse(!is.null(x$call$lambda), x$tp.power, x$average.power) if(is(y,"pwr")) ypwr <- ifelse(!is.null(y$call$lambda), y$tp.power, y$average.power) xpwr - ypwr } `*.pwr` <- function(x,y) { xpwr <- x ypwr <- y if(is(x,"pwr")) xpwr <- ifelse(!is.null(x$call$lambda), x$tp.power, x$average.power) if(is(y,"pwr")) ypwr <- ifelse(!is.null(y$call$lambda), y$tp.power, y$average.power) xpwr * ypwr } `/.pwr` <- function(x,y) { xpwr <- x ypwr <- y if(is(x,"pwr")) xpwr <- ifelse(!is.null(x$call$lambda), x$tp.power, x$average.power) if(is(y,"pwr")) ypwr <- ifelse(!is.null(y$call$lambda), y$tp.power, y$average.power) xpwr / ypwr } `^.pwr` <- function(x,y) { xpwr <- x ypwr <- y if(is(x,"pwr")) xpwr <- ifelse(!is.null(x$call$lambda), x$tp.power, x$average.power) if(is(y,"pwr")) ypwr <- ifelse(!is.null(y$call$lambda), y$tp.power, y$average.power) xpwr ^ ypwr } exp.pwr <- function(x) exp(ifelse(!is.null(x$call$lambda), x$tp.power, x$average.power)) log.pwr <- function(x, base)log(ifelse(!is.null(x$call$lambda), x$tp.power, x$average.power), base) logit.inv.r <- function(x)binomial("logit")$linkinv(max(min(x, 1e8), -1e8)) logitInv.default <- binomial("logit")$linkinv logit.default <- binomial("logit")$linkfun logit <- function(mu)UseMethod("logit") logitInv <- function(eta)UseMethod("logitInv") logit.pwr <- function(mu)logit.default(ifelse(!is.null(mu$call$lambda), mu$tp.power, mu$average.power)) logitInv.pwr <- function(eta)logitInv.default(ifelse(!is.null(eta$call$lambda), eta$tp.power, eta$average.power)) arg.vals <- function(object)attr(object, "arg.vals") "%over%" <- function(x,y) { dx <- dim(x) dy <- dim(y) bad <- any(dx!=dy) && dx[1]!=length(y) if(bad) stop("Incompatable dimensions") ans <- 0*x bad <- c(which(y==0),which(is.na(y))) if(length(bad)>0) ans[-bad] <- x[-bad]/y[-bad] if(length(bad)==0) ans <- x/y structure(ans, dim=dx) } "f.power" <- function(n.sample, groups, effect.size, e.I, power) { no.n <- missing(n.sample) no.g <- missing(groups) no.e <- missing(effect.size) no.p <- missing(power) if(no.g || no.e) stop("Arguements 'groups' and 'effect.size' are required") bad <- (no.n && no.p) || (!no.n && !no.p) if(bad) stop("You must specify _either_ 'n.sample' or 'power'") do.p <- no.p do.ss <- no.n if(do.ss) { pwr <- power OBJ <- function(x, groups, effect.size, e.I, power) { n.sample <- exp(x) ncp <- n.sample*effect.size^2/2 df1 <- groups - 1 df2 <- groups*(n.sample-1) Fcrit <- qf(1-e.I, df1=df1, df2=df2) ((pwr - (1-pf(Fcrit, ncp=ncp, df1=df1, df2=df2)))^2)^(1/1.25) } norm.ss <- 2*(qnorm(power) + qnorm(1-e.I))^2/effect.size^2 l <- log(1/10*norm.ss) u <- log(10*norm.ss) opt <- optimize(f=OBJ, lower=l, upper=u, groups=groups, effect.size=effect.size, e.I=e.I, power=power) n.sample <- round(exp(opt$minimum)) obj <- opt$objective } if(do.p) { obj <- 0 ncp <- n.sample*effect.size^2/2 df1 <- groups - 1 df2 <- groups*(n.sample-1) Fcrit <- qf(1-e.I, df1=df1, df2=df2) pwr <- 1-pf(Fcrit, ncp=ncp, df1=df1, df2=df2) } ncp <- n.sample*effect.size^2/2 df1 <- groups - 1 df2 <- groups*(n.sample-1) Fcrit <- qf(1-e.I, df1=df1, df2=df2) out <- list(power=pwr, n.sample=n.sample, Fcrit=Fcrit, ncp=ncp, df1=df1, df2=df2, objective=obj) as.data.frame(out) } power.bonferroni <- function(alpha, effect.size, n.pergroup, x, prior.HA, N.tests, groups=2, method=c("a","s"), n.sim=1000) { bad <- missing(alpha) || missing(effect.size) || missing(n.pergroup) || missing(x) || missing(prior.HA) || missing(N.tests) if(bad) stop("Arguments 'alpha', 'effect.size', 'n.pergroup', 'x', 'prior.HA', 'N.tests' are required") theta <- effect.size if(missing(method)) method <- "a" if(missing(groups)) groups <- 2 if(groups<2) stop("groups must be 2 or larger") if(theta<=0) stop("Effect size must be positive") if(missing(n.sim) && method=="s") n.sim <- 1000 m <- N.tests n <- n.pergroup r <- prior.HA d <- groups mu <- theta*(n/2)^0.5 ncp <- mu^2 if(method=="a") { if(d==2) p <- 1-pnorm(qnorm(1-alpha/(2*m))-mu) if(d>2) p <- f.power(n.sample=n, groups=d, effect.size=theta, e.I=alpha/(2*m))$power s <- 0 for(k in x:m) s <- s + choose(m,k)*r^k*(1-r)^(m-k)*(1-pbinom(x-1, prob=p, size=k)) ans <- s } if(method=="s") { s <- 0 cMs <- list(mean, colMeans)[[1 + 1*(d>2)]] for(ii in 1:n.sim) { rej <- 0 for(k in 1:m) { xi <- 1*(runif(1)<=r) X <- matrix(rnorm(n*(d-1), mean=xi*theta, sd=1), n, d-1) X0 <- rnorm(n, mean=0, sd=1) if(d==2) rej <- rej + 1*xi*(n^0.5*(mean(X) - mean(X0))/(var(c(X)) + var(X0))^0.5>qnorm(1-alpha/(2*m))) if(d>2) { SST <- (n*d-1)*var(c(X,X0)) SSW <- sum((n-1)*apply(cbind(X,X0), 2, var)) FF <- ((SST-SSW)/(d-1))/(SSW/(d*(n-1))) rej <- rej + 1*xi*(FF>qf(1-alpha/(2*m), df1=d-1, df2=d*(n-1))) } } s <- s + 1*(rej>=x) } ans <- s/n.sim } ans } "view.presentation" <- function() { n <- grep("pdf", names(options())) system(options()[[n]] %,% " $R_HOME/library/pwrFDR/doc/2021-01-25-NWU-Biostat-Talk.pdf 2> /dev/null &") } "factorial.design" <- function(...) { m <- match.call() cc <- m cc[[1]] <- as.name("c") arg.vals <- eval(cc, sys.parent()) n.args <- length(arg.vals) n.l <- 0 n.r <- n.args-1 fwd.cpd <- c(1, cumprod(arg.vals)) rev.cpd <- c(cumprod(arg.vals[n.args:2])[(n.args-1):1],1) "%,%" <- paste0 main.call <- as.call(expression(cbind)) for(k in 1:n.args) { arg.k <- eval(m[[1+k]], sys.parent()) rep.call <- as.call(expression(rep)) rep.call$x <- 1:arg.k if(n.l>0) rep.call$times <- fwd.cpd[k] if(n.r>0) rep.call$each <- rev.cpd[k] main.call[["x" %,% k]] <- rep.call n.l <- n.l + 1 n.r <- n.r - 1 } eval(main.call) } "nna" <- function(x) { par.env.nms <- ls.str(, envir=parent.frame()) m <- match.call() vnm <- as.character(m[[2]]) exts <- vnm %in% par.env.nms n <- length(get(par.env.nms[1], envir=parent.frame())) ans <- rep(NA, n) if(exts) ans <- get(vnm, envir=parent.frame()) ans } is.formula <- function(x)class(x)=="formula" "if.na.x" <- function(x, x0=FALSE) { d.x <- dim(x) x. <- c(as.matrix(x)) y <- rep(x0, length(x.)) y[!is.na(x.)] <- x.[!is.na(x.)] structure(y, dim=d.x) } if.y.z <- function(x, y=0,z=1) { ans <- x ans[x==y] <- z ans } if.0.rm <- function(x)x[x!=0] pwrfdrmthd.sfx <- c(`FixedPoint`="FP", `simulation`="sim") pwrfdrmthd.vals <- names(pwrfdrmthd.sfx) FDP.cntl.mth.thrsh.def <- c(0.10, 50) FDP.mthd.vals <- c("BHFDR","BHCLT","Romano","Auto","both") type.vals <- c("paired", "balanced", "unbalanced") "is.int" <- function(x)(floor(x)==x) "cma.and" <- function(s){n.s <- length(s); c(rep(", ", n.s-2), " and ", "")} "cma.or" <- function(s){n.s <- length(s); c(rep(", ", n.s-2), " or ", "")} "list.a" <- function(lst, pfx=NULL, sfx=NULL) pfx %,% paste(c(t(cbind("\'" %,% lst %,% "\'", cma.and(lst)))), collapse="") %,% sfx "list.o" <- function(lst, pfx=NULL, sfx=NULL) pfx %,% paste(c(t(cbind("\'" %,% lst %,% "\'", cma.or(lst)))), collapse="") %,% sfx nera <- c("n.sample", "effect.size", "r.1", "alpha") Nnera <- c(nera, "N.tests") dNnera <- c("data", "formula", "alpha") default <- list(u=function(...)seq(from=0,to=1,len=100), alpha=function(...)NA, groups=function(...)2, control=function(groups=groups, alpha=alpha) switch(1*(groups<=2)+2*(groups>2), list(tol=1e-8, max.iter=c(1000,20), distopt=1, CS=list(NULL), sim.level=2, FDP.meth.thresh=FDP.cntl.mth.thrsh.def, verb=FALSE, low.power.stop=TRUE, ast.le.a=TRUE), list(tol=1e-8, max.iter=c(1000,20), distopt=2, CS=list(NULL), sim.level=2, FDP.meth.thresh=FDP.cntl.mth.thrsh.def, verb=FALSE, low.power.stop=TRUE, ast.le.a=TRUE)), type=function(groups=groups,alpha=alpha) c("paired","balanced")[min(max(floor(eval(groups)),1),2)], grpj.per.grp1=function(...)1, method=function(...)"FixedPoint", delta=function(groups=groups, alpha=alpha)alpha) valid.arg.dict <- list(u=function(x)all(x>=0&x<=1), groups=function(x)is.int(x)&(x>0), effect.size=function(x)(x>0), n.sample=function(x)is.int(x)&(x>0), r.1=function(x)(x>0&x<1), alpha=function(x){if(is.na(x)) x <- -1; (x>0 & x < 1)}, N.tests=function(x)is.int(x)&(x>0), average.power=function(x)(x>0.5&x<1), tp.power=function(x)(x>0.5&x<1), lambda=function(x)(x>0&x<1), FDP.control.method=function(x, vals=FDP.mthd.vals) { fdp.mthd <- try(match.arg(x, vals)) class(fdp.mthd)!="try-error" }, method=function(x, vals=pwrfdrmthd.vals) { mthd <- try(match.arg(x, vals)) class(mthd)!="try-error" }, type=function(x, vals=type.vals) { ty <- try(match.arg(x, vals)) class(ty)!="try-error" }, grpj.per.grp1=function(x, vals=1)TRUE, n.sim=function(x)is.int(x)&(x>0), delta=function(x)(x>0&x<1), tempfile=function(x)is.character(x)&length(x)==1) "valid.arg.msg" <- function(x, vrbl) { msg <- switch(vrbl, u=ifelse(!x, "All components of 'u' must be between 0 and 1 inclusive\n", NA), groups=ifelse(!x, "Argument 'groups' must be integral and > 0\n", NA), effect.size=ifelse(!x, "Argument 'effect.size' must be > 0\n", NA), n.sample=ifelse(!x, "Argument 'n.sample' must be integral and > 0\n", NA), r.1=ifelse(!x, "Argument 'r.1' must be between 0 and 1\n", NA), alpha=ifelse(!x, "Argument 'alpha' must be between 0 and 1\n", NA), N.tests=ifelse(!x, "Argument 'N.tests' must be integral and > 0\n", NA), average.power=ifelse(!x,"Argument 'average.power' must be between 1/2 and 1\n",NA), tp.power=ifelse(!x, "Argument 'tp.power' must be between 1/2 and 1\n", NA), lambda=ifelse(!x, "Argument 'lambda' must be between 1/2 and 1\n", NA), FDP.control.method=ifelse(!x, list.o(FDP.mthd.vals, "Argument 'FDP.control.method' must be " %,% "set to one of the values \n"), NA), method=ifelse(!x, list.o(pwrfdrmthd.vals, "Argument 'method' must be set to one " %,% "of the values \n"), NA), n.sim=ifelse(!x, "Argument 'n.sim' must be integral and > 0\n", NA), type=ifelse(!x, "Argument 'type' must be 'paired', 'balanced' or 'unbalanced'\n", NA), grpj.per.grp1=ifelse(!x, "this gets checked in other rules", NA), delta=ifelse(!x, "Argument 'delta' must be between 0 and 1\n", NA), tempfile=ifelse(!x, "Argument 'tempfile' must be a character string\n", NA)) if(is.na(msg)) msg <- NULL msg } other.rules <- function(sppld, frmls, m) { is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls no.n.sample <- is.msng["n.sample"] is.pwr <- (!is.msng["average.power"]) || (!is.msng["tp.power"]) pwr.nera.chk <- (!is.pwr && all(!is.msng[nera])) || (is.pwr && (sum(is.msng[nera])==1)) fdp.needs.N <- c("Auto", "BHCLT","Romano") msg.1 <- msg.2 <- msg.3 <- msg.4 <- msg.5 <- msg.6 <- msg.7 <- msg.8 <- msg.9 <- msg.10 <- msg.11 <- NULL if(!pwr.nera.chk) { msg.1 <- list.o(nera,"When neither 'average.power' or 'tp.power' is specified, " %,% "you must specify each of the arguemtns,", "\n") msg.1 <- msg.1 %,% list.o(nera, "If 'average.power' or 'tp.power' is specified, " %,% "then all but one of arguemtns.", "must be specified") } if(!is.msng["tp.power"] && is.msng["lambda"]) msg.2 <-"Specification of argument 'tp.power' requires specification of argument 'lambda' "%,% "tp.power = P(TPP > lambda)\n" if(is.pwr && m$method=="simulation") msg.3 <- "Sample size calculation not implemented in 'simulation' method.\n" if((m$FDP.control.method %in% fdp.needs.N || m$method=="simulation" || !is.msng["lambda"] || !is.msng["tp.power"])&&is.msng["N.tests"]) msg.4 <- "Argument, 'N.tests' is required for the simulation method, for computing " %,% "tp.power, and for the " %,% list.a(fdp.needs.N, "", " FDP.control.method's\n") if(m$FDP.control.method=="both" && m$method=="FixedPoint") msg.5 <- "FDP.control.method 'both' is for the simulation method only\n" if(m$FDP.control.method=="Auto" && m$method=="simulation") msg.6 <- "FDP.control.method 'Auto' is for the FixedPoint method only\n" if(m$type=="balanced" && !is.msng["grpj.per.grp1"]) msg.7 <- "If 'type' is 'balanced' then argument 'grpj.per.grp1' must be unspecified" if(m$type=="unbalanced" && (is.msng["grpj.per.grp1"] || m$grpj.per.grp1 <= 0)) msg.8 <- "If 'type' is 'unbalanced' then argument 'grpj.per.grp1' must be supplied and > 0" if(m$groups==1 && !is.msng["type"]) msg.9 <- "When argument, 'groups' is 1, then argument 'type' must be unspecified\n" if(m$groups>=2 && m$type=="unbalanced" && length(m$grpj.per.grp1)!=(m$groups-1)) msg.10 <- "If 'groups'>=2 and 'type'=='unbalanced' then 'grpj.per.grp1' must be of length groups - 1" if(m$groups>=3 && !(m$type %in% c("balanced", "unbalanced"))) msg.11 <- "If 'groups>=3' then 'type' must be balanced or unbalanced" msg <- c(msg.1, msg.2, msg.3, msg.4, msg.5, msg.6, msg.7, msg.8, msg.9, msg.10, msg.11) msg } "args.def.err.chk" <- function(m, sppld, frmls, other.rules=TRUE, eval.env) { if(missing(eval.env)) { calling.env <- sys.parent() eval.env <- ifelse(calling.env==0, topenv, sys.parent) } n.sppld <- length(sppld) is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls msng.nms <- names(is.msng)[is.msng] fill.in.default.arg.nms <- match.arg(msng.nms, names(default), several.ok=TRUE) for(v in fill.in.default.arg.nms) m[[v]] <- default[[v]](m$groups, m$alpha) for(k in 1:n.sppld) m[[sppld[k]]] <- eval(m[[sppld[k]]], eval.env()) if(!("control" %in% msng.nms) && ("control" %in% frmls)) { pfdr.cntl.call <- as.call(expression(pwrFDR.control)) pfdr.cntl.call$groups <- m$groups pfdr.cntl.call$alpha <- m$alpha nms.cntl <- names(m$control) n.c <- length(m$control) for(k in 1:n.c) pfdr.cntl.call[[nms.cntl[k]]] <- m$control[[nms.cntl[k]]] m[["control"]] <- eval(pfdr.cntl.call) } err.msg <- NULL chk.valid.arg.nms <- match.arg(sppld, names(valid.arg.dict), several.ok=TRUE) for(v in chk.valid.arg.nms) err.msg <- c(err.msg, valid.arg.msg(valid.arg.dict[[v]](m[[v]]), v)) m[["method"]] <- match.arg(m$method, pwrfdrmthd.vals) m[["FDP.control.method"]] <- match.arg(m$FDP.control.method, FDP.mthd.vals) if(m$method!="simulation") m$n.sim <- NULL if(other.rules) err.msg <- c(err.msg, other.rules(sppld, frmls, m)) m$type <- list(`paired`=1, `balanced`=2, `unbalanced`=3)[[m$type]] m[["control"]]$is.msng <- is.msng attr(m, "err.msg") <- err.msg m } "pwrFDR.control" <- function(tol, max.iter, distopt, CS, sim.level, FDP.meth.thresh, verb, low.power.stop, ast.le.a, groups, alpha) { calling.env <- sys.parent() eval.env <- ifelse(calling.env==0, topenv, sys.parent) m <- match.call() m$groups <- m$alpha <- NULL frmls <- names(formals(pwrFDR.control)) frmls <- frmls[-which(frmls=="groups")] frmls <- frmls[-which(frmls=="alpha")] sppld <- names(m)[-1] n.sppld <- length(sppld) is.msng <- !(frmls %in% sppld) names(is.msng) <- frmls msng.nms <- names(is.msng)[is.msng] default.pwrFDR.cntl <- default$control(groups=groups, alpha=alpha) fill.in.default.arg.nms <- match.arg(msng.nms, names(default.pwrFDR.cntl), several.ok=TRUE) for(v in fill.in.default.arg.nms) m[[v]] <- default.pwrFDR.cntl[[v]] for(k in 1:n.sppld) m[[sppld[k]]] <- eval(m[[sppld[k]]], eval.env()) m[[1]] <- as.name("list") eval(m, eval.env()) } DF <- c(expression(n.sample-1), expression(groups*(n.sample-1)), expression((1/n.sample + sum(1/nii.sample))^2/(1/(n.sample^2*(n.sample-1)) + sum(1/(nii.sample^2*(nii.sample-1)))))) NCP <- c(expression(n.sample^0.5*effect.size), expression((n.sample/groups)^0.5*effect.size), expression(((n.sample-1)/(1 + sum((n.sample-1)/(nii.sample-1))))^0.5*effect.size)) "dists" <- as.data.frame(rbind(c( pars0=as.call(expression(c, 0, ncp=0, sd=1)), pars1=as.call(expression(c, 0, ncp=.NCP., sd=1)), minv=-Inf, ddist=function(x, par) dnorm(x, mean=par[2], sd=par[3]), pdist=function(x, par) pnorm(x, mean=par[2], sd=par[3]), qdist=function(x, par) qnorm(x, mean=par[2], sd=par[3])), c( pars0=as.call(expression(c,1,ncp=0, ndf=.DF.)), pars1=as.call(expression(c,1,ncp=.NCP., ndf=.DF.)), minv=-Inf, ddist=function(x, par) dt(x, ncp=par[2], df=par[3]), pdist=function(x, par) pt(x, ncp=par[2], df=par[3]), qdist=function(x, par) qt(x, ncp=par[2], df=par[3])), c( pars0=as.call(expression(c,2,ncp=0, ndf1=groups-1, ndf2=.DF.)), pars1=as.call(expression(c,2,ncp=.NCP.^2, ndf1=groups-1, ndf2=.DF.)), minv=0, ddist=function(x, par) df(x, ncp=par[2], df1=par[3], df2=par[4]), pdist=function(x, par) pf(x, ncp=par[2], df1=par[3], df2=par[4]), qdist=function(x, par) qf(x, ncp=par[2], df1=par[3], df2=par[4])))) .onAttach <- function(libname, pkgname) { options(stringsAsFactors=FALSE) ver <- read.dcf(file=system.file("DESCRIPTION", package=pkgname), fields="Version") msg <- paste(pkgname, ver) %,% "\n\n" %,% "Type ?pwrFDR" msg <- msg %,% "\n" %,% " or view.presentation()" packageStartupMessage(msg) }
library(sf) library(sp) mtq <- st_read(system.file("gpkg/mtq.gpkg", package="cartography"), quiet = TRUE) expect_silent(choroLayer(mtq, var="MED", method = "q6")) expect_silent(choroLayer(spdf=as(mtq, "Spatial"), var="MED")) mtq$MED[1:3] <- NA expect_silent(choroLayer(x=getPencilLayer(mtq,100), var="MED"))
test_that("TunerAsha works", { learner = lrn("classif.debug", x = to_tune(), iter = to_tune(p_int(1, 16, tags = "budget")) ) test_tuner_successive_halving(n = 16, eta = 2, learner) }) test_that("TunerAsha works with r_max > n", { learner = lrn("classif.debug", x = to_tune(), iter = to_tune(p_int(1, 17, tags = "budget")) ) test_tuner_successive_halving(n = 16, eta = 2, learner) }) test_that("TunerAsha works with r_max < n", { learner = lrn("classif.debug", x = to_tune(), iter = to_tune(p_int(1, 15, tags = "budget")) ) test_tuner_successive_halving(n = 16, eta = 2, learner) }) test_that("repeating successive halving works", { learner = lrn("classif.debug", x = to_tune(), iter = to_tune(p_int(1, 16, tags = "budget")) ) instance = tune( method = "successive_halving", task = tsk("pima"), learner = learner, resampling = rsmp("cv", folds = 3), measures = msr("classif.ce"), repeats = TRUE, term_evals = 62) expect_equal(nrow(instance$archive$data), 62) instance = tune( method = "successive_halving", task = tsk("pima"), learner = learner, resampling = rsmp("cv", folds = 3), measures = msr("classif.ce"), repeats = FALSE) expect_equal(nrow(instance$archive$data), 31) })
nlscontour=function (x, param1 = 1, param2 = 2, range1 = NULL, range2 = NULL, npoints = 100, filled = FALSE,colored=FALSE) { pars <- x$m$getPars() cat("Parameters inherited from nls :\n") print(pars) A <- summary(x) stderrpars <- A$parameters[, 2] cat("Standard error on parameters :\n") print(stderrpars) if (is.null(range1)) range1 <- c(pars[param1] - 4 * stderrpars[param1], pars[param1] + 4 * stderrpars[param1]) if (is.null(range2)) range2 <- c(pars[param2] - 4 * stderrpars[param2], pars[param2] + 4 * stderrpars[param2]) cat("parameter 1 - name : ", names(stderrpars[param1]), "central value : ", pars[param1], " range : ", range1, " \n") cat("parameter 2 - name : ", names(stderrpars[param2]), "central value : ", pars[param2], " range : ", range2, " \n") np <- round(sqrt(npoints)) dx <- (range1[2] - range1[1])/(np - 1) dy <- (range2[2] - range2[1])/(np - 1) ax <- seq(range1[1], range1[2], dx) by <- seq(range2[1], range2[2], dy) grid <- matrix(0, np, np) valpar <- pars for (i in 1:np) for (j in 1:np) { valpar[param1] <- ax[i] valpar[param2] <- by[j] nlm <- nlsModel(formula(x), data = eval(x$data), start = valpar) az <- sum(nlm$resid()^2) grid[i, j] <- az } paletta <- colors()[seq(153, 254, 10)] if (filled) { if(colored) filled.contour(ax, by, as.matrix(grid),col = rainbow(20), nlevels = 20, plot.axes={axis(1);axis(2);points(pars[param1],pars[param2],pch=20);abline(pars[param2],0);abline(v=pars[param1])}) else filled.contour(ax, by, as.matrix(grid), col = paletta, nlevels = 20, plot.axes={axis(1);axis(2);points(pars[param1],pars[param2],pch=20,col="white");abline(pars[param2],0);abline(v=pars[param1])}) } else { par(pty = "m") contour(ax, by, grid, nlevels = 25) abline(v = pars[param1]) abline(pars[param2], 0) } title(paste("Sum of squares - parameters :", as.character(names(valpar[param1])), ",", as.character(names(valpar[param2])))) gr <- NULL gr$x <- ax gr$y <- by gr$grid <- as.data.frame(grid) class(gr) <- "nlsgrid" invisible(gr) }
test_that("resample works with weights", { task = makeClassifTask(data = iris, target = "Species", weights = as.integer(iris$Species)) res = resample(task = task, learner = "classif.rpart", resampling = makeResampleDesc("CV", iters = 2)) expect_s3_class(res$pred, "ResamplePrediction") })
hard_thres <- function(a,lam){ ind <- (abs(a)<lam) a[ind] <- 0 out <- a return(out) }
pop_iita<-function(imp, ce, lg, items, dataset = NULL, A = NULL, v){ if(v != 1 && v != 2 && v !=3){ stop("IITA version must be specified") } if(is.null(dataset) == FALSE && is.null(A) == FALSE){ stop("Either the dataset or the selection set can be specified") } p_pop<-vector(length = items) b_pop<-matrix(0,ncol = items, nrow = items) bs_pop_alt<-matrix(0,ncol = items, nrow = items) bs_pop_neu<-matrix(0,ncol = items, nrow = items) bs_pop_num<-matrix(0,ncol = items, nrow = items) error_pop_theo<-matrix(ncol = items, nrow = items) pop_matrix<-matrix(0,nrow = 2^items, ncol = items+1) for(i in 1:items){ pop_matrix[,i]<-c(rep(0, 2^(items-i)), rep(1, 2^(items-i))) } R_2<-matrix(1, ncol = items, nrow = items) for(i in 1:items){ for(j in 1:items){ if(!is.element(set(tuple(i,j)), imp) && i != j){R_2[j,i]<-0} } } base<-list() for(i in 1:items){ tmp<-vector() for(j in 1:items){ if(R_2[i,j] == 1){tmp<-c(tmp, j)} } base[[i]]<-sort(tmp) } base_list<-list() for(i in 1:items){ base_list[[i]]<-set() for(j in 1:length(base[[i]])) base_list[[i]]<-set_union(base_list[[i]], set(base[[i]][j])) } G<-list() G[[1]]<-set(set()) G[[2]]<-set() for(i in 1:length(base[[1]])){G[[2]]<-set_union(G[[2]], base[[1]][i])} G[[2]]<-set(set(), G[[2]]) for(i in 2:items){ H<-set(set()) for(j in G[[i]]){ check<-0 if(set_is_subset(base_list[[i]], j) == FALSE){ for(d in 1:i){ if(set_is_subset(base_list[[d]], set(j, base_list[[i]])) == TRUE){ if(set_is_subset(base_list[[d]], j)){ H<-set_union(H,set(set_union(j,base_list[[i]]))) } } if(set_is_subset(base_list[[d]], set(j, base_list[[i]])) == FALSE){ H<-set_union(H,set(set_union(j,base_list[[i]]))) } } } } G[[i+1]]<-set_union(G[[i]], H) } P<-matrix(0, ncol = items, nrow = length(G[[items+1]])) i<-1 for(k in (G[[items+1]])){ for(j in 1:items){ if(is.element(j, k)){P[i,j]<-1} } i<-i+1 } r_pop<-matrix(1, ncol = length(G[[items+1]]), nrow = 2^items) for(i in 1:2^items){ for(j in 1:(length(G[[items+1]]))){ for(k in 1:items){ if(pop_matrix[i,k] == 0 && P[j,k] == 1){r_pop[i,j]<-r_pop[i,j] * ce} if(pop_matrix[i,k] == 1 && P[j,k] == 1){r_pop[i,j]<-r_pop[i,j] * (1-ce)} if(pop_matrix[i,k] == 1 && P[j,k] == 0){r_pop[i,j]<-r_pop[i,j] * lg} if(pop_matrix[i,k] == 0 && P[j,k] == 0){r_pop[i,j]<-r_pop[i,j] * (1-lg)} } pop_matrix[i,items+1]<-pop_matrix[i,items+1] + r_pop[i,j]/length(G[[items+1]]) } } for(i in 1:items){ p_pop[i]<-sum(pop_matrix[pop_matrix[,i] == 1,items+1 ]) for(j in 1:items){ tmp1<-which(pop_matrix[,i] == 0) tmp2<-which(pop_matrix[,j] == 1) if(i != j){b_pop[i,j]<-sum(pop_matrix[c(tmp1,tmp2)[duplicated(c(tmp1, tmp2))] ,items+1])} } } if(is.null(dataset) && is.null(A)){ S<-list() A<-list() M<-list() S[[1]]<-set() A[[1]]<-set() M[[1]]<-set() elements<-sort(b_pop)[!duplicated(sort(b_pop))] elements<-elements[2:(length(elements))] k<-2 for(elem in elements){ S[[k]]<-set() A[[k]]<-set() M[[k]]<-set() for(i in 1:items){ for(j in 1:items){ if(b_pop[i,j] <= elem && i !=j && is.element(set(tuple(i,j)), A[[k-1]]) == FALSE){S[[k]]<-set_union(S[[k]], set(tuple(i,j)))} } } if(set_is_empty(S[[k]])){A[[k]]<-A[[k-1]]} if(set_is_empty(S[[k]]) == FALSE){ M[[k]]<-S[[k]] brake_test<-1 while(brake_test != 0){ brake<-M[[k]] for(i in M[[k]]){ for(h in 1:items){ if(h != as.integer(i)[1] && h != as.integer(i)[2] && is.element(set(tuple(as.integer(i)[2],h)), set_union(A[[k-1]], M[[k]])) == TRUE && is.element(set(tuple(as.integer(i)[1],h)), set_union(A[[k-1]], M[[k]])) == FALSE){M[[k]]<-set_intersection(M[[k]], set_symdiff(M[[k]],set(i)))} if(h != as.integer(i)[1] && h != as.integer(i)[2] && is.element(set(tuple(h,as.integer(i)[1])), set_union(A[[k-1]], M[[k]])) == TRUE && is.element(set(tuple(h,as.integer(i)[2])), set_union(A[[k-1]], M[[k]])) == FALSE){M[[k]]<-set_intersection(M[[k]], set_symdiff(M[[k]],set(i)))} } } if(brake == M[[k]]){brake_test<-0} } A[[k]]<-set_union(A[[k-1]], (M[[k]])) } k<-k+1 } A<-A[(!duplicated(A))] A<-A[!set_is_empty(A)] }else{ if(is.null(dataset) == FALSE){ A<-ind_gen(ob_counter(dataset)) } } error_pop<-vector(length = (length(A))) error_pop_num<-vector(length = (length(A))) for(i in 1:items){ error_pop_theo[,i]<-b_pop[,i] / p_pop[i] } if(v == 3 | v == 2){ all_imp<-set() for(i in 1:(items-1)){ for(j in (i+1):items){ all_imp<-set_union(all_imp, set(tuple(i,j), tuple(j,i))) } } for(k in 1:length(A)){ for(i in A[[k]]){ error_pop[k]<-error_pop[k] + ((b_pop[as.integer(i[1]), as.integer(i[2])]) / sum(p_pop[as.integer(i[2])])) } if(set_is_empty(A[[k]])){error_pop[k]<-NA} if(set_is_empty(A[[k]]) == FALSE) {error_pop[k]<-error_pop[k] / length(A[[k]])} } } if(v == 1){ for(k in 1:length(A)){ x<-rep(0,4) for(i in 1:items){ for(j in 1:items){ if(is.element(set(tuple(i,j)), A[[k]]) == TRUE && i != j){ x[2]<-x[2]-2*b_pop[i,j] * p_pop[j] x[4]<-x[4]+2 * p_pop[j]^2 } if(is.element(set(tuple(i,j)), A[[k]]) == FALSE && is.element(set(tuple(j,i)), A[[k]]) == TRUE && i != j){ x[1]<-x[1]-2*b_pop[i,j]*p_pop[i] + 2 * p_pop[i] * p_pop[j] - 2 * p_pop[i]^2 x[3]<-x[3]+2*p_pop[i]^2 } } } error_pop_num[k]<- -(x[1] + x[2]) / (x[3] + x[4]) } } if(v == 3){ diff_value_pop_alt<-vector(length = length(A)) for(k in 1:length(A)){ for(i in 1:items){ for(j in 1:items){ if(is.element(set(tuple(i,j)), A[[k]]) == TRUE && i != j){bs_pop_alt[i,j]<-error_pop[k] * p_pop[j]} if(is.element(set(tuple(i,j)), A[[k]]) == FALSE && i != j){bs_pop_alt[i,j]<-(1-p_pop[i]) * p_pop[j] * (1-error_pop[k])} } } if(set_is_empty(A[[k]])){diff_value_pop_alt[k]<-NA} if(set_is_empty(A[[k]]) == FALSE) {diff_value_pop_alt[k]<-sum((b_pop - bs_pop_alt)^2) / (items^2 - items)} } obj<-list(pop.diff = diff_value_pop_alt, pop.matrix = pop_matrix, error.pop = error_pop, selection.set = A, v = v) class(obj)<-"popiita" return(obj) } if(v == 2){ diff_value_pop_neu<-vector(length = length(A)) for(k in 1:length(A)){ for(i in 1:items){ for(j in 1:items){ if(is.element(set(tuple(i,j)), A[[k]]) == TRUE && i != j){bs_pop_neu[i,j]<-error_pop[k] * p_pop[j]} if(is.element(set(tuple(i,j)), A[[k]]) == FALSE && is.element(set(tuple(j,i)), A[[k]]) == FALSE && i != j){bs_pop_neu[i,j]<-(1-p_pop[i]) * p_pop[j]} if(is.element(set(tuple(i,j)), A[[k]]) == FALSE && is.element(set(tuple(j,i)), A[[k]]) == TRUE && i != j){bs_pop_neu[i,j]<-p_pop[j] - p_pop[i] + p_pop[i] * error_pop[k]} } } if(set_is_empty(A[[k]])){diff_value_pop_neu[k]<-NA} if(set_is_empty(A[[k]]) == FALSE) {diff_value_pop_neu[k]<-sum((b_pop - bs_pop_neu)^2) / (items^2 - items)} } obj<-list(pop.diff = diff_value_pop_neu, pop.matrix = pop_matrix, error.pop = error_pop, selection.set = A, v = v) class(obj)<-"popiita" return(obj) } if(v == 1){ diff_value_pop_num<-vector(length = length(A)) for(k in 1:length(A)){ for(i in 1:items){ for(j in 1:items){ if(is.element(set(tuple(i,j)), A[[k]]) == TRUE && i != j){bs_pop_num[i,j]<-error_pop_num[k] * p_pop[j]} if(is.element(set(tuple(i,j)), A[[k]]) == FALSE && is.element(set(tuple(j,i)), A[[k]]) == FALSE && i != j){bs_pop_num[i,j]<-(1-p_pop[i]) * p_pop[j]} if(is.element(set(tuple(i,j)), A[[k]]) == FALSE && is.element(set(tuple(j,i)), A[[k]]) == TRUE && i != j){bs_pop_num[i,j]<-p_pop[j] - p_pop[i] + p_pop[i] * error_pop_num[k]} } } if(set_is_empty(A[[k]])){diff_value_pop_num[k]<-NA} if(set_is_empty(A[[k]]) == FALSE) {diff_value_pop_num[k]<-sum((b_pop - bs_pop_num)^2) / (items^2 - items)} } obj<-list(pop.diff = diff_value_pop_num, pop.matrix = pop_matrix, error.pop = error_pop_num, selection.set = A, v = v) class(obj)<-"popiita" return(obj) } }
get_question <- function(do, q){ if(exists(do)){ if(utils::hasName(get(do), q)){ message(labelled::var_label(get(q, get(do)))) } else{ message("Warning: Variable is not in dataset") } } else{ message("Warning: Data object does not exist") } }
.aggData <- function(cnames, data, gather, FUN){ cnames <- cnames[cnames %in% colnames(data)] if(length(cnames) == 0)return( list(data = numeric(0)) ) FAC <- F df <- data[,cnames] if(FUN == 'factor'){ FAC <- T tf <- fnames <- character(0) df <- numeric(0) for(j in 1:length(cnames)){ kf <- as.character(data[,cnames[j]]) tf <- cbind(tf, kf) fnames <- append(fnames,list(sort(unique(kf)))) df <- cbind(df, match(kf,fnames[[j]]) ) } colnames(df) <- cnames FUN <- 'max' } tmp <- aggregate(df, by=gather, FUN=FUN) ord <- do.call(order,list(tmp[,names(gather)])) colnames(tmp)[-c(1:length(gather))] <- cnames if(FAC){ for(j in 1:length(cnames)){ kf <- fnames[[j]][tmp[,cnames[j]]] tmp[,cnames[j]] <- as.factor(kf) } } list(ord = ord, data = tmp[ord,]) } .setLoHi <- function(plist, pmat, xnames, ynames){ pnames <- names(plist) wx <- which(pnames %in% xnames) for(k in wx)pmat[pnames[k],] <- plist[[k]] wy <- which(pnames %in% ynames) for(k in wy)pmat[,pnames[k]] <- plist[[k]] comb <- grep('_',pnames) for(k in comb){ ck <- unlist( strsplit(pnames[k],'_') ) ik <- 1; jk <- 2 wx <- which(xnames == ck[ik]) if(length(wx) == 0){ ik <- 2; jk <- 1 wx <- which(xnames == ck[ik]) } wy <- which(ynames == ck[jk]) pmat[wx,wy] <- plist[[comb[k]]] } pmat } .myBoxPlot <- function(mat, tnam, snames, specColor, label, LEG=F){ ord <- order(colMeans(mat),decreasing=F) mat <- mat[,ord] tnam <- tnam[ord] bb <- specColor[ match(tnam, snames) ] ry <- quantile(mat, c(.01, .99)) ymin <- quantile(mat, .01) - diff(ry)*.15 ymax <- quantile(mat, .99) + diff(ry)*.7 bx <- .getColor(bb,.4) tmp <- .boxplotQuant( mat, xaxt='n',outline=F,ylim=c(ymin,ymax), col=bx, border=bb, lty=1) abline(h=0,lwd=2,col='grey',lty=2) dy <- .05*diff(par()$yaxp[1:2]) cext <- .fitText2Fig(tnam,fraction=1) text((1:length(ord)) - .1,dy + tmp$stats[5,],tnam,srt=70,pos=4, col=bb, cex=cext) pl <- par('usr') xtext <- pl[1] ytext <- pl[3] + diff(pl[3:4])*.85 .plotLabel(label,location='topleft', cex=1.0) lg <- unique(names(bb)) if(!is.null(lg) & LEG){ colb <- bb[lg] legend('bottomright',legend=lg,text.col=colb,bty='n') } } .splitNames <- function(nameVec, snames=NULL, split='_'){ vnam <- matrix( unlist( strsplit(nameVec,split) ),ncol=2,byrow=T) if(is.null(snames))return( list(vnam = vnam, xnam = NULL) ) ix <- 1 nc <- 2 y1 <- which(vnam[,1] %in% snames) y2 <- which(vnam[,2] %in% snames) if(length(y1) > length(y2))ix <- 2 if(ix == 2)nc <- 1 xnam <- vnam[,ix] vnam <- vnam[,nc] list(vnam = vnam, xnam = xnam) } .updateBetaMet <- function(X, Y, B, lo, hi, loc, REDUCT, sig=NULL, sinv=NULL, sp=.01 ){ bnew <- B mnow <- X%*%B bnew[loc] <- .tnorm(nrow(loc),lo[loc],hi[loc],B[loc],sp) mnew <- X%*%bnew if(REDUCT){ pnow <- colSums( dnorm(Y,mnow,sqrt(sig),log=T) ) pnew <- colSums( dnorm(Y,mnew,sqrt(sig),log=T) ) z <- which( runif(length(pnow),0,1) < exp(pnew - pnow) ) if(length(z) > 0)B[,z] <- bnew[,z] }else{ pnow <- sum( .dMVN(Y,mnow,sinv=sinv,log=T) ) pnew <- sum( .dMVN(Y,mnew,sinv=sinv,log=T) ) z <- runif(1,0,1) < exp(pnew - pnow) if(z)B <- bnew } B } .getPattern <- function(mat, wloc){ mat <- mat*0 + NA mat[ wloc ] <- 0 rows <- numeric(0) pattern <- numeric(0) aa <- mat*0 aa[wloc] <- 1 U <- nrow(mat) SS <- ncol(mat) cc <- 1:U wk <- which( rowSums(abs(mat+1), na.rm=T) == 0 ) if(length(wk) > 0){ aa[cc[wk],] <- NA cc <- cc[-wk] } if(length(cc) == 0)return( list(rows = rows, pattern = pattern) ) for(k in 1:U){ if(length(cc) == 0)break ak <- aa[drop=F,cc,] ac <- matrix(ak[1,],nrow(ak),ncol(ak),byrow=T) ac[is.na(ac)] <- 0 am <- ak - ac w1 <- which( duplicated(am) & rowSums(am,na.rm=T) == 0 ) w1 <- c(1,w1) cw <- cc[w1] rr <- matrix( cw, 1 ) pp <- matrix( which(aa[rr[1],] != 0), 1) if(length(pp) == 0)pp <- matrix(1:SS,1) aa[cw,] <- NA cc <- cc[-w1] if( length(rows) == 0 ){ rows <- rr pattern <- pp next } else { if( ncol(rr) == ncol(rows) )rows <- rbind(rows,rr) if( ncol(rr) > ncol(rows) ){ rk <- matrix(NA,nrow(rows),ncol(rr)) rk[,1:ncol(rows)] <- rows rows <- rbind(rk,rr) } if( ncol(rows) > ncol(rr) ){ rj <- matrix(NA,1,ncol(rows)) rj[1:length(rr)] <- rr rows <- rbind(rows,rj) } if( ncol(pp) == ncol(pattern) )pattern <- rbind(pattern,pp) if( ncol(pp) > ncol(pattern) ){ rk <- matrix(NA,nrow(pattern),ncol(pp)) rk[,1:ncol(pattern)] <- pattern pattern <- rbind(rk,pp) } if( ncol(pattern) > ncol(pp) ){ rj <- matrix(NA,1,ncol(pattern)) rj[1:length(pp)] <- pp pattern <- rbind(pattern,rj) } } if(length(cc) == 0)break } list(rows = rows, pattern = pattern) } .alphaPrior <- function(ww, tindex, ap, notOther){ S <- ncol(ww) lo <- ap$lo hi <- ap$hi al <- (lo + hi)/2 al[ lo == hi ] <- NA tmp <- .getURowCol( mat = al, notOther ) uindex <- tmp$uindex Amat <- tmp$Amat wA <- tmp$wA aindex <- tmp$aindex loA <- hiA <- Amat loA[ wA ] <- lo[ aindex[,c('toW','fromW')] ] hiA[ wA ] <- hi[ aindex[,c('toW','fromW')] ] list(Amat = Amat, loAmat = loA, hiAmat = hiA, wA = wA, uindex = uindex, aindex = aindex) } .betaPrior <- function(beta, notOther, loBeta, hiBeta){ BPRIOR <- F loB <- hiB <- NULL bg <- beta wB <- which(!is.na(t(loBeta[,notOther])) & t(loBeta[,notOther] != hiBeta[,notOther]), arr.ind=T)[,c(2,1)] colnames(wB) <- c('row','col') bg <- bg*0 bg[ wB ] <- -999 zB <- which(is.na(bg) | bg != -999) bg <- (loBeta + hiBeta)/2 bg[ is.nan(bg) ] <- 0 loB <- loBeta[,notOther] hiB <- hiBeta[,notOther] list(beta = bg, loB = loB, hiB = hiB, wB = wB, zB = zB, BPRIOR = BPRIOR) } .rhoPrior <- function(lprior, w, x, tindex, xnames, snames, other, notOther, timeZero = NULL){ loRho <- lprior$lo hiRho <- lprior$hi rho <- (loRho + hiRho)/2 if(length(other) > 0)loRho[,other] <- hiRho[,other] <- NA lkeep <- which(!is.na(loRho)) M <- nrow(rho) rownames(rho)[1] <- 'intercept' S <- ncol(rho) SS <- length(notOther) n <- nrow(x) wz <- w gindex <- kronecker(diag(S),rep(1,M)) gindex <- gindex[lkeep,] wg <- which(gindex == 1,arr.ind=T) wc <- matrix(rep(1:M,S*M),S*M,S)[lkeep,] rowG <- wc[wg] gindex <- cbind(rowG,wg) tmp <- as.vector( t(outer(colnames(rho)[notOther], rownames(rho),paste,sep='_') ) ) rownames(gindex) <- tmp[lkeep] colX <- match(rownames(rho),colnames(x)) colX <- colX[rowG] gindex <- cbind(colX, gindex) colnames(gindex)[3:4] <- c('rowL','colW') nV <- nrow(gindex) Vmat <- matrix(0,n,nV) wz[wz < 0] <- 0 Vmat[tindex[,2],] <- wz[tindex[,1], gindex[,'colW']]*x[tindex[,2], gindex[,'colX']] Vmat[timeZero,] <- wz[timeZero, gindex[,'colW']]*x[timeZero, gindex[,'colX']] Rmat <- matrix(NA,nV,S) rownames(Rmat) <- rownames(gindex) loRmat <- hiRmat <- Rmat[,notOther] Rmat[ gindex[,c('rowL','colW')] ] <- rho[ gindex[,c('rowG','colW')] ] lo <- hi <- Rmat*0 lo[ gindex[,c('rowL','colW')] ] <- loRho[ gindex[,c('rowG','colW')] ] hi[ gindex[,c('rowL','colW')] ] <- hiRho[ gindex[,c('rowG','colW')] ] Rmat[ is.nan(Rmat) ] <- 0 wL <- which(!is.na(Rmat[,notOther]),arr.ind=T) lo[is.na(lo)] <- 0 hi[is.na(hi)] <- 0 list(Rmat = Rmat, loRmat = lo[,notOther], hiRmat = hi[,notOther], wL = wL, gindex = gindex, Vmat = Vmat) } .plotXbyY <- function(xdata, yy, ee, vname, xlim=range(xdata[,vname],na.rm=T)){ plotj <- as.character(xdata[,'plot']) sitej <- .splitNames(plotj)$vnam[,1] sitea <- sort(unique(sitej)) years <- sort(unique(xdata[,'year'])) nyr <- length(years) labs <- rep(1:12,nyr) week <- (1:(nyr*12))*30 midYr <- (1:(nyr*2))*365/2 S <- ncol(yy) ynames <- colnames(yy) mfrow <- .getPlotLayout(S) xaxt <- 's' if(vname == 'JD'){ xaxt <- 'n' xlim <- c(130,365*nyr) } par(mfrow=mfrow,bty='n',mar=c(4,4,1,1)) for(s in 1:S){ ys <- yy[,s]/ee[,s] plot(NULL,xlim=xlim,ylim=range(ys,na.rm=T),xlab=' ',ylab='count/14 day/m2', xaxt=xaxt) if(vname == 'JD'){ abline(v=midYr,col='grey',lty=2) axis(1,at=week,labels=labs) } for(k in 1:length(sitea)){ for(j in 1:nyr){ wk <- which(sitej == sitea[k] & xdata[,'year'] == years[j]) if(length(wk) == 0)next lines((j-1)*365 + xdata[wk,vname],ys[wk]) } } title(ynames[s]) } } .pasteCols <- function(mm){ tmp <- apply(mm,1,paste0,collapse='-') names(tmp) <- NULL tmp } .getURowCol <- function(mat, notOther){ rownames(mat) <- colnames(mat) <- NULL S <- ncol(mat) ww <- which(is.finite(t(mat)),arr.ind=T) ww <- ww[,c(2,1)] colnames(ww) <- c('toW','fromW') wnames <- .pasteCols(ww) ar <- matrix(0,S,S) ar[ww] <- 1 ar[ww[,c(2,1)]] <- 1 wa <- which(ar == 1,arr.ind=T) wa <- wa[wa[,2] >= wa[,1],] wa <- wa[order(wa[,1],wa[,2]),] uindex <- wa un <- .pasteCols(wa) nu <- .pasteCols(wa[,c(2,1)]) arow <- match(wnames,un) vrow <- match(wnames,nu) aindex <- ww arow[is.na(arow)] <- vrow[is.na(arow)] rownames(ww) <- un[arow] wA <- cbind(arow,ww[,1]) colnames(wA) <- c('rowA','toW') Amat <- matrix(NA,nrow(uindex),S) Amat[wA] <- mat[ aindex[,c('toW','fromW')] ] rownames(Amat) <- un rownames(uindex) <- un wnot <- which( aindex[,1] %in% notOther & aindex[,2] %in% notOther ) wA <- wA[wnot,] aindex <- aindex[wnot,] list(uindex = uindex, Amat = Amat, wA = wA, aindex = aindex) } .invertCondKronecker <- function(sinv1, sinv2, cindex){ ns1 <- nrow(sinv1) ns2 <- nrow(sinv2) n <- ns1*ns2 i1 <- c(1:n)[cindex] i0 <- c(1:n)[-cindex] ck <- kronecker(sinv1,sinv2) sk <- solveRcpp( .invertSigma(ck[i1,i1],REDUCT=F ) ) sinverse <- ck[i0,i0] - ck[i0,i1]%*%sk%*%ck[i1,i0] sinverse } gjamFillMissingTimes <- function(xdata, ydata, edata, groupCol, timeCol, groupVars = groupCol, FILLMEANS = FALSE, typeNames = NULL, missingEffort = .1){ if(is.null(colnames(xdata)))stop('xdata must have column names') if(is.null(colnames(ydata)))stop('ydata must have column names') if(FILLMEANS & is.null(typeNames)){ stop(" if FILLMEANS then provide typeNames as single value (e.g., 'DA') or vector for each column of ydata") } if(is.character(xdata[,timeCol])){ stop( paste('the time index xdata$',timeCol, ' must be numeric', sep='') ) } if(!is.null(groupVars))groupVars <- groupVars[ groupVars %in% colnames(xdata) ] wna <- which( is.na(edata) | edata == 0, arr.ind=T ) if(length(wna) > 0){ nna <- nrow(wna) pna <- signif( nna/length(as.vector(edata)) ) me <- apply(edata, 2, quantile, .5, na.rm=T ) mm <- me[ wna[,2] ] mm[ mm == 0 ] <- missingEffort edata[wna] <- mm*missingEffort print( paste( nna, ' missing values (', pna, '%) in edata', sep='') ) } ord <- order(xdata[,groupCol], xdata[,timeCol]) xdata <- xdata[ord, ] ydata <- ydata[ord, ] edata <- edata[ord, ] groupIndex <- xdata[,groupCol] if(is.factor(groupIndex))groupIndex <- as.character(groupIndex) allGroups <- sort(unique(groupIndex)) groupIndex <- match(groupIndex,allGroups) ngroups <- length(allGroups) allTimes <- sort(unique(xdata[,timeCol])) allTimes <- min(xdata[,timeCol], na.rm=T):max(xdata[,timeCol], na.rm=T) timeIndex <- match(xdata[,timeCol],allTimes) xdata <- cbind(groupIndex,timeIndex,xdata) timeZero <- numeric(0) tord <- order(groupIndex, timeIndex, decreasing=F) xtmp <- xdata[tord,] ytmp <- as.matrix( ydata[tord,] ) etmp <- as.matrix( edata[tord,] ) timeIndex <- xtmp[,'timeIndex'] groupIndex <- xtmp[,'groupIndex'] notFactor <- !sapply(xtmp,is.factor) notChar <- !sapply(xtmp,is.character) notFactor <- which(notFactor & notChar) insert <- 0 xtmp <- cbind(insert, xtmp) x1 <- xtmp[drop=F, 1, ] y1 <- as.matrix( ytmp[drop=F, 1, ] ) + NA e1 <- as.matrix( etmp[drop=F, 1, ] )*0 for(m in 1:ncol(x1))x1[,m] <- NA x1[,'insert'] <- 1 xnew <- ynew <- enew <- numeric(0) for(j in 1:ngroups){ wj <- which(xtmp$groupIndex == j) mj <- range(xtmp[wj,timeCol], na.rm=T) nr <- diff(mj) + 2 jt <- (mj[1]-1):mj[2] tt <- c(1:nr) - 1 xj <- x1 if(!is.null(groupVars)){ groupVars <- groupVars[ groupVars %in% colnames(xtmp) ] if(length(groupVars) > 0)xj[,groupVars] <- xtmp[wj[1],groupVars] } xj <- xj[rep(1, nr),] xj[,timeCol] <- jt xj[,'timeIndex'] <- tt mm <- match(xtmp[wj,timeCol], xj[,timeCol]) xj[mm,] <- xtmp[wj,] xj[,'timeIndex'] <- tt xj[,'groupIndex'] <- j xj[mm,'insert'] <- 0 yj <- y1[rep(1, nr),] yj[mm,] <- ytmp[wj,] ej <- e1[rep(1, nr),] ej[mm,] <- etmp[wj,] xnew <- rbind(xnew, xj) ynew <- rbind(ynew, yj) enew <- rbind(enew, ej) } rn <- columnPaste(xnew[,'groupIndex'],xnew[,'timeIndex']) rownames(xnew) <- rownames(ynew) <- rownames(enew) <- rn timeZero <- which(xnew[,'timeIndex'] == 0) timeLast <- timeZero[-1] - 1 timeLast <- c(timeLast,nrow(xnew)) colnames(xnew)[colnames(xnew) == 'groupIndex'] <- 'groups' colnames(xnew)[colnames(xnew) == 'timeIndex'] <- 'times' noEffort <- which(rowSums(etmp,na.rm=T) == 0) noEffort <- noEffort[!noEffort %in% timeZero] rowInserts <- which(xnew[,'insert'] == 1) ymiss <- which( is.na(ynew), arr.ind=T ) if(FILLMEANS){ if(length(typeNames) == 1)typeNames <- rep(typeNames, ncol(ynew)) sl <- rep(colnames(ynew), each = nrow(ynew)) gl <- rep(xnew[,'groups'], nrow(ynew)) ym <- tapply(ynew, list(group = rep(xnew[,'groups'], ncol(ynew)), species = sl), mean, na.rm=T) if(!is.matrix(ym)){ ym <- t( as.matrix(ym) ) rownames(ym) <- xnew[1,'groups'] } ym <- ym[drop=FALSE,,colnames(ynew)] rym <- round( ym[drop=FALSE, ,typeNames %in% c('DA','PA','CC')] ) ym[,typeNames %in% c('DA','PA','CC')] <- rym rr <- match( xnew[ ymiss[,1],'groups'], rownames(ym) ) cc <- match( colnames(ynew)[ymiss[,2]], colnames(ym) ) ynew[ ymiss ] <- ym[ cbind(rr, cc) ] ynew[timeZero, ] <- ynew[timeZero + 1, ] ynew[ ymiss ] <- ynew[ ymiss ]*missingEffort ynew[,typeNames %in% c('DA','PA','CC')] <- round( ynew[,typeNames %in% c('DA','PA','CC')] ) sl <- rep(colnames(ynew), each = nrow(ynew)) enew <- enew[,colnames(ynew)] em <- enew em[ em == 0 ] <- NA em <- tapply(as.vector(em), list(group = rep(xnew[,'groups'], ncol(enew)), species = sl), mean, na.rm=T) if(!is.matrix(em)){ em <- t( as.matrix(em) ) rownames(em) <- xnew[1,'groups'] } em <- em*missingEffort enew[ ymiss ] <- em[ cbind(rr, cc) ] } timeList <- list(times = timeCol, groups = groupCol, timeZero = timeZero, timeLast = timeLast, rowInserts = rowInserts, noEffort = noEffort) list(xdata = xnew, ydata = as.matrix(ynew), edata = enew, timeList = timeList) } .traitTables <- function(specs, traitTab, groups, types='CA', fill=T){ wi <- which( !duplicated(groups[,1]) ) groups <- groups[wi,] traitTab <- traitTab[wi,] for(j in 2:ncol(specs)){ specs[,j] <- .cleanNames(as.character(specs[,j])) groups[,j] <- .cleanNames(as.character(groups[,j])) } ng <- ncol(groups) ns <- nrow(specs) nt <- ncol(traitTab) stt <- matrix(0,ns,nt) i <- match(specs[,1],groups[,1]) wi <- which(is.finite(i)) stt[wi,] <- as.matrix( traitTab[i[wi],] ) rownames(stt) <- specs[,1] colnames(stt) <- colnames(traitTab) tabList <- list(stt) for(k in 2:ng){ sk0 <- tabList[[k-1]] kn <- rownames(sk0) allk <- unique(specs[,k]) ii <- match(specs[,k],allk) i <- rep( ii, nt ) j <- rep( 1:nt, each=ns) nall <- length(allk) mm <- matrix(0,nall,nt) sk0[sk0 == 0] <- NA stk <- .byGJAM(as.vector(sk0), i, j, mm,mm, fun='mean') colnames(stk) <- colnames(traitTab) rownames(stk) <- allk stk <- stk[specs[,k],] stk[is.finite(sk0)] <- sk0[is.finite(sk0)] tabList <- append(tabList, list(stk)) } traitMeans <- colMeans(traitTab,na.rm=T) if(fill){ ww <- which(tabList[[ng]] == 0, arr.ind=T) if(length(ww) > 0){ tabList[[ng]][ww] <- traitMeans[ww[,2]] } } list(traitMeans = traitMeans, traitList = tabList, specs = specs) } .combineFacLevels <- function(xfactor,fname=NULL, aname = 'reference', vminF=1){ tmp <- as.character(xfactor) tmp[tmp %in% fname] <- aname tab <- table(tmp) wm <- names(tab)[tab < vminF] tmp[tmp %in% wm] <- aname as.factor(tmp) } .getColor <- function(col,trans){ tmp <- col2rgb(col) rgb(tmp[1,], tmp[2,], tmp[3,], maxColorValue = 255, alpha = 255*trans, names = paste(col,trans,sep='_')) } .figure1 <- function(){ sig <- .9 mu <- 3.1 offset <- -2 par(mfrow=c(1,2),bty='n',mar=c(6,5,3,.1)) part <- c(0,2,3.3,4.9,6.6) w <- seq(-1,7,length=500) dw <- dnorm(w,mu,sig) dp <- dw[ findInterval(part,w) ] pw <- pnorm(part,mu,sig) pw[-1] <- diff(pw) plot(w,2*dw - .5,type='l',ylim=c(-.5,4),yaxt='n', ylab= expression(paste(italic(y),'|(',italic(w),', ',bold(p),')',sep='')), xlab= expression(paste(italic(w),'|(',bold(x)[i],', ',bold(beta), ', ',bold(Sigma),')',sep='')), xlim=c(offset,7), lwd=2) axis(2, at = c(0:5)) db <- .15 int <- 4 polygon( c(w,rev(w)), 2*c(dw,w*0) - .5, col='grey', lwd=2) lines(c(-1,part[1]),c(0,0),lwd=2) for(j in 1:(length(part))){ lines( part[j:(j+1)],c(j,j), lwd=3) ww <- which(w >= part[j] & w <= part[j+1]) if(j == 3){ w1 <- ww[1] w2 <- max(ww) suppressWarnings( arrows( mean(w[ww]), 2*max(dw[ww]) - .4, mean(w[ww]), j - .4, angle=20,lwd=3, col = 'grey', length=.2) ) suppressWarnings( arrows( w[w1] - .5 , j , -.7, j , angle= 20, lwd = 3, col='grey', length=.2) ) text( c(w[w1], w[w2]),c(3.3,3.3), expression(italic(p)[4], italic(p)[5])) text( w[w2] + .3,.6,expression( italic(w)[italic(is)] )) text( 0,3.5,expression( italic(y)[italic(is)] )) } coll <- 'white' if(j == int)coll <- 'grey' rect( offset, j - 1 - db, 2*pw[j] + offset, j - 1 + db, col=coll, border='black', lwd=2) } ww <- which(w >= part[int - 1] & w <= part[int]) abline(h = -.5, lwd = 2) title('a) Data generation',adj=0, font.main = 1, font.lab =1) plot(w,2*dw - .5,type='l',ylim=c(-.5,4), yaxt='n', ylab= expression(italic(y)), xlab= expression(paste(italic(w),'|(',italic(y),', ',bold(p),')',sep='')), xlim=c(offset,7), lwd=2,col='grey') axis(2, at = c(0:5)) lines(c(-1,part[1]),c(0,0),lwd=2) abline(h=-.5, lwd=2, col='grey') for(j in 1:(length(part))){ lines( part[j:(j+1)],c(j,j), lwd=3) lines(part[c(j,j)],2*c(0,dp[j])-.5, col='grey') coll <- 'white' if(j -- int)coll <- 'grey' if(j == int){ rect( offset, j - 1 - db, 2*pw[j] + offset, j - 1 + db, col='black', border='black') } } ww <- which(w >= part[int - 1] & w <= part[int]) polygon( w[c(ww,rev(ww))], 2*c(dw[ww],ww*0) - .5, col='grey', lwd=2) suppressWarnings( arrows( mean(w[ww]), int - 1.3,mean(w[ww]), 2*max(dw) - .5, angle=20,lwd=3, col = 'grey', length=.2) ) suppressWarnings( arrows( -.5, int - 1, min(w[ww]) - .4, int - 1, angle= 20, lwd = 3, col='grey', length=.2) ) title('b) Inference',adj=0, font.main = 1, font.lab = 1) } .add2matrix <- function(values,xmat=NULL){ if(is.null(xmat)){ n <- length(values) cc <- sort(unique(values)) xmat <- matrix(0,n,length(cc),dimnames = list(1:n,cc)) xmat[ cbind( c(1:n),match(values,cc)) ] <- 1 return(xmat) } n <- nrow(xmat) if(length(values) != n)stop('vector length must equal rows in xmat') all <- sort( unique( c(values,as.numeric(colnames(xmat))) )) nc <- length(all) xnew <- matrix(0,n,nc,dimnames = list(1:n,all)) xnew[,colnames(xmat)] <- xmat xnew[ cbind(c(1:n),match(values,all)) ] <- xnew[ cbind(c(1:n),match(values,all)) ] + 1 xnew } .appendMatrix <- function(m1,m2,fill=NA,SORT=F,asNumbers=F){ if(length(m1) == 0){ if(is.matrix(m2)){ m3 <- m2 } else { m3 <- matrix(m2,nrow=1) } if( !is.null(names(m2)) )colnames(m3) <- names(m2) return(m3) } if(length(m2) == 0){ if(!is.matrix(m1))m1 <- matrix(m1,nrow=1) return(m1) } if( is.vector(m1) | (length(m1) > 0 & !is.matrix(m1)) ){ nn <- names(m1) if(is.null(nn))warning('cannot append matrix without names') m1 <- matrix(m1,1) colnames(m1) <- nn } if( is.vector(m2) | (length(m2) > 0 & !is.matrix(m2)) ){ nn <- names(m2) if(is.null(nn))warning('cannot append matrix without names') m2 <- matrix(m2,1) colnames(m2) <- nn } c1 <- colnames(m1) c2 <- colnames(m2) r1 <- rownames(m1) r2 <- rownames(m2) n1 <- nrow(m1) n2 <- nrow(m2) allc <- unique( c(c1,c2) ) if(SORT & !asNumbers)allc <- sort(allc) if(SORT & asNumbers){ ac <- as.numeric(allc) allc <- as.character( sort(ac) ) } nr <- n1 + n2 nc <- length(allc) if(is.null(r1))r1 <- paste('r',c(1:n1),sep='-') if(is.null(r2))r2 <- paste('r',c((n1+1):nr),sep='-') new <- c(r1,r2) mat1 <- match(c1,allc) mat2 <- match(c2,allc) out <- matrix(fill,nr,nc) colnames(out) <- allc rownames(out) <- new out[1:n1,mat1] <- m1 out[(n1+1):nr,mat2] <- m2 out } .byIndex <- function(xx,INDICES,FUN,coerce=F,...){ nl <- length(INDICES) tmp <- unlist(by( as.vector(xx),INDICES,FUN,...) ) nd <- dim(tmp) tmp <- array(tmp,dim=nd, dimnames=dimnames(tmp)) tmp[is.na(tmp)] <- 0 if(!coerce)return(tmp) dname <- dimnames(tmp) mk <- rep(0,length(nd)) for(k in 1:length(nd))mk[k] <- max(as.numeric(dimnames(tmp)[[k]])) wk <- which(mk > nd) if(length(wk) > 0){ tnew <- array(0,dim=mk) if(length(dim(tnew)) == 1)tnew <- matrix(tnew,dim(tnew),1) for(k in wk){ newk <- c(1:mk[k]) mat <- match(dimnames(tmp)[[k]],newk) if(k == 1){ tnew[mat,] <- tmp rownames(tnew) <- 1:nrow(tnew) } if(k == 2){ tnew[,mat] <- tmp colnames(tnew) <- c(1:ncol(tnew)) } tmp <- tnew } } tmp } .chains2density <- function(chainMat,labs=NULL,reverseM=F,varName=NULL, cut=0){ chNames <- colnames(chainMat) if(!is.null(varName)){ wc <- grep(varName,colnames(chainMat),fixed=T) if(length(wc) == 0)stop('varName not found in colnames(chainMat)') ww <- grep('_',colnames(chainMat),fixed=T) if(length(ww) > 0){ tmp <- .splitNames(colnames(chainMat))$vnam wc <- which(tmp[,2] == varName) if(length(wc) == 0)wc <- which(tmp[,1] == varName) } chainMat <- chainMat[,wc] if(!is.matrix(chainMat))chainMat <- matrix(chainMat,ncol=1) colnames(chainMat) <- chNames[wc] } nj <- ncol(chainMat) nd <- 512 clab <- colnames(chainMat) if(is.null(labs) & !is.null(clab))labs <- clab if(is.null(labs) & is.null(clab)) labs <- paste('v',c(1:nj),sep='-') xt <- yt <- matrix(NA,nj,nd) rownames(xt) <- rownames(yt) <- labs xrange <- signif(range(chainMat),2) for(j in 1:nj){ xj <- chainMat[,j] tmp <- density(xj,n = nd, cut=cut, na.rm=T) xt[j,] <- tmp$x yt[j,] <- tmp$y } yymax <- max(yt,na.rm=T) if(reverseM){ xt <- -t( apply(xt,1,rev) ) yt <- t( apply(yt,1,rev) ) } list(x = xt, y = yt, xrange = xrange, ymax = yymax, chainMat = chainMat) } .checkDesign <- function( x, intName='intercept', xflag=':', isFactor = character(0) ){ p <- ncol(x) if(ncol(x) < 3){ return( list(VIF = 0, correlation = 1, rank = 2, p = 2, isFactor=isFactor) ) } if(is.null(colnames(x))){ colnames(x) <- paste('x',c(1:p),sep='_') } xrange <- apply(x,2,range,na.rm=T) wi <- which(xrange[1,] == 1 & xrange[2,] == 1) if(length(wi) > 0)colnames(x)[wi] <- 'intercept' wx <- grep(xflag,colnames(x)) wi <- which(colnames(x) == 'intercept') wi <- unique(c(wi,wx)) xname <- colnames(x) wmiss <- which(is.na(x),arr.ind=T) if(length(wmiss) > 0){ rowTab <- table( table(wmiss[,1]) ) colTab <- table(wmiss[,2]) } VIF <- rep(NA,p) names(VIF) <- xname GETF <- F if(length(isFactor) > 0)GETF <- T for(k in 1:p){ if(xname[k] %in% wi)next notk <- xname[xname != xname[k] & !xname %in% xname[wi]] ykk <- x[,xname[k]] xkk <- x[,notk,drop=F] wna <- which(is.na(ykk) | is.na(rowSums(xkk))) if(length(wna) > 0){ ykk <- ykk[-wna] xkk <- xkk[-wna,] } ttt <- suppressWarnings( lm(ykk ~ xkk) ) tkk <- suppressWarnings( summary(ttt)$adj.r.squared ) VIF[k] <- 1/(1 - tkk) xu <- sort( unique(x[,k]) ) tmp <- identical(c(0,1),xu) if(GETF)if(tmp)isFactor <- c(isFactor,xname[k]) } VIF <- VIF[-wi] corx <- cor(x[,-wi], use="complete.obs") if(length(wna) == 0){ rankx <- qr(x)$rank } else { rankx <- qr(x[-wna,])$rank } corx[upper.tri(corx,diag=T)] <- NA findex <- rep(0,p) findex[xname %in% isFactor] <- 1 designTable <- list('table' = rbind( round(VIF,2),findex[-wi],round(corx,2)) ) rownames(designTable$table) <- c('VIF','factor',xname[-wi]) designTable$table <- designTable$table[-3,] if(p == rankx)designTable$rank <- paste('full rank:',rankx,'= ncol(x)') if(p < rankx) designTable$rank <- paste('not full rank:',rankx,'< ncol(x)') list(VIF = round(VIF,2), correlation = round(corx,2), rank = rankx, p = p, isFactor = isFactor, designTable = designTable) } .fitText2Fig <- function(xx, width=T, fraction=1, cex.max=1){ px <- par('pin')[1] py <- par('pin')[2] cl <- max( strwidth(xx, units='inches') ) ch <- strheight(xx, units='inches')[1]*length(xx) if(width){ xf <- fraction*px/cl yf <- fraction*py/ch } else { xf <- fraction*px/ch yf <- fraction*py/cl } cexx <- min(c(xf,yf)) if(cexx > cex.max)cexx <- cex.max cexx } .cov2Dist <- function(sigma){ n <- nrow(sigma) matrix(diag(sigma),n,n) + matrix(diag(sigma),n,n,byrow=T) - 2*sigma } .distanceMatrix <- function(mat, DIST=F){ if(isSymmetric(mat)){ if( all(diag(mat) == 1) ){ mmm1 <- mat if(DIST)mmm1 <- .cov2Dist(mat) } else { if(DIST){ mmm1 <- .cov2Dist( mat ) } else { mmm1 <- cor(mat) } } } else { if(DIST){ mmm1 <- .cov2Dist( cov(mat) ) } else { mmm1 <- cor(mat) } } mmm1 } .reorderMatrix <- function(mat, DIST, opt=NULL){ mmm <- .distanceMatrix(mat, DIST) imm <- .distanceMatrix(t(mat), DIST) if(is.null(opt)){ clist <- list(PLOT=F, DIST = DIST) }else{ clist <- opt clist$PLOT <- T } h1 <- .clusterPlot( imm, opt = clist) rord <- h1$corder h2 <- .clusterPlot( mmm, opt = clist ) cord <- h2$corder list(rowOrder = rord, colOrder = cord, rowTree = h1, colTree = h2) } .clustMat <- function(mat, SYM){ mrow <- mat DIST <- T if(SYM){ if(all(diag(mrow) == 1)){ DIST <- F mrow <- cor(mat) if(nrow(mrow) != nrow(mat))mrow <- cor(t(mat)) }else{ mrow <- .cov2Dist(cov(mat)) if(nrow(mrow) != nrow(mat))mrow <- .cov2Dist(cov(t(mat))) } }else{ mrow <- .cov2Dist(cov(mat)) if(nrow(mrow) != nrow(mat))mrow <- .cov2Dist(cov(t(mat))) } list(cmat = mrow, DIST = DIST) } .clusterWithGrid <- function(mat1, mat2=NULL, opt, expand=1){ leftClus <- rightClus <- topClus1 <- topClus2 <- leftLab <- rightLab <- topLab1 <- topLab2 <- lower1 <- diag1 <- lower2 <- diag2 <- SYM1 <- SYM2 <- sameOrder <- FALSE colOrder1 <- colOrder2 <- rowOrder <- colCode1 <- colCode2 <- rowCode <- slim1 <- slim2 <- horiz1 <- horiz2 <- vert1 <- vert2 <- NULL mainLeft <- main1 <- main2 <- ' ' DIST1 <- DIST2 <- T ncluster <- 4 for(k in 1:length(opt))assign( names(opt)[k], opt[[k]] ) if(isSymmetric(mat1))SYM1 <- T doneLeft <- done1 <- done2 <- F nr <- nrow(mat1) nc1 <- ncol(mat1) nc2 <- 0 twoMat <- F if(!is.null(mat2)){ if( min(dim(mat2)) < 2 )return() if(isSymmetric(mat2))SYM2 <- T twoMat <- T nc2 <- ncol(mat2) if(nrow(mat2) != nr)stop('matrices must have same no. rows') } cwide <- .15 mg <- .08 lg <- rg <- tg <- mg gg <- .24 if(leftLab) lg <- gg if(topLab1 | topLab2) tg <- gg if(rightLab)rg <- gg xwide <- mg if(leftLab) xwide <- c(xwide,lg) if(leftClus)xwide <- c(xwide,cwide) xg <- .8 if(twoMat){ xg <- expand*xg*nc1/(nc1+nc2) xg <- c(xg,1 - xg) } xwide <- c(xwide,xg) if(rightClus)xwide <- c(xwide,cwide) if(rightLab) xwide <- c(xwide,rg) xwide <- c(xwide,mg) xloc <- cumsum(xwide)/sum(xwide) ywide <- c(mg,.8) if(topClus1 | topClus2)ywide <- c(ywide,cwide) if(topLab1 | topLab2) ywide <- c(ywide,tg) ywide <- c(ywide,mg) yloc <- cumsum(ywide)/sum(ywide) if(is.null(rowCode)) rowCode <- rep('black',nr) if(is.null(colCode1))colCode1 <- rep('black',nc1) if(is.null(colCode2))colCode2 <- rep('black',nc2) tmp <- .clustMat(mat1, SYM1) m1Row <- tmp$cmat DIST1 <- tmp$DIST tmp <- .clustMat(t(mat1), SYM1) m1Col <- tmp$cmat if(is.null(rowOrder)){ if(nrow(m1Row) != nrow(mat1))m1Row <- cor(t(mat1)) if(ncluster > nrow(m1Row)/2)ncluster <- 2 copt <- list( PLOT=F, DIST = DIST1, ncluster=ncluster ) tmp <- .clusterPlot( m1Row, copt) clus <- tmp$clusterIndex cord <- tmp$corder rowClust <- clus[cord] rowOrder <- cord } if(is.null(colOrder1)){ if(SYM1){ colOrder1 <- rowOrder colClust1 <- rowClust }else{ copt <- list( PLOT=F, DIST = DIST1, ncluster=ncluster ) tmp <- .clusterPlot( m1Col, copt) clus <- tmp$clusterIndex cord <- tmp$corder colClust1 <- clus[cord] colOrder1 <- cord } } if(twoMat){ tmp <- .clustMat(t(mat2), SYM2) m2Col <- tmp$cmat DIST2 <- tmp$DIST if(is.null(colOrder2)){ if(sameOrder){ colOrder2 <- rowOrder m2Col <- t(mat2) }else{ copt <- list( PLOT=F, DIST = DIST2 ) tmp <- .clusterPlot( m2Col, copt) if(is.null(tmp)){ colOrder2 <- 1:nrow(m2Col) }else{ clus <- tmp$clusterIndex cord <- tmp$corder colClust2 <- clus[cord] colOrder2 <- cord } } } } rowLabs <- rownames(mat1)[rowOrder] NEW <- add <- F xi <- 0:1 yi <- 1:2 if(leftLab){ xi <- xi + 1 par(plt=c(xloc[xi],yloc[yi]),bty='n', new=NEW) plot(NULL,col='white',xlim=c(0,1),ylim=c(0,nr), xaxt='n',yaxt='n',xlab='',ylab='') xl <- rep(1,nr) yl <- c(1:nr)*nr/diff(par('usr')[3:4]) cex <- .fitText2Fig(rowLabs,fraction=.96) text( xl,yl, rowLabs ,pos=2,cex=cex, col = rowCode[rowOrder]) NEW <- add <- T mtext(mainLeft,2) doneLeft <- T } if(leftClus){ xi <- xi + 1 par(plt=c(xloc[xi],yloc[yi]),bty='n', new=NEW) copt <- list( main=' ',cex=.2, colCode=rowCode, ncluster=ncluster, LABELS = F, horiz=T, noaxis=T, DIST=DIST1 ) tmp <- .clusterPlot( m1Row, copt) clus <- tmp$clusterIndex cord <- tmp$corder rowClust <- clus[cord] NEW <- add <- T if(!doneLeft)mtext(mainLeft,2) doneLeft <- T } xi <- xi + 1 yz <- yi if(topClus1){ yz <- yz + 1 par(plt=c(xloc[xi],yloc[yz]),bty='n',new=NEW) copt <- list( main=' ', colCode=colCode1, DIST = DIST1, LABELS = F, horiz=F, noaxis=T, add=T ) tmp <- .clusterPlot( m1Col ,copt) NEW <- add <- T if(!topLab1){ mtext(main1,3) done1 <- T } } par(plt=c(xloc[xi],yloc[yi]), bty='n', new=NEW) mai <- mat1 diag(mai) <- NA if(is.null(slim1))slim1 = quantile(mai,c(.01,.99), na.rm=T) slim1 <- signif(slim1,2) tmp <- .colorSequence(slim1) scale <- tmp$scale colseq <- tmp$colseq ww <- as.matrix(expand.grid(c(1:nr),c(1:nc1))) mt <- mat1[rev(rowOrder),colOrder1] win <- which(ww[,1] >= ww[,2]) mask <- lower.tri(mt,diag=!diag1) mask <- apply(mask,2,rev) if(lower1){ if(min(scale) > 0 | max(scale) < 0){mt[mask] <- mean(scale) }else{ mt[mask] <- 0 } } icol <- findInterval(mt[ww],scale,all.inside=T) coli <- colseq[icol] xlim=c(range(ww[,2])); xlim[2] <- xlim[2] + 1 ylim=c(range(ww[,1])); ylim[2] <- ylim[2] + 1 sides <- cbind( rep(1,nrow(ww)), rep(1,nrow(ww)) ) plot(NULL,cex=.1,xlab=' ',ylab=' ', col='white', xaxt='n',yaxt='n', xlim=xlim, ylim=ylim) symbols(ww[,2] + .5,nr - ww[,1] + 1 + .5,rectangles=sides, fg=coli,bg=coli,inches=F, xlab=' ',ylab=' ', xaxt='n',yaxt='n', add=T) if(!is.null(horiz1)){ cut <- which(diff(rowClust) != 0) + 1 ncc <- length(cut) for(i in 1:ncc){ lines(c(0,cut[i]-2),cut[c(i,i)],lty=2) } text(rep(1,ncc),cut,2:(ncc+1),pos=3) } if(!is.null(vert1)){ cut <- which(diff(colClust1) != 0) + .5 ncc <- length(cut) for(i in 1:ncc){ lines(cut[c(i,i)],c(cut[i]+2,nc1),lty=2) } text(cut,rep(nc1,ncc),2:(ncc+1),pos=4) } NEW <- add <- T if(!doneLeft)mtext(mainLeft,2) doneLeft <- T if(topLab1){ yz <- yz + 1 par(plt=c(xloc[xi], yloc[yz]),bty='n', new=NEW) plot(c(0,0),c(0,0),col='white',xlim=c(1,nc1) ,ylim=c(0,1), xaxt='n',yaxt='n',xlab='',ylab='') yl <- rep(0,nc1) xl <- .99*c(1:nc1)*(nc1-1)/diff(par('usr')[1:2]) cex <- .fitText2Fig(colnames(m1Col), width=F, fraction=.95) text( xl - .1,yl,colnames(m1Col)[colOrder1],pos=4,cex=cex,srt=90, col=colCode1[colOrder1]) } if(!done1)mtext(main1,3) par(plt=c(xloc[xi],c(.3*yloc[yi[1]],yloc[yi[1]])), bty='n', new=NEW) lx1 <- .3 lx2 <- .7 lx <- seq(lx1,lx2,length=length(scale)) wx <- diff(lx)[1] ly <- lx*0 + .3*yloc[yi[1]] rx <- cbind(lx*0 + wx, ly*0 + .7*diff(yloc[yi])) symbols(lx,ly,rectangles=rx,fg=colseq,bg=colseq,xaxt='n',yaxt='n', xlab='',ylab='',xlim=c(0,1),ylim=c(0,yloc[yi[1]])) text(lx[1],ly[1],slim1[1],pos=2, cex=.9) text(lx[length(lx)],ly[1],slim1[2],pos=4, cex=.9) if(twoMat){ xi <- xi + 1 yz <- yi if( topClus2 ){ yz <- yz + 1 par(plt=c(xloc[xi],yloc[yz]),bty='n',new=NEW) copt <- list( main=' ', LABELS = F, colCode=colCode2, horiz=F, noaxis=T, add=T, DIST=DIST2 ) ttt <- .clusterPlot( m2Col, copt) if(!topLab2){ mtext(main2,3) done2 <- T } } par(plt=c(xloc[xi],yloc[yi]), bty='n', new=T) if(is.null(slim2))slim2 = quantile(mat2,c(.01,.99)) slim2 <- signif(slim2,1) tmp <- .colorSequence(slim2) scale <- tmp$scale colseq <- tmp$colseq ww <- as.matrix(expand.grid(c(1:nr),c(1:nc2))) mt <- mat2[rev(rowOrder),colOrder2] if(lower2){ mask <- lower.tri(mt,diag=!diag1) mask <- apply(mask,2,rev) mt[mask] <- 0 if(min(scale) > 0 | max(scale) < 0){ mt[mask] <- mean(scale) }else{ mt[mask] <- 0 } } icol <- findInterval(mt[ww],scale,all.inside=T) coli <- colseq[icol] xlim=c(range(ww[,2])); xlim[2] <- xlim[2] + 1 ylim=c(range(ww[,1])); ylim[2] <- ylim[2] + 1 sides <- cbind( rep(1,nrow(ww)), rep(1,nrow(ww)) ) plot(0,0,cex=.1,xlab=' ',ylab=' ', col='white',xaxt='n',yaxt='n', xlim=xlim, ylim=ylim) symbols(ww[,2] + .5,nr - ww[,1] + 1 + .5, rectangles=sides, fg=coli, bg=coli, inches=F, xlab=' ',ylab=' ', xaxt='n', yaxt='n', add=T) if(!is.null(horiz2)){ cut <- which(diff(rowClust) != 0) + 1 ncc <- length(cut) for(i in 1:ncc){ xmm <- c(0,cut[i]-2) if(!lower2)xmm[2] <- nc2 + 1 lines(xmm,cut[c(i,i)],lty=2) } if(lower2) text(rep(1,ncc),cut,2:(ncc+1),pos=3) if(!lower2)text(rep(nc2+1,ncc),cut,2:(ncc+1),pos=3) } if(!is.null(vert2)){ cut <- which(diff(vert2[colOrder2]) != 0) + .5 ncc <- length(cut) for(i in 1:ncc){ lines(cut[c(i,i)],c(cut[i]+2,nc1),lty=2) } text(cut,rep(nc1,ncc),2:(ncc+1),pos=4) } if(topLab2){ yz <- yz + 1 par(plt=c(xloc[xi],yloc[yz]),bty='n', new=NEW) plot(c(0,0),c(0,0),col='white',xlim=c(1,nc2),ylim=c(0,1), xaxt='n',yaxt='n',xlab='',ylab='') yl <- rep(0,nc2) xl <- c(1:nc2)*(nc2-1)/diff(par('usr')[1:2]) if(xl[1] < 1)xl[1] <- 1.2 cex <- .fitText2Fig(colnames(m2Col),width=F, fraction=.95) text( xl - .05,yl,colnames(m2Col)[colOrder2],pos=4,cex=cex,srt=90, col=colCode2[colOrder2]) } if(!done2)mtext(main2,3) } par(plt=c(xloc[xi],c(.3*yloc[yi[1]],yloc[yi[1]])), bty='n', new=NEW) lx1 <- .3 lx2 <- .7 lx <- seq(lx1,lx2,length=length(scale)) wx <- diff(lx)[1] ly <- lx*0 + .3*yloc[yi[1]] rx <- cbind(lx*0 + wx, ly*0 + .7*diff(yloc[yi])) symbols(lx,ly,rectangles=rx,fg=colseq,bg=colseq,xaxt='n',yaxt='n', xlab='',ylab='',xlim=c(0,1),ylim=c(0,yloc[yi[1]])) text(lx[1],ly[1],slim2[1],pos=2, cex=.9) text(lx[length(lx)],ly[1],slim2[2],pos=4, cex=.9) if(rightClus){ xi <- xi + 1 par(plt=c(xloc[xi], yloc[yi]), bty='n', mgp=c(3,1,0), new=NEW) mmm <- .distanceMatrix(t(mat2), DIST1) copt <- list( main=' ',cex=.2, REV=T, LABELS = F,horiz=T, noaxis=T ) tmp <- .clusterPlot( mmm , copt) } if(rightLab){ xi <- xi + 1 par(plt=c(xloc[xi],yloc[yi]),bty='n', new=NEW) plot(c(0,0),c(0,0),col='white',xlim=range(c(0,1)),ylim=c(0,nr), xaxt='n',yaxt='n',xlab='',ylab='') xl <- rep(0,nr) yl <- c(1:nr)*nr/diff(par('usr')[3:4]) cex <- .fitText2Fig(rownames(m1Row),fraction=.8) text( xl,yl,rev( rownames(m1Row) ),pos=4,cex=cex, col=rev(rowCode[rowOrder])) } } .clusterPlot <- function(dmat, opt = NULL){ main <- xlab <- ' ' method <- 'complete' cex <- 1; ncluster <- 2; textSize <- 1 add <- REV <- reverse <- noaxis <- DIST <- F xlim <- colCode <- NULL horiz <- LABELS <- PLOT <- T for(k in 1:length(opt))assign( names(opt)[k], opt[[k]] ) getTreeLabs <- function ( tree ){ getL <- function(tree_node) { if(is.leaf(tree_node)) attr(tree_node, 'label') } unlist( dendrapply(tree, getL) ) } nr <- nrow(dmat) nn <- nrow(dmat) if( min(c(nr,nn) ) < 3)return() if(DIST){ if(!isSymmetric(dmat))dmat <- dist(dmat) diss <- as.dist( dmat ) }else{ diss <- as.dist(.cov2Dist(dmat)) } htree <- hclust(diss,method) ctmp <- cutree(htree,k=1:ncluster) wclus <- ctmp[,ncluster] clusterCol <- NULL clusterIndex <- ctmp[, ncluster, drop=F] clusterList <- character(0) notLab <- F if(is.null(colCode)){ colF <- colorRampPalette(c('black','blue','orange','brown','red')) mycols <- colF(ncluster) notLab <- T colCode <- mycols[ctmp[,ncluster]] names(colCode) <- rownames(ctmp) } col.lab <- colCode if(!LABELS)col.lab <- rep('white',length(colCode)) colLab <- function(n) { if(is.leaf(n)) { a <- attributes(n) attr(n, "nodePar") <- c(a$nodePar, list(col = col.lab[n[1]], lab.col = col.lab[n[1]])) } n } tdendro <- as.dendrogram(htree) if(reverse)tdendro <- rev(tdendro) dL <- dendrapply(tdendro,colLab) tlab <- getTreeLabs(tdendro) corder <- match(tlab,colnames(dmat)) names(corder) <- colnames(dmat)[corder] nodePar <- list(cex = .1, lab.cex=textSize) leafLab <- "textlike" nodePar$leaflab <- leafLab if(!PLOT){ return( invisible(list( clusterList = clusterList, colCode = colCode, clusterIndex = clusterIndex, corder = corder) ) ) } if(horiz){ if(is.null(xlim))xlim <- c(attr(dL,'height'),0) if(REV)xlim <- rev(xlim) } axes <- T if(noaxis)axes <- F new <- F if(add)new <- T tmp <- plot( dL,nodePar=nodePar, horiz=horiz, xlim=xlim, axes = axes) if(!LABELS & !notLab){ col <- colCode[corder] pvar <- par('usr') wi <- abs(diff(pvar[1:2])/10) hi <- abs(diff(pvar[3:4])/10) if(horiz){ xx <- rep(pvar[2],nn) yy <- 1:nn rec <- cbind( rep(wi,nn), rep(1,nn) ) symbols(xx,yy,rectangles=rec,fg=col, bg=col, inches=F, add=T) } else { xx <- 1:nn yy <- rep(pvar[3],nn) rec <- cbind( rep(1,nn), rep(hi,nn) ) symbols(xx,yy,rectangles=rec,fg=col, bg=col, inches=F, add=T) } } title(main) invisible(list( clusterList = clusterList, colCode = colCode, clusterIndex = clusterIndex, corder = corder) ) } .colorLegend <- function(xx,yy,ytick=NULL, scale=seq(yy[1],yy[2],length=length(cols)), cols,labside='right', text.col=NULL, bg=NULL,endLabels=NULL){ nn <- length(scale) ys <- seq(yy[1],yy[2],length=nn) for(j in 1:(length(scale)-1)){ rect(xx[1],ys[j],xx[2],ys[j+1],col=cols[j],border=NA) } if(!is.null(bg))rect(xx[1],yy[1],xx[2],yy[2],border=bg,lwd=3) if(!is.null(ytick)){ ys <- diff(yy)/diff(range(ytick))*ytick yt <- ys - min(ys) + yy[1] for(j in 1:length(yt)){ lines(xx,yt[c(j,j)]) } } if(!is.null(endLabels)){ cx <- cols[c(1,nn)] if(!is.null(text.col))cx <- text.col if(!is.null(text.col))cx <- text.col if(labside == 'right')text(diff(xx)+c(xx[2],xx[2]),yy,endLabels,col=cx) if(labside == 'left')text(c(xx[1],xx[1]),yy,endLabels,pos=2,col=cx) } } .capFirstLetter <- function(xx) { s <- unlist(strsplit(xx, " ")) s <- paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "", collapse = " ") unlist(strsplit(s, " ")) } .lowerFirstLetter <- function(xx){ s <- unlist(strsplit(xx, " ")) s <- paste(tolower(substring(s, 1, 1)), substring(s, 2), sep = "", collapse = " ") unlist(strsplit(s, " ")) } .colorSequence <- function(slim, colorGrad=NULL, ncol=200){ if(is.null(colorGrad)){ colorSeq <- c('darkblue','darkblue','blue', 'green','white', 'yellow','red','brown','brown') colorSeq <- rev( c(' ' ' ' colorGrad <- colorRampPalette(colorSeq) } colseq <- colorGrad(ncol) if(slim[1] < 0 & slim[2] > 0){ dp <- slim[2] - 0 dm <- 0 - slim[1] ncol <- 200 colseq <- colorGrad(ncol) if(dp < dm)colseq <- colseq[101 + c(-100:round(dp/dm*100))] if(dp > dm)colseq <- colseq[ round((1 - dm/dp)*100):200 ] ncol <- length(colseq) } scale <- seq(slim[1],slim[2],length.out=ncol) list(colseq = colseq, scale = scale ) } .corPlot <- function(cmat, slim=NULL,PDIAG=F,plotScale=1, makeColor=NULL,textSize=NULL, textCol = rep('black',nrow(cmat)), CORLINES=T,tri='lower',colorGrad = NULL, cex=1, SPECLABS = T, squarePlot = T,LEGEND = T, widex=5.5,widey=6.5,add=F,new=T){ if(is.null(slim))slim = quantile(cmat,c(.01,.99)) slim <- signif(slim,1) if(tri == 'upper')cmat[lower.tri(cmat)] <- 0 if(tri == 'lower')cmat[upper.tri(cmat)] <- 0 dy <- nrow(cmat) dx <- ncol(cmat) d <- dx xtext <- rep(c(1,100),dx/2) if(length(xtext) < d)xtext <- c(xtext,1) if(d < 20)xtext <- xtext*0 + 1 xtext <- xtext*0 + 1 if(!is.null(colorGrad)){ ncol <- 200 colseq <- colorGrad(ncol) scale <- seq(slim[1],slim[2],length.out=ncol) } else { tmp <- .colorSequence(slim, colorGrad) scale <- tmp$scale colseq <- tmp$colseq } ww <- as.matrix(expand.grid(c(1:dy),c(1:dx))) if(tri == 'upper'){ ww <- ww[ww[,1] <= ww[,2],] ww <- ww[order(ww[,1]),] } if(tri == 'lower'){ ww <- ww[ww[,1] >= ww[,2],] ww <- ww[order(ww[,1]),] } icol <- findInterval(cmat[ww],scale,all.inside=T) coli <- colseq[icol] if(PDIAG)coli[ww[,1] == ww[,2]] <- 'white' ss <- max(c(dx,dy))/5/plotScale if(squarePlot).mapSetup(c(0,dx),c(0,dy),scale=ss, widex=widex,widey=widey) if(squarePlot){ symbols(ww[,2],dy - ww[,1] + 1,squares=rep(1,nrow(ww)), xlim=c(0,dx+4),ylim=c(0,dy+4), fg=coli,bg=coli,inches=F,xlab=' ',ylab=' ',xaxt='n',yaxt='n', add=add) } else { sides <- cbind( rep(1,nrow(ww)), rep(1,nrow(ww)) ) symbols(ww[,2],dy - ww[,1] + 1,rectangles=sides, xlim=c(0,dx+4),ylim=c(0,dy+4), fg=coli,bg=coli,inches=F,xlab=' ',ylab=' ',xaxt='n',yaxt='n', add=add) } if(!is.null(makeColor)){ for(k in 1:length(makeColor)){ mm <- makeColor[[k]] if(length(mm) == 0)next if(tri == 'upper')mm <- mm[mm[,1] <= mm[,2],] if(tri == 'lower')mm <- mm[mm[,1] >= mm[,2],] ss <- matrix(0,dy,dx) ss[mm] <- 1 wk <- which(ss[ww] == 1) ccc <- names(makeColor)[[k]] symbols(ww[wk,2],dy - ww[wk,1]+1,squares=rep(1,length(wk)), fg=ccc,bg=ccc,inches=F,xaxt='n',yaxt='n',add=T) } } ncolor <- length(unique(textCol)) ll <- 1/d + 1 if(tri == 'lower'){ for(kk in 1:d){ kb <- kk - .5 ke <- d - kk + .5 if(CORLINES){ if(kk <= d)lines(c(kb,kb),c(0,ke),col='grey',lwd=1.5) if(kk > 1){ lines( c(.5,kb),c(ke,ke),col='grey',lwd=1.5) lines(c(kb,kb+.5),c(ke,ke+.5),col='grey',lwd=1.5) } } if(!SPECLABS & ncolor > 1){ xp <- c(kb, kb, kb + ll + .5, kb + ll + 1.5, kb + 1) yp <- c(ke, ke + 1, ke + ll + 1.5, ke + ll + .5, ke) polygon(xp, yp, border = textCol[kk], col = textCol[kk]) } } } rect(0,-1,d+1,.5,col='white',border=NA) if(is.null(textSize))textSize <- exp(-.02*ncol(cmat)) labels <- rev(rownames(cmat)) if(!SPECLABS)labels <- F if(tri == 'lower' & SPECLABS)text( c(d:1)+.1*xtext, c(1:d)+.5, rev(colnames(cmat)),pos=4,srt=45, col = rev(textCol), cex=textSize) if(tri == 'both'){ labels <- rev(rownames(cmat)) par(las = 1) .yaxisHorizLabs( labels, at=c(1:length(labels)), xshift=.05, col = textCol, pos=2) par(las = 0) if(SPECLABS){ text( c(dx:1)-.1*xtext, xtext*0+dy+.8, rev(colnames(cmat)), pos=4, srt=55, col = rev(textCol), cex=textSize) } else { sides <- cbind( rep(1,dx),rep(1/dy,dx) ) symbols(1:dx,rep(1+dy,dx),rectangles=sides, fg=textCol,bg=textCol, add=T) } } labside <- 'left' wk <- which(scale >= slim[1] & scale <= slim[2]) px <- par('usr') xs <- .01*diff(px[1:2]) midx <- .95*mean( c(dx,px[2]) ) yx <- c(1*dy - .25*dy, 1*dy ) if(LEGEND).colorLegend(c(midx-xs,midx+xs),yx,ytick=c(slim[1],0,slim[2]), scale[wk],cols=colseq[wk],labside=labside, endLabels=range(slim),text.col='black') } .cor2Cov <- function(sigvec,cormat){ n <- nrow(cormat) d <- length(sigvec) if(d == 1)sigvec <- rep( sigvec, n ) s <- matrix(sigvec,n,n) cormat*sqrt(s*t(s)) } .cov2Cor <- function(covmat, covInv = NULL){ d <- nrow(covmat) di <- diag(covmat) s <- matrix(di,d,d) cc <- covmat/sqrt(s*t(s)) if(!is.null(covInv)){ dc <- diag(sqrt(di)) ci <- dc%*%covInv%*%dc return(ci) } cc } .cov2Dist <- function(sigma){ n <- nrow(sigma) matrix(diag(sigma),n,n) + matrix(diag(sigma),n,n,byrow=T) - 2*sigma } .dMVN <- function(xx,mu,smat=NULL,sinv=NULL,log=F){ if( !is.matrix(xx) )xx <- matrix(xx,1) if( !is.matrix(mu) )mu <- matrix(mu,1) if(length(smat) > 0){ tmp <- try( dmvnormRcpp(xx, mu, smat, logd=log),silent=T ) if( !inherits(tmp,'try-error') )return(tmp) } ss <- xx - mu k <- ncol(xx) if( !is.null(sinv) ){ logdet <- log( det(sinv) ) z <- rowSums( ss %*% sinv * ss) dens <- as.vector((-k/2) * log(2 * pi) + 0.5 * logdet - 0.5 * z) if (log == FALSE) dens <- exp(dens) return(dens) } } .directIndirectCoeffs <- function( snames, xvector, chains, MEAN = T, factorList = NULL, keepNames, omitY, sdScaleY = F, sdScaleX, standX, otherpar = NULL, REDUCT = F, ng, burnin, nsim = 50){ if(is.matrix(xvector)) stop('xvector must be a row vector with variable names') xnames <- names(xvector) N <- otherpar$N r <- otherpar$r bchain <- chains$bgibbs schain <- chains$sgibbs sigErrGibbs <- kchain <- NULL if(REDUCT){ kchain <- chains$kgibbs sigErrGibbs <- chains$sigErrGibbs } ns <- nsim simIndex <- sample(burnin:ng,ns,replace=T) if(sdScaleY){ tmp <- .expandSigmaChains(snames, sgibbs = schain, otherpar = otherpar, simIndex = simIndex, sigErrGibbs, kchain, REDUCT, CHAINSONLY=F, verbose = FALSE) if(REDUCT)kchain <- kchain[simIndex,] schain <- schain[simIndex,] sigErrGibbs <- sigErrGibbs[simIndex] } else { bchain <- bchain[simIndex,] schain <- schain[simIndex,] } if(length(factorList) > 0){ factorNames <- factorList for(j in 1:length(factorList)){ tmp <- matrix( unlist(strsplit(factorList[[j]],names(factorList)[j])), ncol=2,byrow=T)[,2] tmp[nchar(tmp) == 0] <- paste(names(factorList)[j],c(1:length(tmp)), sep='') factorNames[[j]] <- tmp } } S <- S1 <- length(snames) sindex <- c(1:S) knames <- snames nc <- nrow(bchain) gs <- 1:nrow(bchain) if(length(omitY) > 0){ wob <- grep(paste(omitY,collapse="|"),colnames(bchain)) bchain[,wob] <- 0 sindex <- sindex[!snames %in% omitY] knames <- snames[sindex] S1 <- length(knames) } nspec <- length(snames) ww <- grep(':',xnames) main <- xnames if(length(ww) > 0)main <- xnames[-ww] main <- main[main != 'intercept'] int <- unique( unlist( strsplit(xnames[ww],':') ) ) mainEffect <- matrix(NA,nspec,length(main)) colnames(mainEffect) <- main rownames(mainEffect) <- snames intEffect <- dirEffect <- indEffectTo <- mainEffect mainSd <- dirSd <- intSd <- indSdTo <- mainEffect maxg <- length(main)*length(sindex)*length(gs) pbar <- txtProgressBar(min=1,max=maxg,style=1) ig <- 0 for(j in 1:length(main)){ ttt <- .interactionsFromGibbs(mainx=main[j], bchain=bchain, specs=snames, xmnames=names(xvector), xx=xvector, omitY = omitY, sdScaleX=F, standX) maine <- ttt$main inter <- ttt$inter indirTo <- maine*0 direct <- maine + inter if(MEAN){ dmain <- colMeans(maine) inte <- colMeans(inter) dir <- colMeans(direct) } else { dmain <- apply(maine,2,median) inte <- apply(inter,2,median) dir <- apply(direct,2,median) } mainEffect[sindex,j] <- dmain intEffect[sindex,j] <- inte dirEffect[sindex,j] <- dir mainSd[sindex,j] <- apply(maine,2,sd) intSd[sindex,j] <- apply(inter,2,sd) dirSd[sindex,j] <- apply(direct,2,sd) for(g in gs){ if(REDUCT){ Z <- matrix(schain[g,],N,r) ss <- .expandSigma(sigErrGibbs[g], S, Z = Z, kchain[g,], REDUCT = T)[sindex,sindex] if(sdScaleY)cc <- .cov2Cor(ss) } else { ss <- .expandSigma(schain[g,], S = S, REDUCT = F)[sindex,sindex] if(sdScaleY)cc <- .cov2Cor(ss) } for(s in 1:length(sindex)){ if(REDUCT){ si <- invWbyRcpp(sigErrGibbs[g], Z[kchain[g,sindex[-s]],]) if(sdScaleY){ dc <- diag(sqrt(diag(ss)))[-s,-s] ci <- dc%*%si%*%dc } } else { si <- solveRcpp(ss[-s,-s]) if(sdScaleY)ci <- solveRcpp(cc[-s,-s]) } if(!sdScaleY){ sonk <- ss[drop=F,s,-s] e2 <- sonk%*%si%*%direct[g,-s] } else { sonk <- cc[drop=F,s,-s] e2 <- sonk%*%ci%*%direct[g,-s] } indirTo[g,s] <- e2 ig <- ig + 1 setTxtProgressBar(pbar,ig) } } if(MEAN){ indirectTo <- colMeans(indirTo[gs,]) } else { indirectTo <- apply(indirTo[gs,],2,median) } indEffectTo[sindex,j] <- indirectTo indSdTo[sindex,j] <- apply(indirTo[gs,],2,sd) } if(!is.null(keepNames)){ wk <- which(rownames(mainEffect) %in% keepNames) mainEffect <- mainEffect[wk,] intEffect <- intEffect[wk,] dirEffect <- dirEffect[wk,] indEffectTo <- indEffectTo[wk,] mainSd <- mainSd[wk,] dirSd <- dirSd[wk,] indSdTo <- indSdTo[wk,] } list(mainEffect = mainEffect, intEffect = intEffect, dirEffect = dirEffect, indEffectTo = indEffectTo, mainSd = mainSd, dirSd = dirSd, intSd = intSd, indSdTo = indSdTo) } .interactionsFromGibbs <- function(mainx,bchain,specs,xmnames=names(xx), xx=colMeans(xx), omitY=NULL, sdScaleX, standX){ if(length(omitY) > 0){ wob <- numeric(0) for(k in 1:length(omitY)){ wob <- c(wob, grep(omitY[k],colnames(bchain))) } bchain[,wob] <- 0 specs <- specs[!specs %in% omitY] } ww <- grep(':',xmnames) int <- unique( unlist( strsplit(xmnames[ww],':') ) ) int <- int[int != mainx] xj <- paste(mainx,specs,sep='_') wj <- which(colnames(bchain) %in% xj) if(length(wj) == 0){ xj <- paste(specs,mainx,sep='_') wj <- which(colnames(bchain) %in% xj) } maine <- bchain[,xj] inter <- maine*0 m1 <- paste(mainx,':',sep='') m2 <- paste(':',mainx,sep='') i1 <- grep( m1,xmnames ) i2 <- grep( m2,xmnames ) if(sdScaleX)maine <- maine*standX[mainx,'xsd'] if( length(i1) > 0 ){ ww <- match(unlist( strsplit(xmnames[i1],m1) ),xmnames) ox <- xmnames[ww[is.finite(ww)]] for(kk in 1:length(i1)){ xi <- paste(xmnames[i1[kk]],specs,sep='_') wi <- which(colnames(bchain) %in% xi) if(length(wi) == 0){ xi <- paste(specs,xmnames[i1[kk]],sep='_') wi <- which(colnames(bchain) %in% xi) } xik <- xx[ox[kk]] bik <- bchain[,xi] if(sdScaleX){ xik <- (xik - standX[ox[kk],'xmean'])/standX[ox[kk],'xsd'] bik <- bik*standX[mainx,'xsd']*standX[ox[kk],'xsd'] } inter <- inter + bik*xik } } if( length(i2) > 0 ){ ww <- match(unlist( strsplit(xmnames[i2],m2) ),xmnames) ox <- xmnames[ww[is.finite(ww)]] for(kk in 1:length(i2)){ xi <- paste(xmnames[i2[kk]],specs,sep='_') wi <- which(colnames(bchain) %in% xi) if(length(wi) == 0){ xi <- paste(specs,xmnames[i2[kk]],sep='_') wi <- which(colnames(bchain) %in% xi) } xik <- xx[ox[kk]] bik <- bchain[,xi] if(sdScaleX){ xik <- (xik - standX[ox[kk],'xmean'])/standX[ox[kk],'xsd'] bik <- bik*standX[mainx,'xsd']*standX[ox[kk],'xsd'] } inter <- inter + bik*xik } } list(main = maine, inter = inter) } .stackedBoxPlot <- function( stackList, stackSd=character(0), ylim=NULL,sortBy = NULL, barnames=NULL, col=rep(NULL,length(stackList)), border=rep(NA,length(stackList)), decreasing=T, nsd=1.96, cex=1, legend=NULL, scaleLegend=.1){ nn <- length(stackList) ord <- c(1:length(stackList[[1]])) nx <- length(ord) xx <- 0:(nx-1) if(is.null(ylim)){ ymax <- ymin <- 0 for(j in 1:nn){ ymax <- ymax + max( c(0,stackList[[j]]),na.rm=T ) ymin <- ymin + min( c(0,stackList[[j]]),na.rm=T ) } ylim <- c(ymin,ymax) yscale <- diff(ylim,na.rm=T)*.4 ylim[1] <- ylim[1] - yscale ylim[2] <- ylim[2] + yscale } if(!is.null(sortBy)){ if(length(sortBy) > 1){ ord <- sortBy } else { ord <- order( stackList[[sortBy]], decreasing = decreasing) } if(!is.null(barnames))barnames <- barnames[ord] } dy <- diff(ylim) xlim <- c(0,1.2*length(ord)) add <- F offset <- offsetPos <- offsetNeg <- rep(0,length(stackList[[1]])) if(is.null(col))col <- c(1:nn) for(j in 1:nn){ xj <- stackList[[j]][ord] names(xj) <- NULL wp <- which(xj > 0) wn <- which(xj < 0) offset[wp] <- offsetPos[wp] offset[wn] <- offsetNeg[wn] hj <- xj barplot(height= hj,offset=offset,xlim=xlim,ylim=ylim, col=col[j],border=border[j],add=add) ww <- grep(names(stackList)[j],names(stackSd)) if(length(ww) > 0){ xz <- xx + .5 xz <- xz*1.2 tall <- nsd*stackSd[[ww]] y1 <- hj + offset + tall y2 <- hj + offset - tall for(i in 1:length(ord)){ lines(xz[c(i,i)],c(y1[i],y2[i]),lwd=6,col='white') lines(c(xz[i]-.1,xz[i]+.1),y1[c(i,i)],lwd=6,col='white') lines(c(xz[i]-.1,xz[i]+.1),y2[c(i,i)],lwd=6,col='white') lines(xz[c(i,i)],c(y1[i],y2[i]),lwd=2,col=col[j]) lines(c(xz[i]-.1,xz[i]+.1),y1[c(i,i)],lwd=2,col=col[j]) lines(c(xz[i]-.1,xz[i]+.1),y2[c(i,i)],lwd=2,col=col[j]) } } if(j == 1)add <- T offsetPos[wp] <- offsetPos[wp] + hj[wp] offsetNeg[wn] <- offsetNeg[wn] + hj[wn] if(j == nn & !is.null(barnames)){ xall <- par('usr')[1:2] xtic <- c(1:nx)*(diff(xall) - 1)/nx - .8 yy <- offsetPos + .2*dy pos <- yy*0 + 1 wl <- which(abs(offsetNeg) < abs(offsetPos)) yy[wl] <- offsetNeg[wl] - .2*dy pos[wl] <- 4 text(xtic,yy,barnames,srt=90.,pos=pos,cex=cex) } } if(!is.null(legend)){ dy <- diff(ylim)*scaleLegend dx <- 1.2 x1 <- length(ord)*.02 + 1 y1 <- ylim[1] pos <- 4 if(legend == 'topright'){ x1 <- length(ord) y1 <- ylim[2] dy <- -dy dx <- -dx pos <- 2 } if(legend == 'topleft'){ y1 <- ylim[2] dy <- -dy } if(legend == 'bottomright'){ x1 <- length(ord) dx <- -dx pos <- 2 } for(j in 1:length(stackList)){ y2 <- y1 + dy rect(x1,y1,x1 + 1,y2,col=col[j],border=border[j]) y1 <- y2 colj <- col[j] if(colj == 'white')colj <- border[j] text(x1 + dx,y1 - dy/2,names(stackList)[[j]],col=colj,pos=pos,cex=cex) } } invisible( ord ) } .getScoreNorm <- function(x,mu,xvar){ - ( (x - mu)^2)/xvar - log(xvar) } .gjamBaselineHist <- function(y1, bins = NULL, ylim = NULL, htFraction = .5, nclass=20){ y1 <- y1[ is.finite(y1) ] y1[y1 < min(bins)] <- min(bins) y1[y1 > max(bins)] <- max(bins) if(!is.null(bins)){ hh <- hist(y1,breaks=bins,plot=F) } else { hh <- hist(y1,nclass=nclass,plot=F) } xvals <- rep(hh$breaks,each=2) yvals <- rep(hh$density,each=2) nb <- length(hh$breaks) yvals <- c( 0, yvals, 0) xy <- rbind(xvals, yvals) minx <- min(xvals) maxx <- max(xvals) miny <- min(yvals) dy <- diff( range(yvals) ) xy[2,] <- miny + .3*xy[2,]*dy/max(xy[2,]) xy[1,xy[1,] < minx] <- minx xy[2,xy[2,] < miny] <- miny if(!is.null(ylim)){ dy <- diff(ylim) sc <- htFraction*dy/max(xy[2,]) xy[2,] <- ylim[1] + (xy[2,] - ylim[1])*sc } xy } .gjamCensorSetup <- function(y,w,z,plo,phi,wm,censorMat){ nc <- ncol(censorMat) br <- numeric(0) nk <- length(wm) n <- nrow(y) zk <- y[,wm]*0 blast <- -Inf for(j in 1:nc){ valuej <- censorMat[1,j] bj <- censorMat[2:3,j] names(bj) <- paste('c-',names(bj),j,sep='') if(j > 1){ if(censorMat[2,j] < censorMat[3,j-1] ) stop('censor intervals must be unique') if(bj[1] == br[length(br)])bj <- bj[2] } br <- c(br,bj) nb <- length(br) zk[ y[,wm] > blast & y[,wm] < bj[1] ] <- nb - 2 zk[ y[,wm] == valuej ] <- nb - 1 blast <- br[length(br)] } if(nc == 1){ zk[zk == 0] <- 2 br <- c(br,Inf) } zk[zk == 0] <- 1 br <- matrix(br,nk,length(br),byrow=T) censk <- which(y[,wm] %in% censorMat[1,]) z[,wm] <- zk tmp <- .gjamGetCuts(z,wm) cutLo <- tmp$cutLo cutHi <- tmp$cutHi plo[,wm] <- br[cutLo] phi[,wm] <- br[cutHi] ww <- which(plo[,wm,drop=F] == -Inf,arr.ind=T) if(length(ww) > 0){ if(length(wm) == 1){ mm <- w[,wm] }else{ mm <- apply(w[,wm],2,max) } plo[,wm][ww] <- -10*mm[ww[,2]] } tmp <- .tnorm(nk*n,plo[,wm],phi[,wm],w[,wm],1) w[,wm][censk] <- tmp[censk] imat <- w*0 imat[,wm][censk] <- 1 censValue <- which(imat == 1) list(w = w, z = z, cutLo = cutLo, cutHi = cutHi, plo = plo, phi = phi, censValue = censValue, breakMat = br) } .gjamCuts2theta <- function(tg,ss){ if(length(ss) == 1)return(tg/sqrt(ss)) nc <- ncol(tg) sr <- nrow(ss) tg/matrix( sqrt(diag(ss)),sr,nc) } .gjamGetCuts <- function(zz,wk){ nk <- length(wk) n <- nrow(zz) cutLo <- cbind( rep(1:nk,each=n), as.vector(zz[,wk]) ) cutHi <- cbind( rep(1:nk,each=n), as.vector(zz[,wk]) + 1 ) list(cutLo = cutLo, cutHi = cutHi) } .gjamGetTypes <- function(typeNames=NULL){ TYPES <- c('CON','PA','CA','DA','CAT','FC','CC','OC') FULL <- c('continuous','presenceAbsence','contAbun','discAbun', 'categorical','fracComp','countComp','ordinal') LABS <- c('Continuous','Presence-absence','Continuous abundance', 'Discrete abundance', 'Categorical','Fractional composition', 'Count composition','Ordinal') if(is.null(typeNames)){ names(FULL) <- TYPES return( list(typeCols = NULL, TYPES = TYPES, typeFull = FULL, labels = LABS ) ) } S <- length(typeNames) typeCols <- match(typeNames,TYPES) ww <- which(is.na(typeCols)) if(length(ww) > 0)stop( paste('type code error',typeNames[ww],sep=' ') ) list(typeCols = typeCols, TYPES = TYPES, typeFull = FULL[typeCols], typeNames = typeNames, labels = LABS[typeCols]) } .gjamHoldoutSetup <- function(holdoutIndex,holdoutN,n){ if(length(holdoutIndex) > 0)holdoutN <- length(holdoutIndex) if(holdoutN > (n/5))stop('too many holdouts') inSamples <- c(1:n) if(holdoutN > 0){ if(length(holdoutIndex) == 0)holdoutIndex <- sort( sample(n,holdoutN) ) inSamples <- inSamples[-holdoutIndex] } nIn <- length(inSamples) list(holdoutIndex = holdoutIndex, holdoutN = holdoutN, inSamples = inSamples, nIn = nIn) } .gjamMissingValues <- function(x, y, factorList, typeNames, verbose = FALSE){ n <- nrow(x) xnames <- colnames(x) xmiss <- which(!is.finite(x),arr.ind=T) nmiss <- nrow(xmiss) missX <- missX2 <- xprior <- yprior <- numeric(0) xbound <- apply(x,2,range,na.rm=T) if(nmiss > 0){ xmean <- colMeans(x,na.rm=T) x[xmiss] <- xmean[xmiss[,2]] xprior <- x[xmiss] nmiss <- nrow(xmiss) fmiss <- signif(100*nmiss/length(x[,-1]),2) if(verbose) cat( paste('\n', nmiss,' values (',fmiss,'%) missing in X imputed\n'), sep='' ) missX <- missX2 <- rep(0,nmiss) } tmp <- gjamTrimY(y,minObs=0,OTHER=F) wzo <- which(tmp$nobs == 0) if(length(wzo) > 0){ stop( ' remove from ydata types never present:', paste0(names(wzo),collapse=', ')) } fobs <- tmp$nobs/n wlo <- which(fobs < .01) if(length(wlo) > 0){ flo <- paste0(names(fobs)[wlo],collapse=', ') if(verbose) cat(paste('\nPresent in < 1% of obs:',flo,'\n') ) } ymiss <- which(!is.finite(y),arr.ind=T) mmiss <- nrow(ymiss) missY <- missY2 <- numeric(0) if(mmiss > 0){ ymean <- colMeans(y,na.rm=T) y[ymiss] <- ymean[ymiss[,2]] yprior <- jitter(y[ymiss]) fmiss <- round(100*mmiss/length(y),1) mmiss <- nrow(ymiss) missY <- missY2 <- rep(0,mmiss) if(verbose) cat( paste('\n', mmiss,' values (',fmiss,'%) missing in Y imputed'), sep='' ) } disTypes <- c('DA','CC','OC') wdd <- which(disTypes %in% typeNames) if(length(wdd) > 0){ www <- which( typeNames[ymiss[,2]] %in% disTypes ) yprior[www] <- floor(yprior[www]) } if(nmiss > 0){ x[xmiss] <- xprior if(length(factorList) > 0){ for(k in 1:length(factorList)){ wm <- which(xnames[ xmiss[,2] ] == factorList[[k]][1]) if(length(wm) == 0)next wk <- sample(length(factorList[[k]]),length(wm),replace=T) xtmp <- x[xmiss[wm,1],factorList[[k]],drop=F]*0 xtmp[ cbind(1:nrow(xtmp),wk) ] <- 1 x[xmiss[wm,1],factorList[[k]]] <- xtmp } } } if(mmiss > 0)y[ymiss] <- yprior list(xmiss = xmiss, xbound = xbound, missX = missX, missX2 = missX2, ymiss = ymiss, missY = missY, xprior = xprior, yprior = yprior, x = x, y = y) } .gjamPlotPars <- function(type='CA',y1,yp,censm=NULL){ if(!is.matrix(y1))y1 <- matrix(y1) if(!is.matrix(yp))yp <- matrix(yp) n <- nrow(y1) nk <- ncol(y1) nbin <- NULL nPerBin <- max( c(10,n*nk/15) ) breaks <- NULL xlimit <- range(y1,na.rm=T) ylimit <- range(yp,na.rm=T) wide <- NULL MEDIAN <- T LOG <- F yss <- quantile(as.vector(y1),.5, na.rm=T)/mean(y1,na.rm=T) if(type == 'CA'){ wpos <- length( which(y1 > 0) ) nPerBin <- max( c(10,wpos/15) ) } if(type %in% c('PA', 'CAT')){ breaks <- c(-.05,.05,.95,1.05) wide <- rep(.08,4) nPerBin <- NULL ylimit <- c(0,1) xlimit <- c(-.1,1.1) } if(type == 'OC'){ breaks <- seq(min(y1,na.rm=T)-.5,max(y1,na.rm=T) + .5,by=1) wide <- 1/max(y1) nPerBin <- NULL ylimit <- range(yp,na.rm=T) xlimit <- c( min(floor(y1),na.rm=T), max(ceiling(y1),na.rm=T) ) } if(type == 'DA')MEDIAN <- F if(type %in% c('DA','CA')){ if(yss < .8){ xlimit <- range(y1,na.rm=T) xlimit[2] <- xlimit[2] + 1 LOG <- T } } if(type %in% c('FC','CC')){ MEDIAN <- F nPerBin <- round( n*nk/50,0 ) } if(type == 'CC'){ xlimit[2] <- xlimit[2] + 1 if(yss < 1){ LOG <- T xlimit[1] <- ylimit[1] <- 1 } } if( !is.null(censm) ){ cc <- censm$partition breaks <- NULL nPerBin <- n*nk/15 xlimit <- range(y1,na.rm=T) ylimit <- quantile(yp,c(.01,.99),na.rm=T) if(ncol(cc) > 1){ cm <- unique( as.vector(cc[-1,]) ) breaks <- cm[is.finite(cm)] nbin <- nPerBin <- NULL uncens <- cbind(cc[3,-ncol(cc)],cc[2,-1]) wu <- which( uncens[,1] != uncens[,2] ) for(m in wu){ sm <- seq(uncens[m,1],uncens[m,2],length=round(10/length(wu),0)) if(type == 'DA') sm <- c(uncens[m,1]:uncens[m,2]) breaks <- c(breaks,sm) } if(max(cc[1,]) < Inf){ breaks <- c(breaks, seq(max(breaks),(max(y1,na.rm=T)+1),length=12) ) } else { breaks <- c(breaks,max(y1,na.rm=T) + 1) } breaks <- sort( unique(breaks) ) } } if(LOG){ xlimit[1] <- ylimit[1] <- quantile(y1[y1 > 0],.001, na.rm=T) w0 <- which(y1 == 0) y1[w0] <- ylimit[1] w0 <- which(yp == 0) yp[w0] <- ylimit[1] ylimit[2] <- max(yp,na.rm=T) } list( y1 = y1, yp = yp, nbin=nbin, nPerBin=nPerBin, xlimit=xlimit,ylimit=ylimit,breaks=breaks,wide=wide,LOG=LOG, POINTS=F,MEDIAN=MEDIAN ) } .gjamPredictTraits <- function(w,specByTrait,traitTypes){ M <- nrow(specByTrait) tn <- rownames(specByTrait) ww <- w ww[ww < 0] <- 0 ww%*%t(specByTrait) } .initW <- function(tw, x, yy, minw = -ncol(yy), cat=F){ X <- x X[,-1] <- jitter(X[,-1],factor=1) XX <- crossprod(X) IXX <- solveRcpp(XX) for(j in 1:50){ bb <- IXX%*%crossprod(X,tw) muw <- X%*%bb tw[yy == 0] <- muw[yy == 0] tw[yy == 0 & tw > 0] <- 0 } tw[tw < minw] <- minw tw } .gjamSetup <- function(typeNames, x, y, breakList=NULL, holdoutN, holdoutIndex, censor=NULL, effort=NULL, maxBreaks=1000 ){ Q <- ncol(x) n <- nrow(y) S <- ncol(y) effMat <- effort$values tmp <- .gjamGetTypes(typeNames) typeFull <- tmp$typeFull typeCols <- tmp$typeCols allTypes <- unique(typeCols) cuts <- cutLo <- cutHi <- numeric(0) minOrd <- maxOrd <- breakMat <- numeric(0) ordShift <- NULL ordCols <- which(typeNames == 'OC') disCols <- which(typeNames == 'DA') compCols <- which(typeNames == 'CC') corCols <- which(typeNames %in% c('PA','OC','CAT')) catCols <- which(typeNames == c('CAT')) CCgroups <- attr(typeNames,'CCgroups') if(length(CCgroups) == 0)CCgroups <- rep(0,S) ngroup <- max(CCgroups) FCgroups <- attr(typeNames,'FCgroups') if(length(FCgroups) == 0)FCgroups <- rep(0,S) fgroup <- max(FCgroups) CATgroups <- attr(typeNames,'CATgroups') if(length(CATgroups) == 0)CATgroups <- rep(0,S) cgroup <- max(CATgroups) wo <- grep('others',colnames(y)) if(length(wo) > 0){ colnames(y)[wo] <- .replaceString(colnames(y)[wo],'others','other') } other <- grep('other',colnames(y)) colnames(y) <- .cleanNames(colnames(y)) w <- y if( !is.null(effort) )w <- w/effort$values maxy <- apply(w,2,max,na.rm=T) miny <- apply(w,2,min,na.rm=T) miny[miny > -maxy] <- -maxy[miny > -maxy] maxy[maxy < 0] <- -maxy[maxy < 0] maxy <- matrix(maxy, n, S, byrow=T) z <- w*0 z[y == 0] <- 1 z[y > 0] <- 2 plo <- phi <- y*0 plo[z == 1] <- -maxy[z == 1]/2 phi[z == 2] <- 2*maxy[z == 2] censorCON <- censorCA <- censorDA <- numeric(0) sampleW <- y*0 sampleW[is.na(sampleW)] <- 1 for(k in allTypes){ wk <- which(typeCols == k) nk <- length(wk) if( typeFull[wk[1]] == 'presenceAbsence' ){ sampleW[,wk] <- 1 plo[,wk][z[,wk] == 1] <- -3 phi[,wk][z[,wk] == 2] <- 3 w[,wk] <- .tnorm(nk*n,plo[,wk],phi[,wk],0,1) br <- c(-3,0,3) br <- matrix(br,nk,length(br),byrow=T) colnames(br) <- as.character(c(1:ncol(br))) rownames(br) <- paste('PA',wk,sep='-') rownames(br) <- paste(colnames(y)[wk],rownames(br),sep='_') breakMat <- .appendMatrix(breakMat,br,SORT=T,asNumbers=T) } if( typeFull[wk[1]] == 'continuous' ){ sampleW[,wk] <- 0 z[,wk] <- 1 plo[,wk] <- -2*maxy[,wk] phi[,wk] <- 2*maxy[,wk] if( !is.null(censor) & 'CON' %in% names(censor) ){ wc <- which(names(censor) == 'CON') bc <- censorCON <- numeric(0) for(m in wc){ wm <- censor[[m]]$columns cp <- censor[[m]]$partition for(ii in 1:ncol(cp)){ wmm <- which( y[,wm] == cp[1,ii] | (y[,wm] > cp[2,ii] & y[,wm] < cp[3,ii]) ) mmm <- cp[2,ii] if(mmm == -Inf)mmm <- cp[3,ii] - 10 censor[[m]]$partition[2,ii] <- mmm plo[,wm][wmm] <- mmm phi[,wm][wmm] <- cp[3,ii] } tmp <- .gjamCensorSetup(y,w,z,plo,phi,wm,censorMat= censor[[m]]$partition) z[,wm] <- tmp$z[,wm] censorCON <- c(censorCON,tmp$censValue) bt <- tmp$breakMat colnames(bt) <- as.character(c(1:ncol(bt))) rownames(bt) <- paste('CA',wm,sep='-') bc <- .appendMatrix(bc,bt,SORT=T,asNumbers=T) } } br <- c(-Inf,-Inf,Inf) br <- matrix(br,nk,length(br),byrow=T) colnames(br) <- as.character(c(1:ncol(br))) rownames(br) <- paste('CON',wk,sep='-') rownames(br) <- paste(colnames(y)[wk],rownames(br),sep='_') breakMat <- .appendMatrix(breakMat,br,SORT=T,asNumbers=T) } if( typeFull[wk[1]] == 'contAbun' ){ phi[,wk] <- 2*maxy[,wk] plo[,wk] <- -phi[,wk]/4 wy1 <- which(y[,wk] > 0) w[,wk][wy1] <- y[,wk][wy1] wy0 <- which(y[,wk] == 0) phi[,wk][wy0] <- 0 w[,wk] <- .initW(w[,wk], x, y[,wk], minw = -max(y[,wk],na.rm=T)*5) w[,wk][wy1] <- y[,wk][wy1] br <- c(-Inf,0,Inf) br <- matrix(br,nk,length(br),byrow=T) colnames(br) <- as.character(c(1:ncol(br))) rownames(br) <- paste('CA',wk,sep='-') sampleW[,wk][y[,wk] == 0] <- 1 if( !is.null(censor) & 'CA' %in% names(censor) ){ wc <- which(names(censor) == 'CA') bc <- censorCA <- numeric(0) for(m in wc){ wm <- censor[[m]]$columns cp <- censor[[m]]$partition for(ii in 1:ncol(cp)){ wmm <- which(y[,wm] == cp[1,ii] | (y[,wm] > cp[2,ii] & y[,wm] < cp[3,ii]) ) plo[,wm][wmm] <- cp[2,ii] phi[,wm][wmm] <- cp[3,ii] } tmp <- .gjamCensorSetup(y,w,z,plo,phi,wm,censorMat= censor[[m]]$partition) z[,wm] <- tmp$z[,wm] censorCA <- c(censorCA,tmp$censValue) bt <- tmp$breakMat colnames(bt) <- as.character(c(1:ncol(bt))) rownames(bt) <- paste('CA',wm,sep='-') bc <- .appendMatrix(bc,bt,SORT=T,asNumbers=T) } mm <- match(rownames(bc),rownames(br)) if(is.na(min(mm)))stop('error in censor list, check for conflicts') bb <- br[-mm,] tmp <- .appendMatrix(bc,bb,SORT=T,asNumbers=T) o <- as.numeric( matrix( unlist(strsplit(rownames(tmp),'-')), ncol=2,byrow=T)[,2] ) br <- tmp[drop=F,order(o),] } rownames(br) <- paste(colnames(y)[wk],rownames(br),sep='_') breakMat <- .appendMatrix(breakMat,br,SORT=T,asNumbers=T) } if( typeFull[wk[1]] == 'discAbun' ){ plo[,wk] <- (y[,wk] - .5)/effMat[,wk] plo[,wk][y[,wk] == 0] <- -.5*maxy[,wk][y[,wk] == 0] phi[,wk] <- (y[,wk] + .5)/effMat[,wk] sampleW[,wk] <- 1 disCols <- wk z[,wk] <- y[,wk] + 1 w[,wk] <- .tnorm(nk*n,plo[,wk],phi[,wk],w[,wk],1) n <- nrow(y) S <- ncol(y) mx <- max(y[,wk]) - 1 if(mx > maxBreaks){ mx <- maxBreaks cat( paste('\nNote: large values of y/effort, max set to', mx ) ) } br <- c( -Inf, seq(0, mx), Inf) br <- matrix(br,nk,length(br),byrow=T) colnames(br) <- as.character(c(1:ncol(br))) rownames(br) <- paste('DA',wk,sep='-') if( !is.null(censor) & 'DA' %in% names(censor) ){ wc <- which(names(censor) == 'DA') bc <- censorDA <- numeric(0) for(m in wc){ wm <- censor[[m]]$columns tmp <- .gjamCensorSetup(y,w,z,plo,phi,wm, censorMat=censor[[m]]$partition) w[,wm] <- tmp$w[,wm] z[,wm] <- tmp$z[,wm] plo[,wm] <- tmp$plo[,wm] phi[,wm] <- tmp$phi[,wm] censorDA <- c(censorDA,tmp$censValue) bt <- tmp$breakMat colnames(bt) <- as.character(c(1:ncol(bt))) rownames(bt) <- paste('DA',wm,sep='-') bc <- .appendMatrix(bc,bt,SORT=T,asNumbers=T) } mm <- match(rownames(bc),rownames(br)) bb <- br[-mm,] tmp <- .appendMatrix(bc,bb,SORT=T,asNumbers=T) o <- as.numeric( matrix( unlist(strsplit(rownames(tmp),'-')), ncol=2,byrow=T)[,2] ) br <- tmp[order(o),] } rownames(br) <- paste(colnames(y)[wk],rownames(br),sep='_') breakMat <- .appendMatrix(breakMat,br,SORT=T,asNumbers=T) } if( typeFull[wk[1]] == 'fracComp' ){ wss <- which(y[,wk] == 0 | y[,wk] == 1) sampleW[,wk][wss] <- 1 for(i in 1:fgroup){ if(fgroup == 1){ wki <- wk } else { wki <- which(typeCols == k & FCgroups == i) } nki <- length(wki) yki <- y[,wki] lo <- plo[,wki] hi <- phi[,wki] lo[lo < -200/S] <- -200/S hi[hi > 3] <- 3 plo[,wki] <- lo phi[,wki] <- hi w[,wki] <- .initW(w[,wki], x, yki, minw = -200/S) } br <- c(-1,0,1) br <- matrix(br,nk,length(br),byrow=T) colnames(br) <- as.character(c(1:ncol(br))) rownames(br) <- paste('FC',wk,sep='-') rownames(br) <- paste(colnames(y)[wk],rownames(br),sep='_') breakMat <- .appendMatrix(breakMat,br,SORT=T,asNumbers=T) } if( typeFull[wk[1]] %in% c('countComp','categorical')){ sampleW[,wk] <- 1 ntt <- ngroup if(typeFull[wk[1]] == 'categorical')ntt <- cgroup for(i in 1:ntt){ if(ntt == 1){ wki <- wk } else { wki <- which( typeCols == k ) wki <- wki[ CCgroups[wki] == i | CATgroups[wki] == i ] } nki <- length(wki) yki <- y[,wki] if( wki[1] %in% catCols ){ lo <- hi <- yki*0 lo[yki == 0] <- -100 hi[yki == 0] <- 0 hi[yki == 1] <- 100 mu <- yki*0 mu[lo == 0] <- 20 mu[hi == 0] <- -20 } else { ee <- rowSums(yki) + 1 lo <- (yki - .5)/ee hi <- (yki + .5)/ee lo[lo < 0] <- -20/S mu <- yki/ee } z[,wki] <- yki + 1 plo[,wki] <- lo phi[,wki] <- hi tmp <- matrix( .tnorm(nki*n,as.vector(lo),as.vector(hi), as.vector(mu), sig=5),n,nki ) tt <- tmp if( !wki[1] %in% catCols ){ tt[tt < 0] <- 0 tsum <- rowSums(tt) tt <- sweep(tt,1,tsum,'/') tt[tmp < 0] <- tmp[tmp < 0] } w[,wki] <- tt } br <- c(-1,0,1) br <- matrix(br,nk,length(br),byrow=T) colnames(br) <- as.character(c(1:ncol(br))) rownames(br) <- paste('CC',wk,sep='-') rownames(br) <- paste(colnames(y)[wk],rownames(br),sep='_') breakMat <- .appendMatrix(breakMat,br,SORT=T,asNumbers=T) } if( typeFull[wk[1]] == 'ordinal' ){ miny <- ordShift <- apply(y[,wk,drop=F],2,min) y[,wk] <- y[,wk] - matrix(miny,n,nk,byrow=T) nc <- apply(y[,wk,drop=F],2,max) sampleW[,wk] <- 1 ii <- list(spec = as.vector(matrix(c(1:nk),n,nk,byrow=T)), ss = as.vector(y[,wk,drop=F])) ctmp <- tapply(as.vector(y[,wk,drop=F])*0+1,ii,sum) ccol <- range( as.numeric(colnames(ctmp)) ) ccol <- ccol[1]:ccol[2] ct <- matrix(0, nrow(ctmp), length(ccol), dimnames = list(rownames(ctmp), ccol) ) ct[rownames(ctmp),colnames(ctmp)] <- ctmp ct[ is.na(ct) ] <- 0 ctmp <- ct ncc <- nc + 1 if(max(ncc) > ncol(ctmp))ncc <- nc maxOne <- which(ctmp[ cbind(1:nk,ncc) ] == 1) if(length(maxOne) > 0){ for(m in 1:length(maxOne)){ mc <- wk[maxOne[m]] y[y[,mc] == nc[maxOne[m]],mc] <- nc[maxOne[m]] - 1 } nc <- apply(y[,wk,drop=F],2,max) } ncut <- max(y[,wk,drop=F]) crow <- c(0:ncut) cuts <- t( matrix(crow,(ncut+1),nk) ) cuts[ cbind((1:nk),nc+1) ] <- Inf call <- t( apply(cuts,1,cumsum) ) cuts[call == Inf] <- Inf cuts <- cbind(-Inf,cuts) if(!is.matrix(cuts))cuts <- matrix(cuts,1) tmp <- .gjamGetCuts(y + 1,wk) cutLo <- tmp$cutLo cutHi <- tmp$cutHi ss <- seq(0,(nk-1)*n,by=n) wh <- as.vector( outer(holdoutIndex,ss,'+') ) c1 <- cutLo if(length(wh) > 0)c1 <- cutLo[-wh,] otab <- .byIndex(c1[,1]*0 + 1,INDICES=list('i'=c1[,1], 'j'=c1[,2]),sum,coerce=T) oo <- cbind(0,t( apply(otab,1,cumsum) )) wo <- which(oo == 0,arr.ind=T) wo[,2] <- as.numeric(colnames(otab))[wo[,2]] minOrd <- .byIndex(wo[,2],wo[,1],max) oo <- cbind(0,t( apply( t(apply(otab,1,rev)),1,cumsum) )) wo <- which(oo == 0,arr.ind=T) maxOrd <- ncut - .byIndex(wo[,2],wo[,1],max) + 2 plo[,wk] <- cuts[cutLo] phi[,wk] <- cuts[cutHi] z[,wk] <- y[,wk] + 1 w[,wk] <- matrix( .tnorm(nk*n,plo[,wk],phi[,wk],y[,wk],1),n,nk ) colnames(cuts) <- c(1:ncol(cuts)) rownames(cuts) <- paste('OC',wk,sep='-') rownames(cuts) <- paste(colnames(y)[wk],rownames(cuts),sep='_') breakMat <- .appendMatrix(breakMat,cuts,SORT=T,asNumbers=T) } } sord <- .splitNames(rownames(breakMat))$vnam[,1] yord <- match(colnames(y),sord) breakMat <- breakMat[yord,] sampleW[censorCON] <- 1 sampleW[censorCA] <- 1 sampleW[censorDA] <- 1 wCols <- which(colSums(sampleW) > 0) wRows <- which(rowSums(sampleW) > 0) attr(sampleW,'type') <- 'cols' attr(sampleW,'index') <- wCols if( sum(sampleW) == 0)attr(sampleW,'type') <- 'none' if( sum(sampleW) > 0 & (length(wRows) < length(wCols)) ){ attr(sampleW,'type') <- 'rows' attr(sampleW,'index') <- wRows } ii <- list(spec = as.vector(matrix(c(1:S),n,S,byrow=T)), discrete_class = as.vector(z)) classBySpec <- .byIndex(as.vector(z)*0+1,ii,sum) rownames(classBySpec) <- colnames(y) ncc <- min(20,ncol(classBySpec)) nrr <- min(20,nrow(classBySpec)) list(w = w, z = z, y = y, other = other, cuts = cuts, cutLo = cutLo, cutHi = cutHi, ordShift = ordShift, plo = plo, phi = phi, ordCols=ordCols, disCols = disCols, compCols = compCols, corCols = corCols, classBySpec = classBySpec, breakMat = breakMat, minOrd = minOrd, maxOrd = maxOrd, sampleW = sampleW, censorCA = censorCA, censorDA = censorDA, censorCON = censorCON ) } .gjamTrueVest <- function( pchains, true, typeCode, allTypes, xlim=NULL, ylim=NULL, label=NULL, colors=NULL, add=F, legend=T){ ntypes <- length(allTypes) if(is.null(ylim))ylim <- quantile(pchains, c(.025, .975), na.rm=T) if(is.null(xlim))xlim <- range(true,na.rm=T) if( !is.matrix(pchains) ){ pchains <- matrix(pchains,ncol=1) bCoeffTable <- c(mean(pchains),sd(pchains),quantile(pchains,c(.025,.975)),true) bCoeffTable <- matrix(bCoeffTable,1) } else { bCoeffTable <- .chain2tab( pchains, colnames(true), rownames(true) ) } if(is.null(colors)){ colors <- 1 if(ntypes > 1)colors <- typeCode } if(length(colors) == 1) colors <- rep(colors,ntypes) if(is.matrix(true)){ tlabs <- outer(rownames(true), colnames(true), paste, sep='_') mm <- match(tlabs, colnames(pchains)) wn <- which( !is.finite(mm) ) if(length(wn) > 0){ tlabs <- t( outer(colnames(true), rownames(true), paste, sep='_') ) mm <- match(tlabs, colnames(pchains)) wn <- which( !is.finite(mm) ) } tvec <- as.vector(true) names(tvec) <- as.vector(tlabs) tvec <- tvec[ match( colnames(pchains), names(tvec) ) ] }else{ tvec <- true } .predVsObs(tvec, p=pchains, xlab='true', xlim=xlim, ylim=ylim, ylab='estimated', colors=colors,add=add) if(ntypes > 1 & legend)legend('topleft',allTypes,text.col=colors,bty='n') if(!is.null(label)).plotLabel(label,above=T) invisible( bCoeffTable ) } .conditionalMVN <- function( xx, mu, sigma, cdex, p=ncol(mu) ){ if(ncol(xx) != ncol(sigma))stop('ncol(xx) != ncol(sigma)') if(ncol(mu) != ncol(sigma))stop('ncol(mu) != ncol(sigma)') if(max(cdex) > ncol(mu))stop('max(cdex) > ncol(mu)') ci <- (1:p)[-cdex] new <- c(ci, cdex) cnew <- match(cdex, new) pnew <- 1:(p - length(cnew)) condMVNRcpp(cnew-1, pnew-1, xx[,new, drop=F], mu[,new, drop=F], sigma[new,new]) } .byGJAM <- function(x, i, j, summat=matrix(0,max(i),max(j)), totmat=summat, fun='mean'){ nn <- length(x) if( nn != length(i) | nn != length(j) ) stop('vectors unequal in byFunctionRcpp') if( nrow(summat) < max(i) | ncol(summat) < max(j) ) stop('matrix too small') ww <- which(is.na(x)) if(length(ww) > 0){ x <- x[-ww] i <- i[-ww] j <- j[-ww] } frommat <- cbind(i,j,x) nr <- nrow(frommat) maxmat <- summat*0 - Inf minmat <- summat*0 + Inf tmp <- byRcpp(nr, frommat, totmat, summat, minmat, maxmat) if(fun == 'sum')return(tmp$sum) if(fun == 'mean'){ mu <- tmp$sum/tmp$total mu[is.na(mu)] <- 0 return(mu) } if(fun == 'min'){ return( tmp$min ) } tmp$max } .tnormMVNmatrix <- function(avec, muvec, smat, lo=matrix(-1000,nrow(muvec),ncol(muvec)), hi=matrix(1000,nrow(muvec),ncol(muvec)), whichSample = c(1:nrow(smat)) ){ lo[lo < -1000] <- -1000 hi[hi > 1000] <- 1000 if(max(whichSample) > length(muvec)) stop('whichSample outside length(muvec)') r <- avec a <- trMVNmatrixRcpp(avec, muvec, smat, lo, hi, whichSample, idxALL = c(0:(nrow(smat)-1)) ) r[,whichSample] <- a[,whichSample] r } .whichFactor <- function(dframe){ if(!is.data.frame(dframe))return(character(0)) tmp <- model.frame(data = dframe) ym <- attr( attributes(tmp)$terms, 'dataClasses' ) which(ym == 'factor') } .xpredSetup <- function(Y, xx, bgg, isNonLinX, factorObject, intMat, standMatSd, standMatMu, notOther, notStandard ){ isFactor <- factorObject$isFactor factorList <- factorObject$factorList linFactor <- numeric(0) Q <- ncol(xx) if(Q == 1){ return( list(linFactor = linFactor, xpred = xx, px = 1, lox = 1, hix = 1) ) } xpred <- xx n <- nrow(xx) xpnames <- colnames(xx) SO <- length(notOther) px <- 1:Q if(length(isNonLinX) > 0)px <- px[-isNonLinX] px <- px[!xpnames[px] %in% isFactor] px <- px[px != 1] ii <- grep(':',xpnames,fixed=T) i2 <- grep('^2',xpnames,fixed=T) qx <- c( 1, ii, i2) qx <- c(1:Q)[-qx] bx <- solveRcpp( crossprod(xx[,qx,drop=F]) )%*%crossprod(xx[,qx,drop=F], Y[,notOther]) cx <- crossprod(t(bx)) if(length(cx) == 1){ cx <- 1/(cx*1.01) } else { diag(cx) <- .0000001 + diag(cx) cx <- solve(cx) } xk <- (Y[,notOther] - matrix(bgg[1,notOther],n,SO,byrow=T))%*%t(bx)%*%cx colnames(xk) <- xpnames[qx] scol <- colnames(xk)[!colnames(xk) %in% notStandard] xk[,scol] <- sweep(xk[,scol,drop=F],2,colMeans(xk[,scol,drop=F]),'-') xk[,scol] <- sweep(xk[,scol,drop=F],2,apply(xk[,scol,drop=F],2,sd),'/') xpred[,qx] <- xk xmu <- apply(xx, 2, sd) xse <- apply(xx, 2, sd) propx <- xse/10 lo <- xmu - 3*xse hi <- xmu + 3*xse xl <- matrix( lo, nrow(xpred), ncol(xpred), byrow=T) xh <- matrix( hi, nrow(xpred), ncol(xpred), byrow=T) xpred[xpred < xl] <- xl[xpred < xl] xpred[xpred > xh] <- xh[xpred > xh] xpred[!is.finite(xpred)] <- 0 rm(xl, xh) if(length(intMat) > 0){ for(k in 1:nrow(intMat)){ xpred[,intMat[k,1]] <- xpred[,intMat[k,2]]*xpred[,intMat[k,3]] } } if(length(isFactor) > 0){ xpred[,isFactor] <- 0 for(k in 1:length(factorList)){ kf <- lf <- factorList[[k]] if( !is.null(isNonLinX) ){ xin <- xpnames[isNonLinX] lf <- kf[!kf %in% xin] } if(length(lf) == 0)next lf <- match(lf,xpnames) ww <- which(is.finite(lf)) wt <- colSums(xx[,c(1,lf)]) wt <- wt/sum(wt) sk <- sample(c(1,lf),n, replace=T, prob=wt) xpred[ cbind(c(1:n),sk) ] <- 1 if(length(ww) == 0)next lf <- c(1,lf) linFactor <- append(linFactor, list(lf)) names(linFactor)[length(linFactor)] <- names(factorList)[k] } } lox <- apply(xx,2 ,min) hix <- apply(xx,2, max) lox[isFactor] <- -3 hix[isFactor] <- 3 if(length(intMat) > 0){ lox[intMat[,1]] <- -3 hix[intMat[,1]] <- 3 } if( length(notStandard) > 0 ){ ws <- which(notStandard %in% xpnames) if(length(ws) == 0){ notStandard <- NULL } else { notStandard <- notStandard[ws] lox[notStandard] <- standMatMu[notStandard,1] - 3*standMatSd[notStandard,1] hix[notStandard] <- standMatMu[notStandard,1] + 3*standMatSd[notStandard,1] } } list(linFactor = linFactor, xpred = xpred, px = px, propx = propx, lox = lox, hix = hix) } .blockDiag <- function(mat1,mat2){ if(length(mat1) == 0)return(mat2) namesc <- c(colnames(mat1),colnames(mat2)) namesr <- c(rownames(mat1),rownames(mat2)) nr1 <- nrow(mat1) nr2 <- nrow(mat2) nc1 <- ncol(mat1) nc2 <- ncol(mat2) nr <- nr1 + nr2 nc <- nc1 + nc2 new <- matrix(0,nr,nc) new[ 1:nr1, 1:nc1 ] <- mat1 new[ (nr1+1):nr, (nc1+1):nc ] <- mat2 colnames(new) <- namesc rownames(new) <- namesr new } .getContrasts <- function(facK, fnames){ ff <- paste(facK,fnames,sep='') Q <- length(fnames) cc <- diag(Q) cc[1,] <- -1 dd <- cc dd[1] <- 1 cc[,1] <- 1 colnames(cc) <- colnames(dd) <- c('intercept',ff[-1]) rownames(cc) <- rownames(dd) <- fnames L <- t( solve(cc) ) rownames(cc) <- rownames(L) <- rownames(dd) <- ff list(C = cc, D = dd, L = L) } .getUnstandX <- function(formula, x, standRows, xmu, xsd, factorColumns = NULL ){ if(length(standRows) == 0)return( list( xu = x, S2U = diag( ncol(x)) ) ) xu <- x xu[,standRows] <- t( xmu[standRows] + t(x[,standRows,drop=F])*xsd[standRows] ) if( !is.null(factorColumns) ){ xu <- data.frame( xu, factorColumns ) } xu <- model.matrix(formula, data.frame(xu), drop.unused.levels = FALSE ) colnames(xu)[1] <- 'intercept' s2u <- solve( crossprod(xu) )%*%crossprod(xu, x) s2u[ abs(s2u) < 1e-14 ] <- 0 list(xu = xu, S2U = s2u) } .getStandX <- function(formula, xu, standRows, xmu=NULL, xsd=NULL){ if( length(standRows) == 0 )return( list(xstand = xu, xmu = xmu, xsd = xsd, U2S = diag(ncol(xu)) ) ) xu <- as.data.frame( xu ) inCols <- colnames(xu) ifact <- which( sapply(data.frame(xu), is.factor) ) if( length(ifact) > 0 ){ xtmp <- xu[, -ifact, drop = F] } if( is.null(xmu) )xmu <- colMeans(xu[,standRows, drop=F], na.rm=T) if( is.null(xsd) )xsd <- apply(xu[,standRows, drop=F], 2, sd, na.rm=T) xs <- xu wna <- which( sapply(xu, is.na), arr.ind=T ) wni <- which(wna[,2] %in% ifact) if( length(wni) > 0 ){ stop('cannot have NA in factor levels') } if( nrow(wna) > 0 ){ wmu <- sapply( xu, mean, na.rm=T ) wnaCol <- colnames(xu)[wna[,2]] xs[ wna ] <- wmu[ wna[,2] ] xu[ wna ] <- wmu[ wna[,2] ] } sc <- standRows if( !is.character(sc) )sc <- names( standRows ) xs[, sc] <- t( ( t( xs[, sc, drop = F] ) - xmu[sc] )/xsd[sc] ) xs <- model.matrix(formula, data.frame(xs) ) colnames(xs)[1] <- 'intercept' xd <- model.matrix(formula, data.frame(xu) ) colnames(xd)[1] <- 'intercept' bigSD <- apply(xs, 2, range) wk <- which( abs(bigSD) > 20, arr.ind=T ) if( length(wk) > 0){ b <- paste0( colnames(bigSD)[wk[,2]], collapse=', ' ) cat( paste('\nNote: Values in x more than 20 SDs from the mean of fitted data: ',b, sep='' ) ) FLAG <- T } if( nrow(wna) > 0 ){ wna[,2] <- match( wnaCol, colnames(xs) ) xs[ wna ] <- NA } if( length(ifact) > 0 ){ xtmp[,standRows] <- xs[,standRows] xs <- xu xs[,standRows] <- xtmp[,standRows] } if( identical(colnames(xd), colnames(xs) ) & length(ifact) == 0 ){ ssx <- try( solve( crossprod( xs ) ), T ) if( inherits( ssx,'try-error') ){ u2s <- diag( ncol(xs) ) }else{ u2s <- ssx%*%crossprod(xs,xd) u2s[ abs(u2s) < 1e-12 ] <- 0 } }else{ u2s <- diag( ncol(xs) ) } list(xstand = xs, xmu = xmu, xsd = xsd, U2S = u2s) } .getHoldLoHi <- function(yh, wh, pl, ph, eff, ymax, typeNames, cutg, ordCols){ allTypes <- unique(typeNames) for(k in 1:length(allTypes)){ tk <- allTypes[k] wk <- which(typeNames == tk) if(tk == 'CON')next if(tk == 'PA'){ pl[,wk][yh[,wk] == 0] <- -10 pl[,wk][yh[,wk] == 1] <- 0 ph[,wk][yh[,wk] == 0] <- 0 ph[,wk][yh[,wk] == 1] <- 10 } if(tk == 'CA'){ ym <- max(ymax[wk]) pl[,wk][yh[,wk] == 0] <- -5*ym pl[,wk][yh[,wk] > 0] <- 0 ph[,wk][yh[,wk] == 0] <- 0 ph[,wk][yh[,wk] > 0] <- 5*ym } if(tk == 'DA'){ ym <- max(ymax[wk]) ee <- 1 if(!is.null(eff))ee <- eff[,wk] pl[,wk] <- (yh[,wk] - .5)/ee ph[,wk] <- (yh[,wk] + .5)/ee pl[,wk][yh[,wk] == 0] <- -5*ym pl[,wk][yh[,wk] == ym] <- 5*ym } if(tk == 'FC'){ pl[,wk][yh[,wk] == 0] <- -5 pl[,wk][yh[,wk] > 0] <- 0 pl[,wk][yh[,wk] > 1] <- 1 ph[,wk][yh[,wk] == 0] <- 0 ph[,wk][yh[,wk] > 0] <- 1 ph[,wk][yh[,wk] == 1] <- 5 } if(tk == 'CC'){ ym <- rowSums(yh[,wk,drop=F]) ee <- matrix(ym,nrow(yh),length(wk)) pl[,wk] <- (yh[,wk] - .5)/ee ph[,wk] <- (yh[,wk] + .5)/ee pl[,wk][yh[,wk] == 0] <- -5 pl[,wk][yh[,wk] == ee] <- 5 } } list(pl = pl, ph = ph) } .setupReduct <- function(modelList, S, Q, n){ REDUCT <- F N <- r <- rl <- NULL reductList <- modelList$reductList if( !is.null(reductList) ){ N <- floor( min( c(reductList$N, S/2) ) ) r <- min( c(reductList$r, .7*N) ) rl <- list(N = N, r = ceiling(r) ) return( rl ) } if(n < 2*S | S > 200){ N <- round( S/3 ) if(N > 25)N <- 25 if(N < 4)N <- 4 r <- ceiling( N/2 ) rl <- list(r = r, N = N, alpha.DP = S) warning( 'dimension reduction' ) } rl } .getTimeIndex <- function(timeList, other, notOther, xdata, x, xl, y, w, termB, termR, termA ){ Q <- ncol(x) n <- nrow(x) xnames <- colnames(x) snames <- colnames(y) loBeta <- hiBeta <- alphaPrior <- Rmat <- Rpattern <- wL <- gindex <- Vmat <- Rrows <- loRmat <- hiRmat <- Arows <- Amat <- Apattern <- wA <- Umat <- uindex <- loAmat <- hiAmat <- aindex <- Brows <- bg <- Bpattern <- wB <- loB <- hiB <- zB <- zA <- zR <- NULL timeZero <- timeList$timeZero timeLast <- timeList$timeLast if(length(timeZero) != length(timeLast)) stop('timeZero and timeLast different lengths') times <- timeList$times if(is.null(times)) stop(' column name "times" needed for time-series model' ) timeZero <- which(xdata[,'times'] == 0) if(length(timeZero) == 0)stop(' must have time zero in xdata[,time] ') timeLast <- timeZero - 1 timeLast <- timeLast[-1] timeLast <- c(timeLast,nrow(xdata)) w2 <- which(timeLast - timeZero < 2) if(length(w2) > 0) stop('some sequences have only 2 time intervals, need at least 3') ix <- 1:n t1 <- ix[-timeZero] t0 <- t1 - 1 t2 <- t1 + 1 tindex <- cbind(t0,t1,t2) S <- ncol(y) ns <- length(timeZero) nt <- nrow(tindex) i1 <- i2 <- numeric(0) for(k in 1:ns){ tl <- timeLast[k] sk <- timeZero[k] wk <- which(tindex[,1] >= sk & tindex[,2] <= tl) k1 <- wk[ seq(1, length(wk), by = 2) ] k2 <- k1 + 1 k2 <- k2[ k2 <= nt ] k2 <- k2[ tindex[k2,2] <= tl ] i1 <- c(i1, k1) i2 <- c(i2, k2) } maxTime <- max(xdata$times) inSamples <- tindex[,2] if(termB){ if('betaPrior' %in% names(timeList)){ loBeta <- timeList$betaPrior$lo hiBeta <- timeList$betaPrior$hi beta <- (loBeta + hiBeta)/2 beta[ is.nan(beta) | beta == -Inf | beta == Inf ] <- 0 loBeta[is.na(beta)] <- hiBeta[is.na(beta)] <- 0 beta[is.na(beta)] <- 0 } else{ beta <- matrix(0,Q,S) rownames(beta) <- colnames(x) BPRIOR <- F } tmp <- .betaPrior(beta, notOther, loBeta, hiBeta) bg <- tmp$beta; loB <- tmp$loB; hiB <- tmp$hiB wB <- tmp$wB; zB <- tmp$zB; BPRIOR <- tmp$BPRIOR bg[is.nan(bg) | bg == -Inf | bg == Inf] <- 0 tmp <- .getPattern(bg[,notOther], wB) Brows <- tmp$rows Bpattern <- tmp$pattern bg[!is.finite(bg)] <- 0 } if(termA){ if( 'alphaPrior' %in% names(timeList) ){ loAlpha <- timeList$alphaPrior$lo hiAlpha <- timeList$alphaPrior$hi loAlpha[is.na(loAlpha) | is.na(hiAlpha)] <- hiAlpha[is.na(loAlpha) | is.na(hiAlpha)] <- 0 } else{ alpha <- diag(NA,S) diag(alpha) <- -1 } tmp <- .alphaPrior(w, tindex, ap = timeList$alphaPrior, notOther) Amat <- tmp$Amat; loAmat <- tmp$loAmat; hiAmat <- tmp$hiAmat wA <- tmp$wA; uindex <- tmp$uindex; aindex <- tmp$aindex U <- nrow(Amat) Umat <- matrix(0,n,U) wz <- w wz[wz < 0] <- 0 Umat <- wz[,uindex[,1]]*wz[,uindex[,2]] tmp <- .getPattern(loAmat, wA) Arows <- tmp$rows Apattern <- uindex Apattern[ Apattern[,2] == Apattern[,1], 2] <- NA Amat[!is.finite(Amat)] <- 0 zA <- which(Amat == 0) wrow <- max(wA[,1]) wcol <- max(wA[,2]) Apattern <- Apattern[ Apattern[,1] %in% c(1:wrow),] Apattern <- Apattern[ !Apattern[,1] > wcol,] Apattern[Apattern %in% other] <- NA Apattern <- Apattern[1:wrow,] } if(termR){ if('rhoPrior' %in% names(timeList)){ lprior <- timeList$rhoPrior lprior$lo[ is.na(lprior$lo) | is.na(lprior$hi) ] <- 0 lprior$hi[ is.na(lprior$lo) | is.na(lprior$hi) ] <- 0 } else{ lprior <- timeList$betaPrior } xlnames <- colnames(xl) tmp <- .rhoPrior(lprior, w, xl, tindex, xlnames, snames, other, notOther, timeZero) Rmat <- tmp$Rmat; loRmat <- tmp$loRmat; hiRmat <- tmp$hiRmat wL <- tmp$wL; gindex <- tmp$gindex; Vmat <- tmp$Vmat zR <- which( is.na(Rmat) ) ltmp <- matrix(NA,nrow(Rmat),length(notOther)) ltmp[wL] <- 1 tmp <- .getPattern(ltmp, wL) Rrows <- tmp$rows Rpattern <- tmp$pattern Rmat[!is.finite(Rmat)] <- 0 } list(Rmat = Rmat, Rpattern = Rpattern, wL = wL, gindex = gindex, Vmat = Vmat, Rrows = Rrows, loRmat = loRmat, hiRmat = hiRmat, Arows = Arows, Amat = Amat, Apattern = Apattern, wA = wA, Umat = Umat, uindex = uindex,loAmat = loAmat, hiAmat = hiAmat, aindex = aindex, Brows = Brows, bg = bg, Bpattern = Bpattern, wB = wB, loB = loB, hiB = hiB, zB = zB, zA = zA, zR = zR, timeZero = timeZero, timeLast = timeLast, maxTime = maxTime, inSamples = inSamples, tindex = tindex, i1 = i1, i2 = i2) } .checkYfactor <- function(ydata, typeNames){ yordNames <- NULL wf <- which( sapply(ydata,is.factor) ) if( length(wf) > 0 ){ if(!all(typeNames[wf] == 'CAT')) stop('factors in ydata must be CAT data') } wc <- which( typeNames == 'CAT' ) wc <- which( !wc %in% wf ) if(length(wc) > 0){ ydata <- data.frame(ydata) for(k in wc){ ydata[,k] <- as.factor(ydata[,k]) } } list(ydata = ydata, yordNames = yordNames) } .buildEffort <- function(y, effort, typeNames, verbose){ S <- length(typeNames) effMat <- y*0 + 1 effMat[is.na(effMat)] <- 1 if( is.null(effort) ){ effort <- list(columns = 1:S, values = effMat) } else { if( is.list(effort$values) ){ effort$values <- as.matrix(effort$values) } if( !is.matrix(effort$values) ){ if(length(effort$values) == ncol(y)){ byrow <- T warning('effort$values applied to columns') }else{ byrow <- F if(verbose)cat('\neffort$values applied to rows\n') } effMat <- matrix( effort$values, nrow(y), ncol(y), byrow = byrow) rownames(effMat) <- rownames(y) colnames(effMat) <- colnames(y) } effMat[,effort$columns] <- effort$values effort$values <- as.matrix( effMat ) if(!is.null(colnames(effort$values)))colnames(effMat) <- .cleanNames(colnames(effMat)) } effort$columns <- 1:S effMat <- as.matrix(effMat) we <- which(effort$values == 0 | is.na(effort$values)) if(length(we) > 0){ effort$values[we] <- 1 if( any(c('DA','CC') %in% typeNames) ) warning('missing or zero values in effort') } effMat[,!typeNames == 'DA'] <- 1 effMat[effMat == 0] <- 1 effort <- list(columns = effort$columns, values = effMat) effort } .setupFactors <- function(xdata, xnames, factorObject){ factorList <- factorObject$factorList contrast <- factorObject$contrast Q <- length(xnames) if(Q == 1){ return( list(dCont = matrix(1)) ) } q1 <- Q - 1 fnames <- xnames findex <- character(0) nfact <- length(factorList) if(nfact > 0){ findex <- sort( unique( unlist(factorList) ) ) fnames <- fnames[!fnames %in% findex] } tmp <- diag(length(fnames)) rownames(tmp) <- colnames(tmp) <- fnames if(length(tmp) < 2){ eCont <- frow <- intercept <- numeric(0) } else { eCont <- tmp[drop=F,-1,] frow <- rep(0,nrow(eCont)) intercept <- rep(0,nrow(eCont)) } dCont <- lCont <- eCont if(nfact > 0){ for(k in 1:nfact){ cm <- contrast[[k]] colnames(cm) <- factorList[[k]] rownames(cm) <- paste(names(factorList)[[k]],rownames(cm),sep='') facK <- names(factorList)[[k]] wx <- match(facK,colnames(xdata)) fnames <- as.character( levels(xdata[[wx]]) ) mm <- .getContrasts(facK, fnames) D <- mm$D L <- mm$L C <- mm$C if(length(eCont) > 1){ eCont <- .blockDiag(eCont,cm) dCont <- .blockDiag(dCont,D[,-1,drop=F]) lCont <- .blockDiag(lCont,L[,-1,drop=F]) ec <- nrow(lCont) bc <- ec - nrow(L) + 1 lCont[bc:ec,1] <- L[,1] dCont[bc,1] <- -1 } else { eCont <- cbind(0,cm) colnames(eCont)[1] <- 'intercept' dCont <- D lCont <- L } nr2 <- nrow(cm) nc2 <- ncol(cm) intercept <- c(intercept,rep(1,nr2)) frow <- c(frow,rep(k,nr2)) } eCont[,1] <- intercept } eCont <- eCont[drop=F,,xnames] dCont <- t(dCont[drop=F,,xnames]) dCont[1,] <- abs(dCont[1,]) lCont <- lCont[drop=F,,xnames] q1 <- nrow(eCont) fnames <- rownames(eCont) facList2 <- factorList if(nfact > 0){ for(j in 1:nfact){ wj <- which(names(xdata) == names(factorList)[j]) facList2[[j]] <- levels(xdata[[wj]]) } } fmat <- matrix(0,q1,q1) colnames(fmat) <- rownames(fmat) <- fnames findex <- match(findex,xnames) list(factorList = factorList, facList2 = facList2, fmat = fmat, fnames = fnames, q1 = q1, lCont = lCont, dCont = dCont, eCont = eCont, findex = findex) } gjamSensitivity <- function(output, group=NULL, nsim=100, PERSPECIES = TRUE){ REDUCT <- FALSE standRows <- output$inputs$standRows factorBeta <- output$inputs$factorBeta notOther <- output$inputs$notOther standMatSd <- output$inputs$standMatSd notStandard <- output$modelList$notStandard ng <- output$modelList$ng burnin <- output$modelList$burnin x <- output$inputs$xStand y <- output$inputs$y beta <- output$parameters$betaMu snames <- colnames(y) xnames <- colnames(x) Q <- length(xnames) S <- length(snames) S1 <- length(notOther) bgibbs <- output$chains$bgibbs sgibbs <- output$chains$sgibbs if('kgibbs' %in% names(output$chains)){ REDUCT <- T kgibbs <- output$chains$kgibbs sigErrGibbs <- output$chains$sigErrGibbs N <- output$modelList$reductList$N r <- output$modelList$reductList$r } jj <- sample(burnin:ng,nsim,replace=T) i <- 1 ns <- S if( !is.null(group) )ns <- length(group) for(j in jj){ bg <- matrix(bgibbs[j,],Q,S) rownames(bg) <- xnames colnames(bg) <- snames if(!REDUCT){ sg <- .expandSigma(sgibbs[j,], S = S, REDUCT = F) si <- solveRcpp( sg ) } else { Z <- matrix(sgibbs[j,],N,r) sg <- .expandSigma(sigErrGibbs[j], S, Z = Z, kgibbs[j,], REDUCT = T) si <- invWbyRcpp(sigErrGibbs[j], Z[kgibbs[j,],]) } tmp <- .contrastCoeff(beta=bg[,notOther], notStand = notStandard[notStandard %in% xnames], sigma = sg[notOther,notOther], sinv = si[notOther,notOther], stand = standMatSd, factorObject=factorBeta, conditional = group) if(i == 1){ fmat <- matrix(0,nsim,ncol(tmp$sens)) } fsens <- diag(tmp$sens) if(PERSPECIES)fsens <- fsens/ns fmat[i,] <- fsens i <- i + 1 } colnames(fmat) <- colnames(tmp$sens) fmat } .factorCoeffs2Zero <- function(factorObject, snames, priorObject){ zero <- numeric(0) for(k in 1:factorObject$nfact){ wk <- grep('_',factorObject$missFacSpec[[k]]) if(length(wk) > 0){ sx <- .splitNames(factorObject$missFacSpec[[k]])$vnam ij <- cbind(match(sx[,2],rownames(priorObject$lo)),match(sx[,1],snames)) zero <- rbind(zero,ij) } } zero } .cleanDims <- function(mat){ colnames(mat) <- .cleanNames( colnames(mat) ) rownames(mat) <- .cleanNames( rownames(mat) ) mat } .cleanTimePriors <- function(form, prior, xdata){ formTerms <- unlist( strsplit( as.character(form), '+', fixed=T) ) formTerms <- .replaceString( formTerms[ !formTerms == '~' ], ' ', '') xn <- colnames( model.matrix(form, xdata) ) xn[1] <- 'intercept' rownames(prior$lo) <- .cleanNames(rownames(prior$lo)) rownames(prior$hi) <- .cleanNames(rownames(prior$hi)) plo <- matrix(-Inf, length(xn), ncol(prior$lo)) rownames(plo) <- xn colnames(plo) <- colnames(prior$lo) phi <- -plo prior$lo <- prior$lo[ drop=F, rownames(prior$lo) %in% rownames(plo),] prior$hi <- prior$hi[ drop=F, rownames(prior$hi) %in% rownames(phi),] plo[rownames(prior$lo),] <- prior$lo phi[rownames(prior$hi),] <- prior$hi attr(prior$lo, "formula") <- form attr(prior$hi, "formula") <- form prior$lo <- .cleanDims(prior$lo) prior$hi <- .cleanDims(prior$hi) list( prior = prior, formTerms = formTerms, xnames = xn) } .gjam <- function(formula, xdata, ydata, modelList, verbose = FALSE){ holdoutN <- 0 holdoutIndex <- numeric(0) breakList <- modelSummary <- reductList <- traitList <- NULL specByTrait <- traitTypes <- notStandard <- NULL censor <- censorCA <- censorDA <- CCgroups <- FCgroups <- intMat <- NULL N <- r <- otherpar <- pg <- NULL facNames <- character(0) groupRandEff <- NULL x <- y <- y0 <- effort <- NULL ng <- 2000 burnin <- 500 BPRIOR <- LPRIOR <- REDUCT <- TRAITS <- FULL <- FALSE termB <- termR <- termA <- FALSE PREDICTX <- TRUE rhoPrior <- betaPrior <- alphaPrior <- NULL RANDOM <- FALSE TIME <- FALSE timeList <- timeZero <- timeLast <- timeIndex <- groupIndex <- rowInserts <- Rmat <- Amat <- beta <- NULL formulaBeta <- NULL xl <- NULL ematAlpha <- .5 alpha.DP <- ncol( ydata ) xdata <- as.data.frame( xdata ) colnames(ydata) <- .cleanNames( colnames(ydata) ) colnames(xdata) <- .cleanNames( colnames(xdata) ) wf <- which(sapply(xdata, is.factor)) if(length(wf) > 0){ for(j in wf){ jt <- as.character(xdata[,j]) jt <- .cleanNames( jt ) xdata[,j] <- as.factor(jt) } } if(alpha.DP == 1) stop('this is a multivariate model: at least 2 columns needed in ydata') for(k in 1:length(modelList))assign( names(modelList)[k], modelList[[k]] ) if('CCgroups' %in% names(modelList))attr(typeNames,'CCgroups') <- CCgroups if('FCgroups' %in% names(modelList))attr(typeNames,'FCgroups') <- FCgroups if('CATgroups' %in% names(modelList))attr(typeNames,'CATgroups') <- CATgroups if(missing(xdata)) xdata <- environment(formula) formTerms <- unlist( strsplit( as.character(formula), '+', fixed=T) ) formTerms <- .replaceString( formTerms[ !formTerms == '~' ], ' ', '') ft <- c( grep('_', formTerms), grep('-', formTerms) ) if(length(ft) > 0)stop( " reserved characters '_' or '-' in formula variables, rename" ) if( is.null(timeList) ){ termB <- TRUE if( !is.null(betaPrior) ) BPRIOR <- TRUE }else{ if(verbose)cat('\nFitted as a time series model\n') wterms <- character(0) ww <- which( sapply( timeList, is.null ) ) if(length(ww) > 0)timeList <- timeList[ -ww ] for(k in 1:length(timeList))assign( names(timeList)[k], timeList[[k]] ) if( "betaPrior" %in% names(timeList) ){ tb <- .cleanTimePriors(formulaBeta, timeList$betaPrior, xdata) timeList$betaPrior <- tb$prior formTerms <- tb$formTerms xnames <- tb$xnames wterms <- 'beta' termB <- TRUE if( all(timeList$betaPrior$lo == -Inf) & all(timeList$betaPrior$hi == Inf) ){ betaPrior <- NULL BPRIOR <- FALSE }else{ BPRIOR <- TRUE } } if( "rhoPrior" %in% names(timeList) ){ formulaRho <- timeList$formulaRho tb <- .cleanTimePriors(formulaRho, timeList$rhoPrior, xdata) timeList$rhoPrior <- tb$prior formTerms <- unique( c(formTerms, tb$formTerms) ) xlnames <- tb$xnames wterms <- c( wterms, 'rho') termR <- TRUE LPRIOR <- TRUE } if( "alphaPrior" %in% names(timeList) ){ timeList$alphaPrior$lo <- .cleanDims(timeList$alphaPrior$lo) timeList$alphaPrior$hi <- .cleanDims(timeList$alphaPrior$hi) wterms <- c( wterms, 'alpha') termA <- TRUE APRIOR <- TRUE } if(verbose)cat( paste('\nTime series terms are ', paste0( wterms, collapse = ', ' ), '.\n', sep='') ) formula <- as.formula( paste( '~', paste0(formTerms, collapse = '+') ) ) TIME <- T holdoutN <- 0 holdoutIndex <- numeric(0) } if( is.character(formula) )formula <- as.formula(formula) if( !is.null(traitList) ){ TRAITS <- T for(k in 1:length(traitList))assign( names(traitList)[k], traitList[[k]] ) stt <- .replaceString(colnames(specByTrait),'_','') colnames(specByTrait) <- stt colnames(plotByTrait) <- stt colnames(traitList$specByTrait) <- stt colnames(traitList$plotByTrait) <- stt modelList$traitList <- traitList if(verbose)cat('\nFitted as a trait model\n') } if(burnin >= ng) stop( 'burnin must be < no. MCMC steps, ng' ) if('censor' %in% names(modelList)){ for(k in 1:length(censor)){ if( nrow(censor[[k]]$partition) != 3 ) stop('censor matrix: 3 rows for value, lo, hi') rownames(censor[[k]]$partition) <- c('value','lo','hi') } } S <- ncol(ydata) if(length(typeNames) == 1)typeNames <- rep(typeNames,S) if(length(typeNames) != S) stop('typeNames must be one value or no. columns in y') tmp <- .checkYfactor(ydata, typeNames) ydata <- tmp$ydata; yordNames <- tmp$yordNames if(TRAITS){ if(!all( typeNames %in% c('CC','FC') ) ) stop('trait prediction requires composition data (CC or FC)') if(nrow(plotByTrait) != nrow(ydata)) stop('nrow(plotByTrait) must equal nrow(ydata)') if(ncol(plotByTrait) != length(traitTypes)) stop('ncol(plotByTrait) must equal length(traitTypes)') if(ncol(plotByTrait) != length(traitTypes)) stop('ncol(plotByTrait) must equal length(traitTypes)') ii <- identical(rownames(specByTrait),colnames(ydata)) if(!ii){ ww <- match(colnames(ydata),rownames(specByTrait) ) if( is.finite(min(ww)) ){ specByTrait <- specByTrait[ww,] } else { stop( 'rownames(specByTrait) must match colnames(ydata)' ) } } if(typeNames[1] == 'CC'){ ytmp <- round(ydata,0) ytmp[ytmp == 0 & ydata > 0] <- 1 ydata <- ytmp rm(ytmp) } } tmp <- .buildYdata(ydata, typeNames) y <- as.matrix( tmp$y ) ydataNames <- tmp$ydataNames typeNames <- tmp$typeNames CCgroups <- tmp$CCgroups FCgroups <- tmp$FCgroups CATgroups <- tmp$CATgroups if(TRAITS) rownames(specByTrait) <- colnames(y) S <- ncol(y) n <- nrow(y) if(verbose){ cat("\nObservations and responses:\n") print(c(n, S)) } tmp <- .buildEffort(y, effort, typeNames, verbose) effort <- tmp effMat <- effort$values modelList$effort <- effort y2e <- y/effMat y2e <- y2e[y2e > 0 ] re <- floor( diff( range(log10(y2e),na.rm=T) ) ) if(re > 3 & verbose) cat(paste('\nNote: y/effort > ', re, ' orders of magnitude--consider units near 1\n',sep='') ) tmp <- .gjamGetTypes(typeNames) typeCols <- tmp$typeCols typeFull <- tmp$typeFull typeCode <- tmp$TYPES[typeCols] allTypes <- sort(unique(typeCols)) standard <- colnames(xdata)[!colnames(xdata) %in% notStandard] standard <- standard[ standard != 'intercept' ] tmp <- .gjamXY(formula, xdata, y, typeNames, notStandard, verbose = verbose) x <- tmp$x; y <- tmp$y; snames <- tmp$snames xnames <- tmp$xnames interBeta <- tmp$interaction factorBeta <- tmp$factorAll designTable <- tmp$designTable xscale <- tmp$xscale predXcols <- tmp$predXcols standMatSd <- tmp$standMatSd standMatMu <- tmp$standMatMu xdataNames <- tmp$xdataNames standRows <- tmp$standRows factorRho <- interRho <- NULL xlnames <- character(0) if( termB & TIME ){ tmp <- .gjamXY(formulaBeta, xdata, y, typeNames, notStandard) xnames <- tmp$xnames interBeta <- tmp$interaction factorBeta <- tmp$factorAll designTable <- list(beta = tmp$designTable) standMatSdB <- tmp$standMatSd standMatMuB <- tmp$standMatMu standRowsB <- tmp$standRows notStandardB <- tmp$notStandard } if( termR ){ tmp <- .gjamXY(formulaRho, xdata, y, typeNames, notStandard) xl <- tmp$x xlnames <- tmp$xnames interRho <- tmp$interaction factorRho <- tmp$factorAll designTable <- append( designTable, list(rho = tmp$designTable) ) standMatSdL <- tmp$standMatSd standMatMuL <- tmp$standMatMu standRowsL <- tmp$standRows notStandardL <- tmp$notStandard[tmp$notStandard %in% xlnames] rho <- matrix(0, ncol(xl), ncol(y)) rownames(rho) <- colnames(xl) colnames(rho) <- colnames(y) } modelList$formula <- formula modelList$notStandard <- notStandard Q <- ncol(x) tmp <- .gjamMissingValues(x, y, factorBeta$factorList, typeNames, verbose) xmiss <- tmp$xmiss; xbound <- tmp$xbound; ymiss <- tmp$ymiss; missY <- tmp$missY xprior <- tmp$xprior; yprior <- tmp$yprior nmiss <- nrow(xmiss); mmiss <- nrow(ymiss) x <- tmp$x; y <- tmp$y if( termR ){ tmp <- .gjamMissingValues(xl, y, factorRho$factorList, typeNames) xlmiss <- tmp$xmiss; xlbound <- tmp$xbound; xlprior <- tmp$xprior nlmiss <- nrow(xmiss) xl <- tmp$x } tmp <- .gjamHoldoutSetup(holdoutIndex, holdoutN, n) holdoutIndex <- tmp$holdoutIndex; holdoutN <- tmp$holdoutN inSamples <- tmp$inSamples; nIn <- tmp$nIn tmp <- .gjamSetup(typeNames, x, y, breakList, holdoutN, holdoutIndex, censor=censor, effort=effort) w <- tmp$w; z <- tmp$z; y <- tmp$y; other <- tmp$other; cuts <- tmp$cuts cutLo <- tmp$cutLo; cutHi <- tmp$cutHi; plo <- tmp$plo; phi <- tmp$phi ordCols <- tmp$ordCols; disCols <- tmp$disCols; compCols <- tmp$compCols conCols <- which(typeNames == 'CON') classBySpec <- tmp$classBySpec; breakMat <- tmp$breakMat minOrd <- tmp$minOrd; maxOrd <- tmp$maxOrd; censorCA <- tmp$censorCA censorDA <- tmp$censorDA; censorCON <- tmp$censorCON; ncut <- ncol(cuts); corCols <- tmp$corCols catCols <- which(attr(typeNames,'CATgroups') > 0) sampleW <- tmp$sampleW ordShift <- tmp$ordShift sampleW[censorCA] <- 1 sampleW[censorDA] <- 1 sampleW[censorCON] <- 1 sampleWhold <- tgHold <- NULL wHold <- NULL wmax <- 1.5*apply(y/effMat,2,max,na.rm=T) pmin <- -abs(wmax) if(mmiss > 0){ phi[ ymiss ] <- wmax[ ymiss[,2] ] plo[ ymiss ] <- pmin[ ymiss[,2] ] sampleW[ ymiss ] <- 1 } ploHold <- phiHold <- NULL if( holdoutN > 0 ){ sampleWhold <- sampleW[holdoutIndex,] sampleW[holdoutIndex,] <- 1 tgHold <- cuts wHold <- w[drop=F,holdoutIndex,] ploHold <- plo[drop=F,holdoutIndex,] phiHold <- phi[drop=F,holdoutIndex,] } byCol <- byRow <- F if(attr(sampleW,'type') == 'cols')byCol <- T if(attr(sampleW,'type') == 'rows')byRow <- T indexW <- attr(sampleW,'index') notCorCols <- c(1:S) if(length(corCols) > 0)notCorCols <- notCorCols[-corCols] Q <- ncol(x) sigmaDf <- nIn - Q + S - 1 sg <- diag(.1,S) SO <- S notOther <- c(1:S) sgOther <- NULL if(length(other) > 0){ notOther <- notOther[!notOther %in% other] SO <- length(notOther) sg[other,] <- sg[,other] <- 0 sgOther <- matrix( cbind(other,other),ncol=2 ) sg[sgOther] <- .1 } loB <- hiB <- NULL beta <- bg <- matrix(0, Q, S) rownames(beta) <- colnames(x) wB <- which(bg == 0, arr.ind=T) if( BPRIOR ){ loB <- betaPrior$lo hiB <- betaPrior$hi if( ncol(loB) != ncol(y) | ncol(hiB) != ncol(y))stop('betaPrior$lo or betaPrior$hi do not match ydata columns') xrange <- max( abs(range(x)) ) loB['intercept', loB['intercept',] < -10*xrange] <- -10*xrange hiB['intercept', hiB['intercept',] > 10*xrange] <- 10*xrange if(length(standRows) > 0){ btmp <- loB[standRows,] btmp[ which(btmp < -5) ] <- -5 loB[standRows, ] <- btmp btmp <- hiB[standRows,] btmp[ btmp > 5 ] <- 5 hiB[standRows, ] <- btmp } bg <- (loB + hiB)/2 bg[is.nan(bg)] <- 0 tmp <- .betaPrior(bg, notOther, loB, hiB) bg <- tmp$beta; loB <- tmp$loB; hiB <- tmp$hiB wB <- tmp$wB; zB <- tmp$zB bg[is.nan(bg) | bg == Inf | bg == -Inf] <- 0 tmp <- .getPattern(bg[,notOther], wB) Brows <- tmp$rows Bpattern <- tmp$pattern bg[!is.finite(bg)] <- 0 zeroBeta <- .factorCoeffs2Zero(factorBeta, snames, betaPrior) } zeroRho <- NULL if( TIME ){ wB <- wL <- wA <- numeric(0) mua <- mub <- mug <- muw <- w*0 Umat <- Vmat <- Rmat <- Amat <- NULL Brows <- Rrows <- Arows <- Bpattern <- Rpattern <- Apattern <- NULL tmp <- .getTimeIndex(timeList, other, notOther, xdata, x, xl, y, w, termB, termR, termA) if(termA){ Amat <- tmp$Amat; Apattern <- tmp$Apattern; wA <- tmp$wA; zA = tmp$zA; Umat <- tmp$Umat; uindex <- tmp$uindex; Arows <- tmp$Arows loAmat <- tmp$loAmat; hiAmat <- tmp$hiAmat; aindex <- tmp$aindex Unew <- Umat } if(termR & LPRIOR){ Rmat <- tmp$Rmat; Rpattern <- tmp$Rpattern; wL <- tmp$wL; zR = tmp$zR; Vmat <- tmp$Vmat; Rrows <- tmp$Rrows; gindex <- tmp$gindex loRmat <- tmp$loRmat; hiRmat <- tmp$hiRmat zeroRho <- .factorCoeffs2Zero(factorRho, snames, rhoPrior) timeList$rhoPrior$hi[zeroRho] <- rhoPrior$hi[zeroRho] <- 0 Vnew <- Vmat standMatSdRmat <- Rmat*0 notStandardRmat <- numeric(0) if(length(standRowsL) > 0){ csl <- paste('_',names(standRowsL),sep='') for(j in 1:length(csl)){ wj <- grep(csl[j],rownames(Rmat)) standMatSdRmat[wj,] <- standMatSdL[standRowsL[j],] notStandardRmat <- c(notStandardRmat,wj) } } } if(termB){ Brows <- tmp$Brows; bg <- tmp$bg; Bpattern <- tmp$Bpattern wB <- tmp$wB; zB <- tmp$zB; loB <- tmp$loB; hiB <- tmp$hiB if(BPRIOR)timeList$betaPrior$hi[zeroBeta] <- betaPrior$hi[zeroBeta] <- 0 } timeZero <- tmp$timeZero; timeLast <- tmp$timeLast maxTime <- tmp$maxTime; inSamples <- tmp$inSamples tindex <- tmp$tindex; sindex <- tmp$sindex; i1 <- tmp$i1; i2 <- tmp$i2 if(!REDUCT ){ if(length(wA) > 300)modelList$reductList <- list(N = 8, r = 5) } bigx <- numeric(0) if(termB){ bigx <- x[tindex[,2],xnames] nb <- nrow(bg) } if(termR){ bigx <- cbind(bigx, Vmat[tindex[,2],]) nr <- nrow(Rmat) } if(termA){ bigx <- cbind(bigx, Umat[tindex[,2],]) na <- nrow(Amat) } bigc <- crossprod(bigx) diag(bigc) <- diag(bigc)*1.00001 bigi <- try( solve(bigc), silent = TRUE ) if(inherits(bigi,'try-error'))bigi <- ginv(bigc) Y <- w[tindex[,2],notOther] - w[tindex[,1],notOther] init <- bigi%*%crossprod(bigx, Y) if(termB){ binit <- init[1:nb,] init <- init[-c(1:nb),] binit[binit < loB] <- loB[binit < loB] binit[binit > hiB] <- hiB[binit > hiB] ones <- binit*0 ones[ wB ] <- 1 bg[ 1:length(bg) ] <- as.vector( binit*ones ) } if(termR){ rinit <- init[1:nr,] init <- init[-c(1:nr),] rinit[rinit < loRmat] <- loRmat[rinit < loRmat] rinit[rinit > hiRmat] <- hiRmat[rinit > hiRmat] ones <- rinit*0 ones[ wL ] <- 1 Rmat[1:length(Rmat)] <- as.vector( rinit*ones ) } if(termA){ ainit <- init loA <- loAmat loA[ !is.finite(loA) ] <- 0 hiA <- hiAmat hiA[ !is.finite(hiA) ] <- 0 ainit[ainit < loA] <- loA[ainit < loA] ainit[ainit > hiA] <- hiA[ainit > hiA] ones <- ainit*0 ones[ wA ] <- 1 Amat[1:length(Amat)] <- as.vector( ainit*ones ) } rm(bigx, bigc, bigi, init) } reductList <- .setupReduct(modelList, S, Q, n) if(is.null(reductList)){ REDUCT <- FALSE }else{ N <- reductList$N; r <- reductList$r REDUCT <- T } if(byCol){ inw <- intersect( colnames(y)[indexW], colnames(y)[notOther] ) indexW <- match(inw,colnames(y)[notOther]) } updateBeta <- .betaWrapper(REDUCT, TIME, notOther, betaLim=max(wmax)/2) inSamp <- inSamples .param.fn <- .paramWrapper(REDUCT, inSamp, SS=length(notOther)) sigmaerror <- .1 otherpar <- list(S = S, Q = Q, sigmaerror = sigmaerror, Z = NA, K =rep(1,S), sigmaDf = sigmaDf) sigErrGibbs <- rndEff <- NULL yp <- y wmax <- ymax <- apply(y,2,max) wmax <- wmax/effMat if(REDUCT){ cat( paste('\nDimension reduced from',S,'X',S,'to',N,'X',r,'in Sigma\n') ) otherpar$N <- N; otherpar$r <- r; otherpar$sigmaerror <- 0.1 otherpar$Z <- rmvnormRcpp(N, rep(0,r), 1/S*diag(r)) otherpar$D <- .riwish(df = (2 + r + N), S = (crossprod(otherpar$Z) + 2*2*diag(rgamma(r,shape=1,rate=0.001)))) otherpar$K <- sample(1:N,length(notOther),replace=T) otherpar$alpha.DP <- alpha.DP otherpar$pvec <- .sampleP(N=N, avec=rep(alpha.DP/N,(N-1)), bvec=((N-1):1)*alpha.DP/N, K=otherpar$K) kgibbs <- matrix(1,ng,S) sgibbs <- matrix(0,ng, N*r) nnames <- paste('N',1:N,sep='-') rnames <- paste('r',1:r,sep='-') colnames(sgibbs) <- .multivarChainNames(nnames,rnames) sigErrGibbs <- rep(0,ng) rndEff <- w*0 } else { Kindex <- which(as.vector(lower.tri(diag(S),diag=T))) nK <- length(Kindex) sgibbs <- matrix(0,ng,nK) colnames(sgibbs) <- .multivarChainNames(snames,snames)[Kindex] rndEff <- 0 } out <- .param.fn( x[,xnames,drop=F], beta = bg[,notOther,drop=F], Y = w[,notOther], otherpar ) sg[notOther,notOther] <- out$sg sinv <- solveRcpp(sg[notOther,notOther]) otherpar <- out$otherpar muw <- w if( !TIME ){ Y <- w[inSamp,notOther] sig <- sg[notOther,notOther] if(REDUCT){ Y <- Y - rndEff[inSamp,notOther] sig <- sigmaerror } bg[,notOther] <- updateBeta(X = x[inSamp,], Y, sig, beta = bg[,notOther], BPRIOR, loB, hiB) muw <- x%*%bg sg[other,] <- sg[,other] <- 0 diag(sg)[other] <- .1 }else{ mub <- mua <- mug <- 0 xr <- rndEff if(termR){ mug <- Vmat%*%Rmat xr <- xr + mug } if(termA){ mua <- Umat%*%Amat xr <- xr + mua } Y <- w - xr Y[tindex[,1],] <- Y[tindex[,2],] - w[tindex[,1],] if(REDUCT){ sig <- sigmaerror }else{ sig <- sg[notOther,notOther] } if(termB){ bg[,notOther] <- updateBeta(X = x[tindex[,1],xnames], Y = Y[tindex[,1],notOther], sig = sig, beta = bg[,notOther], PRIOR = BPRIOR, lo = loB[,notOther], hi = hiB[,notOther], rows=Brows, pattern=Bpattern, sinv = sinv, wF = wB) mub <- x[,xnames]%*%bg } colnames(bg) <- snames muw <- mub + mug + mua wpropTime <- .001 + .1*abs(w) } rownames(sg) <- colnames(sg) <- snames rownames(bg) <- xnames cutg <- tg <- numeric(0) if('OC' %in% typeCode){ tg <- cutg <- cuts cnames <- paste('C',1:ncut,sep='-') nor <- length(ordCols) cgibbs <- matrix(0,ng,(ncut-3)*nor) colnames(cgibbs) <- as.vector( outer(snames[ordCols], cnames[-c(1,2,ncut)],paste,sep='_') ) tmp <- .gjamGetCuts(y+1,ordCols) cutLo <- tmp$cutLo cutHi <- tmp$cutHi plo[,ordCols] <- tg[cutLo] phi[,ordCols] <- tg[cutHi] lastOrd <- ncol(tg) } tmp <- .gjamGetTypes(typeNames) typeFull <- tmp$typeFull typeCols <- tmp$typeCols allTypes <- unique(typeCols) Y <- w LOHI <- F if(!LOHI & holdoutN > 0){ minlo <- apply(plo,2,min) minlo[minlo > 0] <- 0 maxhi <- apply(phi,2,max) } if( 'random' %in% names(modelList)) RANDOM <- TRUE if(!TIME){ .updateW <- .wWrapper(REDUCT, RANDOM, S, effMat, corCols, notCorCols, typeNames, typeFull, typeCols, allTypes, holdoutN, holdoutIndex, censor, censorCA, censorDA, censorCON, notOther, sampleW, byRow, byCol, indexW, ploHold, phiHold, sampleWhold, inSamp) }else{ .updateW <- .wWrapperTime(sampleW, y, timeZero, timeLast, i1, i2, tindex, gindex, uindex, notOther, n, S, REDUCT, RANDOM, TIME, termB, termR, termA, corCols) Y <- w Y[ tindex[,1],] <- Y[ tindex[,2],] - w[ tindex[,1],] if(termA) Y <- Y - mua if(termR) Y <- Y - mug if(RANDOM)Y <- Y - rndEff } ycount <- rowSums(y) if('CC' %in% typeCode)ycount <- rowSums(y[,compCols]) bgg <- bg if( TIME & termR){ tmp <- colnames( model.matrix(formula, xdata) ) bgg <- matrix( 0, length(tmp), S) rownames(bgg) <- tmp colnames(bgg) <- snames rownames(bgg)[1] <- 'intercept' } tmp <- .xpredSetup(Y, x, bgg, isNonLinX = interBeta$isNonLinX, factorObject = factorBeta, intMat = factorBeta$intMat, standMatSd = standMatSd, standMatMu = standMatMu, notOther, notStandard ) factorBeta$linFactor <- tmp$linFactor; xpred <- tmp$xpred; px <- tmp$px lox <- tmp$lox; hix <- tmp$hix propx <- tmp$propx priorXIV <- diag(1e-5,ncol(x)) priorX <- colMeans(x) priorX[abs(priorX) < 1e-10] <- 0 linFactor <- NULL if( RANDOM ){ rname <- modelList$random randGroupTab <- table( as.character(xdata[,rname]) ) wss <- names(randGroupTab[randGroupTab <= 2]) if(length(wss) > 0){ cat('\nNote: one or more random groups with one observations\n') } randGroups <- names( randGroupTab ) G <- length(randGroups) groupIndex <- match(as.character(xdata[,rname]),randGroups) rmm <- matrix(groupIndex,length(groupIndex), S) smm <- matrix(1:S, length(groupIndex), S, byrow=T) randGroupIndex <- cbind( as.vector(smm), as.vector(rmm) ) colnames(randGroupIndex) <- c('species','group') xdata[,rname] <- as.factor(xdata[,rname]) alphaRandGroup <- matrix(0, S, G) rownames(alphaRandGroup) <- snames colnames(alphaRandGroup) <- randGroups Cmat <- var(w[,notOther]/2) Cmat <- Cmat + diag(.1*diag(Cmat)) Cprior <- Cmat CImat <- solve(Cprior) Ckeep <- diag(S) alphaRanSums <- alphaRanSums2 <- alphaRandGroup*0 groupRandEff <- w*0 Aindex <- which(as.vector(lower.tri(diag(S),diag=T))) nK <- length(Aindex) alphaVarGibbs <- matrix(0,ng,nK) colnames(alphaVarGibbs) <- .multivarChainNames(snames,snames)[Aindex] if(verbose)cat( paste('\nRandom groups:', randGroups, '\n', sep = '') ) if(verbose){ rpp <- paste0( randGroups, collapse = ', ') cat( paste('\nRandom groups: ', rpp, '\n', sep = '') ) } } Qall <- Q - 1 linFactor <- numeric(0) lf <- factorBeta$linFactor xnAll <- unique( c(xnames, xlnames) ) if( length(lf) > 0 ){ for(k in 1:length(lf)){ kf <- match(xnAll[lf[[k]]],colnames(xpred)) linFactor <- append(linFactor,list(kf)) names(linFactor)[length(linFactor)] <- names(factorBeta$linFactor)[k] } } if( termB & TIME ){ tmp <- .xpredSetup(Y, x, bg, isNonLinX = interBeta$isNonLinX, factorObject = factorBeta, intMat = factorBeta$intMat, standMatSd = standMatSdB, standMatMu = standMatMuB, notOther, notStandardB ) factorBeta$linFactor <- tmp$linFactor linFactorBeta <- numeric(0) lf <- factorBeta$linFactor if( length(lf) > 0 ){ for(k in 1:length(lf)){ kf <- match(xnames[lf[[k]]],colnames(xpred)) linFactorBeta <- append(linFactorBeta,list(kf)) names(linFactorBeta)[length(linFactorBeta)] <- names(factorBeta$linFactor)[k] } } } if( termR ){ rho[ rho %in% c(-Inf, Inf) ] <- 0 tmp <- .xpredSetup(Y, xx = xl, bgg = rho, isNonLinX = interRho$isNonLinX, factorObject = factorRho, intMat = interRho$intMat, standMatSd = standMatSdL, standMatMu = standMatMuL, notOther, notStandard = notStandardL ) factorRho$linFactor <- tmp$linFactor linFactorRho <- numeric(0) lf <- factorRho$linFactor if( length(lf) > 0 ){ for(k in 1:length(lf)){ kf <- match(xlnames[lf[[k]]],colnames(xpred)) linFactorRho <- append(linFactorRho,list(kf)) names(linFactorRho)[length(linFactorRho)] <- names(factorRho$linFactor)[k] } } } if( termB ){ tmp <- .setupFactors(xdata, xnames, factorBeta) ff <- factorBeta[names(factorBeta) != 'factorList'] factorBeta <- append(ff,tmp) } if( termR ){ tmp <- .setupFactors(xdata, xlnames, factorRho) ff <- factorRho[names(factorRho) != 'factorList'] factorRho <- append(ff,tmp) } richness <- richFull <- NULL RICHNESS <- F inRichness <- which(!typeNames %in% c('CON','CAT','OC')) inRichness <- inRichness[!inRichness %in% other] if(length(inRichness) > 2)RICHNESS <- T wrich <- y*0 wrich[,inRichness] <- 1 wrich[ymiss] <- 0 ess <- matrix(0,S,S) colnames(ess) <- rownames(ess) <- snames loESS <- hiESS <- lmESS <- hmESS <- ess esens1 <- esens2 <- rep(0, S) fmat <- factorBeta$fmat fnames <- rownames( factorBeta$lCont ) if( termB & !TIME ){ facNames <- names(factorBeta$factorList) fl <- character(0) for(k in 1:length(facNames)){ kk <- which( startsWith( rownames(factorBeta$lCont), facNames[k] ) ) fc <- rownames( factorBeta$lCont )[kk] fl <- c(fl, fc) } } if( termB & TIME ){ fmat <- factorBeta$fmat fnames <- rownames( factorBeta$lCont ) facNames <- names(factorBeta$factorList) if(!is.null(facNames)){ fl <- character(0) for(k in 1:length(facNames)){ kk <- which( startsWith( rownames(factorBeta$lCont), facNames[k] ) ) fc <- rownames( factorBeta$lCont )[kk] fl <- c(fl, fc) } attr(bg, 'factors') <- facNames attr(bg, 'factorLevels') <- fl } } if( termR ){ facNames <- names(factorRho$factorList) if(!is.null(facNames)){ fl <- character(0) for(k in 1:length(facNames)){ kk <- which( startsWith( rownames(factorRho$lCont), facNames[k] ) ) fc <- rownames( factorRho$lCont )[kk] fl <- c(fl, fc) } attr(Rmat, 'factors') <- facNames attr(Rmat, 'factorLevels') <- fl attr(Rmat, 'formula') <- formulaRho factorRho$LCONT <- rep(TRUE, factorRho$nfact) flnames <- rownames( factorRho$lCont ) } essL <- ess*0 lsens1 <- lsens2 <- rep(0, S) RmatU <- Rmat } if( termA ){ essA <- ess*0 asens1 <- asens2 <- rep(0, S) } presence <- w*0 covx <- cov(x) predx <- predx2 <- xpred*0 yerror <- ypred <- ypred2 <- wpred <- wpred2 <- ymissPred <- ymissPred2 <- y*0 sumDev <- 0 sMean <- sg*0 ntot <- 0 if(nmiss > 0){ xmissSum <- xmissSum2 <- rep(0,nmiss) } predxl <- numeric(0) if(TIME & termR)predxl <- predxl2 <- xl*0 q2 <- length(fnames) if(TRAITS){ specTrait <- specByTrait[colnames(y),] tnames <- colnames(specTrait) M <- ncol(specTrait) specTrait <- t(specTrait) tpred <- tpred2 <- matrix(0,n,M) missTrait <- which(is.na(specTrait),arr.ind=T) if(length(missTrait) > 0){ traitMeans <- rowMeans(specTrait,na.rm=T) specTrait[missTrait] <- traitMeans[missTrait[,2]] warning( paste('no. missing trait values:',nrow(missTrait)) ) } bTraitGibbs <- matrix(0,ng,M*Q) colnames(bTraitGibbs) <- .multivarChainNames(xnames,tnames) bTraitFacGibbs <- matrix(0,ng,q2*M) colnames(bTraitFacGibbs) <- .multivarChainNames(fnames,tnames) mgibbs <- matrix(0,ng,M*M) colnames(mgibbs) <- .multivarChainNames(tnames,tnames) } if( termB ){ bgibbsUn <- NULL fbnames <- colnames( factorBeta$dCont ) bf <- .multivarChainNames( fbnames, snames[notOther] ) bFacGibbs <- matrix(0, ng, length(bf)) colnames(bFacGibbs) <- bf bf <- .multivarChainNames(xnames, snames, keep = wB) bgibbs <- matrix(0, ng, length(bf) ) colnames(bgibbs) <- bf if( length(standRows) > 0 ){ bgibbsUn <- bgibbs } fSensGibbs <- matrix( 0, ng, length(fbnames) ) colnames(fSensGibbs) <- fbnames covE <- cov( x[,xnames]%*%factorBeta$dCont[xnames,fbnames] ) } if( TIME ){ yy <- y*0 yy[rowInserts,] <- 1 ymiss <- which(yy == 1, arr.ind=T) rm(yy) mmiss <- length(ymiss) if(termR){ covL <- cov( xl%*%factorRho$dCont ) nL <- nrow(wL) lgibbs <- matrix(0, ng, nL) colnames(lgibbs) <- rownames(wL) lgibbsUn <- lgibbs spL <- rep(.01, nL) } if(termA){ nA <- nrow(wA) wnames <- apply(wA, 1, paste0, collapse='-') alphaGibbs <- matrix(0, ng, nA) colnames(alphaGibbs) <- wnames spA <- rep(.001, nA) } ni <- length(i1) g1 <- 1 gcheck <- c(50, 100, 200, 400, 800) tinyg <- 1e-6 } pbar <- txtProgressBar(min=1,max=ng,style=1) xf <- NULL if(length(facNames) > 0){ xf <- xdata[, facNames, drop=F] } tmp <- .getUnstandX(formula, x, standRows, standMatMu[,1], standMatSd[,1], factorColumns = xf ) S2U <- tmp$S2U xUnstand <- tmp$xu if( Q == 1 )PREDICTX <- FALSE if(TIME & termB){ tmp <- .getUnstandX(formula, x[,xnames], standRowsB, standMatMuB[,1],standMatSdB[,1], factorColumns = xf ) S2U <- tmp$S2U } if(termR){ facNamesRho <- attr(Rmat, 'factors') xf <- NULL if(length(facNames) > 0){ xf <- xdata[, facNamesRho, drop=F] } tmp <- .getUnstandX( formulaRho, xl, standRowsL, standMatMuL[,1], standMatSdL[,1], factorColumns = xf ) S2UL <- tmp$S2U xlUnstand <- tmp$xu } if(REDUCT)rndTot <- rndTot2 <- w*0 notPA <- which(!typeNames == 'PA' & !typeNames == 'CON') if(length(y) < 10000 | FULL) FULL <- T if(FULL){ ygibbs <- matrix(0,ng,length(y)) } if(RICHNESS){ ypredPres <- ypredPres2 <- ypredPresN <- y*0 shannon <- rep(0,n) } varExp <- varTot <- varExpMean <- varExpRand <- rep( 0, length(notOther) ) sdg <- .1 for(g in 1:ng){ if( REDUCT ){ Y <- w[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] if(TIME){ Y <- Y - mua[,notOther] - mug[,notOther] Y[tindex[,2],] <- Y[tindex[,2],] - w[tindex[,1],notOther] } tmp <- .param.fn(X = x[,xnames], beta = bg[,notOther], Y = Y, otherpar) sg[notOther,notOther] <- tmp$sg otherpar <- tmp$otherpar rndEff[inSamples,notOther] <- tmp$rndEff sigmaerror <- otherpar$sigmaerror kgibbs[g,notOther] <- otherpar$K sgibbs[g,] <- as.vector(otherpar$Z) sigErrGibbs[g] <- sigmaerror sg[sgOther] <- .1*sigmaerror sinv <- .invertSigma(sg[notOther,notOther],sigmaerror,otherpar,REDUCT) sdg <- sqrt(sigmaerror) if( !TIME ){ Y <- w[inSamp,notOther] - rndEff[inSamp,notOther] if(RANDOM)Y <- Y - groupRandEff[inSamp,notOther] bg[,notOther] <- updateBeta(X = x[inSamp,xnames], Y, sig = sigmaerror, beta = bg[,notOther], PRIOR = BPRIOR, lo=loB[,notOther], hi=hiB[,notOther]) muw[inSamp,] <- x[inSamp,]%*%bg } else { mua <- mug <- w*0 if(termA)mua <- Umat%*%Amat if(termR)mug <- Vmat%*%Rmat Y <- w[,notOther] - mua[,notOther] - mug[,notOther] - rndEff[,notOther] Y[tindex[,2],] <- Y[tindex[,2],] - w[tindex[,1],notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] bg[,notOther] <- updateBeta(X = x[tindex[,2],xnames], Y = Y[tindex[,2],], sig = sigmaerror, beta = bg[,notOther], PRIOR = BPRIOR, rows = Brows, pattern = Bpattern, lo=loB[,notOther], hi=hiB[,notOther], wF = wB) mub <- x[,xnames]%*%bg Y <- (w - mub - mua - rndEff)[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] Y[tindex[,2],] <- Y[tindex[,2],] - w[tindex[,1],notOther] Rmat[,notOther] <- updateBeta(X = Vmat[tindex[,2],], Y = Y[tindex[,2],], sig=sigmaerror, beta = Rmat[,notOther], PRIOR = LPRIOR, rows = Rrows, pattern = Rpattern, lo=loRmat, hi=hiRmat, wF = wL ) mug <- Vmat%*%Rmat Y <- (w - mub - mug - rndEff)[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] Y[tindex[,2],] <- Y[tindex[,2],] - w[tindex[,1],notOther] Amat[,notOther] <- updateBeta(X = Umat[tindex[,2],], Y = Y[tindex[,2],], sig = sigmaerror, rows = Arows, pattern = Apattern, beta = Amat[,notOther], PRIOR = TRUE, lo = loAmat[,notOther], hi = hiAmat[,notOther], wF = wA ) mua <- Umat%*%Amat muw <- mub + mug + mua + rndEff } } else { if( !TIME ){ Y <- w[inSamp,notOther] if(RANDOM)Y <- Y - groupRandEff[inSamp,notOther] bg[,notOther] <- updateBeta(X = x[inSamp,], Y, sig = sg[notOther,notOther], beta = bg[,notOther], BPRIOR, lo=loB, hi=hiB) muw[inSamp,] <- x[inSamp,]%*%bg }else{ muw <- mub <- mua <- mug <- w*0 if(termR)mug <- Vmat%*%Rmat if(termA)mua <- Umat%*%Amat if(termB){ Y <- w[,notOther] Y[tindex[,1],] <- w[tindex[,2],] - w[tindex[,1],notOther] if(termA) Y <- Y - mua[,notOther] if(termR) Y <- Y - mug[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] bg[,notOther] <- updateBeta(X = x[tindex[,1],xnames], Y = Y[tindex[,1],], sig = sg[notOther,notOther], beta = bg[,notOther], PRIOR = BPRIOR, rows = Brows, pattern = Bpattern, lo=loB[,notOther], hi=hiB[,notOther], sinv = sinv, wF = wB) mub[tindex[,1],] <- x[tindex[,1],xnames]%*%bg mub[timeLast,] <- x[drop=F, timeLast,xnames]%*%bg muw <- muw + mub } if(termR){ Y <- w[,notOther] Y[tindex[,1],] <- Y[tindex[,2],] - w[tindex[,1],notOther] if(termA) Y <- Y - mua[,notOther] if(termB) Y <- Y - mub[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] Rmat[,notOther] <- updateBeta(X = Vmat[tindex[,1],], Y = Y[tindex[,1],notOther], sig=sg[notOther,notOther], beta = Rmat[,notOther], PRIOR = LPRIOR, rows = Rrows, pattern = Rpattern, lo = loRmat, hi = hiRmat, sinv = sinv, wF = wL) mug[tindex[,1],] <- Vmat[tindex[,1],]%*%Rmat mug[timeLast,] <- Vmat[drop=F, timeLast,]%*%Rmat muw <- muw + mug } if(termA){ Y <- w[,notOther] Y[tindex[,1],] <- Y[tindex[,2],] - w[tindex[,1],] if(termR) Y <- Y - mug[,notOther] if(termB) Y <- Y - mub[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] Amat[,notOther] <- updateBeta(X = Umat[tindex[,1],], Y = Y[tindex[,1],], sig=sg[notOther,notOther], beta = Amat[,notOther], PRIOR = TRUE, lo=loAmat[,notOther], hi=hiAmat[,notOther], rows = Arows, pattern = Apattern, sinv = sinv, wF = wA) mua[tindex[,1],] <- Umat[tindex[,1],]%*%Amat mua[timeLast,] <- Umat[drop=F, timeLast,]%*%Amat muw[,notOther] <- muw[,notOther] + mua[,notOther] } } if( TIME | BPRIOR ){ W <- w if(TIME){ W[tindex[,1],] <- W[tindex[,2],] - w[tindex[,1],] SS <- crossprod(W[tindex[,1],notOther] - muw[tindex[,1],notOther]) }else{ SS <- crossprod(W[,notOther] - muw[,notOther]) } SI <- solveRcpp(SS) }else{ Y <- w[inSamp,notOther] if(RANDOM)Y <- Y - groupRandEff[inSamp,notOther] XIXXX <- x[inSamp,]%*%solveRcpp( crossprod(x[inSamp,]) )%*%t(x[inSamp,] ) XUV <- t(Y)%*%XIXXX%*%Y SI <- solve( crossprod(Y) - XUV ) } sinv <- .rwish(sigmaDf, SI) sg[notOther,notOther] <- solveRcpp(sinv) sgibbs[g,] <- sg[Kindex] } if(termB)alphaB <- .sqrtMatrix(bg, sg, DIVIDE=T) if( 'OC' %in% typeCode ){ tg <- .updateTheta(w,tg,cutLo,cutHi,ordCols, holdoutN,holdoutIndex,minOrd,maxOrd) if(TIME){ cutg <- tg }else{ cutg <- .gjamCuts2theta(tg,ss = sg[ordCols,ordCols]) } breakMat[ordCols,1:lastOrd] <- cutg cgibbs[g,] <- as.vector( cutg[,-c(1,2,ncut)] ) plo[,ordCols] <- cutg[cutLo] phi[,ordCols] <- cutg[cutHi] } if(RANDOM){ cw <- w - muw if( TIME ){ cw[tindex[,1],] <- w[tindex[,2],] - w[tindex[,1],] - muw[tindex[,2],] } if(REDUCT){ cw <- cw - rndEff v <- 1/sigmaerror*.byGJAM(as.vector(cw), randGroupIndex[,1], randGroupIndex[,2], alphaRandGroup*0, fun='sum')[notOther,] sinv <- diag(1/sigmaerror, SO) }else{ v <- .byGJAM(as.vector(cw), randGroupIndex[,1], randGroupIndex[,2], alphaRandGroup*0, fun='sum')[notOther,] v <- sinv%*%v } alphaRandGroup[notOther,] <- randEffRcpp(v, randGroupTab, sinv, CImat) if(length(other) > 0)alphaRandGroup[other,] <- 0 if(g < 10){ alphaRandGroup[notOther,] <- sweep( alphaRandGroup[notOther,], 2, colMeans(alphaRandGroup[notOther,]), '-') } SS <- crossprod(t(alphaRandGroup[notOther,])) SS <- S*SS + Cmat testv <- try( chol(SS) ,T) if( inherits(testv,'try-error') ){ tiny <- .01*diag(SS) SS <- SS + diag(diag(SS + tiny)) } Ckeep[notOther,notOther] <- .riwish( df = S*G + 1, SS ) CImat <- solveRcpp(Ckeep[notOther,notOther]) alphaVarGibbs[g,] <- Ckeep[Aindex] groupRandEff <- t(alphaRandGroup)[groupIndex,] } if(TIME){ tmp <- .updateW(w, plo, phi, wpropTime, xl, yp, Rmat, Amat, rndEff, groupRandEff, sdg, muw, mub, Umat, Vmat, sinv) w <- tmp$w; muw <- tmp$muw; yp <- tmp$yp; Umat <- tmp$Umat; Vmat <- tmp$Vmat groups <- NULL for(k in allTypes){ wk <- which(typeCols == k) nk <- length(wk) wo <- which(wk %in% notOther) wu <- which(typeCols[notOther] == k) wp <- w[, wk, drop=F] yp <- yp[, wk, drop=F] yy <- y[,wk,drop=F] if(typeFull[wk[1]] == 'countComp')groups <- CCgroups if(typeFull[wk[1]] == 'fracComp')groups <- FCgroups if(typeFull[wk[1]] == 'categorical')groups <- CATgroups glist <- list(wo = wo, type = typeFull[wk[1]], yy = yy, wq = wp, yq = yp, cutg = cutg, censor = censor, censorCA = censorCA, censorDA = censorDA, censorCON = censorCON, eff = effMat[,wk,drop=F], groups = groups, k = k, typeCols = typeCols, notOther = notOther, wk = wk, sampW = sampleW[,wk]) tmp <- .gjamWLoopTypes( glist ) w[,wk] <- tmp[[1]] yp[,wk] <- tmp[[2]] } if( ncol(x) > 1 ){ ww <- w ww[ww < 0] <- 0 xtmp <- xpred xtmp[,-1] <- .tnorm(n*Qall, -3, 3, xpred[,-1], .1) if( length(linFactor) > 0 ){ for(k in 1:length(linFactor)){ mm <- linFactor[[k]] wcol <- sample(mm,n,replace=T) xtmp[,mm[-1]] <- 0 xtmp[ cbind(1:n, wcol) ] <- 1 } } if(length(intMat) > 0){ xtmp[,intMat[,1]] <- xtmp[,intMat[,2]]*xtmp[,intMat[,3]] } muNow <- muNew <- w*0 + rndEff if(termB){ muNow[,notOther] <- muNow[,notOther] + xpred[,xnames]%*%bg[,notOther] muNew[,notOther] <- muNew[,notOther] + xtmp[,xnames]%*%bg[,notOther] } if(termA){ mua <- Umat%*%Amat muNow[,notOther] <- muNow[,notOther] + mua[,notOther] muNew[,notOther] <- muNew[,notOther] + mua[,notOther] } if(termR){ Vnow <- Vnew <- Vmat Vnow[tindex[,1],] <- ww[drop = FALSE,tindex[,1],gindex[,'colW']]* xpred[drop = FALSE,tindex[,1],xlnames][drop = FALSE,,gindex[,'rowG']] mugNow <- Vnow%*%Rmat muNow[,notOther] <- muNow[,notOther] + mugNow[,notOther] Vnew[tindex[,1],] <- ww[drop = FALSE,tindex[,1],gindex[,'colW']]* xtmp[drop = FALSE,tindex[,1],xlnames][drop = FALSE,,gindex[,'rowG']] mugNew <- Vnew%*%Rmat muNew[,notOther] <- muNew[,notOther] + mugNew[,notOther] } ww <- w ww[tindex[,1],] <- ww[tindex[,2],] - ww[tindex[,1],] ww[timeZero,] <- ww[timeZero+1,] ww[timeLast,] <- ww[timeLast-1,] if(REDUCT){ pnow <- dnorm(ww[,notOther],muNow[,notOther],sdg,log=T) pnew <- dnorm(ww[,notOther],muNew[,notOther],sdg,log=T) a1 <- exp( rowSums(pnew - pnow) ) }else{ pnow <- .dMVN(ww[,notOther],muNow[,notOther],smat=sg,log=T) pnew <- .dMVN(ww[,notOther],muNew[,notOther],smat=sg,log=T) a1 <- exp(pnew - pnow) } z <- runif(length(a1),0,1) za <- which(z < a1) if(length(za) > 0){ xpred[za,] <- xtmp[za,] } if(termR){ if(nlmiss > 0)xl[xlmiss] <- xpred[,colnames(xl)][xlmiss] } if(nmiss > 0){ x[xmiss] <- xpred[xmiss] xf <- NULL if(length(facNames) > 0){ xf <- xdata[, facNames, drop=F] } tmp <- .getUnstandX(formula, x, standRows, standMatMu[,1], standMatSd[,1], factorColumns = xf ) S2U <- tmp$S2U XX <- crossprod(x) IXX <- solveRcpp(XX) } } }else{ tmp <- .updateW( rows=1:n, x, w, y, bg, sg, alpha=alphaB, cutg, plo, phi, rndEff, groupRandEff, sigmaerror, wHold ) w <- tmp$w yp <- tmp$yp wHold <- tmp$wHold Y <- w[,notOther] if(holdoutN > 0) Y[holdoutIndex,] <- wHold[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] if(nmiss > 0){ x[xmiss] <- .imputX_MVN(x,Y,bg[,notOther],xmiss,sinv,xprior=xprior, xbound=xbound)[xmiss] if( length(standRows) > 0 ){ xf <- NULL if(length(facNames) > 0){ xf <- xdata[, facNames, drop=F] } tmp <- .getUnstandX( formula, x, standRows, standMatMu[,1], standMatSd[,1], factorColumns = xf ) S2U <- tmp$S2U XX <- crossprod(x) IXX <- solveRcpp(XX) } } if( PREDICTX & length(predXcols) > 0 ){ if( length(interBeta$isNonLinX) > 0 ){ xpred <- .predictY2X_nonLinear(xpred, yy=Y, bb=bg[,notOther], ss=sg[notOther,notOther], priorIV = priorXIV, priorX=priorX, factorObject = factorBeta, interObject = interBeta, lox, hix, propx)$x } if( length(px) > 0 ){ wn <- which(!is.finite(xpred),arr.ind=T) if(length(wn) > 0){ tmp <- matrix(priorX,Q,nrow(wn)) xpred[wn[,1],] <- t(tmp) } xpred[,px] <- .predictY2X_linear(xpred, yy=Y, bb=bg[,notOther], ss=sg[notOther,notOther], sinv = sinv, priorIV = priorXIV, priorX=priorX, predCols=px, REDUCT=REDUCT, lox, hix, propx)[,px] wn <- which(!is.finite(xpred),arr.ind=T) if(length(wn) > 0){ tmp <- matrix(priorX,Q,nrow(wn)) xpred[wn[,1],] <- t(tmp) } } if( length(factorBeta$linFactor) > 0 ){ xtmp <- xpred xtmp[,factorBeta$findex] <- .predictY2X_linear(xpred, yy=Y, bb=bg[,notOther], ss=sg[notOther,notOther], sinv = sinv, priorIV = priorXIV, priorX=priorX,predCols=factorBeta$findex, REDUCT=REDUCT, lox, hix, propx)[,factorBeta$findex] for(k in 1:length(factorBeta$linFactor)){ mm <- factorBeta$linFactor[[k]] tmp <- xtmp[,mm] tmp[,1] <- 0 ix <- apply(tmp,1,which.max) tmp <- tmp*0 tmp[ cbind(1:n,ix) ] <- 1 tmp <- tmp[,-1,drop=F] xpred[,mm[-1]] <- tmp } } xpred[,1] <- 1 } } setTxtProgressBar(pbar,g) if(termR){ rho[ gindex[,c('rowG','colW')]] <- Rmat[wL] lgibbs[g,] <- Rmat[wL] rhoU <- Rmat } if(termA)alphaGibbs[g,] <- Amat[wA] if(termB)bgibbs[g,] <- bg[wB] if( length(standRows) > 0 ){ if(termB){ bgU <- S2U%*%bg bgibbsUn[g,] <- bgU[wB] } } if( TIME ){ if(termR & length(standRowsL) > 0){ if(ncol(xl) > 1){ Vunst <- Vmat wz <- w wz[wz < 0] <- 0 vww <- wz[drop = FALSE,tindex[,1],gindex[,'colW']]* xlUnstand[drop = FALSE,tindex[,1],xlnames][drop = FALSE,,gindex[,'rowG']] Vunst[tindex[,1],] <- vww Y <- w[,notOther] Y[tindex[,1],] <- Y[tindex[,2],] - w[tindex[,1],] if(termA) Y <- Y - mua[,notOther] if(termB) Y <- Y - mub[,notOther] if(RANDOM)Y <- Y - groupRandEff[,notOther] sig <- sigmaerror if(!REDUCT) sig <- sg[notOther,notOther] RmatU[,notOther] <- updateBeta(X = Vunst[tindex[,1],], Y = Y[tindex[,1],notOther], sig = sig, beta = RmatU[,notOther], PRIOR = LPRIOR, rows = Rrows, pattern = Rpattern, lo = loRmat, hi = hiRmat, sinv = sinv, wF = wL) lgibbsUn[g,] <- RmatU[wL] } } } if( TRAITS ){ Atrait <- bg%*%t(specTrait[,colnames(yp)]) Strait <- specTrait[,colnames(yp)]%*%sg%*%t(specTrait[,colnames(yp)]) bTraitGibbs[g,] <- Atrait mgibbs[g,] <- Strait minv <- ginv(Strait) tmp <- .contrastCoeff(beta=Atrait, notStand = notStandard[notStandard %in% xnames], sigma = Strait, sinv = minv, stand = standMatSd, factorObject=factorBeta ) tagg <- tmp$ag bTraitFacGibbs[g,] <- tagg } if( termB ){ nst <- notStandard[notStandard %in% xnames] stm <- standMatSd if(TIME){ nst <- notStandardB[notStandard %in% xnames] stm <- standMatSdB } tmp <- .contrastCoeff(beta=bg[,notOther], notStand = nst, sigma = sg[notOther,notOther], sinv = sinv, stand = stm, factorObject=factorBeta ) agg <- tmp$ag beg <- tmp$eg fsens <- tmp$sens fsens[ fsens < 1e-12 ] <- 0 fSensGibbs[g,] <- sqrt(diag(fsens))[fbnames] bFacGibbs[g,] <- agg } if(FULL)ygibbs[g,] <- as.vector(yp) if(g > burnin){ ntot <- ntot + 1 ypred <- ypred + yp ypred2 <- ypred2 + yp^2 mpr <- x[inSamp,]%*%bg[,notOther] wpr <- matrix( colMeans( w[inSamp, notOther] ), length(inSamp), length(notOther), byrow = T ) vtot <- diag( var(w[inSamp,notOther]) ) mtot <- diag( var(mpr)) rss <- diag( crossprod( w[inSamp,notOther] - mpr ) ) tss <- diag( crossprod( w[inSamp,notOther] - wpr ) ) vexp <- 1 - rss/tss varExp <- varExp + vexp varTot <- varTot + vtot varExpMean <- varExpMean + mtot/vtot if(RANDOM){ itot <- diag(var(groupRandEff[inSamp,notOther])) varExpRand <- varExpRand + itot/vtot } tmp <- .dMVN(w[,notOther], muw[,notOther], sg[notOther,notOther], log=T) sumDev <- sumDev - 2*sum(tmp) yerror <- yerror + (yp - y)^2 if(termB)fmat <- fmat + fsens sMean <- sMean + sg wpred <- wpred + w wpred2 <- wpred2 + w^2 if(RICHNESS){ yy <- yp if('PA' %in% typeNames){ wpa <- which(typeNames[inRichness] == 'PA') yy[,inRichness[wpa]] <- round(yp[,inRichness[wpa]]) } if(length(notPA) > 0){ w0 <- which(yy[,notPA] <= 0) w1 <- which(yy[,notPA] > 0) yy[,notPA][w0] <- 0 yy[,notPA][w1] <- 1 } shan <- sweep(yp[,inRichness], 1, rowSums(yp[,inRichness]), '/') shan[shan == 0] <- NA shan <- -rowSums(shan*log(shan),na.rm=T) shannon <- shannon + shan wpp <- which(yy > 0) ypredPres[wpp] <- ypredPres[wpp] + yp[wpp] ypredPres2[wpp] <- ypredPres2[wpp] + yp[wpp]^2 ypredPresN[wpp] <- ypredPresN[wpp] + 1 presence[,inRichness] <- presence[,inRichness] + yy[,inRichness] ones <- round(rowSums(yy[,inRichness])) more <- round(rowSums(yy[,inRichness]*wrich[,inRichness,drop=F])) richFull <- .add2matrix(ones,richFull) richness <- .add2matrix(more,richness) } if(RANDOM){ alphaRanSums <- alphaRanSums + alphaRandGroup alphaRanSums2 <- alphaRanSums2 + alphaRandGroup^2 } if(mmiss > 0){ ymissPred[ymiss] <- ymissPred[ymiss] + y[ymiss] ymissPred2[ymiss] <- ymissPred2[ymiss] + y[ymiss]^2 } if(nmiss > 0){ xmissSum <- xmissSum + x[xmiss] xmissSum2 <- xmissSum2 + x[xmiss]^2 } if(PREDICTX & length(predXcols) > 0){ predx <- predx + xpred predx2 <- predx2 + xpred^2 } wa0 <- numeric(0) if( !TIME | (TIME & termB) ){ ag <- agg cx <- t(ag)%*%covE%*%ag ess[notOther,notOther] <- ess[notOther,notOther] + cx esd <- sqrt(diag(cx)) esens1[notOther] <- esens1[notOther] + esd esens2[notOther] <- esens2[notOther] + esd^2 } if( termR){ if(ncol(xl) > 1 ){ covL <- cov(Vmat) cp <- t(Rmat[,notOther,drop=F])%*%covL%*%Rmat[,notOther,drop=F] essL[notOther,notOther] <- essL[notOther,notOther] + cp lsd <- sqrt(diag(cp)) lsens1[notOther] <- lsens1[notOther] + lsd lsens2[notOther] <- lsens2[notOther] + lsd^2 } } if(termA){ covw <- cov(Umat) ca <- t(Amat[,notOther])%*%covw%*%Amat[,notOther] essA[notOther,notOther] <- essA[notOther,notOther] + ca asd <- sqrt(diag(ca)) asens1[notOther] <- asens1[notOther] + asd asens2[notOther] <- asens2[notOther] + asd^2 } loESS[ ess < 0 ] <- loESS[ ess < 0 ] + 1 hiESS[ ess > 0 ] <- hiESS[ ess > 0 ] + 1 eii <- ginv(ess[notOther,notOther]) lmESS[notOther,notOther][ eii < 0 ] <- lmESS[notOther,notOther][ eii < 0 ] + 1 hmESS[notOther,notOther][ eii > 0 ] <- hmESS[notOther,notOther][ eii > 0 ] + 1 if(REDUCT){ rndTot <- rndTot + rndEff rndTot2 <- rndTot2 + rndEff^2 } if(TRAITS){ yw <- sweep(yp,1,rowSums(yp),'/') yw[yw <= 0] <- 0 yw[is.na(yw)] <- 0 Ttrait <- .gjamPredictTraits(yw,specTrait[,colnames(yp)], traitTypes) tpred <- tpred + Ttrait tpred2 <- tpred2 + Ttrait^2 } } } otherpar$S <- S otherpar$Q <- Q otherpar$snames <- snames otherpar$xnames <- xnames presence <- presence/ntot if(RICHNESS){ missRows <- sort(unique(ymiss[,1])) richNonMiss <- richness/ntot yr <- as.matrix(ydata[,inRichness]) yr[yr > 0] <- 1 yr <- rowSums(yr,na.rm=T) vv <- matrix(as.numeric(colnames(richNonMiss)),n, ncol(richNonMiss),byrow=T) rmu <- rowSums( vv * richNonMiss )/rowSums(richNonMiss) rsd <- sqrt( rowSums( vv^2 * richNonMiss )/rowSums(richNonMiss) - rmu^2) vv <- matrix(as.numeric(colnames(richFull)),n,ncol(richFull),byrow=T) rfull <- rowSums( vv * richFull )/rowSums(richFull) rfull[missRows] <- NA rmu <- rowSums(presence) shan <- sweep(y[,inRichness], 1, rowSums(y[,inRichness]), '/') shan[shan == 0] <- NA shanObs <- -rowSums(shan*log(shan),na.rm=T) richness <- cbind(yr, rmu, rsd, rfull, shanObs, shannon/ntot ) colnames(richness) <- c('obs','predMu','predSd','predNotMissing', 'H_obs', 'H_pred') if(TIME)richness[timeZero,] <- NA ypredPresMu <- ypredPres/ypredPresN ypredPresMu[ypredPresN == 0] <- 0 yvv <- ypredPres2/ypredPresN - ypredPresMu^2 yvv[ !is.finite(yvv) | yvv <= 0 ] <- 0 ypredPresSe <- sqrt(yvv) } if('OC' %in% typeNames){ ordMatShift <- matrix(ordShift,n,length(ordCols),byrow=T) onames <- snames[ordCols] wb <- match(paste(onames,'intercept',sep='_'), colnames(bgibbs)) bgibbs[,wb] <- bgibbs[,wb] + matrix(ordShift,ng,length(ordCols),byrow=T) if( !is.null(bgibbsUn)){ bgibbsUn[,wb] <- bgibbsUn[,wb] + matrix(ordShift,ng,length(ordCols),byrow=T) } y[,ordCols] <- y[,ordCols] + ordMatShift } if(mmiss > 0){ ymissPred[ymiss] <- ymissPred[ymiss]/ntot yd <- ymissPred2[ymiss]/ntot - ymissPred[ymiss]^2 yd[!is.finite(yd)| yd < 0] <- 0 ymissPred2[ymiss] <- sqrt(yd) if('OC' %in% typeNames){ ymissPred[,ordCols] <- ymissPred[,ordCols] + ordMatShift } } rmspeBySpec <- sqrt( colSums(yerror)/ntot/n ) rmspeAll <- sqrt( sum(yerror)/ntot/n/S ) sMean <- sMean/ntot varExp <- varExp/ntot varTot <- varTot/ntot varMu <- varExpMean/ntot varRn <- varExpRand/ntot varMod <- varMu + varRn if(termB){ tmp <- .chain2tab(bgibbs[burnin:ng,], snames, xnames, wF = wB) betaStandXmu <- tmp$mu betaStandXse <- tmp$se betaStandXTable <- tmp$tab tmp <- .chain2tab(bFacGibbs[burnin:ng,], snames[notOther], rownames(agg)) betaStandXWmu <- tmp$mu betaStandXWse <- tmp$se betaStandXWTable <- tmp$tab if(!is.null(loB)){ blo <- as.vector( t(loB) ) bhi <- as.vector( t(hiB) ) names(blo) <- names(bhi) <- bf bprior <- cbind(blo[rownames(betaStandXTable)], bhi[rownames(betaStandXTable)]) colnames(bprior) <- c('priorLo','priorHi') betaStandXTable <- cbind(betaStandXTable[,1:4], bprior) } if( length(standRows) > 0 ){ tmp <- .chain2tab(bgibbsUn[burnin:ng,], snames, xnames, wF = wB) betaMu <- tmp$mu betaSe <- tmp$se betaTable <- tmp$tab }else{ betaMu <- betaStandXmu betaSe <- betaStandXse betaTable <- betaStandXTable betaWMu <- betaStandXWmu betaWSe <- betaStandXWse betaWTable <- betaStandXWTable betaStandXmu <- betaStandXse <- betaStandXTable <- NULL betaStandXWmu <- betaStandXWse <- betaStandXWTable <- NULL } tmp <- .chain2tab(fSensGibbs[burnin:ng,,drop=F]) sensTable <- tmp$tab[,1:4] } if(TIME){ if(termR){ RmatStandXmu <- RmatStandXse <- Rmat*0 rhoMu <- rhoSe <- rhoTable <- NULL loL <- loRmat[wL] hiL <- hiRmat[wL] tmp <- .chain2tab(lgibbs[drop = FALSE, burnin:ng,], snames[notOther], xlnames, sigfig = 4) rhoStandXmu <- tmp$mu rhoStandXse <- tmp$se rhoStandXTable <- data.frame( rownames(tmp$tab), tmp$tab[,1:4], stringsAsFactors = F) rlo <- loRmat[wL] rhi <- hiRmat[wL] rprior <- cbind(rlo, rhi) rownames(rprior) <- rownames(wL) colnames(rprior) <- c('priorLo','priorHi') rhoStandXTable <- cbind( rhoStandXTable[,1:5], rprior[ rownames(rhoStandXTable), ]) rhoStandXTable[,1] <- .replaceString( rhoStandXTable[,1], '_', ', ') ss <- 'rho_{to, from}' colnames(rhoStandXTable)[1] <- ss rhoStandXTable <- rhoStandXTable[!rhoStandXmu == 0 & !rhoStandXse == 0, ] rownames(rhoStandXTable) <- NULL tmp <- .chain2tab(lgibbs[drop = FALSE, burnin:ng,], colnames(Rmat), rownames(Rmat), sigfig = 4) RmatStandXmu[ wL ] <- tmp$tab[,'Estimate'] RmatStandXse[ wL ] <- tmp$tab[,'SE'] if( ncol(xl) > 1 ){ Rmu <- Rmat*0 tmp <- .chain2tab(lgibbsUn[drop = FALSE, burnin:ng,], snames[notOther], xlnames, sigfig = 4) rhoMu <- tmp$mu rhoSe <- tmp$se rhoTable <- data.frame( rownames(tmp$tab), tmp$tab[,1:4], stringsAsFactors = F) rhoTable[,1] <- .replaceString( rhoTable[,1], '_', ', ') ss <- 'rho_{to, from}' colnames(rhoTable)[1] <- ss rownames(rhoTable) <- NULL rhoTable <- rhoTable[!rhoMu == 0 & !rhoSe == 0, ] }else{ lgibbsUn <- lgibbs rhoMu <- rhoStandXmu rhoSe <- rhoStandXse rhoTable <- rhoStandXTable } } if(termA){ ss <- matrix( as.numeric( columnSplit( colnames(alphaGibbs), '-' )), ncol = 2) ss <- matrix( snames[aindex[,c('toW','fromW')]], ncol=2) st <- columnPaste( ss[,1], ss[,2], ', ' ) tmp <- .chain2tab(alphaGibbs[drop = FALSE, burnin:ng,], ss[,1], ss[,2], sigfig = 4) alphaTable <- data.frame( st, tmp$tab[, 1:4], stringsAsFactors = F ) alo <- loAmat[wA] ahi <- hiAmat[wA] aprior <- cbind(alo, ahi) colnames(aprior) <- c('priorLo','priorHi') alphaTable <- cbind( alphaTable[,1:5], aprior) colnames(alphaTable)[1] <- 'alpha_{to, from}' loA <- matrix(0,S,S) rownames(loA) <- colnames(loA) <- snames hiA <- alphaMu <- alphaSe <- loA tmp1 <- colMeans(alphaGibbs[burnin:ng,]) tmp2 <- apply(alphaGibbs[burnin:ng,],2,sd) alphaMu[ aindex[,c('toW','fromW')] ] <- tmp1 alphaSe[ aindex[,c('toW','fromW')] ] <- tmp2 loA[ aindex[,c('toW','fromW')] ] <- loAmat[wA] hiA[ aindex[,c('toW','fromW')] ] <- hiAmat[wA] Amu <- Ase <- Amat*0 Amu[wA] <- tmp1 Ase[wA] <- tmp2 } } yMu <- ypred/ntot if('CA' %in% typeNames){ ytmp <- yMu[,'CA' %in% typeNames] ytmp[ ytmp < 0 ] <- 0 yMu[,'CA' %in% typeNames] <- ytmp } y22 <- ypred2/ntot - yMu^2 y22[y22 < 0] <- 0 ySd <- sqrt(y22) cMu <- cuts cSe <- numeric(0) wMu <- wpred/ntot wpp <- pmax(0,wpred2/ntot - wMu^2) wSd <- sqrt(wpp) if('OC' %in% typeNames){ yMu[,ordCols] <- yMu[,ordCols] + ordMatShift wMu[,ordCols] <- wMu[,ordCols] + ordMatShift } meanDev <- sumDev/ntot beta <- betaStandXmu if( is.null(beta) )beta <- betaMu beta[ is.na(beta) ] <- 0 if(!TIME){ muw <- x%*%beta[,notOther] tmp <- .dMVN(wMu[,notOther], muw, sMean[notOther,notOther], log=T) pd <- meanDev - 2*sum(tmp ) DIC <- pd + meanDev } yscore <- colSums( .getScoreNorm(y[,notOther],yMu[,notOther], ySd[,notOther]^2),na.rm=T ) xscore <- xpredMu <- xpredSd <- NULL standX <- xmissMu <- xmissSe <- NULL if(RANDOM){ ns <- 500 simIndex <- sample(burnin:ng,ns,replace=T) tmp <- .expandSigmaChains(snames, alphaVarGibbs, otherpar, simIndex=simIndex, sigErrGibbs, kgibbs, REDUCT=F, CHAINSONLY=F) alphaRandGroupVarMu <- tmp$sMu alphaRandGroupVarSe <- tmp$sSe alphaRandByGroup <- alphaRanSums/ntot a2 <- alphaRanSums2/ntot - alphaRandByGroup^2 a2[ a2 < 0 ] <- 0 alphaRandByGroupSe <- sqrt(a2) } if(PREDICTX){ xpredMu <- predx/ntot xpredSd <- predx2/ntot - xpredMu^2 xpredSd[xpredSd < 0] <- 0 xpredSd <- sqrt(xpredSd) if(!TIME){ xrow <- standRows xmu <- standMatMu[,1] xsd <- standMatSd[,1] }else{ if(termB | termR){ xrow <- numeric(0) if(termB){xrow <- standRows} if(termR){ xrow <- c( xrow, standRowsL ) ww <- !duplicated(names(xrow)) xrow <- names(xrow)[ww] xmu <- xsd <- numeric(0) if(termB){ xmu <- standMatMu[xrow,1] xsd <- standMatSd[xrow,1] } if(termR){ ww <- which(!rownames(standMatMuL) %in% names(xrow) ) ww <- ww[ ww != 1 ] if(length(ww) > 0){ xmu <- c(xmu, standMatMuL[ww,1]) xsd <- c(xsd,standMatSdL[ww,1]) } } } } } if( ncol(x) > 1 ){ xf <- NULL if(length(facNames) > 0){ xf <- xdata[, facNames, drop=F] } xpredMu <- .getUnstandX(formula, x = xpredMu, xrow, xmu = xmu, xsd = xsd, factorColumns = xf )$xu xpredSd[,xrow] <- xpredSd[,xrow]*matrix( xsd[xrow], n, length(xrow), byrow=T ) } if(Q == 2)xscore <- mean( .getScoreNorm(x[,2], xpredMu[,2],xpredSd[,2]^2) ) if(Q > 2)xscore <- colMeans(.getScoreNorm(x[,-1], xpredMu[,-1],xpredSd[,-1]^2) ) if(TIME){ wz <- muw <- wMu wz[wz < 0] <- 0 if(termB){ muw <- x[,rownames(beta)]%*%beta[,notOther] } if(termR){ Vmat[tindex[,2],] <- wz[tindex[,2], gindex[,'colW']]*xl[tindex[,2], gindex[,'colX']] Vmat[timeZero,] <- wz[timeZero, gindex[,'colW']]*xl[timeZero, gindex[,'colX']] Rmat[ gindex[,c('rowL','colW')] ] <- RmatStandXmu[ gindex[,c('rowG','colW')] ] muw <- muw + Vmat%*%Rmat[,notOther] } if(termA){ Umat <- wz[,uindex[,1]]*wz[,uindex[,2]] Amat[ wA ] <- alphaMu[ aindex[,c('toW','fromW')] ] muw <- muw + Umat%*%Amat[,notOther] } } } tmp <- .dMVN(wMu[,notOther],muw, sMean[notOther,notOther], log=T ) pd <- meanDev - 2*sum(tmp ) DIC <- pd + meanDev if(termB){ if(nmiss > 0){ xmissMu <- xmissSum/ntot xmissSe <- sqrt( xmissSum2/ntot - xmissMu^2 ) } } if(length(standRows) > 0){ standX <- cbind(standMatMu[,1],standMatSd[,1]) colnames(standX) <- c('xmean','xsd') rownames(standX) <- rownames(standMatSd) } ns <- 200 simIndex <- sample(burnin:ng,ns,replace=T) tmp <- .expandSigmaChains(snames, sgibbs, otherpar, simIndex=simIndex, sigErrGibbs, kgibbs, REDUCT, CHAINSONLY=F, verbose) corMu <- tmp$rMu; corSe <- tmp$rSe sigMu <- tmp$sMu; sigSe <- tmp$sSe whichZero <- which(loESS/ntot < ematAlpha & hiESS/ntot < ematAlpha,arr.ind=T) whConZero <- which(lmESS/ntot < ematAlpha & hmESS/ntot < ematAlpha,arr.ind=T) if( !TIME | (TIME & termB) ){ ematrix <- ess/ntot fmatrix <- fmat/ntot sensBetaMu <- esens1/ntot sensBetaSe <- sqrt( esens2/ntot - sensBetaMu^2 ) sensBeta <- cbind( sensBetaMu, sensBetaSe ) colnames(sensBeta) <- c('Estimate', 'SE') rownames(sensBeta) <- colnames(y) } if(termR){ if(ncol(xl) > 1){ ematrixL <- essL/ntot sensRhoMu <- lsens1/ntot sensRhoSe <- sqrt( lsens2/ntot - sensRhoMu^2 ) sensRho <- cbind( sensRhoMu, sensRhoSe ) colnames(sensRho) <- c('Estimate', 'SE') rownames(sensRho) <- colnames(y) } } if(termA){ ematrixA <- essA/ntot sensAlphaMu <- asens1/ntot sensAlphaSe <- sqrt( asens2/ntot - sensAlphaMu^2 ) sensAlpha <- cbind( sensAlphaMu, sensAlphaSe ) colnames(sensAlpha) <- c('Estimate', 'SE') rownames(sensAlpha) <- colnames(y) } tMu <- tSd <- tMuOrd <- btMu <- btSe <- stMu <- stSe <- numeric(0) if(TRAITS){ tMu <- tpred/ntot tSd <- sqrt(tpred2/ntot - tMu^2) wo <- which(traitTypes == 'OC') M <- ncol(tMu) if(length(wo) > 0){ tMuOrd <- tMu*0 for(j in wo)tMuOrd[,j] <- round(tMu[,j],0) - 1 tMuOrd <- tMuOrd[,wo] } tmp <- .chain2tab(bTraitGibbs[burnin:ng,], tnames, xnames) betaTraitXMu <- tmp$mu betaTraitXTable <- tmp$tab tmp <- .chain2tab(mgibbs[burnin:ng,], tnames, tnames) varTraitMu <- tmp$mu varTraitTable <- tmp$tab tmp <- .chain2tab(bTraitFacGibbs[burnin:ng,], tnames, rownames(tagg) ) betaTraitXWmu <- tmp$mu betaTraitXWTable <- tmp$tab } if('OC' %in% typeNames){ nk <- length(ordCols) nc <- ncut - 3 os <- rep(ordShift,nc) cgibbs <- cgibbs + matrix(os,ng,length(os),byrow=T) tmp <- .processPars(cgibbs)$summary cMu <- matrix(tmp[,'estimate'],nk,nc) cSe <- matrix(tmp[,'se'],nk,ncut-3) cMu <- cbind(ordShift,cMu) cSe <- cbind(0,cSe) colnames(cMu) <- colnames(cSe) <- cnames[-c(1,ncut)] rownames(cMu) <- rownames(cSe) <- snames[ordCols] breakMat[ordCols,c(2:(2+(ncol(cMu))-1))] <- cMu } if('PA' %in% typeNames){ zMu <- yMu zSd <- ySd } varContribution <- signif(rbind(varTot, varMu, varExp, varRn, varMod), 3) rownames(varContribution) <- c('total variance', 'mean fraction','R2', 'RE fraction', 'mean + RE fraction') if(!RANDOM)varContribution <- varContribution[1:3,] if(length(reductList) == 0)reductList <- list(N = 0, r = 0) reductList$otherpar <- otherpar modelList$effort <- effort; modelList$formula <- formula modelList$typeNames <- typeNames; modelList$censor <- censor modelList$effort <- effort; modelList$holdoutIndex <- holdoutIndex modelList$REDUCT <- REDUCT; modelList$TRAITS <- TRAITS modelList$ematAlpha <- ematAlpha; modelList$traitList <- traitList modelList$reductList <- reductList; modelList$ng <- ng modelList$burnin <- burnin inputs <- list(xdata = xdata, xStand = x, xUnstand = xUnstand, xnames = xnames, effMat = effMat, y = y, notOther = notOther, other = other, breakMat = breakMat, classBySpec = classBySpec, RANDOM = RANDOM) missing <- list(xmiss = xmiss, xmissMu = xmissMu, xmissSe = xmissSe, ymiss = ymiss, ymissMu = ymissPred, ymissSe = ymissPred2) parameters <- list(corMu = corMu, corSe = corSe, sigMu = sigMu, sigSe = sigSe, whichZero = whichZero, whConZero = whConZero, wMu = wMu, wSd = wSd) prediction <- list(presence = presence, xpredMu = xpredMu, xpredSd = xpredSd, ypredMu = yMu, ypredSd = ySd, richness = richness) chains <- list(sgibbs = sgibbs) fit <- list(DIC = DIC, yscore = yscore, xscore = xscore, rmspeAll = rmspeAll, rmspeBySpec = rmspeBySpec, fractionExplained = varContribution ) parXS <- 'standardized for X' parXU <- 'unstandardized for X' parWS <- 'correlation scale for W' parWU <- 'variance scale for W' parXF <- 'centered factors' parSep <- ', ' getDescription <- function( nlist, words ){ out <- numeric(0) nm <- character(0) for(k in 1:length(nlist)){ vk <- get( nlist[k] ) if(is.null(vk))next attr( vk, 'description') <- words out <- append( out, list(assign( nlist[k], vk )) ) nm <- c( nm, nlist[k]) } names(out) <- nm out } if( !TIME | (TIME & termB) ){ nlist <- c( 'ematrix', 'fmatrix' ) words <- paste( parXS, parWS, parXF, sep=parSep) tlist <- getDescription( nlist, words ) for( k in 1:length(tlist) ) assign( names(tlist)[k], get( names(tlist[k]) ) ) parameters <- c(parameters, list(ematrix = ematrix, fmatrix = fmatrix, sensBeta = sensBeta)) } if(termB){ nlist <- c('betaMu', 'betaSe', 'betaTable', 'bgibbsUn' ) words <- paste( parXU, parWU, sep=parSep) tlist <- getDescription( nlist, words ) for( k in 1:length(tlist) ) assign( names(tlist)[k], get( names(tlist[k]) ) ) nlist <- c('betaStandXmu', 'betaStandXTable', 'bgibbs') words <- paste( parXU, parWU, sep=parSep ) tlist <- getDescription( nlist, words ) for( k in 1:length(tlist) ) assign( names(tlist)[k], get( names(tlist[k]) ) ) nlist <- c('betaStandXWmu', 'betaStandXWTable', 'sensTable', 'fSensGibbs', 'bFacGibbs' ) words <- paste( parXS, parWS, parXF, sep = parSep) tlist <- getDescription( nlist, words ) for( k in 1:length(tlist) ) assign( names(tlist)[k], get( names(tlist[k]) ) ) attr(sensBeta, 'description') <- parXS inputs <- c(inputs, list(standMatSd = standMatSd, standRows = standRows, standX = standX, notOther = notOther, other = other, designTable = designTable, factorBeta = factorBeta, interBeta = interBeta, linFactor = linFactor, intMat = intMat) ) chains <- c(chains, list(bgibbs = bgibbs, bgibbsUn = bgibbsUn, fSensGibbs = fSensGibbs, bFacGibbs = bFacGibbs) ) parameters <- c(parameters, list(betaMu = betaMu, betaSe = betaSe, betaTable = betaTable, betaStandXmu = betaStandXmu, betaStandXTable = betaStandXTable, betaStandXWmu = betaStandXWmu, betaStandXWTable = betaStandXWTable, sensTable = sensTable)) } if(FULL)chains <- append(chains, list(ygibbs = ygibbs)) if(RANDOM){ parameters <- append(parameters, list( randGroupVarMu = alphaRandGroupVarMu, randGroupVarSe = alphaRandGroupVarSe, randByGroupMu = alphaRandByGroup, randByGroupSe = alphaRandByGroupSe, groupIndex = groupIndex) ) } if(RICHNESS){ prediction <- append(prediction, list(yPresentMu = ypredPresMu, yPresentSe = ypredPresSe)) } if(REDUCT) { rndEffMu <- rndTot/ntot rndEffSe <- sqrt( rndTot2/ntot - rndEffMu^2) parameters <- append( parameters, list(rndEffMu = rndEffMu, rndEffSe = rndEffSe) ) chains <- append( chains, list(kgibbs = kgibbs, sigErrGibbs = sigErrGibbs) ) } if('OC' %in% typeNames){ parameters <- c(parameters,list(cutMu = cMu, cutSe = cSe)) chains <- c(chains,list(cgibbs = cgibbs)) modelList <- c(modelList,list(yordNames = yordNames)) } if(TRAITS){ parameters <- c(parameters, list(betaTraitXMu = betaTraitXMu, betaTraitXTable = betaTraitXTable, varTraitMu = varTraitMu, varTraitTable = varTraitTable, betaTraitXWmu = betaTraitXWmu, betaTraitXWTable = betaTraitXWTable)) prediction <- c(prediction, list(tMuOrd = tMuOrd, tMu = tMu, tSe = tSd)) chains <- append( chains,list(bTraitGibbs = bTraitGibbs, bTraitFacGibbs = bTraitFacGibbs, mgibbs = mgibbs) ) } if(TIME){ inputs <- c(inputs, list(timeList = timeList)) if(termB){ parameters <- c(parameters, list(wB = wB, tindex = tindex)) } if(termR){ nlist <- c('lgibbs', 'rhoStandXmu', 'rhoStandXse', 'rhoStandXTable') tlist <- getDescription( nlist, words = parXS ) for( k in 1:length(tlist) ) assign( names(tlist)[k], get( names(tlist[k]) ) ) nlist <- c('lgibbsUn', 'rhoMu', 'rhoSe', 'rhoTable') tlist <- getDescription( nlist, words = parXU ) for( k in 1:length(tlist) ) assign( names(tlist)[k], get( names(tlist[k]) ) ) inputs <- c(inputs, list(xlnames = xlnames, xRho = xl, interRho = interRho, factorRho = factorRho)) chains <- c(chains, list(lgibbs = lgibbs, lgibbsUn = lgibbsUn)) parameters <- c(parameters, list(gindex = gindex, rhoMu = rhoMu, rhoSe = rhoSe, rhoStandXmu = rhoStandXmu, rhoStandXse = rhoStandXse, rhoTable = rhoTable, rhoStandXTable = rhoStandXTable, RmatStandXmu = RmatStandXmu, RmatStandXse = RmatStandXse, rhoLo = loL, rhoHi = hiL, wL = wL)) if(ncol(xl) > 1){ attr(ematrixL, 'description') <- attr(sensRho, 'description') <- parXS parameters <- c(parameters, list(ematrixL = ematrixL, sensRho = sensRho)) } } if(termA){ chains <- c(chains, list(alphaGibbs = alphaGibbs)) parameters <- c(parameters, list(alphaTable = alphaTable, alphaMu = signif(alphaMu, 4), alphaSe = signif(alphaSe, 4), Amu = signif(Amu, 4), Ase = signif(Ase, 4), alphaLo = loA, alphaHi = hiA, aindex = aindex, wA = wA, uindex = uindex, ematrixA = ematrixA, sensAlpha = sensAlpha, alphaEigen = eigen(alphaMu)$values)) } } chains <- chains[ sort( names(chains) )] fit <- fit[ sort( names(fit) )] inputs <- inputs[ sort( names(inputs) )] missing <- missing[ sort( names(missing) )] modelList <- modelList[ sort( names(modelList) )] parameters <- parameters[ sort( names(parameters) )] prediction <- prediction[ sort( names(prediction) )] all <- list(chains = chains, fit = fit, inputs = inputs, missing = missing, modelList = modelList, parameters = parameters, prediction = prediction) all$call <- match.call() all <- all[ sort(names(all)) ] class(all) <- "gjam" all } designFull <- function( form, xdata ){ n <- nrow(xdata) tmp <- model.frame( form, xdata) terms <- attributes( tmp )$terms xnames <- attr( terms, 'term.labels' ) facts <- which( attr( terms,'dataClasses' ) == 'factor' ) ints <- grep(':', xnames) xfull <- numeric(0) for(k in 1:ncol(tmp)){ if( !k %in% facts){ x <- matrix( tmp[,k], ncol = 1) colnames(x) <- colnames(tmp)[k] xfull <- cbind(xfull, x) next } levs <- levels(tmp[,k]) xk <- matrix(0, n, length(levs)) colnames(xk) <- paste(names(facts)[k], levs, sep='') mm <- match( as.character(tmp[,k]), levs ) xk[ cbind(1:n, mm) ] <- 1 xfull <- cbind(xfull, xk) } csum <- colSums(abs(xfull), na.rm=T) xfull <- xfull[,csum > 0] if(length(ints) > 0){ interactions <- numeric(0) for(k in ints){ xi <- columnSplit( xnames[k], ':' ) x1 <- which( startsWith(colnames(xfull), xi[1] ) ) x2 <- which( startsWith(colnames(xfull), xi[2] ) ) cnames <- outer( colnames(xfull)[x1], colnames(xfull)[x2], paste, sep=':' ) xint <- matrix(0, n, length(cnames)) colnames(xint) <- cnames for(i in x1){ for(j in x2){ ij <- paste( colnames(xfull)[i], colnames(xfull)[j], sep=':') xint[,ij] <- xfull[,i] * xfull[,j] } } interactions <- cbind(interactions, xint) } xfull <- cbind(xfull, interactions) } csum <- colSums(abs(xfull), na.rm=T) xfull <- xfull[,csum > 0] } .contrastCoeff <- function(beta, sigma, sinv, notStand, stand, factorObject, conditional=NULL){ SO <- ncol(beta) agg <- .sqrtMatrix(beta,sigma,DIVIDE=T) if(factorObject$nfact > 0){ agg <- factorObject$lCont%*%agg for(k in 1:factorObject$nfact){ f2 <- factorObject$facList2[[k]] fk <- paste(names(factorObject$facList2)[k],f2,sep='') amu <- colMeans(agg[drop=F,fk,]) nl <- length(fk) agg[fk,] <- agg[fk,] - matrix(amu,nl,SO,byrow=T) egg <- agg } } else { agg <- agg[drop=F,-1,] egg <- agg } if(is.null(conditional)){ sens <- egg%*%sinv%*%t(egg) }else{ con <- which(colnames(beta) %in% conditional) if( length(con) == 0 )stop( 'group must be in colnames(ydata)' ) nc <- c(1:SO)[-con] sg <- sigma[con,con] - sigma[con,nc]%*%solve(sigma[nc,nc])%*%sigma[nc,con] sens <- egg[,con]%*%solve(sg)%*%t(egg[,con]) } list(ag = agg, eg = egg, sens = sens) } .chain2tab <- function(chain, snames = NULL, xnn = NULL, wF = NULL, sigfig = 3){ mu <- colMeans(chain) SE <- apply(chain,2,sd) CI <- apply(chain,2,quantile,c(.025,.975)) splus <- rep('', length=length(SE)) splus[CI[1,] > 0 | CI[2,] < 0] <- '*' tab <- cbind( mu, SE, t(CI)) tab <- signif(tab, sigfig) colnames(tab) <- c('Estimate','SE','CI_025','CI_975') tab <- as.data.frame(tab) tab$sig95 <- splus attr(tab, 'note') <- '* indicates that zero is outside the 95% CI' mmat <- smat <- NULL if(!is.null(snames)){ Q <- length(xnn) S <- length(snames) mmat <- matrix(NA, Q, S) colnames(mmat) <- snames rownames(mmat) <- xnn smat <- mmat if(is.null(wF)){ wF <- 1:length(mmat) } mmat[ wF ] <- signif(mu, sigfig) smat[ wF ] <- signif(SE, sigfig) ww <- which(rowSums(mmat, na.rm=T) != 0) mmat <- mmat[drop = FALSE, ww,] smat <- smat[drop = FALSE, ww,] } list(mu = mmat, se = smat, tab = tab) } summary.gjam <- function(object,...){ TRAITS <- F bb <- sens <- NULL termB <- termR <- termA <- F if('betaMu' %in% names(object$parameters)){ termB <- T beta <- object$parameters$betaMu } n <- nrow(object$inputs$y) S <- ncol(object$inputs$y) Q <- ncol(object$inputs$xStand) notOther <- object$inputs$notOther other <- object$inputs$other ng <- object$modelList$ng burnin <- object$modelList$burnin if("betaTraitTable" %in% names(object$parameters))TRAITS <- T if('fSensGibbs' %in% names(object$chains)){ sens <- .chain2tab(object$chains$fSensGibbs[burnin:ng,])$tab[,1:4] cat("\nSensitivity by predictor variables f:\n") print( sens ) } RMSPE <- object$fit$rmspeBySpec imputed <- rep(0,S) missingx <- rep(0,Q) if(length(object$missing$xmiss) > 0){ xtab <- table(object$missing$xmiss[,2]) missingx[ as.numeric(names(xtab)) ] <- xtab } if(length(object$missing$ymiss) > 0){ xtab <- table(object$missing$ymiss[,2]) imputed[ as.numeric(names(xtab)) ] <- xtab } if(termB){ RMSPE <- RMSPE[notOther] bb <- t( signif(rbind(beta[,notOther], RMSPE),3) ) cat("\nCoefficient matrix B:\n") print( t(bb) ) cat("\nCoefficient matrix B:\n") print(object$parameters$betaTable) cat("\nLast column indicates if 95% posterior distribution contains zero.\n") if( !is.null(object$parameters$betaStandXtable) ){ cat("\nCoefficient matrix B, standardized for X:\n") print(object$parameters$betaStandXtable) cat("\nLast column indicates if 95% posterior distribution contains zero.\n") } if( !is.null(object$parameters$betaStandXWtable) ){ cat("\nCoefficient matrix B, standardized for X and W:\n") print(object$parameters$betaStandXWtable) cat("\nLast column indicates if 95% posterior distribution contains zero.\n") } cat("\nVariance contributions from model mean and random effects:\n") print( object$fit$fractionExplained ) } if(TRAITS){ cat("\nCoefficient matrix for traits:\n") print(object$parameters$betaTraitTable) cat("\nLast column indicates if 95% posterior distribution contains zero.\n") cat("\nCoefficient matrix for traits, standardized for X and W:\n") print(object$parameters$betaTraitXWTable) cat("\nLast column indicates if 95% posterior distribution contains zero.\n") } if( length(object$modelSummary$missFacSpec) > 0 ){ cat("\nMissing factor combinations:\n") print(object$modelSummary$missFacSpec) } dt <- object$inputs$designTable if(!is.null(dt)){ cat("\n Design Table: VIF and correlations\n") print(dt) } words <- .summaryWords(object) cat("\n",words) res <- list(DIC=object$fit$DIC) if(!is.null(sens))res$sensitivity <- sens if(!is.null(bb))res$Coefficients <- bb class(res) <- "summary.gjam" invisible(res) } .summaryWords <- function(object){ Q <- ncol(object$inputs$xStand) n <- nrow(object$inputs$y) S <- ncol(object$inputs$y) other <- object$inputs$other notOther <- object$inputs$notOther nxmiss <- nrow( object$missing$xmiss ) nymiss <- nrow( object$missing$ymiss ) nholdout <- length(object$modelList$holdoutIndex) types <- unique(object$modelList$typeNames) if(length(types) == 1)types <- rep(types,S) ef <- "" if( 'DA' %in% types ){ wd <- which(types == 'DA') rf <- object$modelList$effort$values[,wd] gf <- signif( range(rf), 2) wr <- signif( range(object$inputs$y[,wd]/rf), 3) if(gf[1] == gf[2]){ ab <- paste(" DA effort is ",gf[1]," for all observations. ",sep="") }else{ ab <- paste(" DA effort ranges from ", gf[1], " to ", gf[2],".",sep="") } ef <- paste(ab, " DA counts per effort (W) ranges from ", wr[1], " to ", wr[2], ".",sep="") } if( 'CC' %in% types ){ wd <- which(types == 'CC') rr <- round( range(object$inputs$y[,wd]) ) ef <- paste(ef, " CC count range is (", rr[1],", ", rr[2], ").", sep="") } oc <- "" if(length(other) > 0){ oc <- paste(" 'other' class detected in ydata, '", colnames(object$inputs$y)[other], " column ", "', not fitted. ",sep='') } ty <- paste0( unique(types), collapse=", ") words <- paste("Sample contains n = ", n, " observations on S = ", S, " response variables. Data types (typeNames) include ", ty, ".", ef, oc, " There are ", nxmiss, " missing values in X and ", nymiss, " missing values in Y. The RMSPE is ", signif(object$fit$rmspeAll,3), ", and the DIC is ",round(object$fit$DIC),".", sep="") dr <- "" if(object$modelList$REDUCT){ nr <- object$chains$kgibbs nd <- t( apply(nr,1,duplicated) ) nr[!nd] <- 0 nr[nr > 0] <- 1 nk <- rowSums(1 - nr) nk <- max(nk[object$modelList$burnin:object$modelList$ng]) dr <- paste(" Dimension reduction was implemented with N = ",nk, " and r = ",object$modelList$reductList$r,".", sep="") } ho <- "" if(nholdout > 0)ho <- paste(" Held out were",nholdout,"observations.") comp <- paste(" Computation involved ", object$modelList$ng, " Gibbs steps, with a burnin of ", object$modelList$burnin, ".",dr,ho,sep='') paste(words, comp) } print.gjam <- function(x, ...){ summary.gjam(x) } .getSigTable <- function(chain, SS, QQ, xn, sn){ bci <- apply(chain,2,quantile,c(.025,.975)) tmp <- .between(rep(0,SS*QQ),bci[1,],bci[2,],OUT=T) ii <- rep(' ',SS*QQ) ii[tmp[bci[1,tmp] < 0]] <- '-' ii[tmp[bci[2,tmp] > 0]] <- '+' bTab <- data.frame( matrix(ii,QQ,SS) ) colnames(bTab) <- sn rownames(bTab) <- xn data.frame( t(bTab) ) } .getPlotLayout <- function(np){ if(np == 1)return( c(1,1) ) if(np == 2)return( c(1,2) ) if(np == 3)return( c(1,3) ) if(np <= 4)return( c(2,2) ) if(np <= 6)return( c(2,3) ) if(np <= 9)return( c(3,3) ) if(np <= 12)return( c(3,4) ) if(np <= 16)return( c(4,4) ) if(np <= 20)return( c(4,5) ) if(np <= 25)return( c(5,5) ) if(np <= 25)return( c(5,6) ) return( c(6,6) ) } sqrtSeq <- function( xx, nbin = 15){ maxval <- max(xx, na.rm = T) minval <- min(xx, na.rm = T) by <- 2 if(maxval >= 5) by <- 10 if(maxval >= 10) by <- 20 if(maxval >= 20) by <- 100 if(maxval >= 30) by <- 200 if(maxval >= 50) by <- 500 if(maxval >= 70) by <- 1000 if(maxval >= 100) by <- 2000 if(maxval >= 200) by <- 10000 if(maxval >= 500) by <- 50000 if(maxval >= 700) by <- 100000 if(maxval >= 1000)by <- 200000 if(maxval >= 1500)by <- 400000 labs <- seq(0, maxval^2, by = by) while(length(labs) < nbin){ labs <- seq(minval^2, maxval^2, by = by) by <- by/2 } while(length(labs) > (nbin + 2)){ labs <- seq(minval^2, maxval^2, by = by) by <- 1.2*by } at <- sqrt(labs) labs <- signif(labs, 2) list(at = at, labs = labs) } .plotObsPred <- function(xx, yy, opt = NULL, col='darkgreen', points = F, add = F){ atx <- aty <- breaks <- NULL xlabel <- 'Observed' ylabel <- 'Predicted' trans <- .8 xlimit <- range(xx, na.rm=T) ylimit <- range(yy, na.rm=T) if(!is.null(opt))for(k in 1:length(opt))assign( names(opt)[k], opt[[k]] ) if( is.na(col) )col <- 'darkgreen' ww <- which(is.finite(xx) & is.finite(yy)) xx <- xx[ww] yy <- yy[ww] if( !add ){ if( !points ){ plot(NA, xlim = xlimit, xlab = xlabel, ylab = ylabel, ylim = ylimit) }else{ plot(xx, yy, col = .getColor( col, trans), cex = .3, xlim = xlimit, xlab = xlabel, ylab = ylabel, ylim = ylimit, xaxt = 'n',yaxt = 'n') } } if( is.null(atx) )atx <- breaks if( is.null(atx) ){ tmp <- .bins4data( xx ) atx <- breaks <- tmp$bins } bins <- atx if( length(atx) < 8 )bins <- breaks <- .bins4data( xx )$bins nbin <- length(bins) xb <- findInterval(xx, bins, all.inside = TRUE) tt <- table(xb) kbin <- as.numeric(names(tt)) xf <- (tt/sum(tt))^.5 xf[ xf < .002 ] <- .002 xs <- xf^.2 wide <- diff(bins)/2 wide[ wide > 2*min(wide) ] <- 2*min(wide) wide <- c( wide, wide[ length(wide) ] ) db <- 1 for(k in kbin){ qk <- which(xb == k) q <- quantile(yy[qk],c(.5,.025,.158,.841,.975),na.rm=T) if(!is.finite(q[1]))next if(q[2] == q[5])next if(k > 1)db <- bins[k] - bins[k-1] if(k < nbin){ if(bins[k] > 0 & bins[k+1] > 0){ xp <- sqrt( bins[k]*bins[k+1] ) }else{ xp <- mean( bins[k:(k+1)] ) } }else{ xp <- bins[k] + db/2 } rwide <- wide[k] xtrans <- xs[ as.character(k) ] ftrans <- xf[ as.character(k) ] suppressWarnings( arrows(xp, q[2], xp, q[5], lwd=2, angle=90, code=3, col=.getColor(col,xtrans), length=.02) ) lines(c(xp-.5*rwide,xp+.5*rwide),q[c(1,1)],lwd=2, col=.getColor(col,sqrt(ftrans))) rect(xp-.4*rwide,q[3],xp+.4*rwide,q[4], border = .getColor(col,xtrans), col=.getColor(col,ftrans)) } } sqrtSeq <- function(maxval, nbin = 10){ by <- signif(maxval^1.7, 1) labs <- seq(0, maxval^2, by = by) while(length(labs) < nbin){ by <- .5*by labs <- seq(0, maxval^2, by = by) } at <- sqrt(labs) labs <- signif(labs, 2) ww <- which(!duplicated(labs)) labs <- labs[ww] at <- at[ww] list(at = at, labs = labs) } .getBinSqrt <- function(xx, yy, nbin = 10 ){ yy[ yy < 0 ] <- 0 sxx <- suppressWarnings( sqrt(xx) ) syy <- suppressWarnings( sqrt(yy) ) tx <- sqrtSeq( maxval = max(sxx, na.rm=T), nbin ) ty <- sqrtSeq( maxval = max(syy, na.rm=T), nbin ) atx <- tx$at lax <- tx$labs xtick <- atx xlab <- lax ix <- findInterval(sxx, atx, all.inside = T) ix <- table(ix) px <- ix/sum(ix) if( max(px) > .3 ){ qx <- quantile(sxx[sxx != 0], seq(0, 1, length.out = nbin), na.rm=T ) ux <- unique(qx) rx <- length(ux)/length(qx) nb <- ceiling( nbin/rx ) qx <- quantile(sxx[sxx != 0], seq(0, 1, length.out = nb), na.rm=T ) atx <- unique(qx) lax <- round( atx^2 ) atx <- c(0, atx) lax <- c(0, lax) wx <- which( !duplicated(lax) ) atx <- atx[wx] lax <- lax[wx] } aty <- ty$at if(length(atx) == 1)atx <- range(xtick) list(xlim = range(tx$at, na.rm=T), ylim = range(aty, na.rm=T), atx = atx, labx = lax, xtick = atx, aty = aty, laby = ty$labs) } .shadeInterval <- function(xvalues,loHi,col='grey',PLOT = TRUE, add = TRUE, xlab=' ',ylab=' ', xlim = NULL, ylim = NULL, LOG = FALSE, trans = .5){ tmp <- smooth.na(xvalues,loHi) xvalues <- tmp[,1] loHi <- tmp[,-1] xbound <- c(xvalues,rev(xvalues)) ybound <- c(loHi[,1],rev(loHi[,2])) if(is.null(ylim))ylim <- range(as.numeric(loHi)) if(is.null(xlim))xlim <- range(xvalues) if(!add){ if(!LOG)plot(NULL, xlim = xlim, ylim=ylim, xlab=xlab, ylab=ylab) if(LOG)suppressWarnings( plot(NULL, xlim = xlim, ylim=ylim, xlab=xlab, ylab=ylab, log='y') ) } if(PLOT)polygon(xbound,ybound, border=NA,col=.getColor(col, trans)) invisible(cbind(xbound,ybound)) } smooth.na <- function(x,y){ if(!is.matrix(y))y <- matrix(y,ncol=1) wy <- which(!is.finite(y),arr.ind = TRUE) if(length(wy) == 0)return(cbind(x,y)) wy <- unique(wy[,1]) ynew <- y[-wy,] xnew <- x[-wy] cbind(xnew,ynew) } .getBin <- function(xx, yy, minbin = 5, length = 15){ xi <- xr <- seq(min(xx, na.rm=T), max(xx, na.rm=T), length = length) xc <- findInterval(xx, xi, all.inside = T) tab <- table(xc) while( tab[1] < (minbin/2) ){ xi <- xi[-1] xc <- findInterval(xx, xi, all.inside = T) tab <- table(xc) } nt <- length(tab) nx <- length(xi) while( tab[nt] < (minbin/2) ){ xi <- xi[-nx] xc <- findInterval(xx, xi, all.inside = T) tab <- table(xc) nx <- length(xi) nt <- length(tab) } while(min(tab) < minbin){ length <- length - 1 xi <- seq(min(xi, na.rm=T), max(xi, na.rm=T), length = length) xc <- findInterval(xx, xi, all.inside = T) tab <- table(xc) nx <- length(xi) nt <- length(tab) } xi[1] <- xr[1] xi[nx] <- xr[length(xr)] xmids <- (xi[1:(nx-1)] + xi[2:nx])/2 list(xseq = xi, xmids = xmids, xbin = xc) } .gjamPlot <- function(output, plotPars, verbose = FALSE){ FACNAMES <- TRUE PLOTALLY <- TRAITS <- GRIDPLOTS <- SAVEPLOTS <- REDUCT <- TV <- SPECLABS <- SMALLPLOTS <- F PREDICTX <- BETAGRID <- PLOTY <- PLOTX <- CORLINES <- SIGONLY <- CHAINS <- RANDOM <- T omitSpec <- trueValues <- censor <- otherpar <- ng <- NULL traitList <- specByTrait <- typeNames <- classBySpec <- x <- y <- burnin <- richness <- betaTraitMu <- corSpec <- cutMu <- ypredMu <- DIC <- yscore <- missingIndex <- xpredMu <- plotByTrait <- tMu <- tMuOrd <- traitTypes <- isFactor <- betaMu <- betaMuUn <- corMu <- modelSummary <- randByGroup <- randGroupVarMu <- NULL unstandardX <- NULL specColor <- NULL ematAlpha <- alphaEigen <- .5 ematrix <- ematrixL <- ematrixA <- eComs <- NULL ymiss <- eCont <- modelList <- timeList <- timeZero <- NULL random <- NULL kgibbs <- NULL chains <- inputs <- parameters <- prediction <- reductList <- bgibbs <- sgibbs <- sigErrGibbs <- factorBeta <- gsens <- bFacGibbs <- alphaGibbs <- times <- alphaMu <- rhoMu <- factorBetaList <- factorRho <- rhoMuUn <- notOther <- other <- NULL xStand <- wL <- wA <- xUnstand <- sensAlpha <- sensRho <- sensBeta <- rhoStandXmu <- evecs <- NULL holdoutN <- 0 TIME <- termB <- termR <- termA <- FALSE cex <- 1 holdoutIndex <- numeric(0) clusterIndex <- clusterOrder <- numeric(0) xlnames <- character(0) ncluster <- min(c(4,ncol(y))) outFolder <- 'gjamOutput' outfile <- character(0) width <- height <- 3 oma <- c(1,1,0,0) mar <- c(1,1,1,0) tcl <- -0.1 mgp <- c(0,0,0) traitColor <- textCol <- 'black' for(k in 1:length(output))assign( names(output)[k], output[[k]] ) for(k in 1:length(chains))assign( names(chains)[k], chains[[k]] ) for(k in 1:length(fit))assign( names(fit)[k], fit[[k]] ) for(k in 1:length(inputs))assign( names(inputs)[k], inputs[[k]] ) for(k in 1:length(missing))assign( names(missing)[k], missing[[k]] ) for(k in 1:length(modelList))assign( names(modelList)[k], modelList[[k]] ) for(k in 1:length(parameters))assign( names(parameters)[k], parameters[[k]] ) for(k in 1:length(prediction))assign( names(prediction)[k], prediction[[k]] ) for(k in 1:length(reductList))assign( names(reductList)[k], reductList[[k]] ) if('bgibbs' %in% names(chains)) termB <- TRUE if('lgibbs' %in% names(chains)) termR <- TRUE if('alphaGibbs' %in% names(chains))termA <- TRUE x <- xStand rm(xStand) if(!is.null(plotPars))for(k in 1:length(plotPars))assign( names(plotPars)[k], plotPars[[k]] ) if( !is.null(traitList) ){ TRAITS <- T for(k in 1:length(traitList))assign( names(traitList)[k], traitList[[k]] ) } if( 'trueValues' %in% names(plotPars) ){ TV <- T for(k in 1:length(trueValues))assign( names(trueValues)[k], trueValues[[k]] ) if(termB){ matchTrue <- match(colnames(betaMu),colnames(beta)) beta <- beta[,matchTrue] } if(termR){ matchTrue <- match(colnames(rhoMu),colnames(rho)) rho <- rho[,matchTrue] } if('sigma' %in% names(trueValues)){ sigma <- sigma[matchTrue,matchTrue] } if('corSpec' %in% names(trueValues)){ corSpec <- corSpec[matchTrue,matchTrue] } } if(!is.null(timeList)){ for(k in 1:length(timeList))assign( names(timeList)[k], timeList[[k]] ) ypredMu[timeZero,] <- NA TIME <- T } if(length(xpredMu) == 0)PREDICTX <- F if(!PREDICTX)PLOTX <- F if(!is.null(random)){ RANDOM <- T } oma <- c(0,0,0,0) mar <- c(4,4,2,1) tcl <- -0.5 mgp <- c(3,1,0) if(SAVEPLOTS){ ff <- file.exists(outFolder) if(!ff)dir.create(outFolder) } chainNames <- names(chains) allTypes <- unique(typeNames) ntypes <- length(allTypes) typeCode <- match(typeNames,allTypes) specs <- rownames(classBySpec) Q <- ncol(x) nhold <- length(holdoutIndex) ncut <- ncol(classBySpec) + 1 S <- ncol(y) n <- nrow(y) snames <- colnames(y) xnames <- colnames(x) gindex <- burnin:ng if(S < 20)SPECLABS <- T if(S > 10)CORLINES <- F if(S < 4){ if(GRIDPLOTS)message('no GRIDPLOTS if S < 4') GRIDPLOTS <- F } cvec <- c(' ' colF <- colorRampPalette( cvec, space = "Lab" ) if(is.null(specColor))specColor <- colF(S) if(is.numeric(specColor))specColor <- colF(S)[ specColor ] names(specColor) <- .cleanNames(names(specColor)) if(length(specColor) == 1)specColor <- rep(specColor, S) boxCol <- .getColor(specColor,.4) omit <- c(which(colnames(y) %in% omitSpec),other) notOmit <- 1:S SO <- length(notOther) if(length(omit) > 0)notOmit <- notOmit[-omit] SM <- length(notOmit) snames <- colnames(y) xnames <- colnames(x) xSd <- 0 if(Q > 1)xSd <- sqrt( diag(cov(x)) ) HOLD <- F if(holdoutN > 0)HOLD <- T if( !TRAITS & !is.null(richness) ){ cvr <- sd( richness[,'obs'], na.rm=T)/mean( richness[,'obs'], na.rm=T) if(cvr > .5){ if(TIME)richness[timeZero,] <- NA w1 <- which(richness[,1] > 0) if(HOLD)w1 <- w1[!w1 %in% holdoutIndex] xlimit <- range(richness[w1,1]) if(diff(xlimit) > 0){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'richness.pdf') ) par(mfrow=c(1,2), bty='n', omi=c(.3,.3,0,0), mar=c(3,2,2,1), tcl= tcl, mgp=mgp) xc <- c('obs','H_obs') yc <- c('predMu','H_pred') for(k in 1:2){ kx <- richness[w1,xc[k]] ky <- richness[w1,yc[k]] if(k == 2){ kx <- exp(kx) ky <- exp(ky) } ylimit <- range(ky) rr <- range(kx,na.rm=T) bins <- seq(rr[1] - .5, ceiling(rr[2] + .5), by=1) nbin <- length(bins) rh <- hist(kx,bins,plot=F) xy <- rbind(c(bins[1],bins,bins[nbin]),c(0,rh$density,0,0)) xy <- .gjamBaselineHist(kx,bins=bins) xy[2,] <- ylimit[1] + .3*xy[2,]*diff(ylimit)/max(xy[2,]) plot(xy[1,],xy[2,],col='tan',type='s',lwd=2, ylim=ylimit, xlab=' ',ylab='') polygon(xy[1,],xy[2,],border='brown',col='tan') if(HOLD){ xhold <- richness[holdoutIndex,xc[k]] yhold <- richness[holdoutIndex,yc[k]] if(k == 2){ xhold <- exp(xhold) yhold <- exp(yhold) } points(xhold,yhold, col='brown', cex=.3) } opt <- list( xlabel='Observed', ylabel='Predicted', col='darkgreen', atx = bins) .plotObsPred( xx = kx, yy = ky, add=T, opt = opt) abline(0,1,lty=2, lwd=2, col='grey') if(k == 1){ .plotLabel('a) Richness (no. present)',cex=1.2,above=T) }else{ .plotLabel('b) Diversity (H)',cex=1.2,above=T) } } mtext(side=1, 'Observed', outer=T, line=0) mtext(side=2, 'Predicted', outer=T, line=0) if(!SAVEPLOTS){ readline('no. species, effective species -- return to continue ') } else { dev.off( ) } } } } ns <- min( c(ng - burnin, 1000) ) simIndex <- sample(nrow(sgibbs),ns,replace=T) simIndex <- sort(simIndex) burn <- burnin/ng*1000 tmp <- .expandSigmaChains(snames, sgibbs, otherpar, simIndex, sigErrGibbs, kgibbs, REDUCT, CHAINSONLY=F, verbose) corMu <- tmp$rMu; corSe <- tmp$rSe; sigMu <- tmp$sMu; sigSe <- tmp$sSe sgibbsShort <- tmp$chainList$schain rgibbsShort <- tmp$chainList$cchain if(REDUCT){ kgibbsShort <- tmp$chainList$kchain otherpar <- output$modelList$reductList$otherpar } if(REDUCT){ sigmaerror <- mean(sigErrGibbs) sinv <- .invertSigma(sigMu,sigmaerror,otherpar,REDUCT) } else { sinv <- solveRcpp(sigMu[notOther,notOther]) } omitBC <- keepBC <- NULL if(termB){ bgibbsShort <- bgibbs[simIndex,] betaLab <- expression( paste('Coefficient matrix ',hat(bold(B)) )) tmp <- .omitChainCol(bgibbs,'other') omitBC <- tmp$omit keepBC <- tmp$keep } if(termR){ rhoLab <- expression( paste('Growth matrix ',hat(bold(Rho)) )) } if(termA){ alphaLab <- expression( paste('interaction matrix ',hat(bold(Alpha)) )) } SO <- length(notOther) fMat <- output$parameters$fmatrix if( 'factorBeta' %in% names(inputs) & !FACNAMES ){ fcnames <- names( inputs$factorBeta$factorList ) if(length(fcnames) > 0){ for(m in 1:length(fcnames)){ colnames(fMat) <- .replaceString( colnames( fMat ), fcnames[m], '' ) rownames(fMat) <- .replaceString( rownames( fMat ), fcnames[m], '' ) } } } corLab <- expression( paste('Correlation matrix ',hat(bold(R)) )) cutLab <- expression( paste('Partition matrix ',hat(bold(plain(P))) )) AA <- F if(!SMALLPLOTS)AA <- T if( TV ){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'trueVsPars.pdf') ) npl <- length(trueValues[names(trueValues) != 'w']) if(TIME)npl <- length(trueValues[!names(trueValues) %in% c('sigma','w')]) if('OC' %in% typeNames)npl <- npl + 1 mfrow <- .getPlotLayout(npl) par(mfrow=mfrow,bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp) if( termB ){ beta <- trueValues$beta sc <- beta*0 sc[ keepBC ] <- 1 sc <- specColor[ which(sc == 1, arr.ind=T)[,2] ] if( length(beta) < 100 ){ .gjamTrueVest( pchains = chains$bgibbs[burnin:ng,], true = beta, typeCode, allTypes, colors = sc, label = betaLab) } else { opt <- list(xlabel='true', ylabel='estimate', nPerBin=length(beta)/10, fill='lightblue', box.col=sc, POINTS=T, MEDIAN=F, add=F) .plotObsPred(beta[,notOther],betaMu[,notOther], opt = opt) abline(0,1,lty=2) } } if( 'rho' %in% names(trueValues) ){ rho <- trueValues$rho cols <- colF(S) if(length(rho) < 100){ lgibbs <- chains$lgibbs gi <- grep('intercept', colnames(lgibbs)) xlim <- range(rho) ylim <- range(lgibbs) hline <- F .gjamTrueVest(lgibbs[burnin:ng,],true=rho[ wL ], xlim = xlim, ylim = ylim, typeCode, allTypes, colors=cols[wL[,2]], label = rhoLab) abline( h = 0, lty=2) } else { opt <- list(xlabel='true', ylabel='estimate', nPerBin=length(rho)/10, fill='lightblue',box.col = cols[wL[,2]],POINTS=T,MEDIAN=F,add=F) .plotObsPred(rho[wL],rhoMu[wL],opt = opt) abline(0,1,lty=2) } } if('alpha' %in% names(trueValues)){ alpha <- trueValues$alpha aindex <- parameters$aindex aTrue <- alpha[ aindex[,c('toW','fromW')] ] if(length(alpha) < 100){ .gjamTrueVest(chains$alphaGibbs[burnin:ng,],true=aTrue, typeCode,allTypes,colors = cols[wA[,2]] ,label = alphaLab) } else { opt <- list(xlabel='true', ylabel='estimate', nPerBin=length(alpha)/10, fill='lightblue',box.col=cols,POINTS=T,MEDIAN=F,add=F) .plotObsPred(alpha[,notOther],alphaMu[,notOther],opt = opt) abline(0,1,lty=2) } abline( h = 0, lty=2 ) } if( 'corSpec' %in% names(trueValues) ){ cols <- colF(2^ntypes) corTrue <- corSpec diag(corTrue) <- NA if(length(other) > 0){ corTrue[other,] <- NA corTrue[,other] <- NA } cindex <- which(lower.tri(corSpec,diag=T)) pindex <- which(lower.tri(corSpec,diag=T),arr.ind=T) if(!is.matrix(pindex)){ pindex <- matrix(pindex,1) } rindex <- which(is.finite(corTrue[cindex])) cindex <- cindex[rindex] pindex <- pindex[drop=F,rindex,] cols <- colF(ntypes + ntypes*(ntypes-1)/2) rg <- rgibbsShort rg[rg == 1] <- NA xlim <- range(c(-.1,.1,corTrue[cindex]),na.rm=T) ylim <- range(c(-.1,.1,rg),na.rm=T) add <- F m <- 1 combNames <- character(0) combCols <- numeric(0) box <- F for(k in 1:length(allTypes)){ wk <- which(typeNames == allTypes[k]) wk <- wk[wk %in% notOther] wp <- which(pindex[,1] %in% wk & pindex[,2] %in% wk) if( length(wp) == 1 ){ combNames <- c(combNames,allTypes[k]) yci <- quantile( rgibbsShort[,rindex[wp]] ,c(.5,.025,.975)) xmu <- corSpec[matrix(pindex[wp,],1)] if(!add){ plot(xmu,yci[1],xlim=xlim,ylim=ylim, pch=3,col=cols[m], xlab='true',ylab='') add <- T } else { points(xmu,yci[1],pch=3,col=cols[m]) } lines( c(xmu,xmu),yci[2:3],col=cols[m],lwd=2) } if(length(wp) > 1){ if( length(wp) < 100 ){ .gjamTrueVest(rgibbsShort[,rindex[wp]],true=corSpec[cindex[wp]], typeCode,allTypes,label=corLab,xlim=xlim,ylim=ylim, colors=cols[m],legend=F,add=add) } else { box <- T opt <- list(xlabel='true', ylabel='estimate', fill='lightblue', nPerBin=length(wp)/20, box.col=cols[m], POINTS=T, MEDIAN=F, add=add, atx = c(-1, 0, 1), aty = c(-1, 0, 1)) .plotObsPred(corSpec[cindex[wp]], corMu[cindex[wp]], opt = opt) if(!add)abline(0,1,lty=2) } add <- T combNames <- c(combNames,allTypes[k]) combCols <- c(combCols,cols[m]) m <- m + 1 } if(k < length(allTypes)){ for( j in (k+1):length(allTypes) ){ wj <- which(typeNames == allTypes[j]) wj <- wj[wj %in% notOther] wp <- which(pindex[,1] %in% wk & pindex[,2] %in% wj) if(length(wp) == 0){ wp <- which(pindex[,2] %in% wk & pindex[,1] %in% wj) } if(length(wp) == 0)next if(length(wp) == 1){ yci <- quantile( rgibbsShort[,rindex[wp]] ,c(.5,.025,.975)) xmu <- corTrue[cindex[wp]] if(!add){ plot(xmu,yci[1],xlim=xlim,ylim=ylim, pch=3,col=cols[m]) } else { points(xmu,yci[1],pch=3,col=cols[m]) } lines( c(xmu,xmu),yci[2:3],col=cols[m],lwd=2) } else { if(!box){ .gjamTrueVest(rgibbsShort[,rindex[wp]], true=corTrue[cindex[wp]], typeCode,allTypes,add=add,colors=cols[m], legend=F, xlim=c(-.9,.9), ylim=c(-.9,.9)) } else { opt <- list(nPerBin=length(wp)/10, box.col=cols[m], fill='white',POINTS=T, MEDIAN=F,add=add) .plotObsPred(corSpec[cindex[wp]],corTrue[cindex[wp]], opt = opt) } } m <- m + 1 mnames <- paste(allTypes[k],allTypes[j],sep='-') combNames <- c(combNames,mnames) combCols <- c(combCols,rep(cols[m],length(mnames))) add <- T } } } legend('topleft',combNames,text.col=cols,bty='n',ncol=3,cex=.7) } if('OC' %in% allTypes & 'cuts' %in% names(trueValues)){ ctmp <- cutMu wc <- c(1:ncol( ctmp )) + 1 ctrue <- cuts[,wc] wf <- which(is.finite(ctrue*ctmp)[,-1]) cutTable <- .gjamTrueVest(chains$cgibbs[burnin:ng,wf],true=ctrue[,-1][wf], typeCode,allTypes,colors='black', label=cutLab,legend=F, add=F) } if(!SAVEPLOTS){ readline('simulated beta, corSpec vs betaMu, corMu (95%) -- return to continue') } else { dev.off() } } if('OC' %in% typeNames){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'partition.pdf') ) par( mfrow=c(1,1), bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp ) wk <- which(typeNames == 'OC') nk <- length(wk) cgibbs <- output$chains$cgibbs onames <- snames[wk] vnames <- sort(unique(.splitNames(colnames(cgibbs))$vnam[,1])) cgibbs[!is.finite(cgibbs)] <- NA cc <- colSums(abs(cgibbs),na.rm=T) cg <- cgibbs[,cc > 0] if('cuts' %in% names(trueValues))rownames(cuts) <- rownames(cutMu) c1 <- names(cc)[cc > 0] colc <- colF(ncol(cutMu)) nk <- length(vnames) plot(0,0,xlim=c(0,max(cg,na.rm=T)),ylim=c(1,1+nk),cex=.1, xlab='Unit variance scale', ylab=' ',yaxt='n') .yaxisHorizLabs(vnames,at=c(1:nk)) for(k in 1:length(vnames)){ x1 <- 0 ym <- .5 wcg <- grep(vnames[k],colnames(cg)) if(length(wcg) == 0)next tmp <- .chains2density(cg,varName=vnames[k], cut=2.5) xt <- tmp$x yt <- tmp$y yt <- .5*yt/max(yt) yt <- yt + k for(j in 1:nrow(xt)){ if('cuts' %in% names(trueValues)){ lines( rep(cuts[vnames[k],j+2],2),c(k,k+1),lty=2,col=colc[j],lwd=3) } xj <- c(xt[j,],xt[j,ncol(xt)],xt[j,1]) yj <- c(yt[j,],k,k) x2 <- which.max(yj) xm <- .2*x1 + .8*xj[x2] polygon(xj, yj, border=colc[j], col=.getColor(colc[j], .4), lwd=2) if(k == length(vnames)) text(xm,ym+k,j,col=colc[j]) x1 <- xj[x2] } } .plotLabel('Partition by species',above=T) if(!SAVEPLOTS){ readline('cuts vs cutMu -- return to continue') } else { dev.off() } } rmspeAll <- sqrt( mean( (y[,notOther] - ypredMu[,notOther])^2,na.rm=T ) ) eBySpec <- sqrt( colMeans( (y[,notOther]/rowSums(y[,notOther]) - ypredMu[,notOther]/rowSums(ypredMu[,notOther], na.rm=T))^2 ) ) ordFit <- order(eBySpec) score <- mean(yscore) fit <- signif( c(DIC,score,rmspeAll), 5) names(fit) <- c('DIC','score','rmspe') if( PLOTY ){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'yPred.pdf') ) npp <- 0 for(k in 1:length(allTypes)){ wk <- which(typeCode == k) if( length(censor) > 0 ){ ncc <- 0 if( typeNames[wk[1]] %in% names(censor) ){ wm <- which(names(censor) == typeNames[wk[1]]) wnot <- wk for(m in wm){ wnot <- wnot[!wnot %in% censor[[m]]$columns] npp <- npp + 1 } if(length(wnot) > 0)npp <- npp + 1 } else { ncc <- ncc + 1 } } else { ncc <- 1 } npp <- npp + ncc } mfrow <- .getPlotLayout(npp) par( mfrow=mfrow, bty='n', omi=c(.3,.3,0,0), mar=c(3,4,2,1), tcl= tcl, mgp = mgp ) ylab <- ' ' mk <- 0 ypred <- ypredMu yobs <- y ypred[ymiss] <- yobs[ymiss] <- NA if(TIME)ypred[timeZero,] <- NA for(k in 1:length(allTypes)){ wk <- which(typeCode == k) wk <- wk[wk %in% notOther] wkm <- wk nk <- nkm <- length(wk) censm <- NULL wm <- wall <- 1 CENS <- F add <- F if( length(censor) > 0 ){ if( typeNames[wk[1]] %in% names(censor) ){ CENS <- T wm <- which(names(censor) == typeNames[wk[1]]) wall <- wm wnot <- wk for(m in wm){ wnot <- wnot[!wnot %in% censor[[m]]$columns] } if(length(wnot) > 0)wall <- c(wall,max(wall) + 1) } } for(m in wall){ if(CENS){ if(m %in% wm){ censm <- censor[[m]] wkm <- censor[[m]]$columns } else { censm <- NULL wkm <- wnot } nkm <- length(wkm) } mk <- mk + 1 y1 <- yobs[,wkm,drop=F] yp <- ypred[,wkm,drop=F] ww <- which(is.finite(y1) & is.finite(yp) & y1 >= 0 & yp >= 0) sxx <- suppressWarnings( sqrt(y1[ww]) ) syy <- suppressWarnings( sqrt(yp[ww]) ) opt <- .getBinSqrt(y1, yp, nbin = 8 ) if( !typeNames[wk[1]] %in% c('PA','CAT') ){ if(typeNames[wk[1]] == 'FC'){ at <- ceiling( 10*max(y1, na.rm=T) )/10 opt$xtick <- opt$ytick <- opt$atx <- opt$aty <- seq(0, at, by = .1) opt$labx <- opt$laby <- opt$atx opt$xlim <- opt$ylim <- c(0, at) sxx <- y1[ww] syy <- yp[ww] } xy <- .gjamBaselineHist( y1 = sxx, bins = opt$atx, ylim = opt$ylim, nclass=length(opt$atx) ) plot(xy[1,], xy[2,], col='tan', type='s', lwd=2, xlim=opt$xlim, ylim = opt$ylim, xlab='', ylab='', xaxt='n', yaxt='n') polygon(xy[1,],xy[2,],border='tan',col='wheat') axis(1, at = opt$xtick, labels = opt$labx) axis(2, at = opt$aty, labels = opt$laby, las=2) opt <- append(opt, list( xlabel='Observed', ylabel='Predicted', col='darkgreen') ) tmp <- .plotObsPred( xx = sxx, yy = syy, add=T, opt = opt) abline(0, 1, lty=2, lwd = 2, col = 'grey') } else { y11 <- mean(y1,na.rm=T) y00 <- 1 - y11 x11 <- c(-.07,-.07,.07,.07,.93,.93,1.07,1.07,-.07) y11 <- c(0,y00,y00,0,0,y11,y11,0,0) atx <- min(y1):max(y1) aty <- atx xlim <- range( atx + c(-1,1)*.2 ) plot(NULL,col='tan',type='s',lwd=2, xlim= xlim + 1,ylim=range(aty), xlab='Observed',ylab='', xaxt='n',yaxt='n') axis(1, at = atx + 1, labels = atx ) axis(2, at = aty, labels = atx ) polygon(x11 + 1,y11,border='tan',col='wheat') stats <- tapply( as.vector(yp), as.vector(y1), quantile, pnorm(c(-1.96,-1,0,1,1.96)) ) stats <- matrix( unlist(stats), ncol = 2 ) tmp <- .boxplotQuant( yp ~ y1, stats = stats, xaxt='n', yaxt = 'n', outline=F, border='darkgreen', whiskcol='darkgreen', boxfill= .getColor('darkgreen', .6), pars = list(boxwex = 0.1, ylim=range(aty)), lty=1, add = T) abline(-1, 1, lty=2, lwd = 2, col = 'grey') } add <- T if(nhold > 0){ y1h <- y[holdoutIndex,wkm,drop=F] yph <- ypredMu[holdoutIndex,wkm,drop=F] points(y1h,yph,col='brown', pch=21, bg='green',cex=.3) } tf <- .gjamGetTypes(typeNames[wk[1]])$labels tf <- paste(letters[mk],tf, sep=') ') .plotLabel(tf,'topleft',above=AA) } } mtext('Observed', side=1, outer=T) mtext('Predicted', side=2, outer=T) if(!SAVEPLOTS){ readline('obs y vs predicted y -- return to continue ') } else { dev.off() } } nfact <- 0 factorList <- contrast <- numeric(0) if( termB ){ nfact <- factorBeta$nfact factorList <- contrast <- numeric(0) if(!is.null(nfact)){ factorList <- factorBeta$factorList contrast <- factorBeta$contrast } } if( termR ){ if(factorRho$nfact > 0){ factorRho$factorList <- factorRho$factorList[ !factorRho$factorList %in% factorList ] nfact <- nfact + length( factorRho$factorList ) factorList <- append(factorList, factorRho$factorList) contrast <- append(contrast, factorRho$contrast) } } if( PLOTX & PREDICTX & length(xpredMu) > 0 ){ noX <- character(0) colorGrad <- colorRampPalette(c('white','brown','black')) iy <- c(1:n) if(!is.null(timeZero))iy <- iy[-timeZero] if( nfact > 0 ){ nn <- length(unlist(factorList)) mmat <- matrix(0,nn,nn) mnames <- rep('bogus',nn) samples <- rep(0,nn) ib <- 1 par(mfrow=c(1,1),bty='n') mm <- max(nfact,2) useCols <- colorRampPalette(c('brown','orange','darkblue'))(mm) textCol <- character(0) for(kk in 1:nfact){ gname <- names( factorList )[[kk]] fnames <- factorList[[kk]] nx <- length(fnames) if(nx < 1)next ie <- ib + nx - 1 noX <- c(noX,fnames) cont <- contrast[[kk]] refClass <- names(which( rowSums( cont ) == 0) ) hnames <- substring(fnames, nchar(gname) + 1) knames <- c(paste(gname,'Ref',sep=''),fnames) if(TIME){ xtrue <- x[iy,fnames,drop=F] }else{ xtrue <- xUnstand[iy,fnames,drop=F] } nx <- ncol(xtrue) xpred <- xpredMu[iy,fnames,drop=F] cmat <- matrix(0,nx,nx) colnames(cmat) <- hnames rownames(cmat) <- rev(hnames) for(j in 1:nx){ wj <- which(xtrue[,j] == 1) cmat[,j] <- rev( colSums(xpred[drop=F,wj,],na.rm=T)/length(wj) ) } nb <- nn - ib + 1 ne <- nn - ie + 1 samples[ib:ie] <- colSums(xtrue)/n mmat[ne:nb,ib:ie] <- cmat mnames[ib:ie] <- hnames textCol <- c(textCol,rep(useCols[kk],nx)) ib <- ie + 1 } colnames(mmat) <- mnames rownames(mmat) <- rev(mnames) if(length(mmat) == 1){ mc <- c(mmat[1], 1 - mmat[1]) mmat <- cbind(rev(mc),mc) rownames(mmat) <- colnames(mmat) <- factorBeta$facList2[[1]] } graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'xPredFactors.pdf' ) ) par(mfrow=c(1,1),bty='n') slim <- 1.3*c(0,max(mmat)) if(slim[2] > 1)slim[2] <- 1 .corPlot(mmat,slim=slim,plotScale=.8, textCol = textCol, PDIAG=F,CORLINES=T, tri='both', SPECLABS = T, colorGrad = colorGrad, textSize=1, new=F) if(nx > 1){ mloc <- par('usr') text(mean(mloc[1:2]),mloc[3] + .03*diff(mloc[3:4]),'Observed') mtext('Predicted',side=4) } if(!SAVEPLOTS){ readline('x inverse prediction, factors -- return to continue ') } else { dev.off() } } noplot <- c(1,grep(':',xnames),grep('^2',xnames,fixed=T)) vnames <- xnames[-noplot] vnames <- vnames[!vnames %in% noX] if( length(vnames) > 0 ){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'xPred.pdf') ) ylab <- '' xlab <- '' mfrow <- .getPlotLayout( length(vnames) ) par( mfrow=mfrow, bty='n', omi=c(.3,.3,0,0), mar=c(3,2,2,1), tcl= tcl, mgp=mgp ) missX <- missingIndex xmaxX <- apply(x,2,max,na.rm=T) k <- 0 b <- 0 for(j in 2:Q){ if(!xnames[j] %in% vnames)next k <- k + 1 b <- b + 1 if(b == mfrow[2])b <- 0 x1 <- xUnstand[iy,j] x2 <- xpredMu[iy,j] type <- 'CON' if(length(inputs$factorBeta$factorList) > 0){ for(kk in 1:length(inputs$factorBeta$factorList)){ if( xnames[j] %in% inputs$factorBeta$factorList[[kk]] )type <- 'PA' if(all(x[,j] %in% c(0,1)))type <- 'PA' } } if(nhold > 0){ x1 <- x1[-holdoutIndex] x2 <- x2[-holdoutIndex] y1 <- y1[-holdoutIndex,,drop=F] yp <- yp[-holdoutIndex,,drop=F] } xlim <- range(x1, na.rm=T) bins <- seq(xlim[1], xlim[2], length=12) ylim <- range(x2, na.rm=T) if(length(bins) > 0){ breaks <- bins nPerBin <- NULL } ncc <- max( c(100,max(x1, na.rm=T)/20) ) xy <- .gjamBaselineHist(x1, bins=bins, nclass=ncc) xy[2,] <- ylim[1] + .3*xy[2,]*diff(ylim)/max(xy[2,]) plot(xy[1,], xy[2,], col='tan', type='s', lwd=2, xlim=xlim, ylim=ylim, xlab=' ', ylab=ylab) polygon(xy[1,],xy[2,],border='tan',col='wheat') abline(0,1,lty=2,lwd=3,col='grey') add <- T if(nhold > 0){ points(x[holdoutIndex,j],xpredMu[holdoutIndex,j],col='brown', pch=21, bg='blue',cex=.4) } opt <- list(log=F, xlabel='Observed', atx = bins, ylabel='Predicted', col='darkgreen', ylim=ylim, xlim = xlim, add=T) tmp <- .plotObsPred(x1, x2, opt = opt) if(nhold > 0)points(x[holdoutIndex,j],xpredMu[holdoutIndex,j], col='brown',cex=.3) abline(0, 1, col='grey', lty=2, lwd=2) abline(h = mean(x1, na.rm=T), col='grey', lty=2, lwd=2) if(length(missX) > 0){ ww <- which(missX[,2] == j) if(length(ww) > 0){ wz <- missX[ww,] if(!is.matrix(wz))wz <- matrix(wz,1) points(jitter(ww*0+xmaxX[j]),xpredMu[wz],cex=.6,col='blue') } } .plotLabel(paste(letters[j-1],xnames[j],sep=') '), above=AA) } mtext('Observed',side=1, outer=T) mtext('Predicted',side=2,outer=T) if(!SAVEPLOTS){ readline('x inverse prediction, covariates -- return to continue ') } else { dev.off() } } } if( PLOTALLY ){ yy <- y[,notOther] np <- ncol(yy) npage <- 1 o <- 1:np if(np > 16){ npage <- ceiling(np/16) np <- 16 } mfrow <- .getPlotLayout(np) k <- 0 add <- F o <- 1:np o <- o[o <= 16] if(length(other) > 0)o <- o[!o %in% other] for(p in 1:npage){ file <- paste('yPredBySpec_',p,'.pdf',sep='') if(SAVEPLOTS)pdf( file=.outFile(outFolder,file) ) npp <- ncol(yy) - k if(npp > np)npp <- np mfrow <- .getPlotLayout(np) par(mfrow=mfrow, bty='n', omi=c(.3,.3,0,0), mar=c(3,3,2,1), tcl= tcl, mgp=mgp) for(j in o){ censm <- NULL if( length(censor) > 0 ){ if( typeNames[j] %in% names(censor) ){ wjc <- which(names(censor) == typeNames[j]) if(j %in% censor[[wjc]]$columns)censm <- censor[[wjc]] } } if(j > ncol(yy))next y1 <- yy[,j] y1[ y1 < 0 ] <- 0 yp <- ypredMu[,j] if( min(y1) == max(y1) | var(yp, na.rm=T) == 0)next sxx <- sqrt(y1) syy <- sqrt(yp) opt <- .getBinSqrt(y1, yp, nbin = 10 ) if( !typeNames[wk[1]] %in% c('PA','CAT') ){ xy <- .gjamBaselineHist( sxx, bins = opt$atx, ylim = opt$ylim, nclass=length(opt$atx) ) plot(xy[1,], xy[2,], col='tan', type='s', lwd=2, xlim=opt$xlim, ylim = opt$ylim, xlab='', ylab='', xaxt='n', yaxt='n') polygon(xy[1,],xy[2,], border = specColor[j], col = boxCol[j]) axis(1, at = opt$atx, labels = opt$labx) axis(2, at = opt$aty, labels = opt$laby, las=2) opt <- append(opt, list( xlabel='Observed', ylabel='Predicted', col = specColor[j]) ) tmp <- .plotObsPred( xx = sxx, yy = syy, add=T, opt = opt) abline(0, 1, lty=2, col='grey') } else { y11 <- mean(y1,na.rm=T) y00 <- 1 - y11 x11 <- c(-.07,-.07,.07,.07,.93,.93,1.07,1.07,-.07) y11 <- c(0,y00,y00,0,0,y11,y11,0,0) atx <- min(y1):max(y1) aty <- atx xlim <- atx + c(-1,1)*.2 plot(NULL,col='tan',type='s',lwd=2, xlim= xlim + 1,ylim=range(aty), xlab='Observed',ylab='', xaxt='n',yaxt='n') axis(1, at = atx + 1, labels = atx ) axis(2, at = aty, labels = atx ) polygon(x11 + 1,y11, border = specColor[j], col = boxCol[j]) stats <- tapply( as.vector(yp), as.vector(y1), quantile, pnorm(c(-1.96,-1,0,1,1.96)) ) stats <- matrix( unlist(stats), ncol = 2 ) tmp <- .boxplotQuant( yp ~ y1, stats = stats, xaxt='n', yaxt = 'n', outline=F, border=specColor[j], whiskcol=specColor[j], boxfill= boxCol[j], pars = list(boxwex = 0.1, ylim=range(aty)), lty=1, add = T) abline(-1, 1, lty=2, lwd = 2, col = 'grey') } k <- k + 1 if(k > 26)k <- 1 lab <- paste(letters[k],') ',colnames(y)[j],' - ', typeNames[j], sep='') .plotLabel( lab,above=T ) abline(h = mean(yp),lty=2, col='grey') } mtext('Observed', 1, outer=T) mtext('Predicted', 2, outer=T) if(!SAVEPLOTS){ readline('y prediction -- return to continue ') } else { dev.off() } o <- o + 16 o <- o[o <= S] } } if(TRAITS){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'traitPred.pdf') ) tt <- grep('other',colnames(plotByTrait)) if(length(tt) > 0)colnames(plotByTrait)[tt] <- colnames(specByTrait)[tt] traitTypes <- traitList$traitTypes ctrait <- traitTypes if( !is.null( attr(ctrait, 'CCgroups') ) )ctrait <- paste(ctrait, attr(ctrait, 'CCgroups'), sep='_') if( !is.null( attr(ctrait, 'FCgroups') ) )ctrait <- paste(ctrait, attr(ctrait, 'FCgroups'), sep='_') atr <- unique(ctrait) tcols <- colF( length(atr) ) traitColor <- tcols[ match(ctrait, atr) ] yy <- plotByTrait o <- 1:ncol(yy) if(ncol(yy) > 16){ rmspe <- sqrt( colSums( (plotByTrait - tMu)^2 )/n ) o <- order(rmspe)[1:16] yy <- plotByTrait[,o] } mfrow <- .getPlotLayout(length(o)) par(mfrow=mfrow, bty='n', oma=oma, mar=c(3,3,1,1), tcl= tcl, mgp=mgp) k <- 0 for(j in o){ add <- F jname <- colnames(tMu)[j] k <- k + 1 td <- plotByTrait[,jname] tjj <- tMu[,j] wj <- which(colnames(tMu) == jname) tmp <- .gjamPlotPars(type=traitTypes[j],td,tjj) y1 <- tmp$y1; yp <- tmp$yp; nbin <- tmp$nbin; nPerBin <- tmp$nPerBin vlines <- tmp$vlines; xlimit <- tmp$xlimit; ylimit <- tmp$ylimit breaks <- tmp$breaks; wide <- tmp$wide; LOG <- tmp$LOG; POINTS <- F MEDIAN <- tmp$MEDIAN if(nhold > 0){ add <- T log <- '' if(LOG)log <- 'xy' plot(td[holdoutIndex],tjj[holdoutIndex],xlab=' ',ylab=ylab, xlim=xlimit,ylim=ylimit,col='grey',pch=21,bg='brown',cex=.4,log=log) } opt <- list( xlabel=' ',ylabel=ylab,nbin=nbin, nPerBin=nPerBin, xlimit=xlimit,ylimit=ylimit,breaks=breaks, wide=wide,LOG=LOG, fill='grey', col = traitColor[j], POINTS=F,MEDIAN=MEDIAN,add=add ) tmp <- .plotObsPred(td, tjj, opt = opt) abline(0,1,lty=2) abline(h=mean(td,na.rm=T),lty=2) .plotLabel( paste(letters[k],') ',.traitLabel(jname),sep=''),above=AA ) } if(!SAVEPLOTS){ readline('predictive trait distributions -- return to continue ') } else { dev.off() } } if( 'fSensGibbs' %in% names(chains) ){ nfact <- factorBeta$nfact if(!is.matrix(fSensGibbs)){ fSensGibbs <- matrix(fSensGibbs) colnames(fSensGibbs) <- xnames[-1] } if( 'factorBeta' %in% names(inputs) & !FACNAMES ){ fcnames <- names( inputs$factorBeta$factorList ) if(length(fcnames) > 0){ for(m in 1:length(fcnames)){ colnames(fSensGibbs) <- .replaceString( colnames( fSensGibbs ), fcnames[m], '' ) } } } if( ncol(fSensGibbs) > 1){ wc <- c(1:ncol(fSensGibbs)) wx <- grep(':',colnames(fSensGibbs)) wx <- c(wx, grep('^2',colnames(fSensGibbs), fixed=T) ) if(length(wx) > 0)wc <- wc[-wx] wx <- grep('intercept',colnames(fSensGibbs)) if(length(wx) > 0)wc <- wc[-wx] wc <- c(1:ncol(fSensGibbs)) tmp <- apply(fSensGibbs,2,range) wx <- which(tmp[1,] == tmp[2,] | tmp[2,] < 1e-12) if(length(wx) > 0)wc <- wc[-wx] if(length(wc) > 0){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'sensitivity.pdf') ) xx <- fSensGibbs[,wc,drop=F] tcol <- rep('black',ncol(xx)) names(tcol) <- colnames(xx) if(nfact > 0){ mm <- max(nfact,2) useCols <- colorRampPalette(c('brown','orange','darkblue'))(mm) for(i in 1:nfact){ im <- which(colnames(xx) %in% rownames(factorBeta$contrast[[i]])) tcol[im] <- useCols[i] } } par(mfrow=c(1,1),bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp) if(TIME)par(mfrow=c(1,2),bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp) ord <- order( colMeans(xx) ) ylim <- c( quantile(xx,.002), 5*quantile(xx,.99)) tmp <- .boxplotQuant( xx[,ord, drop=F], yaxt='n',outline=F, border=tcol[ord], whiskcol=tcol[ord], boxfill=.getColor(tcol[ord],.4), horizontal = TRUE, pars = list(boxwex = 0.5, ylim=ylim), lty=1, log='x') sensLab <- expression( paste('Sensitivity ',hat(bold(F)) )) mtext(sensLab,side=1,line=3) dy <- .05*diff(par()$yaxp[1:2]) text(dy + tmp$stats[5,],1:length(wc), tmp$names, pos=4,col=tcol[ord], cex=.8) } if(!SAVEPLOTS){ readline('sensitivity over full model -- return to continue ') } else { dev.off() } } } if(termB){ fnames <- rownames(factorBeta$eCont) tmp <- .splitNames(colnames(bgibbs),snames=colnames(y)) vnames <- unique(tmp$vnam) xnam <- unique(tmp$xnam[tmp$xnam != 'intercept']) if(SAVEPLOTS)pdf( file=.outFile(outFolder,'betaChains.pdf') ) if(CHAINS & termB){ cseq <- 1:nrow(bgibbs) if(length(cseq) > 1000)cseq <- seq(1,length(cseq),length=1000) mfrow <- .getPlotLayout(length(xnam)) par(mfrow=mfrow, bty='n', oma=oma, mar=c(2,2,1,1), tcl= tcl, mgp=mgp) flist <- factorBeta$factorList if(length(flist) > 0){ flist <- sort(unique(unlist(flist))) } for(k in 1:length(xnam)){ tname <- xnam[k] tmp <- .chains2density(bgibbs[cseq,],varName=tname, cut=3) xt <- tmp$x yt <- tmp$y chainMat <- tmp$chainMat if(ncol(chainMat) > 20)chainMat <- chainMat[,sample(ncol(chainMat),20)] cols <- colF(nrow(xt)) snamek <- .splitNames(colnames(chainMat),colnames(y))$vnam nn <- nrow(chainMat) jk <- 1:ncol(chainMat) if(length(jk) > 20)jk <- sample(jk,20) plot(0,0,xlim=c(0,(1.4*nn)),ylim=range(chainMat[,jk]), xlab=' ',ylab=' ',cex=.01) for(j in jk){ lines(chainMat[,j],col=cols[j]) if(ncol(chainMat) < 15)text(nn,chainMat[nn,j],snamek[j],col=cols[j],pos=4) abline(v=burn,lty=2) if(k == 1 & j == 1).plotLabel( paste(burnin,":",ng), location='topright' ) } .plotLabel(label=paste(letters[k],') ',tname,sep=''), location='topleft',above=T) abline(h=0,lwd=4,col='white') abline(h=0,lty=2) if(ncol(chainMat) >= 15) text(nn,mean(par('usr')[3:4]), paste(ncol(chainMat),'spp'),pos=4) } if(!SAVEPLOTS){ readline('beta coefficient thinned chains -- return to continue ') } else { dev.off() } } } if(CHAINS){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'corChains.pdf') ) par(mfrow=c(2,2), bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp) w0 <- 1:ncol(sgibbs) if(REDUCT){ same <- .sameByColumn(kgibbs) w0 <- order(same[lower.tri(same,diag=T)]) } else { w0 <- sample(max(w0),80,replace=T) } ww <- 1:20 for(jj in 1:4){ ssj <- w0[ww] ssj <- ssj[is.finite(ssj)] if(length(ssj) == 0)break if(max(ssj) > max(w0))break ww <- ww + 20 tmp <- .chains2density(rgibbsShort[,ssj]) xt <- tmp$x yt <- tmp$y chainMat <- tmp$chainMat cols <- colF(nrow(xt)) stk <- .splitNames(colnames(chainMat))$vnam ws <- which(stk[,1] == stk[,2]) if(length(ws) > 0){ stk <- stk[-ws,] chainMat <- chainMat[,-ws] } rr <- range(chainMat) if(!is.finite(rr[1]) | !is.finite(rr[2]))next if(is.matrix(chainMat)){ snamek <- stk[,1] nn <- nrow(chainMat) plot(0,0,xlim=c(0,(1.4*nn)),ylim=range(chainMat),xlab=' ',ylab=' ',cex=.01) jk <- 1:ncol(chainMat) if(length(jk) > 20)jk <- sample(jk,20) for(j in jk){ lines(chainMat[,j],col=cols[j]) if(ncol(chainMat) < 15)text(nn,chainMat[nn,j],snamek[j],col=cols[j],pos=4) } if(jj == 1).plotLabel( paste(burnin,":",ng),location='topright' ) abline(h=0,lwd=4,col='white') abline(h=0,lty=2) abline(v=burn,lty=2) if(ncol(chainMat) >= 15) text(nn,mean(par('usr')[3:4]), paste(ncol(chainMat),'spp'),pos=4) } } if(!SAVEPLOTS){ readline('correlation thinned chains -- return to continue ') } else { dev.off() } } if(TIME & CHAINS){ if(termR){ cseq <- 1:nrow(lgibbs) if(nrow(lgibbs) > 1000)cseq <- seq(1,length(cseq),length=1000) if(SAVEPLOTS)pdf( file=.outFile(outFolder,'rhoChains.pdf') ) tmp <- .splitNames(colnames(lgibbs),colnames(y)) vnames <- unique(tmp$vnam) xnam <- unique(tmp$xnam) mfrow <- .getPlotLayout(length(xnam)) par(mfrow=mfrow, bty='n', oma=oma, mar=c(2,2,1,1), tcl= tcl, mgp=mgp) for(k in 1:length(xnam)){ tname <- xnam[k] tmp <- .chains2density(lgibbs[cseq,],varName=tname, cut=3) xt <- tmp$x yt <- tmp$y chainMat <- tmp$chainMat if(ncol(chainMat) > 20)chainMat <- chainMat[,sample(ncol(chainMat),20)] cols <- colF(nrow(xt)) snamek <- .splitNames(colnames(chainMat),colnames(y))$vnam nn <- nrow(chainMat) jk <- 1:ncol(chainMat) if(length(jk) > 20)jk <- sample(jk,20) plot(0,0,xlim=c(0,(1.4*nn)),ylim=range(chainMat[,jk]), xlab=' ',ylab=' ',cex=.01) for(j in jk){ lines(chainMat[,j],col=cols[j]) if(ncol(chainMat) < 15)text(nn,chainMat[nn,j],snamek[j],col=cols[j],pos=4) if(k == 1 & j == 1).plotLabel( paste(burnin,":",ng), location='topright' ) } if(k == 1)tname <- character(0) lab <- paste('rho',tname) .plotLabel(label=paste(letters[k],') ',lab,sep=''),location='topleft',above=T) abline(h=0,lwd=4,col='white') abline(h=0,lty=2) if(ncol(chainMat) >= 15) text(nn,mean(par('usr')[3:4]), paste(ncol(chainMat),'spp'),pos=4) abline(v=burn,lty=2) } if(!SAVEPLOTS){ readline('rho coefficient chains -- return to continue ') } else { dev.off() } } if(termA){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'alphaChains.pdf') ) cseq <- 1:nrow(alphaGibbs) if(length(cseq) > 1000)cseq <- seq(1,length(cseq),length=1000) kp <- min(c( 4, floor(S/4) ) ) ka <- c(1:S) if(kp > 0){ np <- min(c(S,4)) mfrow <- .getPlotLayout(np) par(mfrow=mfrow, bty='n', oma=oma, mar=c(2,2,1,1), tcl= tcl, mgp=mgp) for(k in 1:np){ wc <- sample(ka,kp) ka <- ka[!ka %in% wc] tmp <- .chains2density(alphaGibbs[drop=F, cseq,wc], cut=3) xt <- tmp$x yt <- tmp$y chainMat <- tmp$chainMat cols <- colF(nrow(xt)) snamek <- .splitNames(colnames(chainMat),colnames(y))$vnam nn <- nrow(chainMat) jk <- 1:ncol(chainMat) if(length(jk) > 20)jk <- sample(jk,20) plot(0,0,xlim=c(0,(1.4*nn)),ylim=range(chainMat[,jk]), xlab=' ',ylab=' ',cex=.01) for(j in jk){ lines(chainMat[,j],col=cols[j]) if(ncol(chainMat) < 15)text(nn,chainMat[nn,j],snamek[j], col=cols[j],pos=4) if(k == 1 & j == 1).plotLabel( paste(burnin,":",ng), location='topright' ) } abline(h=0,lwd=4,col='white') abline(h=0,lty=2) abline(v=burn,lty=2) if(ncol(chainMat) >= 15) text(nn,mean(par('usr')[3:4]), paste(ncol(chainMat),'spp'),pos=4) } if(!SAVEPLOTS){ readline('example alpha coefficient chains -- return to continue ') } else { dev.off() } } } } if(termB){ bfSig <- bFacGibbs if(length(bfSig) > 0){ tmp <- .splitNames(colnames(bfSig), snames) vnam <- tmp$vnam xnam <- tmp$xnam fnames <- unique( xnam ) xpNames <- .replaceString(fnames,':','X') xpNames <- .replaceString(xpNames,'I(','') xpNames <- .replaceString(xpNames,')','') xpNames <- .replaceString(xpNames,'^2','2') xpNames <- .replaceString(xpNames,'*','TIMES') brange <- apply(bfSig,2,range) for(j in 1:length(fnames)){ wc <- which(xnam == fnames[j] & brange[2,] > brange[1,]) if(length(wc) < 2)next plab <- paste('beta_',xpNames[j],'.pdf',sep='') if(SAVEPLOTS)pdf( file=.outFile(outFolder,plab) ) par(mfrow=c(1,1),bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp) .myBoxPlot( mat = bfSig[,wc], tnam = vnam[ wc ], snames = snames, specColor, label=fnames[j], LEG=F) mtext(side=2,'Coefficient', line=2) if( !is.null(names(specColor)) ){ lf <- sort( unique(names(specColor)) ) cc <- specColor[lf] legend('bottomright',names(cc), text.col = cc, bty='n') } if(!SAVEPLOTS){ readline('beta standardized for W/X, 95% posterior -- return to continue ') } else { dev.off() } } if(length(fnames) > 1){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'betaAll.pdf') ) npp <- length(which(table(match(xnam,fnames)) > 1)) mfrow <- .getPlotLayout(npp) par( mfrow=mfrow, bty='n', omi=c(.3,.5,0,0), mar=c(1,1,1,1), tcl= tcl ) k <- 0 for(j in 1:length(fnames)){ wc <- which(xnam == fnames[j]) if(length(wc) < 2)next k <- k + 1 .myBoxPlot( mat = bfSig[,wc], tnam = vnam[ wc ], snames = snames, specColor, label=' ', LEG=F) .plotLabel(fnames[j],'bottomleft') } mtext(side=2,'Coefficient value',outer=T, line=1) if(!SAVEPLOTS){ readline('95% posterior -- return to continue ') } else { dev.off() } } } } if( termR ){ lgibbs <- chains$lgibbs tmp <- .splitNames(colnames(chains$lgibbs), snames) vnam <- tmp$vnam xnam <- tmp$xnam gnames <- unique(xnam) k <- 0 for(j in 1:length(gnames)){ wc <- which(xnam == gnames[j]) if(length(wc) < 2)next k <- k + 1 plab <- paste('rho_',gnames[j],'.pdf',sep='') if(j == 1){ glab <- 'rho' }else{ glab <- paste('rho:',gnames[j]) } if(SAVEPLOTS)pdf( file=.outFile(outFolder,plab) ) par(mfrow=c(1,1),bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp) .myBoxPlot( mat = lgibbs[,wc], tnam = vnam[ wc ], snames = snames, specColor, label=glab) if(!SAVEPLOTS){ readline('95% posterior -- return to continue ') } else { dev.off() } } if(length(gnames) > 1){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'rhoAll.pdf') ) npp <- length(which(table(match(xnam,gnames)) > 1)) mfrow <- .getPlotLayout(npp) par( mfrow=mfrow, bty='n', oma=oma, mar=c(2,2,1,1), tcl= tcl, mgp=mgp ) k <- 0 for(j in 1:length(gnames)){ wc <- which(xnam == gnames[j]) if(length(wc) < 2)next k <- k + 1 if(j == 1){ glab <- 'rho' }else{ glab <- paste('rho:',gnames[j]) } .myBoxPlot( mat = lgibbs[,wc], tnam = vnam[ wc ], snames = snames, specColor, label=glab) } if(!SAVEPLOTS){ readline('95% posterior -- return to continue ') } else { dev.off() } } } if(TRAITS){ M <- nrow(specByTrait) bt <- chains$bTraitFacGibbs wi <- grep( ':', colnames(bt) ) if(length(wi) > 0)bt <- bt[,-wi] vnam <- columnSplit( colnames(bt), '_') mnames <- colnames(specByTrait) xnam <- vnam[,2] vnam <- vnam[,1] if(length(traitColor) == 1)traitColor <- rep(traitColor, M) tboxCol <- .getColor(traitColor,.4) traitSd <- apply(plotByTrait,2,sd,na.rm=T) for(j in 2:length(xnames)){ wc <- which(xnam == xnames[j]) if(length(wc) < 2)next mt <- match( names(traitSd), vnam[wc] ) mx <- which( names(xSd) == xnames[j] ) if(SAVEPLOTS)pdf( file=.outFile(outFolder,'traits.pdf') ) par(mfrow=c(1,1),bty='n', oma=oma, mar=mar, tcl= tcl, mgp=mgp) tsd <- matrix(traitSd[mt], nrow(bt), length(mt), byrow=T) mat <- bt[,wc]*xSd[mx]/tsd vn <- .splitNames(colnames(mat))$vnam[,1] .myBoxPlot( mat, tnam = vn, snames = mnames, traitColor, label='', LEG=F ) .plotLabel(xnames[j],location='bottomright') if(!SAVEPLOTS){ readline('traits, standardized for X/W, 95% posterior -- return to continue ') } else { dev.off() } } } covx <- cov(x) covy <- cov(y[,notOmit]) wo <- which(whichZero[,1] %in% other | whichZero[,2] %in% other) if(length(wo) > 0)whichZero <- whichZero[-wo,] wo <- which(whConZero[,1] %in% other | whConZero[,2] %in% other) if(length(wo) > 0)whConZero <- whConZero[-wo,] nsim <- 500 if(S > 50)nsim <- 100 if(S > 100)nsim <- 20 if( !TIME | (TIME & termB) ){ tmp <- eigen( ematrix[notOther,notOther] ) eVecs <- tmp$vectors eValues <- tmp$values rownames(eVecs) <- snames[notOther] } if(TIME){ sensMu <- sensSe <- numeric(0) acol <- colF(3) names(acol) <- c('movement','DI growth','DD growth') scol <- character(0) if('sensBeta' %in% names(parameters)){ sensMu <- cbind(sensMu, sensBeta[,1]) sensSe <- cbind(sensSe, sensBeta[,1]) colnames(sensMu)[ncol(sensMu)] <- colnames(sensSe)[ncol(sensMu)] <- 'beta' scol <- c(scol, acol[1]) } if('sensRho' %in% names(parameters)){ sensMu <- cbind(sensMu, sensRho[,1]) sensSe <- cbind(sensSe, sensRho[,1]) colnames(sensMu)[ncol(sensMu)] <- colnames(sensSe)[ncol(sensMu)] <- 'rho' scol <- c(scol, acol[2]) } if('sensAlpha' %in% names(parameters)){ sensMu <- cbind(sensMu, sensAlpha[,1]) sensSe <- cbind(sensSe, sensAlpha[,1]) colnames(sensMu)[ncol(sensMu)] <- colnames(sensSe)[ncol(sensMu)] <- 'alpha' scol <- c(scol, acol[3]) } if(length(sensMu) > 0){ osens <- order( colMeans(sensMu), decreasing=T ) sensMu <- sensMu[,osens,drop = FALSE] sensSe <- sensSe[,osens,drop = FALSE] scol <- scol[ osens ] nc <- ncol(sensMu) sensMu <- sensMu[drop = FALSE, notOther,] sensSe <- sensSe[drop = FALSE, notOther,] ord <- order(sensMu[,1], decreasing = T) graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'varianceComponents.pdf') ) mfrow <- c(1,1) if(nc > 1)mfrow <- c(2,1) par( mfrow = mfrow, bty = 'n', mar = c(3,4,1,2) ) if(nc > 1){ sigma <- sqrt( diag( sigMu )[notOther] ) sens <- cbind(sensMu, sigma) sprop <- sweep( sens, 1, rowSums(sens), '/') ord <- order(sprop[,1], decreasing = T) smu <- t(sprop[ord,]) smu <- smu[drop=F, 1:(nrow(smu)-1),] smax <- max( colSums(smu) ) tmp <- barplot( smu, beside = F, col = .getColor(scol, .4), border = scol, xaxt = 'n', ylim = c(0, smax), ylab = 'Proportion of total SD' ) text( tmp - .2*diff(tmp)[1], .04, colnames(smu), srt = 90, pos = 4, cex=.9) } smu <- t(sensMu[drop=F, ord,]) sse <- t(sensSe[drop=F, ord,]) tmp <- barplot( smu, beside = T, col = .getColor(scol, .4), border = scol, xaxt = 'n', ylim = 1*c(0, max(smu + sse)), ylab = 'Std deviation scale' ) for(j in 1:nc){ suppressWarnings( arrows( tmp[j,], smu[j,], tmp[j,], smu[j,] + sse[j,], col = scol[j], lwd=2, angle=90, code=3, length=.04) ) } if(nc == 1)text( tmp[1,], 1.05*apply(smu + sse, 2, max), colnames(smu), srt = 75, pos = 4, cex = .9) legend('topright', names(scol), text.col = scol, bty='n') if(!SAVEPLOTS){ readline('contributions to dynamics -- return to continue ') } else { dev.off() } } if( !is.null(alphaEigen)){ graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'alphaEigenValues.pdf') ) par( mfrow = c(1,1), bty = 'n') if(!is.complex(alphaEigen)){ plot( alphaEigen, alphaEigen*0 , pch=15, xlim = c(-1, 1), ylim = c(-1, 1), xlab = 'Real', ylab = 'Imaginary') }else{ plot(alphaEigen, pch=15 ) } abline(h = 0, lty=2, lwd = 2, col = 'grey') abline(v = 0, lty=2, lwd = 2, col = 'grey') xs <- seq(-1, 1, length=100) ys <- sqrt(1 - xs^2) lines(xs, ys, lwd=2, lty=2, col = 'grey') lines(xs, -ys, lwd=2, lty=2, col = 'grey') if(!SAVEPLOTS){ readline('eigenvalues of alpha -- return to continue ') } else { dev.off() } } } if( !GRIDPLOTS ){ clusterIndex <- NULL clusterOrder <- NULL if( S >= 8 & !is.null(ematrix) ){ opt <- list( ncluster=ncluster, PLOT=F, DIST=F ) clusterDat <- .clusterPlot( ematrix , opt) colCode <- clusterDat$colCode cord <- rev(clusterDat$corder) dord <- notOther[!notOther %in% omit][cord] clusterIndex <- clusterDat$clusterIndex clusterOrder <- clusterDat$corder } invisible( return( list(fit = fit, ematrix = ematrix, clusterIndex = clusterIndex, clusterOrder = clusterOrder) ) ) } if(SAVEPLOTS)pdf( file=.outFile(outFolder,'clusterDataE.pdf') ) mag <- mar mag[4] <- max(mar[4],6) par(mfrow=c(1,2), cex=.7, oma=oma, mar=mag, tcl= tcl, mgp=mgp) LABELS <- T if(S > 100 | !SPECLABS)LABELS <- F dcor <- .cov2Cor(covy) dcor[is.na(dcor)] <- 0 opt <- list( main='',cex=.2,ncluster=ncluster, colCode=specColor[notOmit], textSize=.4, LABELS = LABELS, DIST=F ) tmp <- .clusterPlot( dcor, opt) colCode <- tmp$colCode clusterIndex <- tmp$clusterIndex clusterOrder <- tmp$corder .plotLabel('a) Data correlation',above=T, cex=1.7) if( !is.null(ematrix) ){ emm <- ematrix[notOther,notOther] emm <- .cov2Cor(emm) tmp <- .clustMat(emm, SYM = T) ecor <- tmp$cmat opt <- list( main='',cex=.2, ncluster=ncluster, colCode=specColor[notOmit], textSize=.5, LABELS = LABELS, DIST=F) tmp <- .clusterPlot( ecor , opt ) .plotLabel('b) E correlation',above=T, cex=1.7) clusterIndex <- cbind( clusterIndex, tmp$clusterIndex ) clusterOrder <- cbind( clusterOrder, tmp$corder ) rownames(clusterIndex) <- rownames(clusterOrder) <- snames[notOmit] colnames(clusterIndex) <- colnames(clusterOrder) <- c('data','E') } if(!SAVEPLOTS){ readline('Data and E responses to X -- return to continue ') } else { dev.off() } if(!is.null(ematrix)){ imat <- output$inputs$y imat[imat > 0] <- 1 iord <- colSums(imat) etab <- table(clusterIndex[,'E']) eComs <- matrix(NA,ncluster, max(etab)) ename <- rep( character(0), max(etab) ) egroup <- clusterIndex[,'E'] for(j in 1:ncluster){ wj <- which(clusterIndex[,'E'] == j) jname <- rownames(clusterIndex)[wj] jname <- jname[order(iord[jname],decreasing=T)] eComs[j,1:length(jname)] <- jname mm <- min( c(3,length(jname)) ) jj <- substr(jname[1:mm],1,6) ename[j] <- paste0(jj,collapse='_') } rownames(eComs) <- ename eComs <- t(eComs) if(SAVEPLOTS)pdf( file=.outFile(outFolder,'ordination.pdf') ) clusNames <- eComs[1,] lambda <- eValues/sum(eValues) cl <- cumsum(lambda) cbord <- .getColor(specColor[notOther],.4) cfill <- .getColor(specColor[notOther],.4) par(mfcol=c(2,2), bty='n', cex = cex, mar=c(4,4,1,1)) p1 <- paste('Axis I (',round(100*lambda[1],0),'%)',sep='') p2 <- paste('Axis II (',round(100*lambda[2],0),'%)',sep='') p3 <- paste('Axis III (',round(100*lambda[3],0),'%)',sep='') xlim <- range(eVecs[,1]) plot(eVecs[,1],eVecs[,2],cex=1,col=cbord, bg = cfill, pch=16, xlab=p1, ylab = p2) abline(h=0,col=.getColor('black',.1),lwd=2,lty=2) abline(v=0,col=.getColor('black',.1),lwd=2,lty=2) text(eVecs[clusNames,1],eVecs[clusNames,2],substr(clusNames,1,7)) plot(eVecs[,1],eVecs[,3],cex=1,col=cbord, bg = cfill, pch=16, xlab=p1, ylab = p3) abline(h=0,col=.getColor('black',.1),lwd=2,lty=2) abline(v=0,col=.getColor('black',.1),lwd=2,lty=2) text(eVecs[clusNames,1],eVecs[clusNames,3],substr(clusNames,1,7)) plot(eVecs[,2],eVecs[,3],cex=1,col=cbord, bg = cfill, pch=16, xlab=p2, ylab = p3) abline(h=0,col=.getColor('black',.1),lwd=2,lty=2) abline(v=0,col=.getColor('black',.1),lwd=2,lty=2) text(eVecs[clusNames,2],eVecs[clusNames,3],substr(clusNames,1,7)) plot(cl,type='s',xlab='Rank',ylab='Proportion of variance',xlim=c(.9,S), ylim=c(0,1),log='x') lines(c(.9,1),c(0,cl[1]),lwd=2,type='s') for(j in 1:length(lambda))lines(c(j,j),c(0,cl[j]),col='grey') lines(cl,lwd=2,type='s') abline(h=1,lwd=2,col=.getColor('grey',.5),lty=2) if(!SAVEPLOTS){ readline('ordination of E matrix -- return to continue ') } else { dev.off() } } if(REDUCT){ graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'dimRed.pdf') ) mk <- .modalValuesInArray(kgibbs,2)[notOmit] NK <- table( table(mk) ) mk <- length(NK) r <- otherpar$r par(bty='n') scale <- SO/3 if(SMALLPLOTS)scale <- 10*scale .mapSetup(c(1,SO),c(1,SO),scale=scale) xl <- SO/15 yl <- SO/8 en <- SO*(SO+1)/2 plot(0,0,xlim=c(0,SO+xl),ylim=c(0,SO+xl),cex=.01,xaxt='n',yaxt='n', xlab=' ',ylab=' ') rect(xl,yl,SO+xl,SO+yl,col='wheat',border='wheat',lty=2,lwd=2) polygon(c(xl,SO+xl,xl),c(yl,yl,SO+yl),col='blue',border='darkblue') rect(0,yl/10,r,mk+yl/10,col='blue',border='wheat', lwd=2) text(xl+SO/4,yl+SO/3,bquote(Sigma == .(en)), col='wheat', cex=1.4 ) text(r, yl/20*(mk + 1), paste('Z (',mk,' x ',r,' = ',mk*r,')',sep=''),col='blue', cex=1.,pos=4) .plotLabel('Dimensions','topright') if(!SAVEPLOTS){ readline('reduction from sigma to Z -- return to continue ') } else { dev.off() } } if(SAVEPLOTS)pdf( file=.outFile(outFolder,'clusterGridR.pdf') ) par(mfrow=c(1,1),bty='n',cex=1, oma=oma, mar=mag, tcl= tcl, mgp=mgp) colnames(corMu) <- rownames(corMu) <- colnames(y) psize <- .62 if(SMALLPLOTS)psize <- psize/2 par(plt=c(.03,.15,.1,.9), bty='n', new=F) opt <- list( main=' ',cex=.2, ncluster=ncluster, colCode=specColor[notOmit], textSize=.5, LABELS = F, DIST=F ) tmp <- .clusterPlot( corMu[notOmit,notOmit] , opt) colCode <- tmp$colCode corder <- rev(tmp$corder) rOrder <- snames[notOmit[corder]] clusterIndex <- cbind( clusterIndex, tmp$clusterIndex ) clusterOrder <- cbind( clusterOrder, tmp$corder ) ncc <- ncol(clusterIndex) colnames(clusterIndex)[ncc] <- colnames(clusterOrder)[ncc] <- 'R' if(LABELS){ par(plt=c(.15,.33,.1,.9), bty='n', new=T) plot(c(0,0),c(0,0),col='white',xlim=range(c(0,1)),ylim=c(0,SO), xaxt='n',yaxt='n',xlab='',ylab='') xl <- rep(.5,SO) yl <- c(1:SO) + par('usr')[3] - .75 cex <- .fitText2Fig(rOrder,fraction=1.2) text( xl,yl,rev(rOrder),pos=3,cex=cex, col=rev(colCode[corder])) } tmp <- .invMatZero(sgibbs,nsim=nrow(sgibbs),snames=snames, knames=rOrder,index=NULL, COMPRESS=T, REDUCT=REDUCT, sigErrGibbs = output$chains$sigErrGibbs, kgibbs = output$chains$kgibbs, otherpar = otherpar, alpha=ematAlpha) marIn <- tmp$inMarMat conIn <- tmp$inConMat wm <- which(marIn[,1] %in% omit | marIn[,2] %in% omit) if(length(wm) > 0)marIn <- marIn[-wm,] wm <- which(conIn[,1] %in% omit | conIn[,2] %in% omit) if(length(wm) > 0)conIn <- conIn[-wm,] sigCor <- c(nrow(marIn),nrow(conIn))/SM/(SM - 1) sigCor <- round(100*sigCor,0) names(sigCor) <- c('n_marIn','n_conIn') mor <- notOmit[corder] crr <- corMu[mor,mor] marIn[,1] <- match(marIn[,1],mor) marIn[,2] <- match(marIn[,2],mor) conIn[,1] <- match(conIn[,1],mor) conIn[,2] <- match(conIn[,2],mor) makeCR <- list('white' = conIn,'grey' = marIn) if(!is.null(specColor))textCol = colCode[mor] par(plt=c(.33, .33 + psize,.1,.9), bty='n', new=T) slim <- quantile(crr[lower.tri(crr)],c(.05,.95)) SPECLABS <- F if(S < 30)SPECLABS <- T .corPlot(crr, slim=slim, makeColor=makeCR,plotScale=.99, PDIAG=T,CORLINES=CORLINES, textCol = colCode[corder], SPECLABS = SPECLABS, squarePlot = F, textSize=1, widex = width, widey = height, new=T, add=F) ll <- paste(c('Cond Ind (white) = ', 'Cond & Marg Ind (grey) = '), sigCor,c('%','%'),sep='') legend('topright',ll,bty='n',cex=.8) .plotLabel(expression( paste(hat(bold(R)),'structure' )),above=T, cex=.9) if(!SAVEPLOTS){ readline('posterior correlation for model -- return to continue ') } else { dev.off() } fBetaMu <- output$parameters$betaStandXWmu if( 'factorBeta' %in% names(inputs) & !FACNAMES){ fcnames <- names( inputs$factorBeta$factorList ) for(m in 1:length(fcnames)){ colnames(fBetaMu) <- .replaceString( colnames( fBetaMu ), fcnames[m], '' ) } } if(Q > 4 & !is.null(fMat)){ main1 <- expression( paste('Sensitivity ',hat(F))) main2 <- expression( paste('Responses ',hat(B))) ws <- which( rowSums(fMat) == 0) if(length(ws) > 0){ not0 <- c(1:nrow(fMat))[-ws] fMat <- fMat[drop=F,not0,not0] rn <- intersect( rownames(fMat), rownames(fBetaMu) ) fMat <- fMat[drop=F,rn,rn] fBetaMu <- fBetaMu[rn,] } mat1 <- fMat mat2 <- fBetaMu expand <- ncol(mat1)/ncol(mat2) expand <- max(c(1.,expand)) expand <- min( c(1.5, expand) ) if(nrow(fMat) > 3){ graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'gridF_B.pdf') ) opt <- list(mainLeft=main1, main1=main1, main2 = main2, leftClus=T, topClus2=T, rightLab=F, topLab1=T, topLab2 = T, leftLab=T, ncluster = ncluster, colCode2 = specColor[notOther], lower1 = T, diag1 = T, lower2 = F) tr <- try( .clusterWithGrid(mat1, mat2, expand=expand, opt), TRUE ) if( inherits(tr,'try-error') ){ .clusterWithGrid(mat1, mat2, expand=1, opt) } if(!SAVEPLOTS){ readline('F & beta structure -- return to continue ') } else { dev.off() } } } graphics.off() if(!is.null(ematrix)){ if(SAVEPLOTS)pdf( file=.outFile(outFolder,'clusterGridE.pdf') ) mat1 <- .cov2Cor( ematrix[notOther,notOther] ) main1 <- expression(paste('Species ',hat(E))) opt <- list(mainLeft=main1, leftClus=T, leftLab=T, colCode1 = specColor[notOther], rowCode = specColor[notOther], topLab1=T,ncluster = ncluster, lower1 = T, diag1 = F,horiz1=clusterIndex[,'E']) .clusterWithGrid(mat1, mat2=NULL, expand=1, opt) if(!SAVEPLOTS){ readline('E: model-based response to X -- return to continue ') } else { dev.off() } graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'gridR_E.pdf') ) dcor <- .cov2Cor(covy) dcor[is.na(dcor)] <- 0 mat1 <- dcor mat2 <- .cov2Cor( ematrix[notOther,notOther] ) main1 <- expression(paste('Ordered by error ',hat(R))) main2 <- expression(paste('Response ',hat(E))) opt <- list(mainLeft='Species', main1=main1, main2 = main2, leftClus=T, leftLab=T, rowCode = specColor[notOther], topLab1 = T, topLab2 = T,rightLab=F,ncluster = ncluster, lower1 = T, diag1 = F,lower2 = T, diag2 = T) .clusterWithGrid(mat1, mat2, expand=1, opt) if(!SAVEPLOTS){ readline('comparison R vs E -- return to continue ') } else { dev.off() } graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'gridY_E.pdf') ) ytmp <- jitter(y[,mor],1e-10) cory <- cor(ytmp) mat1 <- cory mat2 <- ematrix[notOther,notOther] main1 <- 'Ordered by data, cor(Y)' main2 <- expression(paste('Response ',hat(E))) topLab1 <- topLab2 <- F if(S < 30)topLab1 <- topLab2 <- T opt <- list(mainLeft='Species', main1=main1, main2 = main2, leftClus=T, leftLab=T, lower1 = T, diag1 = F, rowCode = specColor[notOther], topLab1 = topLab1, topLab2 = topLab2,ncluster = ncluster, lower2 = T, diag2 = T, sameOrder = T) .clusterWithGrid(mat1, mat2=mat2, expand=1, opt ) if(!SAVEPLOTS){ readline('raw data vs E -- return to continue ') } else { dev.off() } } if(is.null(output$parameters$betaStandXWmu)){ BETAGRID <- FALSE }else{ if( nrow(output$parameters$betaStandXWmu) > 2 & ncol(output$parameters$betaStandXWmu) > 1)BETAGRID <- TRUE } if( BETAGRID ){ graphics.off() mat1 <- .cov2Cor( output$parameters$ematrix[notOther,notOther] ) mat2 <- t(output$parameters$betaStandXWmu) if( 'factorBeta' %in% names(inputs) & !FACNAMES){ fcnames <- names( inputs$factorBeta$factorList ) for(m in 1:length(fcnames)){ colnames(mat2) <- .replaceString( colnames( mat2 ), fcnames[m], '' ) rownames(mat2) <- .replaceString( rownames( mat2 ), fcnames[m], '' ) } } if(SAVEPLOTS)pdf( file=.outFile(outFolder,'clusterGridB.pdf') ) main1 <- expression(paste('Species ',hat(E))) main2 <- expression(paste(hat(B),' by predictor')) topLab1 <- F if(S < 30)topLab1 <- T ee <- ncol(mat1)/ncol(mat2) ee <- max(c(ee,.8)) ee <- min(c(ee, 1.2)) opt <- list(mainLeft=main1, main1=main1, main2 = main2, topClus1=T, topClus2=T, topLab1 = topLab1, topLab2=T, leftLab=T,lower1 = T, diag1 = F, ncluster = ncluster, colCode1 = specColor[notOther], rowCode = specColor[notOther], vert1=clusterIndex[,'E'], horiz2=clusterIndex[,'E']) .clusterWithGrid(mat1, mat2, expand=ee, opt) if(!SAVEPLOTS){ readline('beta ordered by response to X -- return to continue ') } else { dev.off() } if(RANDOM){ graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'randGroups.pdf') ) G <- ncol(randByGroup) mat1 <- randGroupVarMu[notOther,notOther] mat1 <- .cov2Cor(mat1) diag(mat1) <- 0 mat2 <- randByGroup[notOther,] main1 <- expression(paste('Species ')) main2 <- expression('Group') topLab1 <- F if(S < 30)topLab1 <- T ee <- ncol(mat1)/ncol(mat2) ee <- max(c(ee,1)) ee <- min(c(ee, 1.2)) opt <- list(mainLeft=main1, main1=main1, main2 = main2,leftClus=T, topClus1=F, topClus2=T, topLab1 = topLab1, topLab2=T, leftLab=T, lower1 = T, diag1 = F, colCode1 = specColor[notOther]) .clusterWithGrid(mat1, mat2, expand=ee, opt) if(!SAVEPLOTS){ readline('random groups correlation, coeffs -- return to continue ') } else { dev.off() } } if(TIME){ graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'clusterTime.pdf') ) mat1 <- alphaMu[notOther,notOther] lam <- rhoStandXmu[,notOther] mat2 <- t(lam) colnames(mat2)[1] <- 'rho' main1 <- expression(paste(hat(alpha),' from')) side1 <- expression(paste(hat(alpha),' to')) main2 <- expression(hat(rho)) mat1[is.na(mat1)] <- 0 mat2[is.na(mat2)] <- 0 topLab1 <- F if(S < 30)topLab1 <- T ee <- ncol(mat1)/(ncol(mat1) + ncol(mat2) ) slim1 <- range(mat1) if(slim1[2] == 0)slim1[2] <- .0001 opt <- list(mainLeft=side1, main1=main1, main2 = main2, ncluster = ncluster, topClus1=F, topClus2=F, topLab1 = topLab1, topLab2=T, leftLab = T, rowCode = specColor[notOther], rowOrder = c(1:S)[notOther], colOrder1 = c(1:S)[notOther], colOrder2 = 1:ncol(mat2), slim1 = slim1, colCode1 = specColor[notOther], lower1 = F, diag1 = F) .clusterWithGrid(mat1, mat2, expand=ee, opt) if(!SAVEPLOTS){ readline('alpha, rho -- return to continue ') } else { dev.off() } graphics.off() if(SAVEPLOTS)pdf( file=.outFile(outFolder,'clusterGridRho.pdf') ) mat1 <- ematrix[notOther,notOther] main1 <- expression(paste('Species ',hat(E))) main2 <- expression(paste(hat(Rho),' by predictor')) topLab1 <- F if(S < 40)topLab1 <- T ee <- max(ee,.05) opt <- list(mainLeft=main1, main1=main1, main2 = main2, colOrder2 = 1:ncol(mat2), ncluster = ncluster, topClus1=T, topClus2=T, topLab1 = topLab1, topLab2=T, colCode1 = specColor[notOther], lower1 = T, diag1 = F) .clusterWithGrid(mat1, mat2, expand=ee, opt) if(!SAVEPLOTS){ readline('Ematrix and rho -- return to continue ') } else { dev.off() } } if(TRAITS){ betaTraitXMu <- output$parameters$betaTraitXWmu if(nrow(betaTraitXMu) > 3){ bb <- betaTraitXMu[-1,] ord <- order(colSums(abs(bb)),decreasing=T) bb <- bb[,ord] bl <- bb[,ord] bh <- bb[,ord] ror <- order(rowSums(abs(bb)),decreasing=T) bb <- bb[ror,] bl <- bl[ror,] bh <- bh[ror,] white <- which(bl < 0 & bh > 0,arr.ind=T) makeColor <- list('white' = white ) if(SAVEPLOTS)pdf( file=.outFile(outFolder,'gridTraitB.pdf') ) plotScale <- max(c(10,c(S,Q)/10)) par(mfrow=c(1,1), bty='n', oma=c(1,1,1,1), mar=c(5,4,4,2), tcl= tcl, mgp=mgp) ht <- nrow(bb)/ncol(bb)*width opt <- list(mainLeft='', main1='', main2 = '', topClus1=T, topClus2=T, topLab1 = T, topLab2=F, leftClus=T, leftLab=T, ncluster = ncluster, colCode1 = traitColor) .clusterWithGrid(mat1=betaTraitXMu[-1,], mat2=NULL, expand=1, opt) if(!SAVEPLOTS){ readline('trait beta -- return to continue ') } else { dev.off() } } } } all <- list(fit = fit, ematrix = ematrix, eComs = eComs, ncluster = ncluster, clusterIndex = clusterIndex, clusterOrder = clusterOrder, eVecs = eVecs, eValues = eValues) all <- all[ order(names(all)) ] invisible(all) } .gjamPrediction <- function(output, newdata, y2plot, PLOT, ylim, FULL, verbose = FALSE){ if( is.null(newdata) ){ if(PLOT){ y1 <- output$inputs$y y2 <- output$prediction$ypredMu if(!is.null(y2plot)){ y1 <- y1[,y2plot] y2 <- y2[,y2plot] } tmp <- .bins4data(y1) breaks <- tmp$breaks bins <- tmp$bins nbin <- tmp$nbin if(length(bins) > 0){ breaks <- bins nPerBin <- NULL } opt <- list(nPerBin = NULL, breaks=breaks, ylimit = range(y2, na.rm=T), fill='lightblue', box.col='darkblue', POINTS=F) .plotObsPred(y1, y2, opt = opt) abline(0,1,lwd=4,col='white') abline(0,1,lwd=2,col='grey',lty=2) } return( list( ypredMu = output$modelSummary$ypredMu, ypredSe = output$modelSummary$ypredSd ) ) } xdata <- xnew <- ydataCond <- interBeta <- groupRandEff <- NULL tiny <- 1e-10 effMat <- wHold <- phiHold <- ploHold <- sampleWhold <- NULL STAND <- COND <- RANDOM <- NEWX <- XCOND <- FALSE cindex <- NULL groupRandEff <- 0 TRAITS <- SAMEY <- FALSE effortSource <- 'output' ng <- output$modelList$ng burnin <- output$modelList$burnin randByGroupMu <- output$parameters$randByGroupMu randByGroupSe <- output$parameters$randByGroupSe groupIndex <- output$parameters$groupIndex rndEffMu <- output$parameters$rndEffMu rndEffSe <- output$parameters$rndEffSe ngroup <- ncol(randByGroupMu) if(!is.null(randByGroupMu))RANDOM <- TRUE Q <- length(output$inputs$xnames) n <- nrow(output$inputs$y) y <- yp <- output$inputs$y x <- output$inputs$xStand S <- SO <- S1 <- ncol(y) xnames <- colnames(x) ynames <- colnames(y) notOther <- output$inputs$notOther other <- output$inputs$other SO <- length(notOther) otherpar <- output$modelList$reductList$otherpar censor <- output$modelList$censor xdata <- output$inputs$xdata notStandard <- output$modelList$notStandard nsim <- 500 if( 'nsim' %in% names(newdata))nsim <- newdata$nsim if( 'xdata' %in% names(newdata))NEWX <- T if( 'ydataCond' %in% names(newdata))COND <- T if( 'xdata' %in% names(newdata) & 'ydataCond' %in% names(newdata) )XCOND <- T if( 'SAMEY' %in% names(newdata) )SAMEY <- newdata$SAMEY if( 'TRAITS' %in% names(output$modelList) )TRAITS <- output$modelList$TRAITS effort <- output$modelList$effort effMat <- effort$values inSamp <- 1:n REDUCT <- output$modelList$REDUCT SAMEX <- F sigmaerror <- NULL if(REDUCT){ otherpar <- output$modelList$reductList$otherpar N <- otherpar$N r <- otherpar$r rndEff <- y*0 sigmaerror <- otherpar$sigmaerror if( !NEWX )SAMEX <- T if(COND)stop('conditional prediction not currently implemented with dimension reduction' ) } cuts <- output$parameters$cutMu if(!is.null(cuts))cuts <- cbind(-Inf,0,cuts,Inf) nfact <- output$inputs$factorBeta$nfact isFactor <- output$inputs$factorBeta$isFactor factorList <- output$inputs$factorBeta$factorList contrasts <- output$inputs$factorBeta$contrast formula <- output$modelList$formula xscale <- output$inputs$standX if(is.matrix(xscale)) xscale <- t(xscale) facNames <- names(factorList) facLevels <- unlist( factorList ) typeNames <- output$modelList$typeNames tmp <- .gjamGetTypes(typeNames) typeFull <- tmp$typeFull typeCols <- tmp$typeCols allTypes <- unique(typeCols) typeCode <- tmp$TYPES[typeCols] FCgroups <- attr(typeNames,'FCgroups') CCgroups <- attr(typeNames,'CCgroups') CATgroups <- attr(typeNames,'CATgroups') condCols <- numeric(0) corCols <- which( typeNames %in% c('PA','OC','CAT') ) notCorCols <- 1:S standRows <- output$inputs$standRows standMatSd <- output$inputs$standMatSd standX <- output$inputs$standX standRows <- standRows[ !names(standRows) %in% facLevels ] standMatSd <- standMatSd[ !names(standMatSd) %in% facLevels ] standX <- standX[ drop=F, !rownames(standX) %in% facLevels, ] xmu <- standX[,1] xsd <- standX[,2] intMat <- interBeta$intMat nx <- n <- nrow(x) if( NEWX ){ xnew <- newdata$xdata nx <- n <- nrow(xnew) colnames(xnew) <- .cleanNames(colnames(xnew)) wna <- which(is.na(xnew),arr.ind=T) if(length(wna) > 0) stop('cannot have NA in prediction grid newdata$xdata') } ymaxData <- apply( output$inputs$y, 2, max ) if( NEWX & RANDOM ){ rname <- output$modelList$random randGroupTab <- table( as.character(xnew[,rname]) ) wss <- names(randGroupTab[randGroupTab <= 2]) if(length(wss) > 0){ cat('\nNote: one or more random groups with one observations\n') } fnow <- names( which( sapply( output$inputs$xdata, is.factor ) ) ) fnew <- names( which( sapply( xnew, is.factor ) ) ) fnow <- fnow[ fnow %in% colnames(xnew) ] ww <- which( !fnow %in% fnew ) if(length(ww) > 0)for(k in ww){ xnew[,fnow[k]] <- as.factor( xnew[,fnow[k]] ) } if( identical( output$inputs$xdata, xnew ) ){ SAMEX <- T if(verbose)cat( paste('\nPredict same X, use any fitted random effects\n', sep = '') ) }else{ if(verbose)cat( paste('\nPredict different X, marginalize any fitted random effects\n', sep = '') ) } } if( !NEWX & RANDOM & verbose ){ SAMEX <- T cat( paste('\nPredict same X, use any fitted random effects\n', sep = '') ) } if( NEWX | XCOND ){ holdoutN <- nx holdoutIndex <- 1:nx if( 'effort' %in% names(newdata) ){ if( is.null(newdata$effort$columns) )newdata$effort$columns <- 1:S effort <- newdata$effort if( is.matrix( effort$values) ){ effMat <- effort$values }else{ effMat <- matrix( 1, nx, S ) effMat[,effort$columns] <- effort$values } effortSource <- 'newdata' }else{ effMat <- matrix(1, nx, S) effortSource <- 'ones' print( 'no effort provided in newdata') if( all( !c('CON','CA','CC','FC') %in% typeNames) )print( 'assumed equal to 1') } if(REDUCT){ if(SAMEY){ cat("\nUsing fitted RE from dimension reduction\n") }else{ cat("\nRandom effects generated by dimension reduction are marginalized") cat(" here, unlike in function gjam where they are used directly for") cat(" prediction. With dimension reduction, predictions here will be") cat(" noisier than from gjam\n") } } effort <- list(columns = c(1:S), values = effMat) ydataCond <- NULL if( nfact > 0 ){ for(j in 1:nfact){ nf <- names(factorList)[j] wf <- which(names(xnew) == nf) wo <- which(names(output$xnew) == nf) wc <- which(names(contrasts) == names(factorList)[j]) cc <- contrasts[[wc]] xnew[[wf]] <- factor( xnew[[wf]], levels = rownames(cc) ) attr(xnew[[wf]],'contrasts') <- cc } } yp <- matrix(0,nx,S) colnames(yp) <- ynames standMatSd <- output$inputs$standX[,'xsd'] standMatMu <- output$inputs$standX[,'xmean'] intMat <- output$inputs$intMat standMatSd <- standMatSd[ !names(standMatSd) %in% facLevels ] standMatMu <- standMatMu[ !names(standMatMu) %in% facLevels ] ig <- grep(':', names(standRows)) if(length(ig) > 0){ standRows <- standRows[-ig] standMatMu <- standMatMu[ names(standRows) ] standMatSd <- standMatSd[ names(standRows) ] } tmp <- .getStandX(formula, xu = xnew, standRows, xmu = standMatMu, xsd = standMatSd ) xnew <- tmp$xstand u2s <- tmp$U2S tmp <- .gjamXY(formula, xnew, yp, typeNames, notStandard = names(xnew), checkX = F, xscale = xscale, verbose) x <- tmp$x beta <- output$parameters$betaStandXmu if( is.null(beta) ){ beta <- output$parameters$betaMu STAND <- FALSE } w <- x%*%beta if( length(corCols) > 0 ){ sg <- output$parameters$sigMu alpha <- .sqrtMatrix( bg, sg, DIVIDE = T ) w[,corCols] <- x%*%alpha[,corCols] } yp <- w*effMat wca <- which(typeNames == 'CA') if(length(wca) > 0){ yp[,wca][yp[,wca] < 0] <- 0 } wda <- which(typeNames == 'DA') if(length(wda) > 0){ yp[,wda] <- round(yp[,wda],0) yp[,wda][yp[,wda] < 0] <- 0 } ordCols <- which(typeNames == 'OC') if(length(ordCols) > 0){ tmp <- .gjamGetCuts(yp + 1, ordCols) cutLo <- tmp$cutLo cutHi <- tmp$cutHi for(k in ordCols){ yp[,k] <- findInterval(yp[,k],cuts[k,]) - 1 } } if( length(FCgroups) > 0 ){ ntt <- max(FCgroups) for(i in 1:ntt){ wk <- which( FCgroups == i ) wo <- which(wk %in% notOther) yp[,wk] <- .gjamCompW2Y(yp[,wk,drop=F], notOther=wo)$ww } } if( length(CCgroups) > 0 ){ if(verbose)cat( '\nFor CC data total effort (count) is taken as 10000' ) ysum <- rep(10000,n) ntt <- max(CCgroups) y <- output$inputs$y wFromY <- sweep( y, 1, rowSums(y, na.rm=T), '/') wFromY[ !is.finite(wFromY) ] <- 0 wmax <- apply( wFromY, 2, max ) wmat <- matrix( wmax, n, S, byrow = T ) yp <- sweep( wmat, 1, rowSums(wmat, na.rm=T), '/') yp <- round( yp*10000 ) } tmp <- .gjamSetup(typeNames, x, y = yp, breakList=NULL, holdoutN=NULL, holdoutIndex=NULL, censor=NULL, effort=effort) w <- tmp$w; z <- tmp$z; yp <- tmp$y; other <- tmp$other plo <- tmp$plo; phi <- tmp$phi ordCols <- tmp$ordCols; disCols <- tmp$disCols; compCols <- tmp$compCols minOrd <- tmp$minOrd; maxOrd <- tmp$maxOrd; censorCA <- tmp$censorCA censorDA <- tmp$censorDA; censorCON <- tmp$censorCON; ncut <- ncol(cuts) corCols <- tmp$corCols if(length(corCols) > 0)notCorCols <- notCorCols[-corCols] catCols <- which(attr(typeNames,'CATgroups') > 0) sampleW <- tmp$sampleW*0 + 1 byCol <- byRow <- F if(attr(sampleW,'type') == 'cols')byCol <- T if(attr(sampleW,'type') == 'rows')byRow <- T indexW <- attr(sampleW,'index') inSamp <- 1:n byCol <- byRow <- F if(attr(sampleW,'type') == 'cols')byCol <- T if(attr(sampleW,'type') == 'rows')byRow <- T indexW <- attr(sampleW,'index') cdex <- c(1:S) } if( RANDOM ){ avm <- output$parameters$randGroupVarMu avs <- output$parameters$randGroupVarSe lt <- lower.tri(avm, diag = T) wrand <- which(lt, arr.ind=T) avg <- matrix(0, S, S) } if( COND | XCOND ){ ydataCond <- newdata$ydataCond if( !is.data.frame(ydataCond) & !is.matrix(ydataCond) )stop( 'ydataCond must be a matrix with column names to match ydata' ) if(is.data.frame(ydataCond))ydataCond <- as.matrix(ydataCond) colnames(ydataCond) <- .cleanNames(colnames(ydataCond)) condNames <- colnames(ydataCond) if('other' %in% condNames){ condNames <- condNames[condNames != 'other'] ydataCond <- ydataCond[,condNames] } if( !XCOND )yp <- y condCols <- match(condNames, colnames(yp)) yp[,condCols] <- as.matrix( ydataCond ) condW <- condCols[ typeNames[condCols] %in% c('CA','DA','PA','OC','CC') ] condCA <- condCols[ typeNames[condCols] == 'CA' ] cdex <- c(1:S)[-condCols] } tmp <- .gjamSetup(typeNames, x, yp, breakList=NULL, holdoutN=NULL, holdoutIndex=NULL,censor=NULL, effort=effort) w <- tmp$w; z <- tmp$z; yp <- tmp$y; other <- tmp$other plo <- tmp$plo; phi <- tmp$phi ordCols <- tmp$ordCols; disCols <- tmp$disCols; compCols <- tmp$compCols minOrd <- tmp$minOrd; maxOrd <- tmp$maxOrd; censorCA <- tmp$censorCA cuts <- tmp$cuts censorDA <- tmp$censorDA; censorCON <- tmp$censorCON; ncut <- ncol(cuts) corCols <- tmp$corCols if(length(corCols) > 0)notCorCols <- notCorCols[-corCols] catCols <- which(attr(typeNames,'CATgroups') > 0) sampleW <- tmp$sampleW sampleW[,-condCols] <- 1 if( XCOND ){ effort <- tmp$effort print( 'with new xdata, effort assumed equal to 1' ) }else{ if( any( c('DA') %in% typeNames & !'effort' %in% names(newdata) ) )print( 'original effort used for prediction' ) } standRows <- output$inputs$standRows standMatSd <- output$inputs$standX[,'xsd'] standMatMu <- output$inputs$standX[,'xmean'] byCol <- byRow <- F if(attr(sampleW,'type') == 'cols')byCol <- T if(attr(sampleW,'type') == 'rows')byRow <- T indexW <- attr(sampleW,'index') yz <- y if( XCOND )yz <- yp if(length(other) > 0)cdex <- cdex[!cdex %in% other] S1 <- length(cdex) yg <- yp if(length(yp) < 10000 | FULL) FULL <- T if(FULL){ ygibbs <- wgibbs <- matrix(0,nsim,length(yp)) } pmax <- apply(output$inputs$y/output$modelList$effort$values,2,max) CCsums <- CCmax <- numeric(0) if( !is.null(CCgroups) ){ ncc <- max(CCgroups) for(j in 1:ncc){ wjk <- which(CCgroups == j) rs <- rowSums( output$inputs$y[,wjk] ) ms <- output$inputs$y[,wjk]/rs ms <- apply(ms, 2, max, na.rm = T) CCmax <- append(CCmax, list( ms ) ) CCsums <- append(CCsums, list( rs ) ) pmax[ wjk ] <- ms } } pmax[ pmax < .1 & typeNames %in% c('DA','CA','PA','OC') ] <- .1 ptmp <- 2*matrix(pmax,n,S,byrow=T) ptmp[,ordCols] <- length(ordCols) + 10 ptmp[,compCols] <- 1.2*ptmp[,compCols] ptmp[,compCols][ptmp[,compCols] > 1] <- 1 ptmp[,catCols] <- 10 if( COND ){ ncc <- sort(unique( c(condCols, other) )) ploCond <- -ptmp[,-ncc, drop = F]/2 phiCond <- ptmp[,-ncc, drop = F] colnames(ploCond) <- colnames(phiCond) <- colnames(y)[-ncc] holdoutN <- 0 holdoutIndex <- NULL ploHold <- phiHold <- NULL } if( !COND & !XCOND & !SAMEX ){ holdoutN <- n holdoutIndex <- c(1:n) plo <- -ptmp*.5 phi <- ptmp ploHold <- -ptmp*.5 phiHold <- ptmp } if( SAMEY ){ holdoutN <- 0 } RD <- F if( (REDUCT & SAMEX) | SAMEY) RD <- T .updateW <- .wWrapper(REDUCT = RD, RANDOM, S, effMat, corCols, notCorCols, typeNames, typeFull, typeCols, allTypes, holdoutN, holdoutIndex, censor, censorCA, censorDA, censorCON, notOther, sampleW, byRow, byCol, indexW, ploHold, phiHold, sampleWhold, inSamp) ypred <- matrix(0,n,S) colnames(ypred) <- ynames ypred2 <- wcred <- wcred2 <- ypred if(TRAITS){ specByTrait <- output$modelList$traitList$specByTrait specTrait <- specByTrait[colnames(y),] tnames <- colnames(specTrait) M <- ncol(specTrait) specTrait <- t(specTrait) traitTypes <- output$modelList$traitList$traitTypes tpred <- matrix(0, n, M) colnames(tpred) <- rownames(specTrait) tpred2 <- tpred } gvals <- sample(burnin:ng,nsim,replace=T) pbar <- txtProgressBar(min=1,max=nsim,style=1) ig <- 0 corColC <- cdex[cdex %in% corCols] corColW <- which(cdex %in% corCols) ddex <- which(notOther %in% cdex) kdex <- c(1:S)[-ddex] pdex <- ddex[ typeNames[ddex] %in% c('CON','CA') ] cutg <- cuts ncut <- ncol(cutg) ccols <- which(typeNames != 'CON') kg <- 1 rndEff <- 0 prPresent <- w*0 emat <- matrix(0,S,S) colnames(emat) <- rownames(emat) <- ynames lo <- hi <- lm <- hm <- ess <- emat eCont <- output$inputs$factorBeta$eCont dCont <- output$inputs$factorBeta$dCont lCont <- output$inputs$factorBeta$lCont covE <- cov( x%*%dCont ) frow <- NULL if(nfact > 0){ frow <- rep(0,Q) for(j in 1:nfact){ frow[ match(factorList[[j]], xnames) ] <- j } } q1 <- nrow(eCont) fnames <- rownames(eCont) facList2 <- factorList if(nfact > 0){ for(j in 1:nfact){ wj <- which(names(xnew) == names(factorList)[j]) facList2[[j]] <- levels(xnew[[wj]]) } } notPA <- which(!typeNames == 'PA' & !typeNames == 'CON') notPA <- notPA[ !notPA %in% condCols ] tiny <- 1e-5 sampW <- 1 + w*0 rows <- 1:nrow(w) for(g in gvals){ bg <- matrix( output$chains$bgibbs[g,], Q, S ) muw <- x%*%bg if( REDUCT ){ sigmaerror <- output$chains$sigErrGibbs[g] if( RD ){ rndEff <- rndEffMu + matrix( rnorm( n*S, 0, rndEffSe ), n, S ) sg <- diag(sigmaerror, S) }else{ rndEff <- 0 Z <- matrix(output$chains$sgibbs[g,],N,r) K <- output$chains$kgibbs[g,] sg <- .expandSigma(sigmaerror, S, Z = Z, K, REDUCT = T) } if( COND ){ Z <- matrix(output$chains$sgibbs[g,],N,r) K <- output$chains$kgibbs[g,] sgcond <- .expandSigma(sigmaerror, S, Z = Z, K, REDUCT = T) } } else { sg <- .expandSigma(output$chains$sgibbs[g,], S = S, REDUCT = F) } if( RANDOM ){ if( SAMEX ){ randByGroup <- rnorm( length(randByGroupMu), randByGroupMu, randByGroupSe ) groupRandEff <- t( matrix( randByGroup, S, ngroup ) )[groupIndex,] }else{ avg[ wrand ] <- rnorm(nrow(wrand), avm[wrand], avs[wrand]) avg[ wrand[,c(2,1)] ] <- avg[ wrand ] groupRandEff <- .rMVN(ngroup, 0, avg)[groupIndex,] } } alpha <- .sqrtMatrix(bg,sg,DIVIDE=T) agg <- .sqrtMatrix(bg[,notOther],sg[notOther,notOther],DIVIDE=T) if(nfact > 0){ agg <- lCont%*%agg for(k in 1:nfact){ fk <- factorList[[k]] mua <- colMeans(agg[drop=F,fk,]) nl <- length(fk) agg[fk,] <- agg[fk,] - matrix(mua,nl,SO,byrow=T) } } else { agg <- agg[drop=F,-1,] } egg <- lCont%*%bg[,notOther] if( 'OC' %in% typeCode ){ cutg[,3:(ncut-1)] <- matrix( output$chains$cgibbs[g,], length(ordCols)) tmp <- .gjamGetCuts(yg + 1,ordCols) cutLo <- tmp$cutLo cutHi <- tmp$cutHi plo[,ordCols] <- cutg[cutLo] phi[,ordCols] <- cutg[cutHi] } tmp <- .updateW( rows=1:n, x, w, y = yp, bg, sg, alpha, cutg, plo, phi, rndEff=rndEff, groupRandEff, sigmaerror, wHold ) w <- tmp$w yg <- tmp$yp if( COND | XCOND ){ if( length(ddex) > 0 ){ gre <- groupRandEff if(length(gre) > 1)gre <- groupRandEff[,notOther] tmp <- .conditionalMVN(w[,notOther], muw[,notOther] + gre, sg[notOther,notOther], cdex = ddex) muc <- tmp$mu sgp <- tmp$vr wd <- which( ddex %in% corCols ) if( length(wd) > 0 ){ css <- .cov2Cor(sg) mus <- x%*%alpha wws <- .sqrtMatrix(w, sg, DIVIDE = T) tmp <- .conditionalMVN(wws, mus + groupRandEff, css, cdex = ddex, S) muk <- tmp$mu sgk <- tmp$vr muc[,wd] <- muk sgp[wd,wd] <- sgk } if( length(ddex) == 1 ){ wex <- matrix( .tnorm(n, ploCond, phiCond, muc, sqrt(sgp[1])) ) } else { lo <- ploCond hi <- phiCond avec <- muc avec[ muc < lo ] <- lo[ muc < lo ] avec[ muc > hi ] <- hi[ muc > hi ] wex <- .tnormMVNmatrix( avec = avec, muvec = muc, smat = sgp, lo=lo, hi=hi) } yPredict <- yg yPredict[,ddex] <- wex groups <- NULL z <- w z[,ddex] <- wex for(k in allTypes){ wk <- which(typeCols == k) nk <- length(wk) wo <- which(wk %in% notOther) wu <- which(typeCols[notOther] == k) wp <- z[, wk, drop=F] yq <- yPredict[, wk, drop=F] if(typeFull[wk[1]] == 'countComp')groups <- CCgroups if(typeFull[wk[1]] == 'fracComp')groups <- FCgroups if(typeFull[wk[1]] == 'categorical')groups <- CATgroups glist <- list(wo = wo, type = typeFull[wk[1]], yy = y[,wk,drop=F], wq = wp, yq = yq, cutg = cutg, censor = censor, censorCA = censorCA, censorDA = censorDA, censorCON = censorCON, eff = effMat[,wk,drop=F], groups = groups, k = k, typeCols = typeCols, notOther = notOther, wk = wk, sampW = sampleW[,wk]) tmp <- .gjamWLoopTypes( glist ) yPredict[,wk] <- tmp[[2]] } } yg[,ddex] <- yPredict[,ddex] muw[,pdex] <- muc yg[,condCols] <- as.matrix( ydataCond ) } if( length(ccols) > 0 ){ mmm <- muw[,ccols] mmm[mmm < 0] <- 0 muw[,ccols] <- mmm } yy <- yg if('PA' %in% typeNames){ wpa <- which(typeNames == 'PA') yy[,wpa] <- round(yg[,wpa]) } if(length(notPA) > 0){ w0 <- which(yy[,notPA] <= 0) w1 <- which(yy[,notPA] > 0) yy[,notPA][w0] <- 0 yy[,notPA][w1] <- 1 } prPresent <- prPresent + yy ig <- ig + 1 setTxtProgressBar(pbar,ig) ypred <- ypred + yg ypred2 <- ypred2 + yg^2 wcred <- wcred + muw wcred2 <- wcred2 + muw^2 ess[notOther,notOther] <- .cov2Cor( t(agg)%*%covE%*%agg ) emat[notOther,notOther] <- emat[notOther,notOther] + ess[notOther,notOther] if(FULL){ ygibbs[kg,] <- as.vector(yg) wgibbs[kg,] <- as.vector(muw) } if(TRAITS){ yw <- yg yw[yw <= 0] <- 0 yw[is.na(yw)] <- 0 yw <- sweep(yw,1,rowSums(yw),'/') Ttrait <- .gjamPredictTraits(yw,specTrait, traitTypes) tpred <- tpred + Ttrait tpred2 <- tpred2 + Ttrait^2 } kg <- kg + 1 } prPresent <- prPresent/nsim ematrix <- emat/nsim xf <- NULL if(length(facNames) > 0){ xf <- xdata[, facNames, drop=F] } xunstand <- try( .getUnstandX( formula, x, standRows, xmu, xsd, factorColumns = xf ), T ) if( inherits(xunstand,'try-error') ){ xunstand <- NULL cat( '\nNote: prediction x is not full rank' ) }else{ xunstand <- xunstand$xu } yMu <- ypred/nsim res <- ypred2/(nsim - 1) - yMu^2 res[res < tiny] <- tiny yPe <- sqrt(res) wMu <- wcred/nsim res <- wcred2/(nsim - 1) - wMu^2 res[res < tiny] <- tiny wSe <- sqrt(res) colnames(yMu) <- colnames(yPe) <- colnames(wMu) <- colnames(wSe) <- ynames sdList <- list( yMu = yMu, yPe = yPe, wMu = wMu, wSe = wSe ) if(TRAITS){ tMu <- tpred/nsim res <- tpred2/(nsim - 1) - tMu^2 res[res < tiny] <- tiny tSe <- sqrt(res) sdList$tMu <- tMu sdList$tSe <- tSe } piList <- NULL if(FULL){ wLo <- matrix( apply(wgibbs,2,quantile,.05), n, S ) wHi <- matrix( apply(wgibbs,2,quantile,.95), n, S ) yLo <- matrix( apply(ygibbs,2,quantile,.05), n, S ) yHi <- matrix( apply(ygibbs,2,quantile,.95), n, S ) colnames(wLo) <- colnames(wHi) <- colnames(yLo) <- colnames(yHi) <- ynames piList <- list( wLo = wLo, wHi = wHi, yLo = yLo, yHi = yHi ) } if(PLOT){ oma <- c(0,0,0,0) mar <- c(4,4,2,1) tcl <- -0.5 mgp <- c(3,1,0) par(oma = oma, mar = mar, tcl = tcl, mgp = mgp, bty='n') wy <- which(colnames(y) %in% y2plot & c(1:S) %in% notOther) t2plot <- typeNames[wy] allTypes <- unique(t2plot) mfrow <- .getPlotLayout(length(allTypes) + 1) par(mfrow=mfrow, bty='n', mar=c(1,2,3,1) ) k <- 0 add <- F for(j in 1:length(allTypes)){ wk <- which(typeNames == allTypes[j] & c(1:S) %in% notOther) ws <- colnames(y)[wk] wm <- which(colnames(yMu) %in% colnames(y)[wk]) wk <- match(colnames(yMu)[wm],colnames(y)) y1 <- y[,wk] if(min(y1) == max(y1))next y2 <- yMu[,wm] tmp <- .gjamPlotPars(type=allTypes[j],y1,y2) y1 <- tmp$y1; yp <- tmp$yp; nbin <- tmp$nbin; nPerBin <- tmp$nPerBin vlines <- tmp$vlines; xlimit <- tmp$xlimit; ylimit <- tmp$ylimit breaks <- tmp$breaks; wide <- tmp$wide; LOG <- tmp$LOG; POINTS <- F MEDIAN <- tmp$MEDIAN log <- '' if(LOG)log <- 'xy' if(LOG){ wn <- which(y1 > 0 & yp > 0) y1 <- y1[wn] yp <- yp[wn] } tmp <- .bins4data(y1,nPerBin=nPerBin,breaks=breaks,LOG=LOG) breaks <- tmp$breaks bins <- tmp$bins nbin <- tmp$nbin if( !allTypes[j] %in% c('PA','CAT') ){ ncc <- max( c(100,max(y1)/20) ) xy <- .gjamBaselineHist(y1,bins=bins,nclass=ncc) xy[2,] <- ylimit[1] + .8*xy[2,]*diff(ylimit)/max(xy[2,]) plot(xy[1,],xy[2,],col='tan',type='s',lwd=2,xlim=xlimit,ylim=ylimit, xlab='Observed',ylab='Predicted') polygon(xy[1,],xy[2,],border='tan',col='wheat') } else { y11 <- mean(y1) y00 <- 1 - y11 x11 <- c(-.07,-.07,.07,.07,.93,.93,1.07,1.07,-.07) y11 <- c(0,y00,y00,0,0,y11,y11,0,0) plot(x11,y11,col='tan',type='s',lwd=2,xlim=xlimit,ylim=ylimit, xlab='Observed',ylab='Predicted') polygon(x11,y11,border='tan',col='wheat') } abline(0,1,lty=2,lwd=3,col='brown') abline(h = mean(y1),lty=2,lwd=3,col='tan') add <- T opt <- list(xlabel='Observed',ylabel='Predicted',nbin=nbin, nPerBin=nPerBin, xlimit=xlimit,ylimit=ylimit, breaks=breaks, wide=wide, LOG=LOG, fill='lightblue', box.col='darkblue',POINTS=F, MEDIAN=MEDIAN, add=add) .plotObsPred(y1, y2, opt = opt) tt <- allTypes[j] if(length(ws) == 1)tt <- paste(ws,tt,sep='-') lab <- paste(letters[j],') ',tt, sep='') .plotLabel( lab,above=T ) } yp <- colMeans(yMu) wy <- match(colnames(yMu),colnames(y)) opt <- list(xlabel='Observed', xlimit=NULL, ylimit=NULL, breaks=breaks, wide=wide, LOG=LOG, fill='lightblue', box.col='darkblue', POINTS=T, ptcol='darkblue') .plotObsPred( colMeans(y[,wy]),yp, opt = opt) abline(0, 1,lty=2,lwd=3,col='brown') abline(h = mean(y1),lty=2,lwd=3,col='tan') .plotLabel( paste(letters[j+1],') By Species',sep=''),above=T ) } xb <- xunstand if(is.null(xb))xb <- x bk <- list( x = xb, sdList = sdList, piList = piList, prPresent = prPresent, ematrix = ematrix, effortSource = effortSource) if(FULL)bk <- append( bk, list(ychains = ygibbs) ) bk } .updateBetaTime <- function(X, Y, sig, rows, pattern, lo=NULL, hi=NULL){ SS <- ncol(Y) B <- t(lo)*0 tiny <- 1e-5 QX <- ncol(X) XX <- crossprod(X) omega <- sig*solveRcpp(XX) muB <- t(omega%*%crossprod((1/sig)*X, Y)) for(k in 1:nrow(rows)){ krow <- rows[k,] krow <- krow[is.finite(krow)] notk <- c(1:QX)[-krow] if(length(notk) == 1){ M1 <- omega[krow,notk, drop=F]/omega[notk,notk] }else{ OI <- try( solveRcpp(omega[notk,notk]), T) if( inherits(OI,'try-error') ){ OI <- diag(1/diag(omega[notk,notk])) } M1 <- omega[krow,notk, drop=F]%*%OI } pk <- pattern[k,] pk <- pk[is.finite(pk)] muk <- muB[pk, krow, drop=F] - muB[pk,notk]%*%t(M1) Mk <- omega[krow,krow] - M1%*%omega[notk,krow] if(is.null(lo)){ if(length(Mk) == 1){ B[pk,krow] <- rnorm(length(pk),muk,sqrt(Mk)) }else{ B[pk,krow] <- .rMVN( length(pk), rep(0,length(krow)), Mk) + muk } } else { if(length(Mk) == 1){ B[pk,krow] <- .tnorm(length(pk),lo[krow,pk],hi[krow,pk],muk,sqrt(Mk)) } else { ll <- t(lo)[pk,krow,drop=F] hh <- t(hi)[pk,krow,drop=F] test <- try( .tnormMVNmatrix( avec=muk, muvec=muk, smat=Mk, lo=ll, hi=hh), T) if( inherits(test,'try-error') ){ mm <- diag(Mk) mm[mm < tiny] <- tiny test <- .tnorm(length(ll),ll,hh,muk,sqrt(mm)) } B[pk,krow] <- test } } } t(B) } .updateTheta <- function(w,tg,cutLo,cutHi,ordCols,holdoutN, holdoutIndex,minOrd,maxOrd){ word <- w[,ordCols,drop=F] ncut <- ncol(tg) nr <- nrow(tg) nc <- ncut - 1 n <- nrow(w) nk <- length(ordCols) tiny <- 1e-5 summat <- matrix(0, nr, ncut) c1 <- cutLo[,1] c2 <- cutLo[,2] c3 <- cutHi[,1] c4 <- cutHi[,2] if(holdoutN > 0){ word <- word[-holdoutIndex,] ss <- seq(0,(nk-1)*n,by=n) wh <- as.vector( outer(holdoutIndex,ss,'+') ) c1 <- c1[-wh] c2 <- c2[-wh] c3 <- c3[-wh] c4 <- c4[-wh] } cmin <- .byGJAM(as.vector(word),c1,c2, summat=summat, fun='min') cmax <- .byGJAM(as.vector(word),c1,c2, summat=summat, fun='max') cmin <- cbind(cmin, Inf) cmax <- cbind(cmax, -Inf) maxw <- 2*max(w, na.rm=T) cmin[,2] <- cmax[,1] <- 0 cmin[ cbind(1:nr,maxOrd+1) ] <- cmax[ cbind(1:nr,maxOrd) ] + .1 cmax[ cbind(1:nr,maxOrd+1) ] <- cmin[ cbind(1:nr,maxOrd+1) ] + .1 icol <- 2:ncut clo <- cmax[drop=F,,1:(ncut-1)] chi <- cmin[drop=F,,icol] rowMax <- apply(cmax, 1, max, na.rm=T) ni <- ncol(clo) for(i in 2:ni){ wi <- which( !is.finite(clo[,i])) if(length(wi) > 0)clo[wi,i] <- chi[wi,i-1] + tiny wi <- which( clo[,i] < chi[,i-1]) if(length(wi) > 0)clo[wi,i] <- clo[wi,i-1] + tiny wi <- which(!is.finite(chi[,i]) & maxOrd == i) if(length(wi) > 0)chi[wi,i] <- maxw wi <- which(!is.finite(chi[,i]) & maxOrd > i) if(length(wi) > 0){ chi[wi,i] <- clo[wi,i] + tiny } wi <- which(chi[,i] < clo[,i]) if(length(wi) > 0)chi[wi,i] <- clo[wi,i] + tiny } wi <- which(is.nan(tg),arr.ind=T) if(length(wi) > 0)tg[wi] <- clo[wi] + tiny cmu <- tg[drop=F,,icol] ww <- which(is.finite(cmu)) tg[,icol][ww] <- .tnorm(length(ww), clo[ww], chi[ww], cmu[ww], .1) tg[,1] <- -10 tg } .censorValues <- function(censor,y,yp){ mm <- length(censor) if(mm == 0)return(yp) if(mm > 0){ for(m in 1:mm){ wc <- censor[[m]]$columns nc <- ncol( censor[[m]]$partition ) ym <- yp[,wc,drop=F] cp <- censor[[m]]$partition for(k in 1:nc){ wlo <- which( ym > cp[2,k] & ym < cp[3,k]) ym[wlo] <- cp[1,k] } yp[,wc] <- ym } } yp } .gjamWLoopTypes <- function( glist ){ wo <- type <- yy <- wq <- yq <- cutg <- censor <- censorCA <- censorDA <- censorCON <- eff <- groups <- k <- typeCols <- notOther <- wk <- sampW <- NULL for(k in 1:length(glist))assign( names(glist)[k], glist[[k]] ) if( type == 'continuous' ){ return( list(wq, yq) ) } nk <- ncol(wq) wkk <- c(1:nk) n <- nrow(wq) if( type == 'ordinal' ){ w2y <- wq for(s in 1:nk){ yq[,s] <- findInterval(yq[,s],cutg[s,]) - 1 } return( list(wq, yq) ) } if( type == 'presenceAbsence' ){ yq <- pnorm(yq) return( list(wq, yq) ) } if( type == 'contAbun' ){ yq[yq < 0] <- 0 return( list(wq,yq) ) } if( type == 'discAbun' ){ yq <- yq*eff yq[yq < 0] <- 0 if( length(censorDA) > 0 ) yq[-censorDA] <- yq[-censorDA] return( list( wq, yq) ) } if( type == 'categorical' ){ ntt <- max( groups ) w2y <- yq for(i in 1:ntt){ if(ntt == 1){ wki <- wkk } else { wki <- which( groups == i ) } nki <- length(wki) wko <- wki wmax <- apply( yq[,wko],1, which.max) yq[,wki] <- 0 yq[,wki][ cbind(1:n,wmax) ] <- 1 wmax <- apply( wq[,wko],1, which.max) w2y[,wki] <- 0 w2y[,wki][ cbind(1:n,wmax) ] <- 1 } return( list(wq, w2y) ) } if( type == 'countComp' ){ ntt <- max( groups ) ww <- wq yq[yq < 0] <- 0 for(i in 1:ntt){ if(ntt == 1){ wki <- wkk } else { wki <- which( groups == i ) } io <- which(wki %in% wo) wc <- .gjamCompW2Y(ww[,wki,drop=F], notOther=io)$ww ww[,wki][wq[,wki] > 0] <- wc[wq[,wki] > 0] yq[,wki] <- .gjamCompW2Y(yq[,wki,drop=F],notOther=io)$ww ysum <- rowSums(yy[,wki,drop=F]) yq[,wki] <- round( sweep(yq[,wki,drop=F],1,ysum,'*'), 0) } return( list(ww,yq) ) } ntt <- max( groups ) wy <- which(yq > 0) wq[wy] <- yq[wy] yq[yq < 0] <- 0 for(i in 1:ntt){ if(ntt == 1){ wki <- wkk } else { wki <- which(groups == i) } io <- which(wki %in% wo) yq[,wki] <- .gjamCompW2Y(yq[,wki,drop=F],notOther=io)$ww } list(wq, yq) } .gjamWcatLoop <- function(y, ws, mus, sgs, notOther, plo, phi, groups, REDUCT = F){ ntt <- max( groups ) n <- nrow(y) for(i in 1:ntt){ wki <- which(groups == i) nki <- length(wki) wko <- wki[wki %in% notOther] w0 <- apply( ws[,wko]*(1 - y[,wko]),1, max) w1 <- apply( ws[,wko]*y[,wko],1, max) w0[w0 < 0] <- 0 si <- sample(wko) for(s in si){ y1 <- which(y[,s] == 1) plo[-y1,s] <- -500 phi[y1,s] <- 500 plo[y1,s] <- w0[y1] phi[-y1,s] <- w1[-y1] if(REDUCT){ ws[,s] <- .tnorm(n,plo[,s],phi[,s],mus[,s],sqrt(sgs[s])) } else { sm <- which(notOther == s) tmp <- .conditionalMVN(ws[,notOther], mus[,notOther], sgs, sm) mue <- tmp$mu vr <- max(tmp$vr,1e-8) ws[,s] <- .tnorm(n,plo[,s],phi[,s],mue,sqrt(vr)) } w1[y1] <- ws[y1,s] w0[-y1] <- apply( ws[-y1,wki]*(1 - y[-y1,wki]),1, max) } } list(w = ws, plo = plo, phi = phi) } .gjamWcatLoop2 <- function(y, ws, mus, sgs, notOther, plo, phi, groups, REDUCT = F){ ntt <- max( groups ) n <- nrow(y) for(i in 1:ntt){ wki <- which(groups == i) nki <- length(wki) wko <- wki[wki %in% notOther] w1 <- apply( ws[,wko]*y[,wko],1, max) so <- match(wko,notOther) for(s in wko){ y1 <- which(y[,s] == 1) sm <- which(notOther == s) sn <- so[so != sm] qs <- wko[wko != s] if(REDUCT){ ws[y1,s] <- .tnorm(length(y1),plo[y1,s],phi[y1,s], mus[y1,s],sqrt(sgs[s])) } else { tmp <- .conditionalMVN(ws[y1,notOther], mus[y1,notOther], sgs, sm) mue <- tmp$mu vr <- max(tmp$vr,1e-8) ws[y1,s] <- .tnorm(length(y1),plo[y1,s],phi[y1,s],mue,sqrt(vr)) } w1[y1] <- ws[y1,s] phi[y1,wki] <- w1[y1] phi[y1,s] <- 500 if(REDUCT){ tmp <- .tnorm(length(y1)*length(qs),plo[y1,qs],phi[y1,qs], mus[y1,qs],sqrt(sgs[s])) } else { tmp <- .tnormMVNmatrix(ws[y1,notOther],mus[y1,notOther], smat=sgs, plo[y1,notOther], hi=phi[y1,notOther], whichSample=so)[,sn,drop=F] } ws[y1,qs] <- tmp if(length(sn) > 0)tmp <- apply( tmp, 1, max ) tmp[tmp < 0] <- 0 plo[y1,s] <- tmp } s <- wki[!wki %in% wko] y1 <- which(y[,s] == 1) tmp <- .tnormMVNmatrix(ws[y1,notOther],mus[y1,notOther], smat=sgs, plo[y1,notOther], hi=phi[y1,notOther], whichSample=so) ws[y1,wko] <- tmp[,so] } list(w = ws, plo = plo, phi = phi) } .gjamWLoop <- function( llist ){ ws <- mus <- sgs <- wkk <- lo <- hi <- sampW <- indexW <- NULL byCol <- T byRow <- F llist <- for(k in 1:length(llist))assign( names(llist)[k], llist[[k]] ) n <- nrow(lo) tiny <- .00001 if(byCol){ iss <- wkk[wkk %in% indexW] for(s in iss){ rs <- which(sampW[,s] > 0) ls <- lo[drop=F,rs,s] hs <- hi[drop=F,rs,s] tmp <- .conditionalMVN( ws[drop=F,rs,], mus[drop=F, rs,], sgs, cdex = s) mu <- tmp$mu vr <- max(tmp$vr,tiny) tmp <- .tnorm(length(rs),ls,hs,mu,sqrt(vr)) wl <- which(tmp == ls) if(length(wl) > 0) tmp[wl] <- ls[wl] + tiny*(ls[wl]) wl <- which(tmp == hs) if(length(wl) > 0) tmp[wl] <- hs[wl] - (1 - tiny)*hs[wl] ws[rs,s] <- tmp } return(ws) } for(i in indexW){ rs <- which(sampW[i,] > 0) rs <- rs[rs %in% wkk] ws[i,rs] <- .tnormMVNmatrix(ws[drop=F,i,], mus[drop=F,i,], smat=sgs, lo[drop=F,i,], hi[drop=F,i,], whichSample=rs)[,rs] } ws } .setContrasts <- function(xx){ levs <- attr(xx,'levels') nl <- length(levs) ml <- nl - 1 ref <- levs[1] intType <- attr(xx,'intType') if(is.null(intType))intType <- 'ref' wr <- which(levs == ref) cj <- matrix(-1/nl,ml,ml) diag(cj) <- ml/nl rownames(cj) <- levs[-wr] colnames(cj) <- levs[-wr] rj <- rep(-1/nl,ml) cj <- rbind(rj,cj) rownames(cj)[1] <- ref levs <- as.character(levs) cj <- cj[drop=F,levs,] if(intType == 'ref'){ cj[cj > 0] <- 1 cj[cj < 0] <- 0 } list(levs = levs, cont = cj) } .gjamXY <- function(formula, xdata, y, typeNames, notStandard, checkX = T, xscale = NULL, verbose = F){ n <- nrow(xdata) S <- ncol(y) snames <- colnames(y) facNames <- character(0) factorList <- contrast <- NULL colnames(xdata) <- .cleanNames(colnames(xdata)) NOX <- T xmean <- 1 xdataNames <- original <- colnames(xdata) if( !is.null(notStandard) )notStandard <- .cleanNames(notStandard) form <- attr( terms(formula), 'term.labels' ) xdata0 <- xdata if( length(form) > 0 ){ NOX <- F form <- .cleanNames(form) form <- paste0(form,collapse=' + ') formula <- as.formula( paste('~',form) ) t1 <- attr( terms(formula), 'term.labels' ) wi <- grep('I(',t1,fixed=T) if(length(wi) > 0)t1 <- t1[-wi] wi <- grep(':',t1,fixed=T) if(length(wi) > 0)t1 <- t1[-wi] xdata0 <- xdata[,t1, drop=F] xnames <- colnames(xdata0) fs <- which( sapply( xdata0, is.character ) ) if(length(fs) > 0)stop( paste( names(fs), 'is a character, change to factor?', sep=' ') ) standX <- !sapply(xdata0,is.factor) facNames <- names(standX)[!standX] standX <- names(standX)[standX] standX <- standX[!standX %in% notStandard] tmp <- .getStandX( formula, xu = xdata0, standRows = standX ) xdata0 <- tmp$xstand xmean <- tmp$xmu xsd <- tmp$xsd xscale <- rbind(xmean,xsd) factorList <- contrast <- vector('list',length = length(facNames)) names(factorList) <- facNames if(length(facNames) > 0){ for(j in 1:length(facNames)){ wj <- which(names(xdata0) == facNames[j]) xf <- as.character(xdata0[[wj]]) cj <- attr(xdata0[[wj]],'contrasts') contrast[[j]] <- cj tt <- .setContrasts(xdata0[[wj]])$cont factorList[[j]] <- paste(facNames[j],colnames(tt),sep='') if(!is.null(cj))next contrast[[j]] <- tt attr(xdata0[[wj]],'contrasts') <- tt } names(contrast) <- facNames } } tmp <- model.frame(formula, data = as.data.frame(xdata0), na.action=NULL) x <- model.matrix(formula, data=tmp) colnames(x)[1] <- 'intercept' xnames <- colnames(x) snames <- colnames(y) Q <- ncol(x) predXcols <- 2:Q isFactor <- character(0) if(Q < 2) checkX <- FALSE notStandard <- notStandard[ notStandard %in% colnames(x) ] facBySpec <- missFacSpec <- NULL VIF <- isNonLinX <- designTable <- NULL isInt <- intMat <- numeric(0) if( !NOX ){ if( length(facNames) > 0 ){ iy <- y*0 iy[y > 0] <- 1 facBySpec <- numeric(0) missFacSpec <- character(0) for(j in 1:length(facNames)){ ij <- which( colnames(x) %in% factorList[[j]] ) ij <- xnames[ij] isFactor <- c(isFactor,ij) if(verbose){ print(paste('observations in factor',facNames[j])) print(colSums(x, na.rm=T)[ij]) } fs <- matrix(NA,S,length(factorList[[j]])) colnames(fs) <- factorList[[j]] rownames(fs) <- snames for(k in 1:length(ij)){ xi <- ij[k] fs[,k] <- colSums( matrix(x[,xi],n,S)*iy, na.rm=T ) } ms <- 'none missing' missFS <- which(fs == 0,arr.ind=T) if(length(missFS) > 0){ ms <- paste(rownames(missFS),ij[missFS[,2]],sep='_') } facBySpec <- append(facBySpec,list(fs)) missFacSpec <- append(missFacSpec,list(ms)) } names(facBySpec) <- names(missFacSpec) <- facNames } if( checkX ){ checkInt <- range(x[,1]) if(checkInt[1] != 1 | checkInt[2] != 1) stop( paste('x[,1] must be intercept (ones)') ) tmp <- .checkDesign(x) if(tmp$rank < tmp$p)stop( 'x not full rank' ) VIF <- tmp$VIF designTable <- tmp$designTable$table wx <- grep('^2',colnames(x),fixed=T) if(length(wx) > 0){ mm <- unique(unlist(strsplit(colnames(x)[wx],'^2)',fixed=T))) mm <- .replaceString(mm,'I(','') mm <- match(mm,colnames(x)) mat <- cbind(wx,mm,mm) colnames(mat) <- c('int','main1','main2') intMat <- mat isInt <- wx isNonLinX <- sort(unique( c(isNonLinX,mm,isInt))) } wx <- grep(':',colnames(x)) if(length(wx) > 0){ mm <- matrix(unlist(strsplit(colnames(x)[wx],':')),ncol=2,byrow=T) mat <- matrix( match(mm,colnames(x)), ncol=2) mat <- cbind(wx,mat) colnames(mat) <- c('int','main1','main2') wx <- c( which(colnames(x) %in% mm),wx ) isInt <- sort(c(isInt,wx)) intMat <- rbind(intMat,mat) } if(!is.null(isInt))isNonLinX <- sort(unique( c(isNonLinX,isInt))) } } standMatSd <- matrix(1,Q,1) rownames(standMatSd) <- xnames standMatMu <- standMatSd - 1 xss <- colnames(xscale) if(length(xss) > 0){ standMatMu[xss,] <- xscale['xmean',xss] standMatSd[xss,] <- xscale['xsd',xss] } if( length(intMat) > 0 ){ for(j in 1:nrow(intMat)){ im <- intMat[j,] s1 <- s2 <- 1 if( xnames[im[2]] %in% colnames(xscale) )s1 <- xscale['xsd',xnames[im[2]]] if( xnames[im[3]] %in% colnames(xscale) )s2 <- xscale['xsd',xnames[im[3]]] standMatSd[im[1],] <- s1*s2 } } standRows <- which(standMatSd[,1] != 1 | standMatMu[,1] != 0) standRows <- standRows[!names(standRows) %in% notStandard] colnames(y) <- .cleanNames(colnames(y)) tiny <- 1 + 1e-10 if('FC' %in% typeNames){ groups <- attr(typeNames,'FCgroups') if(is.null(groups)){ groups <- rep(0,S) groups[typeNames == 'FC'] <- 1 attr(typeNames,'FCgroups') <- groups } ngg <- max(groups) for(kk in 1:ngg){ wf <- which(groups == kk) if(length(wf) == 0)stop( 'FC data must have > 1 column' ) ww <- which(y[,wf] < 0) if(length(ww) > 0)stop( 'FC values cannot be < 0' ) wr <- rowSums(y[,wf],na.rm=T) vv <- unique(wr) ww <- which(vv != 0 & vv > 1.01) if(length(ww) > 0){ wx <- which(wr %in% vv) ii <- paste0(wx, collapse=', ') stop( paste('FC data must sum to zero (all absent) or one, check obs:',ii)) } } } if('CC' %in% typeNames){ wf <- which(typeNames == 'CC') if(length(wf) < 2)stop( 'CC data must have > 1 column' ) } if(is.null(snames))snames <- paste('S',1:S,sep='-') if(is.null(xnames))xnames <- paste('x',1:Q,sep='-') snames <- sub('_','-',snames) xnames <- sub('_','-',xnames) colnames(y) <- snames colnames(x) <- xnames if(length(isNonLinX) == 0)isNonLinX <- NULL if(length(notStandard) == 0)notStandard <- NULL if( !is.null(notStandard) ){ ns <- notStandard[ notStandard %in% colnames(x) ] for(k in 1:length(ns)){ wk <- grep(ns[k],colnames(x)) ns <- c(ns,colnames(x)[wk]) } notStandard <- sort( unique(ns) ) } factorAll <- list(nfact = length(factorList), factorList = factorList, isFactor = isFactor, contrast = contrast, facBySpec = facBySpec, missFacSpec = missFacSpec, facNames = facNames) interaction <- list(isInt = isInt, intMat = intMat, isNonLinX = isNonLinX) list(x = x, y = y, snames = snames, xnames = xnames, predXcols = predXcols, interaction = interaction,factorAll = factorAll, xdata = xdata, designTable = designTable, xmean = xmean, xscale = xscale, standMatMu = standMatMu, standMatSd = standMatSd, standRows = standRows, notStandard = notStandard, xdataNames = xdataNames, formula = formula) } .gjamCompW2Y <- function(ww,notOther=c(1:(ncol(ww)-1))){ pg <- .995 n <- nrow(ww) ww[ ww < 0 ] <- 0 W <- rowSums(ww[,notOther,drop=F]) wh <- which(W > pg) other <- c(1:ncol(ww))[-notOther] if(length(wh) > 0){ contract <- (1 - (1 - pg)^(W[wh]/pg))/W[wh] ww[wh,] <- ww[wh,]*contract } ww[,other] <- 1 - rowSums(ww[,notOther,drop=F]) list(pg = pg, ww = ww ) } .imputX_MVN <- function(xx,yy,beta,xmiss,sinv,xprior=0,xbound=NULL,priorWT=1){ wcol <- unique(xmiss[,2]) S <- nrow(sinv) Q <- nrow(beta) if(is.null(xbound))xbound <- apply(xx,2,range,na.rm=T) for(j in wcol){ wx <- which(xmiss[,2] == j) wj <- xmiss[drop=F,wx,] wr <- wj[,1] xp <- xprior[wx] bj <- matrix(beta[j,],1) bn <- matrix(beta[-j,],Q - 1) xn <- xx[drop=F,wr,-j] z <- yy[drop=F,wr,] - xn%*%bn datwt <- bj%*%sinv%*%t(bj) V <- 1/( datwt + priorWT*datwt ) v <- z %*%sinv%*%t(bj) + xp*priorWT xx[wj] <- .tnorm(length(wr),xbound[1,j],xbound[2,j],v%*%V,sqrt(V)) } xx } .interp <- function(y,INCREASING=F,minVal=-Inf,maxVal=Inf,defaultValue=NULL, tinySlope=NULL){ if(is.null(defaultValue))defaultValue <- NA tiny <- .00001 if(!is.null(tinySlope))tiny <- tinySlope y[y < minVal] <- minVal y[y > maxVal] <- maxVal n <- length(y) wi <- which(is.finite(y)) if(length(wi) == 0)return(rep(defaultValue,n)) if(length(wi) == 1)ss <- tiny xx <- c(1:n) z <- y if(wi[1] != 1) wi <- c(1,wi) if(max(wi) < n)wi <- c(wi,n) ss <- diff(z[wi])/diff(xx[wi]) ss[is.na(ss)] <- 0 if(length(ss) > 1){ if(length(ss) > 2)ss[1] <- ss[2] ss[length(ss)] <- ss[length(ss)-1] } if(INCREASING)ss[ss < tiny] <- tiny if(is.na(y[1])) z[1] <- z[wi[2]] - xx[wi[2]]*ss[1] if(z[1] < minVal)z[1] <- minVal if(z[1] > maxVal)z[1] <- maxVal for(k in 2:length(wi)){ ki <- c(wi[k-1]:wi[k]) yk <- z[wi[k-1]] + (xx[ki] - xx[wi[k-1]])*ss[k-1] yk[yk < minVal] <- minVal yk[yk > maxVal] <- maxVal z[ki] <- yk } z } .interpRows <- function(x,startIndex=rep(1,nrow(x)),endIndex=rep(ncol(x),nrow(x)), INCREASING=F,minVal=-Inf,maxVal=Inf, defaultValue=NULL,tinySlope=.001){ nn <- nrow(x) p <- ncol(x) xx <- c(1:p) if(length(minVal) == 1)minVal <- rep(minVal,nn) if(length(maxVal) == 1)maxVal <- rep(maxVal,nn) ni <- rep(NA,nn) flag <- numeric(0) z <- x for(i in 1:nn){ if(startIndex[i] == endIndex[i]){ z[i,-startIndex[i]] <- NA next } z[i,startIndex[i]:endIndex[i]] <- .interp(x[i,startIndex[i]:endIndex[i]], INCREASING,minVal[i],maxVal[i], defaultValue,tinySlope) } z } .invertSigma <- function(sigma,sigmaerror=NULL,otherpar=NULL, REDUCT){ if(REDUCT){ sinv <- invWbyRcpp(sigmaerror, otherpar$Z[otherpar$K,]) } else { testv <- try( chol(sigma) ,T) if( inherits(testv,'try-error') ){ tiny <- .1*diag(sigma) sigma <- sigma + diag(diag(sigma + tiny)) testv <- try(chol(sigma),T) } sinv <- chol2inv(testv) } sinv } .invMatZero <- function(sgibbs,nsim=2000,snames,knames,index=NULL, COMPRESS = F, REDUCT=F, sigErrGibbs = NULL, kgibbs = NULL, otherpar = NULL, alpha = .95){ S <- length(snames) if(is.null(index))index <- c(1:nrow(sgibbs)) simIndex <- sample(index,nsim,replace=T) if(!REDUCT){ if(COMPRESS){ tmp <- .expandSigmaChains(snames, sgibbs, otherpar, simIndex, sigErrGibbs, kgibbs, REDUCT=REDUCT, CHAINSONLY=T)$chainList$schain sgibbs <- tmp } S1 <- sqrt(ncol(sgibbs)) } else { N <- otherpar$N r <- otherpar$r S1 <- S SS <- matrix(0,S1,S1) } SK <- length(knames) sindex <- match(knames,snames) mm <- matrix(0,SK,SK) rownames(mm) <- colnames(mm) <- knames hiSS <- loSS <- hiSI <- loSI <- mm for(j in simIndex){ if(!REDUCT){ ss <- matrix(sgibbs[j,],S1,S1) si <- chol2inv(chol( ss ) ) } else { Z <- matrix(sgibbs[j,],N,r) ss <- .expandSigma(sigErrGibbs[j], S1, Z = Z, kgibbs[j,], REDUCT = T) si <- invWbyRcpp(sigErrGibbs[j], Z[kgibbs[j,],]) } ss <- ss[sindex,sindex] si <- si[sindex,sindex] hiSS[ss > 0] <- hiSS[ss > 0] + 1/nsim loSS[ss < 0] <- loSS[ss < 0] + 1/nsim hiSI[si > 0] <- hiSI[si > 0] + 1/nsim loSI[si < 0] <- loSI[si < 0] + 1/nsim } loMar <- which(loSS > alpha) hiMar <- which(hiSS > alpha) inMar <- which(loSS < alpha & hiSS < alpha) loCon <- which(loSI > alpha) hiCon <- which(hiSI > alpha) inCon <- which(loSI < alpha & hiSI < alpha) inMarMat <- which(loSS < alpha & hiSS < alpha,arr.ind=T) inConMat <- which(loSI < alpha & hiSI < alpha,arr.ind=T) list( inMarMat = inMarMat, inConMat = inConMat ) } .mapSetup <- function(xlim,ylim,scale=NULL,widex=10.5,widey=6.5){ if(is.null(scale))scale <- 1 px <- diff(xlim)/scale py <- diff(ylim)/scale if(px > widex){ dx <- widex/px px <- widex py <- py*dx } if(py > widey){ dx <- widey/py py <- widey px <- px*dx } par(pin=c(px,py)) invisible( c(px,py) ) } .sameByColumn <- function(mat,fraction=F){ nc <- ncol(mat) sameMat <- matrix(0,nc,nc) for(j in 2:nc){ for(k in 1:(j - 1)){ wj <- which(mat[,j] == mat[,k]) sameMat[j,k] <- length(wj) } } fraction <- sameMat/nrow(mat) fraction[upper.tri(fraction, diag=T)] <- NA fraction } .modalValuesInArray <- function(mat,idim = 1){ as.numeric( apply(mat,idim, function(x) names(which.max(table(x)))) ) } .multivarChainNames <- function(rowNames,colNames, keep = NULL){ tmat <- t(outer(colNames,rowNames,paste,sep='_')) if(!is.null(keep))tmat <- tmat[ keep ] as.vector( tmat ) } .rMVN <- function (nn, mu, sigma = NULL, sinv = NULL){ if(!is.null(sigma)){ m <- ncol(sigma) }else if(!is.null(sinv)){ m <- ncol(sinv) }else{ stop( '.rMNV requires either sigma or sinv' ) } if(length(mu) > 1){ if( !is.matrix(mu) ) mu <- matrix( mu, nn, length(mu) ) if( ncol(mu) == 1 & nn == 1 ) mu <- t(mu) if( length(mu) == m & nn > 1) mu <- matrix( mu, nn, length(mu), byrow=T ) } if(is.null(sinv)){ vv <- try(svd(sigma),T) if( inherits(vv,'try-error') ){ ev <- eigen(sigma, symmetric = TRUE) rr <- t(ev$vectors %*% (t(ev$vectors) * sqrt(ev$values))) } else { rr <- vv$v %*% (t(vv$u) * sqrt(vv$d)) } }else{ L <- chol(sinv) rr <- backsolve(t(L), diag(m), upper.tri = F) } ps <- matrix(rnorm(nn * m), nn) %*% rr ps + mu } .omitChainCol <- function(cmat,omitCols){ keep <- c(1:ncol(cmat)) ocol <- numeric(0) for(j in 1:length(omitCols)){ ocol <- c(ocol,grep(omitCols[j],colnames(cmat))) } if(length(ocol) > 0)keep <- keep[-ocol] list(keep = keep, omit = ocol) } .outFile <- function(outFolder=character(0),file){ paste(outFolder,file,sep='/') } .plotLabel <- function(label,location='topleft',cex=1.3,font=1, above=F,below=F,bg=NULL){ if(above){ adj <- 0 if(location == 'topright')adj=1 title(label,adj=adj, font.main = font, font.lab =font) return() } if(below){ adj <- 0 if(location == 'bottomright')adj=1 mtext(label,side=1,adj=adj, outer=F,font.main = font, font.lab =font,cex=cex) return() } if(is.null(bg)){ tmp <- legend(location,legend=' ',bty='n') } else { tmp <- legend(location,legend=label,bg=bg,border=bg,text.col=bg,bty='o') } xt <- tmp$rect$left yt <- tmp$text$y pos <- 4 tmp <- grep('right',location) if(length(tmp) > 0)pos <- 2 XX <- par()$xlog YY <- par()$ylog if(XX)xt <- 10^xt if(YY)yt <- 10^yt text(xt,yt,label,cex=cex,font=font,pos=pos) } .bins4data <- function(obs, nPerBin=NULL, breaks=NULL, nbin=NULL, LOG=F, POS=T){ if(!is.null(nPerBin)){ mb <- 20 if(length(obs)/nPerBin > mb)nperBin <- length(obs)/mb } if( is.null(breaks) ){ if( is.null(nbin) )nbin <- 20 br <- range(obs[is.finite(obs)],na.rm=T) bins <- seq(br[1],br[2],length=nbin) if(LOG){ yy <- obs[obs > 0] oo <- min( yy,na.rm=T ) ybin <- seq(log10(oo),log10(max(yy, na.rm=T)),length=20) bins <- 10^c(log10(.1*oo),ybin) bins <- unique(bins) nbin <- length(bins) nPerBin <- NULL } if( !is.null(nPerBin) ){ nbb <- nPerBin/length(obs) if(nbb < .05)nbb <- .05 nbb <- seq(0,1,by=nbb) if(max(nbb) < 1)nbb <- c(nbb,1) oo <- obs if(POS)oo <- obs[obs > 0] bins <- quantile(oo,nbb,na.rm=T) bins <- c(min(oo,na.rm=T),bins) bins <- sort(unique(bins)) db <- diff(bins) qo <- quantile(obs,c(.1,.9),na.rm=T) wb <- which( db/diff(range(qo)) < .02) wb <- wb[wb != 1] if(length(wb) > 0)bins <- bins[-wb] nbin <- length(bins) } } else { bins <- breaks nbin <- length(bins) } list(breaks = breaks, bins = bins, nbin = nbin) } .predictY2X_linear <- function(xpred,yy,bb,ss,sinv=NULL, priorIV = diag(1e-10,ncol(xpred)), priorX = matrix(0,ncol(xpred)), predCols = c(2:ncol(xpred)),REDUCT, lox, hix, propx){ prX <- priorX[predCols] if(!is.matrix(prX))prX <- matrix(prX) nn <- nrow(yy) notPred <- c(1:ncol(xpred))[-predCols] bp <- matrix(bb[drop=F,predCols,],length(predCols)) if(length(notPred) > 0){ bn <- matrix(bb[notPred,],length(notPred)) yy <- yy - xpred[,notPred]%*%bn } pp <- length(predCols) if(is.null(sinv))sinv <- chol2inv(chol(ss)) bs <- bp%*%sinv V <- chol2inv(chol( bs%*%t(bp) + priorIV[predCols,predCols] ) ) v <- yy%*%t(bs) + matrix( priorIV[predCols,predCols] %*% prX,nn,pp,byrow=T) mu <- v%*%V qq <- ncol(mu) if(qq > 1){ xpred[,predCols] <- .tnormMVNmatrix(avec=xpred[,predCols, drop=F],muvec=mu,smat=V, lo=matrix(lox[predCols],nn,qq,byrow=T), hi=matrix(hix[predCols],nn,qq,byrow=T)) } else { xpred[,predCols] <- .tnorm(nn,lox[predCols],hix[predCols], mu,sqrt(V)) } xpred } .predictY2X_nonLinear <- function(xx,yy,bb,ss, priorIV = diag(1e-10,ncol(xx)), priorX=matrix(0,ncol(xx)), factorObject, interObject, lox, hix, propx){ predCols <- interObject$isNonLinX isInt <- interObject$isInt intMat <- interObject$intMat isFactor <- factorObject$isFactor factorList <- factorObject$factorList contrast <- factorObject$contrast iFcol <- NULL priorX <- priorX[predCols] if(!is.matrix(priorX))priorX <- matrix(priorX) nn <- nrow(yy) intercept <- xx[,1] xnew <- xx xv <- as.vector(xx[,predCols]) nv <- length(xv) lo <- rep(lox[predCols],each=nn) hi <- rep(hix[predCols],each=nn) sx <- rep(propx[predCols],each=nn)/10 xnew[,predCols] <- .tnorm(nv,lo,hi,xv,sx) if(length(isFactor) > 0){ np <- length(factorList) for(k in 1:np){ nf <- length(factorList[[k]]) + 1 tm <- contrast[[k]][sample(nf,nn,replace=T),] xnew[,factorList[[k]]] <- tm } iFcol <- match(isFactor,colnames(xx)) } if(length(intMat) > 0){ xnew[,intMat[,1]] <- xnew[,intMat[,2]]*xnew[,intMat[,3]] } mux <- matrix( priorX, nn, length(priorX), byrow=T ) pnow <- .dMVN(yy,xx%*%bb,smat=ss,log=T) + .dMVN(xx[,predCols,drop=F], mux, priorIV[drop=F, predCols,predCols] ) pnew <- .dMVN(yy,xnew%*%bb,smat=ss,log=T)+ .dMVN(xnew[,predCols,drop=F], mux, priorIV[drop=F, predCols,predCols] ) a <- exp(pnew - pnow) z <- runif(nn,0,1) wa <- which(z < a) xx[wa,] <- xnew[wa,] list(x = xx, accept = length(wa)) } .predVsObs <- function(true,p,xlim=range(true),ylim=range(p,na.rm=T),xlab=' ', ylab=' ', colors=rep(1,length(true)),lwd=2,add=F){ if(!is.matrix(p))p <- matrix(p,ncol=1) if(length(colors) == 1)colors <- rep(colors, length(true)) nn <- length(true) y <- apply(p, 2, quantile, c(.5,.025,.975)) ys <- apply(p, 2, quantile, pnorm( c(-1, 1) ) ) if(!add)plot(true,y[1,],xlim=xlim,ylim=ylim,xlab=xlab, ylab=ylab,col=colors,pch=3,lwd=lwd) points(true,y[1,],col=colors,pch=3,lwd=lwd) for(j in 1:nn)lines( c(true[j],true[j]), y[2:3,j], col=colors[j],lwd=lwd/2) for(j in 1:nn)lines( c(true[j],true[j]), ys[1:2,j], col=colors[j],lwd=2*lwd) abline(0,1,lty=2) invisible(y) } .processPars <- function(xgb,xtrue=numeric(0),CPLOT=F,DPLOT=F, sigOnly = F,burnin=1,xlimits = NULL){ if(!is.matrix(xgb))xgb <- matrix(xgb,ncol=1) if(is.null(colnames(xgb)))colnames(xgb) <- paste('V',c(1:ncol(xgb)),sep='-') NOPARS <- F if(sigOnly){ wi <- grep('intercept',colnames(xgb)) btmp <- xgb if(length(wi) > 0){ btmp <- xgb[,-wi] if(length(xtrue) > 0)xtrue <- xtrue[-wi] } wq <- apply(btmp,2,quantile,c(.025,.975),na.rm=T) wq <- which(wq[1,] < 0 & wq[2,] > 0) if(length(wq) == ncol(btmp))NOPARS <- T if(NOPARS) warning('no significant pars to plot') if(length(wq) > 0 & !NOPARS){ xgb <- btmp[,-wq] if(length(xtrue) > 0)xtrue <- xtrue[-wq] } } if(!is.matrix(xgb))xgb <- as.matrix(xgb) if(burnin > 1){ if(burnin > (nrow(xgb) + 100))stop("burnin too large") xgb <- xgb[-c(1:burnin),] } if(!is.matrix(xgb))xgb <- as.matrix(xgb) nc <- ncol(xgb) nf <- round(sqrt(nc),0) out <- t(rbind(apply(xgb,2,mean,na.rm=T),apply(xgb,2,sd,na.rm=T), apply(xgb,2,quantile,c(.025,.975),na.rm=T))) if(!is.null(colnames(xgb)))rownames(out) <- colnames(xgb) colnames(out) <- c('estimate','se','0.025','0.975') if(length(xtrue) > 0){ out <- cbind(out,xtrue) colnames(out) <- c('estimate','se','0.025','0.975','true value') } if(CPLOT | DPLOT)par(mfrow=c((nf+1),nf),mar=c(4,2,2,2)) if(CPLOT & DPLOT)par(mfrow=c((nf+1),nc),mar=c(4,2,2,2)) if(CPLOT & !NOPARS){ for(j in 1:nc){ plot(xgb[,j],type='l') abline(h=out[j,],lty=2) if(length(xtrue) > 0)abline(h=xtrue[j],col='red') abline(h = 0, col='grey',lwd=2) title(colnames(xgb)[j]) } } xlims <- xlimits if(DPLOT & !NOPARS){ for(j in 1:nc){ xj <- density(xgb[,j]) if(is.null(xlimits))xlims <- range(xj$x) plot(xj$x,xj$y,type='l',xlim=xlims) abline(v=out[j,],lty=2) if(length(xtrue) > 0)abline(v=xtrue[j],col='red') title(colnames(xgb)[j]) } } list(summary = signif(out,4)) } .replaceString <- function(xx,now='_',new=' '){ ww <- grep(now,xx,fixed=T) if(length(ww) == 0)return(xx) for(k in ww){ s <- unlist( strsplit(xx[k],now,fixed=T) ) ss <- s[1] if(length(s) == 1)ss <- paste( ss,new,sep='') if(length(s) > 1)for(kk in 2:length(s)) ss <- paste( ss,s[kk],sep=new) xx[k] <- ss } xx } .cleanNames <- function(xx){ xx <- .replaceString(xx,'-','') xx <- .replaceString(xx,'_','') xx <- .replaceString(xx,' ','') xx <- .replaceString(xx,"'",'') xx } .buildYdata <- function(ydata, ytypes){ S <- ncol(ydata) wd <- which(duplicated(colnames(ydata))) if(length(wd) > 0){ warning('duplicated colummn names in ydata') for(k in 1:length(wd)){ dname <- colnames(ydata)[wd[k]] wk <- which(colnames(ydata) == dname) colnames(ydata)[wk] <- paste(dname,1:length(wk),sep='') } } original <- colnames(ydata) colnames(ydata) <- .cleanNames(colnames(ydata)) new <- colnames(ydata) ydataNames <- rbind(original,new) CCgroups <- attr(ytypes,'CCgroups') FCgroups <- attr(ytypes,'FCgroups') CATgroups <- attr(ytypes,'CATgroups') ngroup <- 0 ccg <- CCgroups fcg <- FCgroups y <- numeric(0) snames <- colnames(ydata) nc <- ncol(ydata) wfact <- .whichFactor(ydata) nfact <- length(wfact) wnot <- c(1:nc) if(nfact > 0)wnot <- wnot[-wfact] ntypes <- character(0) if(length(wnot) > 0){ if(is.null(ccg)) ccg <- rep(0,length(wnot)) if(is.null(fcg)) fcg <- rep(0,length(wnot)) snames <- snames[wnot] ntypes <- ytypes[wnot] y <- ydata[,wnot,drop=F] wcomp <- grep('CC',ytypes[wnot]) ncomp <- length(wcomp) if(ncomp > 0){ if( max(ccg[wnot[wcomp]]) == 0 )ccg[wnot[wcomp]] <- 1 goo <- grep('other',snames[wcomp]) if( length(goo) == 0 )snames[wcomp[ncomp]] <- paste(snames[wcomp[ncomp]],'other',sep='') } wcomp <- grep('FC',ytypes[wnot]) ncomp <- length(wcomp) if(ncomp > 0){ if( max(fcg[wnot[wcomp]]) == 0)fcg[wnot[wcomp]] <- 1 goo <- grep('other',snames[wcomp]) if(length(goo) == 0)snames[wcomp[ncomp]] <- paste(snames[wcomp[ncomp]],'other',sep='') } } if(nfact > 0){ ngroup <- 0 ycat <- cag <- numeric(0) if(length(ccg) > 0)cag <- ccg*0 for(j in 1:nfact){ ngroup <- ngroup + 1 conj <- contrasts(ydata[,wfact[j]],contrasts=F) cj <- colnames(conj) yj <- conj[ydata[,wfact[j]],] colnames(yj) <- paste(colnames(ydata)[wfact[j]],cj,sep='') w11 <- which(colSums(yj) > 0) yj <- yj[,w11] cj <- cj[w11] goo <- grep('other',colnames(yj)) if(length(goo) == 0){ colnames(yj)[ncol(yj)] <- paste(colnames(ydata)[wfact[j]],'other',sep='') cj[ncol(yj)] <- colnames(yj)[ncol(yj)] } ycat <- cbind(ycat, yj) cag <- c(cag,rep(ngroup,length(cj))) fcg <- c(fcg,rep(0,length(cj))) ccg <- c(ccg,rep(0,length(cj))) ntypes <- c(ntypes,rep('CAT',length(cj))) } rownames(ycat) <- NULL n1 <- ncol(y) + 1 n2 <- ncol(ycat) y <- cbind(y,ycat) attr(ntypes,'CATgroups') <- cag } if(max(ccg) > 0)attr(ntypes,'CCgroups') <- ccg if(max(fcg) > 0)attr(ntypes,'FCgroups') <- fcg list(y = as.matrix(y), CCgroups = ccg, FCgroups = fcg, CATgroups = attr(ntypes,'CATgroups'), typeNames = ntypes, ydataNames = ydataNames) } .setUpSim <- function(n, S, Q, x, typeNames){ if(length(typeNames) == 1)typeNames <- rep(typeNames,S) notOther <- c(1:S) snames <- character(0) tnames <- character(0) sN <- S catCols <- NULL ngroup <- fgroup <- cgroup <- 1 GROUPS <- F CCgroups <- FCgroups <- CATgroups <- numeric(0) s <- 0 wcc <- which(!typeNames %in% c('CC','FC','CAT')) ncc <- length(wcc) if(ncc > 0){ snames <- paste('S',c(1:ncc),sep='') CCgroups <- FCgroups <- CATgroups <- rep(0,ncc) tnames <- typeNames[wcc] s <- ncc } wcc <- which(typeNames == 'CC') ncc <- length(wcc) if(ncc > 0){ ss <- c( (s+1):(s+ncc)) CCgroups <- c(CCgroups,rep(1,ncc)) FCgroups <- c(FCgroups,rep(0,ncc)) tnames <- c(tnames,rep('CC',ncc)) snn <- paste('S',ss,sep='') snn[ncc] <- paste(snn[ncc],'other',sep='') snames <- c(snames, snn) ngroup <- 1 s <- max(ss) } wcc <- which(typeNames == 'FC') ncc <- length(wcc) if(ncc > 0){ ss <- c( (s+1):(s+ncc)) FCgroups <- c(FCgroups,rep(1,ncc)) CCgroups <- c(CCgroups,rep(0,ncc)) tnames <- c(tnames,rep('FC',ncc)) snn <- paste('S',ss,sep='') snn[ncc] <- paste(snn[ncc],'other',sep='') snames <- c(snames, snn) fgroup <- 1 s <- max(ss) } CATgroups <- CCgroups*0 if( 'CAT' %in% typeNames ){ wk <- which(typeNames == 'CAT') ncomp <- length(wk) ncat <- sample(3:4,ncomp,replace=T) nall <- sum(ncat) ntot <- s + nall CATgroups <- rep(0,s) js <- s for(j in 1:ncomp){ js <- js + 1 sseq <- (s+1):(s + ncat[j]) cj <- paste('S',js,letters[1:ncat[j]],sep='') cj[ncat[j]] <- paste('S',js,'other',sep='') snames <- c(snames,cj) CATgroups <- c(CATgroups,rep(j,ncat[j])) tnames <- c(tnames,rep('CAT',ncat[j])) s <- max(sseq) } CCgroups <- c(CCgroups,rep(0,sum(ncat))) FCgroups <- c(FCgroups,rep(0,sum(ncat))) catCols <- which(CATgroups > 0) cgroup <- ncomp } sN <- length(tnames) oo <- grep('other',snames) notOther <- c(1:sN)[-oo] tmp <- .gjamGetTypes(tnames) typeCols <- tmp$typeCols typeFull <- tmp$typeFull typeCode <- tmp$TYPES[typeCols] allTypes <- sort(unique(typeCols)) typeNames <- tmp$typeNames if(is.null(x)){ x <- matrix( rnorm(n*Q,.1), n, Q) x[,1] <- 1 } beta <- matrix(0, Q, sN) ss <- diag(.01,sN) colnames(beta) <- colnames(ss) <- rownames(ss) <- snames wkeep <- numeric(0) cnames <- tnames <- character(0) for(k in allTypes){ wk <- which(typeCols == k) nk <- length(wk) if( typeFull[wk[1]] == 'presenceAbsence' ){ diag(ss)[wk] <- 1 beta[,wk] <- runif(Q*nk,-.8,.8) wkeep <- c(wkeep,wk) tnames <- c(tnames,typeNames[wk]) cnames <- c(cnames,colnames(beta)[wk]) } if(typeFull[wk[1]] %in% c('continuous','contAbun')){ diag(ss)[wk] <- .4 beta[,wk] <- runif(Q*nk,-.5,2) wkeep <- c(wkeep,wk) tnames <- c(tnames,typeNames[wk]) cnames <- c(cnames,colnames(beta)[wk]) } if(typeFull[wk[1]] == 'discAbun'){ diag(ss)[wk] <- .5 beta[,wk] <- runif(Q*nk,-1,1) wkeep <- c(wkeep,wk) tnames <- c(tnames,typeNames[wk]) cnames <- c(cnames,colnames(beta)[wk]) } if(typeFull[wk[1]] == 'ordinal'){ diag(ss)[wk] <- 1 beta[,wk] <- runif(Q*nk,-.4,2) wkeep <- c(wkeep,wk) tnames <- c(tnames,typeNames[wk]) cnames <- c(cnames,colnames(beta)[wk]) } if( typeFull[wk[1]] %in% c('fracComp','countComp','categorical') ){ if(length(wk) < 2)stop('composition data must have at least 2 columns') ntt <- cgroup if( typeFull[wk[1]] == 'fracComp' ){ ntt <- fgroup attr(tnames,'FCgroups') <- FCgroups } if( typeFull[wk[1]] == 'countComp' ){ ntt <- ngroup attr(tnames,'CCgroups') <- CCgroups } if( typeFull[wk[1]] == 'categorical' ){ attr(tnames,'CATgroups') <- CATgroups } for(i in 1:ntt){ if(ntt == 1){ wki <- wk } else { if( typeFull[wk[1]] == 'countComp' )wki <- which(typeCols == k & CCgroups == i) if( typeFull[wk[1]] == 'fracComp' )wki <- which(typeCols == k & FCgroups == i) if( typeFull[wk[1]] == 'categorical' )wki <- which(typeCols == k & CATgroups == i) } nki <- length(wki) if( typeFull[wk[1]] == 'categorical' ){ bb <- matrix( rnorm(Q*nki,0,.5), Q,nki) bb[1,] <- bb[1,]*0 for(kk in 1:5){ mu <- x%*%bb w <- mu cols <- apply(w,1,which.max) mindex <- cbind( c(1:n),cols ) wmax <- w[mindex] ww <- which(wmax < 0) nw <- length(ww) if(nw > 0) w[mindex[ww,]] <- .tnorm(nw,0,10,mu[mindex[ww,]],1) bb <- solveRcpp(crossprod(x))%*%crossprod(x,w) } keep <- as.numeric( names(table(cols)) ) wkeep <- c(wkeep,wki[keep]) tnames <- c(tnames,rep('CAT',length(keep))) bbb <- colnames(beta)[wki[keep]] if(length(keep) < nki){ bbb <- substr(bbb,1,2) labs <- c(letters[1:(length(bbb) - 1)],'other') bbb <- paste(bbb,labs,sep='') } cnames <- c(cnames,bbb) beta[,wki] <- bb diag(ss)[wk] <- 1 } else { bb <- matrix( rnorm(Q*nki,0,1/nki), Q, nki) bb[1,] <- bb[1,]*0 w <- x%*%bb for(m in 1:3){ w1 <- w w1[w < 0] <- 0 w2 <- sweep(w1,1,rowSums(w1),'/') w[w >= 0] <- w2[w >= 0] bb <- solveRcpp(crossprod(x))%*%crossprod(x,w) w <- x%*%bb } wkeep <- c(wkeep,wki) tnames <- c(tnames,typeNames[wki]) cnames <- c(cnames,colnames(beta)[wki]) diag(ss)[wk] <- .1/nk^2.5 beta[,wki] <- bb } } } } S <- length(wkeep) beta <- beta[,wkeep] sigma <- ss[wkeep,wkeep] colnames(beta) <- colnames(sigma) <- rownames(sigma) <- cnames CCgroups <- CCgroups[wkeep] FCgroups <- FCgroups[wkeep] CATgroups <- CATgroups[wkeep] snames <- cnames other <- numeric(0) notOther <- c(1:S) other <- grep('other',snames) if(length(other) > 0)notOther <- notOther[-other] list(beta = beta, x = x, sigma = sigma, CCgroups = CCgroups, FCgroups = FCgroups, CATgroups = CATgroups, typeNames = tnames, other = other, notOther = notOther, snames = snames) } .between <- function(x,lo,hi,ILO = T, IHI = T, OUT=F){ if(length(x) == 0) return( numeric(0) ) if(OUT)return( which(x < lo | x > hi) ) if(!ILO & !IHI ) return( which(x > lo & x < hi) ) if(!ILO & IHI ) return( which(x > lo & x <= hi) ) if( ILO & !IHI ) return( which(x >= lo & x < hi) ) if( ILO & IHI ) return( which(x >= lo & x <= hi) ) } .simData <- function( n, S, Q, x, typeNames, nmiss, effort ){ if(length(typeNames) == 1)typeNames <- rep(typeNames,S) typeNotCat <- typeNames cgrep <- grep('CAT',typeNames) if(length(cgrep) > 0){ ycat <- vector( mode = 'list', length=length(cgrep) ) names(ycat) <- paste('CAT',1:length(cgrep),sep='_') } cuts <- numeric(0) tmp <- .setUpSim(n, S, Q, x, typeNames) beta <- tmp$beta x <- tmp$x sig <- tmp$sigma snames <- colnames(beta) typeNames <- tmp$typeNames other <- tmp$other notOther <- tmp$notOther CCgroups <- tmp$CCgroups FCgroups <- tmp$FCgroups CATgroups <- tmp$CATgroups tmp <- .gjamGetTypes(typeNames) typeCols <- tmp$typeCols typeFull <- tmp$typeFull typeCode <- tmp$TYPES[typeCols] allTypes <- sort(unique(typeCols)) S <- length(typeNames) xnames <- paste('x',1:Q,sep='') SS <- matrix(1,S,S) SS[lower.tri(SS)] <- runif(S*(S - 1)/2,-.98,.98) SS[upper.tri(SS)] <- SS[lower.tri(SS)] SS <- cor( .rMVN(S+5,0,SS) ) SS <- .cor2Cov(diag(sig),SS) sigma <- .rwish(S+2,SS)/(S + 2) corCols <- which(typeNames %in% c('PA','OC','CAT')) if(length(corCols) > 0){ corSpec <- .cov2Cor(sigma) sigma[corCols,corCols] <- corSpec[corCols,corCols] } beta[,other] <- 0 mu <- w <- matrix(0,n,S) mu[,notOther] <- x%*%beta[,notOther] w[,notOther] <- mu[,notOther] + .rMVN(n,0,sigma[notOther,notOther]) colnames(w) <- snames y <- w z <- w*0 z[w <= 0] <- 1 z[w > 0] <- 2 for(k in allTypes){ wk <- which(typeCols == k) nk <- length(wk) if( typeFull[wk[1]] %in% c('fracComp','countComp','categorical') ){ if( typeFull[wk[1]] == 'fracComp' ) groups <- attr(typeNames,'FCgroups') <- FCgroups if( typeFull[wk[1]] == 'countComp' ) groups <- attr(typeNames,'CCgroups') <- CCgroups if( typeFull[wk[1]] == 'categorical' ) groups <- attr(typeNames,'CATgroups') <- CATgroups ntt <- max(c(1,groups)) for(i in 1:ntt){ if(ntt == 1){ wki <- wk } else { wki <- which(typeCols == k & groups == i) } nki <- length(wki) if( typeFull[wk[1]] == 'categorical' ){ wko <- wki[1:(nki-1)] wcol <- apply(w[,wko],1,which.max) w0 <- which( w[,wko][ cbind( c(1:n),wcol ) ] < 0 ) if(length(w0) > 0)wcol[w0] <- nki wtab <- tabulate(wcol) if(length(wtab) < nki){ ww <- rep(0,nki) ww[1:length(wtab)] <- wtab wtab <- ww } if(min(wtab) < 5){ wlo <- which(wtab < 5) for(s in 1:length(wlo)){ wro <- sample(n,5) wcol[wro] <- wlo[s] tmp <- w[wro,wki] if(wlo[s] == nki){ tmp[tmp > -.01] <- -.01 tmp[,nki] <- .1 } else { mm <- pmax(0,apply(tmp,1,max)) tmp[,wlo[s]] <- mm + .1 } w[wro,wki] <- tmp } } mindex <- cbind(1:n,wcol) vv <- colnames(w)[wki[wcol]] mm <- nchar(vv) vv <- substr(vv,3,mm) ycat[[i]] <- vv yk <- w[,wki]*0 yk[ mindex ] <- 1 y[,wki] <- yk z[,wki] <- yk + 1 } else { noto <- c(1:nki)[-grep('other',snames[wki])] ww <- w[,wki] for(j in 1:5){ w0 <- which(ww < 0) ww[w0] <- 0 yk <- .gjamCompW2Y(ww,notOther=noto)$ww yplus <- which(yk > 0) yminu <- which(yk < 0) ww[yplus] <- yk[yplus] bb <- solveRcpp(crossprod(x))%*%crossprod(x,ww) muk <- x%*%bb ww <- muk + .rMVN(n,0,sigma)[,wki] } zk <- ww*0 + 1 zk[w0] <- 0 w[,wki] <- ww beta[,wki] <- bb if(typeFull[wk[1]] == 'fracComp'){ y[,wki] <- yk z[,wki] <- zk } if( typeFull[wk[1]] == 'countComp' ){ mm <- S*20 a <- 4 b <- mm/a ee <- rpois(n,rgamma(n,shape=a,scale=b)) yy <- sweep(yk,1,ee,'*') ww <- ceiling(yy) ww[ww < 0] <- 0 y[,wki] <- ww z[,wki] <- ww + 1 } } } } if( typeFull[wk[1]] != 'continuous' ) y[,wk][y[,wk] < 0] <- 0 if( typeFull[wk[1]] == 'presenceAbsence' ){ y[,wk] <- z[,wk] - 1 } if( typeFull[wk[1]] == 'discAbun' ){ wk <- which(typeNames == 'DA') if( !is.null(effort) ){ we <- wk[wk %in% effort$columns] y[,we] <- round( w[,we]*effort$values ) } else { w0 <- round(w[,wk,drop=F],0) y[,wk] <- w0 } y[,wk][y[,wk] < 0] <- 0 z[,wk] <- y[,wk] + 1 } if( typeFull[wk[1]] == 'ordinal' ){ yy <- w[,wk,drop=F] ncut <- 8 maxw <- floor(max(yy)) cuts <- t( matrix( c(-Inf, seq(0,(maxw-1),length=(ncut-2)) ,Inf), ncut,nk) ) rownames(cuts) <- snames[wk] for(j in 1:nk){ z[,wk[j]] <- findInterval(yy[,j],cuts[j,]) } y[,wk] <- z[,wk] - 1 } } noMore <- F if( 'categorical' %in% typeFull & noMore){ wss <- w*0 wss[,notOther] <- .sqrtMatrix(w[,notOther],sigma[notOther,notOther], DIVIDE=T) css <- .cov2Cor(sigma[notOther,notOther]) alpha <- .sqrtMatrix(beta,sigma, DIVIDE=T) muss <- x%*%alpha wk <- which(typeNames == 'CAT') wo <- which(wk %in% notOther) plo <- w*0 - 5 phi <- w*0 + 5 phi[y == 0] <- 0 plo[y == 1] <- w[y == 1] IXX <- solveRcpp(crossprod(x)) for(k in 1:25){ tmp <- .gjamWcatLoop2(y, ws = wss, mus = muss, sgs = css, notOther, plo, phi, groups = CATgroups) wss[,wk] <- tmp$w[,wk] plo <- tmp$plo phi <- tmp$phi beta[,wo] <- IXX%*%crossprod(x,wss[,wo]) muss[,wo] <- x%*%beta[,wo] } w[,wo] <- wss[,wo] } beta <- solveRcpp(crossprod(x))%*%crossprod(x,w) if( 'discAbun' %in% typeFull ){ } sigma[notOther,notOther] <- var(w[,notOther] - x%*%beta[,notOther]) sigma[other,] <- sigma[,other] <- 0 diag(sigma)[other] <- diag(sig)[other] ydata <- data.frame(y) typeFrame <- typeNames if('CAT' %in% typeNames){ wcat <- grep('CAT',typeNames) wnot <- c(1:S)[-wcat] nss <- length(wnot) + 1 ncc <- length(wnot) + length(ycat) names(ycat) <- paste('S',nss:ncc,sep='') ydata <- as.data.frame(ycat) if(length(wnot) > 0)ydata <- cbind(y[,wnot,drop=F],ydata) typeFrame <- c(typeNames[wnot], rep('CAT',length(ycat))) } if(nmiss > 0){ x[ sample(length(x),nmiss) ] <- NA x[,1] <- 1 wmiss <- which(is.na(x),arr.ind=T) nmiss <- nrow(wmiss) } xnames[1] <- 'intercept' colnames(y) <- snames colnames(beta) <- rownames(sigma) <- colnames(sigma) <- snames colnames(x) <- rownames(beta) <- xnames form <- as.formula( paste('~ ',paste(colnames(x)[-1],collapse='+' )) ) list(formula = form, xdata = data.frame(x), ydata = ydata, y = y, w = w, typeNames = typeFrame, typeY = typeNames, effort = effort, trueValues = list(beta = beta, sigma = sigma, corSpec = .cov2Cor(sigma), cuts = cuts)) } .tnorm <- function(n,lo,hi,mu,sig){ tiny <- 10e-6 if(length(lo) == 1 & length(mu) > 1)lo <- rep(lo,length(mu)) if(length(hi) == 1 & length(mu) > 1)hi <- rep(hi,length(mu)) q1 <- pnorm(lo,mu,sig) q2 <- pnorm(hi,mu,sig) z <- runif(n,q1,q2) z <- qnorm(z,mu,sig) z[z == Inf] <- lo[z == Inf] + tiny z[z == -Inf] <- hi[z == -Inf] - tiny z } .traitLabel <- function(tname){ tname <- .replaceString(tname,now='soilFactor',new='') tname[tname == 'gmPerSeed'] <- 'Seed mass' tname[tname == 'gmPerCm'] <- 'Wood dens' tname[tname == 'woodSG'] <- 'Wood dens (green)' tname[tname == 'maxHt'] <- 'Max ht' tname[tname == 'leafN'] <- 'leaf [N]' tname[tname == 'leafP'] <- 'leaf [P]' tname[tname == "other"] <- 'Deciduous' tname[tname == "broaddeciduous"] <- 'Deciduous' tname[tname == "broadevergreen"] <- 'BL evergrn' tname[tname == "needleevergreen"] <- 'NL evergrn' tname[tname == "dioecious"] <- 'Dioecious' tname[tname == "u1"] <- 'Slope' tname[tname == "u2"] <- 'Aspect 1' tname[tname == "u3"] <- 'Aspect 2' tname[tname == "ringPorous"] <- 'RP xylem' tname[tname == "temp"] <- 'Winter temperature' tname[tname == "stdage"] <- 'Stand age' for(j in length(tname)){ tname[j] <- paste(toupper(substring(tname[j], 1, 1)), substring(tname[j], 2),sep = "", collapse = " ") } tname } .updateWishartNoPrior <- function(xx,yy,df,beta=NULL,IXX=NULL,WX=NULL,WIX=NULL, TRYPRIOR=F){ S <- ncol(yy) index <- 0 XX <- crossprod(xx) IXX <- solveRcpp(XX) D <- diag(1,nrow(xx)) - xx%*%IXX%*%t(xx) SS <- t(yy)%*%D%*%yy testv <- try(chol(SS),T) if( inherits(testv,'try-error') ){ tiny <- 1e-8 SS[SS < tiny] <- tiny message('warning: updateWishartNoPrior') SS <- crossprod(yy - xx%*%beta) + diag(diag(SS)*.001) SS <- SS + diag(diag(SS)*.1) testv <- try(chol(SS),T) index <- 1 } SI <- chol2inv(testv) z <- matrix(rnorm(df*S),df,S)%*%chol(SI) sinv <- crossprod(z) sigma <- solveRcpp(sinv) list( sigma = sigma, sinv = sinv, indicator = index ) } .sqrtMatrix <- function(xmat,sigma,DIVIDE=T){ if(DIVIDE){ if(length(sigma) == 1)return(xmat/sqrt(sigma)) return( xmat%*%diag(1/sqrt(diag(sigma))) ) } if(length(sigma) == 1)return(xmat*sqrt(sigma)) xmat%*%diag(sqrt(diag(sigma)) ) } .yaxisHorizLabs <- function( labels, at=c(1:length(labels)), xshift=.05, col = 'black', pos=NULL){ text(par('usr')[3] - xshift*par('usr')[4] - par('usr')[3], y=at, labels, xpd=T, pos = pos, col=col) } .sampleP <- function(N, avec, bvec, K){ a <- avec + vapply(1:(N-1), function(k)sum(K == k), 0) b <- bvec + vapply(1:(N-1), function(k)sum(K > k), 0) V <- rbeta((N - 1), a, b) p <- vector("numeric",length=N) p[1] <- V[1] for(l in 2:(N - 1))p[l] <- prod(1 - V[1:(l - 1)])*V[l] p[N] <- prod(1 - V) p } .getPars <- function( X, N, r, Y, B, D, Z, sigmaerror, K, pvec, alpha.DP, inSamples,...){ p <- ncol(X) S <- ncol(Y) nn <- length(inSamples) covR <- solveRcpp( (1/sigmaerror)*crossprod(Z[K,]) + diag(r) ) z1 <- crossprod( Z[K,]/sigmaerror,t(Y[inSamples,] - X[inSamples,]%*%t(B)) ) RR <- rmvnormRcpp(nn, mu = rep(0,r), sigma = covR ) + t(crossprod( covR,z1)) rndEff <- RR%*%t(Z[K,]) res <- sum((Y[inSamples,] - X[inSamples,]%*%t(B) - rndEff )^2) sigmaerror <- 1/rgamma(1,shape=(S*nn + 1)/2, rate=res/2) avec <- 1/rgamma(r, shape = ( 2 + r )/2, rate = ((1/1000000) + 2*diag(solveRcpp(D)) ) ) D <- .riwish(df = (2 + r + N - 1), S = (crossprod(Z) + 2*2*diag(1/avec))) Z <- fnZRcpp(kk=K, Yk=Y[inSamples,], Xk=X[inSamples,], Dk=D, Bk=B, Wk=RR, sigmasqk=sigmaerror, Nz=N) pmat <- getPmatKRcpp(pveck = pvec,Yk = Y[inSamples,], Zk = Z, Xk = X[inSamples,], Bk = B, Wk = RR, sigmasqk = sigmaerror) K <- unlist( apply(pmat, 1, function(px)sample(1:N, size=1, prob=px)) ) pvec <- .sampleP(N = N, avec = rep(alpha.DP/N,(N-1)), bvec = ((N-1):1)*alpha.DP/N, K = K) list(A = Z[K,], D = D, Z = Z, K = K, pvec = pvec, sigmaerror = sigmaerror, rndEff = rndEff) } .wWrapperTime <- function(sampleW, y, timeZero, timeLast, i1, i2, tindex, gindex, uindex, notOther, n, S, REDUCT, RANDOM, TIME, termB, termR, termA, corCols){ function(w, plo, phi, wpropTime, xl, yp, Rmat, Amat, rndEff, groupRandEff, sdg, muw, mub, Umat, Vmat, sinv){ if(RANDOM)muw <- muw + groupRandEff W <- matrix( .tnorm( n*S,plo,phi,w,wpropTime ),n,S ) W[sampleW == 0] <- y[sampleW == 0] ii <- i1 ni <- length(ii) yp <- yp*0 for(im in 1:2){ w[sampleW == 0] <- y[sampleW == 0] if(im == 2)ii <- i2 i00 <- tindex[ii,1] i11 <- tindex[ii,2] i22 <- tindex[ii,3] t00 <- which(i00 %in% timeZero) w0 <- which(!i22 %in% c(timeLast+1) ) i00 <- i00[w0] i11 <- i11[w0] i22 <- i22[w0] ww <- W[i11,] w0 <- ww w0[ ww < 0 ] <- 0 muStar <- muw[i11,]*0 if(termB)muStar <- muStar + mub[i11,] if(termR){ mugStar <- (w0[,gindex[,'colW']]*xl[i11,gindex[,'rowG']])%*%Rmat muStar <- muStar + mugStar } if(termA){ muaStar <- (w0[,uindex[,1]]*w0[,uindex[,2]] )%*%Amat muStar[,notOther] <- muStar[,notOther] + muaStar[,notOther] } if(RANDOM)muStar <- muStar + groupRandEff[i11,] if(REDUCT)muStar <- muStar + rndEff[i11,] dw <- w*0 dw[ i00, ] <- w[ i11, ] - w[ i00 , ] dw[ i11, ] <- w[ i22, ] - w[ i11 , ] dw[ timeZero,] <- dw[timeZero+1, ] dW <- W*0 dW[ i00, ] <- W[ i11, ] - w[ i00 , ] dW[ i11, ] <- w[ i22, ] - W[ i11 , ] dW[ timeZero,] <- dW[timeZero+1, ] if(REDUCT){ pnow <- dnorm( dw[ i00, ], muw[i00,],sdg,log=T) + dnorm( dw[ i11, ], muw[i11,],sdg,log=T) pnew <- dnorm(dW[ i00, ], muw[i00,],sdg,log=T) + dnorm(dW[ i11, ], muStar,sdg,log=T) za <- which( runif(length(pnow),0,1) < exp(pnew - pnow) ) if(length(za) > 0){ w[i11,][za] <- W[i11,][za] ww <- w[i11,] ww[ww < 0] <- 0 muw[i11,][za] <- muStar[za] Umat[i11,] <- ww[,uindex[,1]]*ww[,uindex[,2]] Vmat[i11,] <- ww[,gindex[,'colW']]*xl[i11,gindex[,'rowG']] } }else{ pnow <- .dMVN(dw[ i00, ], muw[i00,], sinv=sinv, log=T) + .dMVN(dw[ i11, ], muw[i11,], sinv=sinv,log=T) pnew <- .dMVN(dW[ i00, ], muw[i00,], sinv=sinv, log=T) + .dMVN(dW[ i11, ], muStar, sinv=sinv, log=T) za <- which( runif(length(pnow),0,1) < exp(pnew - pnow) ) if(length(za) > 0){ w[i11[za],] <- W[i11[za],] ww <- w[i11,] w0 <- ww w0[ ww < 0 ] <- 0 muw[i11[za],] <- muStar[za,] if(termA)Umat[i11,] <- w0[,uindex[,1]]*w0[,uindex[,2]] if(termR)Vmat[i11,] <- w0[,gindex[,'colW']]*xl[i11,gindex[,'rowG']] } } W[i11,] <- w[i11,] } nz <- length(timeLast) W <- matrix( .tnorm(nz*S, plo[timeLast,], phi[timeLast,], w[timeLast,], wpropTime[timeLast,]), nz, S) z1 <- w[ timeLast , ] - w[ timeLast - 1 , ] Z1 <- W - w[timeLast - 1,] if(REDUCT){ pnow <- dnorm( z1, muw[timeLast-1,], sdg, log=T) pnew <- dnorm( Z1, muw[timeLast-1,], sdg, log=T) za <- which( runif(length(pnow),0,1) < exp(pnew - pnow) ) if(length(za) > 0){ w[timeLast,][za] <- W[za] } }else{ pnow <- .dMVN( z1, muw[timeLast-1,], sinv=sinv,log=T) pnew <- .dMVN( Z1, muw[timeLast-1,], sinv=sinv,log=T) za <- which( runif(length(pnow),0,1) < exp(pnew - pnow) ) if(length(za) > 0){ w[timeLast[za],] <- W[za,] } } nz <- length(timeZero) W <- matrix( .tnorm(nz*S, plo[timeZero,], phi[timeZero,], w[timeZero,], wpropTime[timeZero,]), nz, S) ww <- W[drop=FALSE, ,] w0 <- ww w0[ ww < 0 ] <- 0 muStar <- ww*0 if(termB)muStar <- muStar + mub[timeZero,] if(termR){ mugStar <- (w0[drop=FALSE, ,gindex[,'colW']]*xl[timeZero,gindex[,'rowG']])%*%Rmat muStar <- muStar + mugStar } if(termA){ muaStar <- (w0[drop=FALSE, ,uindex[,1]]*w0[,uindex[,2]] )%*%Amat muStar[,notOther] <- muStar[,notOther] + muaStar[,notOther] } z1 <- w[timeZero+1,notOther] - w[timeZero,notOther] Z1 <- w[timeZero+1,notOther] - W[,notOther] if(RANDOM)muStar <- muStar + groupRandEff[timeZero,] if(REDUCT){ muStar <- muStar + rndEff[timeZero,] pnow <- dnorm( z1, muw[timeZero,notOther], sdg, log=T) pnew <- dnorm( Z1, muStar[,notOther], sdg, log=T) if(length(corCols) > 0){ pnow[,corCols] <- dnorm( z1[,corCols], muw[timeZero,corCols], 1, log=T) pnew[,corCols] <- dnorm( Z1[,corCols], muStar[,corCols], 1, log=T) } za <- which( runif(length(pnow),0,1) < exp(pnew - pnow) ) if(length(za) > 0){ w[timeZero,][za] <- W[za] ww <- w[drop=FALSE, timeZero,] w0 <- ww w0[ ww < 0 ] <- 0 muw[timeZero,][za] <- muStar[za] Umat[timeZero,] <- w0[drop=FALSE, ,uindex[,1]]*w0[drop=FALSE, ,uindex[,2]] Vmat[timeZero,] <- w0[drop=FALSE, ,gindex[,'colW']]*xl[timeZero,gindex[,'colX']] } }else{ pnow <- .dMVN( z1, muw[timeZero,notOther], sinv=sinv,log=T) pnew <- .dMVN( Z1, muStar[,notOther], sinv=sinv,log=T) za <- which( runif(length(pnow),0,1) < exp(pnew - pnow) ) if(length(za) > 0){ w[timeZero[za],] <- W[za,] ww <- w[drop=FALSE,timeZero,] w0 <- ww w0[ ww < 0 ] <- 0 muw[timeZero[za],] <- muStar[za,] if(termA)Umat[timeZero,] <- w0[,uindex[,1]]*w0[,uindex[,2]] if(termR)Vmat[timeZero,] <- w0[,gindex[,'colW']]*xl[timeZero,gindex[,'rowG']] } } mu <- muw[,notOther] mu[tindex[,2],] <- w[tindex[,1],notOther] + muw[tindex[,1],] mu[timeZero,] <- w[timeZero,notOther] if(REDUCT){ yp <- matrix(rnorm(n*S,mu,sdg),n,S) }else{ yp[,notOther] <- .rMVN(n, mu, sinv = sinv[notOther,notOther]) } list(Umat = Umat, Vmat = Vmat, w = w, muw = muw, yp = yp) } } .wWrapper <- function(REDUCT, RANDOM, S, effMat, corCols, notCorCols, typeNames, typeFull, typeCols, allTypes, holdoutN, holdoutIndex, censor, censorCA, censorDA, censorCON, notOther, sampleW, byRow, byCol, indexW, ploHold, phiHold, sampleWhold, inSamp){ if(REDUCT){ function(rows, x, w, y, bg, sg, alpha, cutg, plo, phi, rndEff, groupRandEff, sigmaerror, wHold){ n <- nrow(y) w0 <- which(sampleW == 1) SC <- ncol(y) scol <- c(1:S) sigvec <- rep(sigmaerror,S) if(holdoutN > 0){ wHold <- w[drop=F,holdoutIndex,] } yPredict <- w*0 SN <- length(notCorCols) if( length(notCorCols) > 0 ){ mue <- x%*%bg if(RANDOM)mue <- mue + groupRandEff muf <- mue + rndEff w[w0] <- .tnorm(length(w0), plo[w0], phi[w0], muf[w0], sqrt(sigmaerror)) w[-w0] <- y[-w0] if(holdoutN < n){ yPredict[,notCorCols] <- rnorm(n*SN, muf[,notCorCols], sqrt(sigmaerror)) } if( holdoutN > 0 ){ if(holdoutN < n){ wHold[,notCorCols] <- matrix( .tnorm(holdoutN*SN, as.vector(ploHold[,notCorCols]), as.vector(phiHold[,notCorCols]), as.vector(muf[drop=F,holdoutIndex,notCorCols] ), sqrt(sigmaerror)),holdoutN,SN) } w[holdoutIndex,notOther] <- yPredict[holdoutIndex,notOther] <- .rMVN(holdoutN,mue[holdoutIndex,notOther], sg[notOther,notOther]) } } if( length(corCols) > 0 ){ css <- sg*0 css[notOther,notOther] <- .cov2Cor(sg[notOther,notOther]) muo <- x%*%alpha if(RANDOM)muo <- muo + groupRandEff if(holdoutN < n){ mur <- muo if(length(rndEff) > 1)mur <- mur + .sqrtMatrix(rndEff,sg,DIVIDE=T) SC <- length(corCols) w[,corCols] <- matrix( .tnorm(n*SC, as.vector(t(plo[,corCols])), as.vector(t(phi[,corCols])), as.vector(t(mur[,corCols])),1), n,SC, byrow=T) yPredict[,corCols] <- rnorm(n*SC,mur[,corCols],1) } if(holdoutN > 0){ if(holdoutN < n){ wHold[,corCols] <- matrix( .tnorm(holdoutN*SC, as.vector(ploHold[,corCols]), as.vector(phiHold[,corCols]), as.vector(t(mur[holdoutIndex,corCols])), 1),holdoutN,SC) } w[holdoutIndex,corCols] <- yPredict[holdoutIndex,corCols] <- rmvnormRcpp(holdoutN,rep(0,length(corCols)), css[corCols,corCols]) + muo } } if( !is.null(sampleW) )w[sampleW == 0] <- y[sampleW == 0] if( holdoutN > 0 ){ wHold[sampleWhold == 0] <- y[holdoutIndex,][sampleWhold == 0] } FCgroups <- attr(typeNames,'FCgroups') CCgroups <- attr(typeNames,'CCgroups') CATgroups <- attr(typeNames,'CATgroups') for(k in allTypes){ wk <- which(typeCols == k) wo <- which(wk %in% notOther) nk <- length(wk) wu <- which(typeCols[notOther] == k) wp <- w[, wk, drop=F] yp <- yPredict[, wk, drop=F] groups <- NULL if(typeFull[wk[1]] == 'countComp') groups <- CCgroups[wk] if(typeFull[wk[1]] == 'fracComp') groups <- FCgroups[wk] if( typeFull[wk[1]] == 'categorical' ){ groups <- CATgroups[wk] if(holdoutN < n){ tmp <- .gjamWcatLoop2(y, ws = wp, mus = muf, sgs = sigvec, notOther = notOther, plo, phi, groups = CATgroups, REDUCT=T) wp[,wo] <- tmp$w[,wo] plo <- tmp$plo phi <- tmp$phi } if(holdoutN > 0){ ws <- w[, wk, drop=F] ws[holdoutIndex,] <- wHold[, wk, drop=F] if(holdoutN < n)wHold[,wo] <- .gjamWcatLoop2(y, ws, mus = muf, sgs = sigvec, notOther = notOther, ploHold, phiHold, groups = CATgroups, REDUCT=T) } } glist <- list(wo = wo, type = typeFull[wk[1]], yy = y[,wk,drop=F], wq = wp, yq = yp, cutg = cutg, censor = censor, censorCA = censorCA, censorDA = censorDA, censorCON = censorCON, eff = effMat[rows,wk,drop=F],groups = groups, k = k, typeCols = typeCols, notOther = notOther, wk = wk, sampW = sampleW[,wk]) if( holdoutN < n ){ tmp <- .gjamWLoopTypes( glist ) w[,wk] <- tmp[[1]] yPredict[inSamp,wk] <- tmp[[2]][inSamp,] } if( holdoutN > 0 ){ glist$wq <- wHold[,wk,drop=F] glist$yq <- yPredict[holdoutIndex, wk, drop=F] glist$yy <- y[holdoutIndex,wk,drop=F] glist$eff <- effMat[holdoutIndex, wk, drop=F] glist$sampW <- sampleW[,wk] tmp <- .gjamWLoopTypes( glist ) if(holdoutN < n)wHold[,wk] <- tmp[[1]] yPredict[holdoutIndex,wk] <- tmp[[2]] } yPredict[,wk] <- .censorValues(censor,y,yPredict)[,wk] } if(!is.null(sampleW))w[sampleW[rows,] == 0] <- y[sampleW[rows,] == 0] if(holdoutN > 0){ wHold[sampleWhold == 0] <- y[holdoutIndex,][sampleWhold == 0] } list(w = w, wHold = wHold, yp = yPredict, plo = plo, phi = phi ) } } else { function(rows, x, w, y, bg, sg, alpha, cutg, plo, phi, rndEff = NULL, groupRandEff, sigmaerror = NULL, wHold){ n <- nrow(y) sampW <- sampleW[rows,notOther] w[sampleW[rows,] == 0] <- y[sampleW[rows,] == 0] if(holdoutN > 0){ wHold[sampleWhold == 0] <- y[holdoutIndex,][sampleWhold == 0] } yPredict <- w*0 muw <- x%*%bg if( length(notCorCols) > 0 ){ if(RANDOM)muw <- muw + groupRandEff yPredict[,notOther] <- rmvnormRcpp(n,rep(0,length(notOther)), sg[notOther,notOther]) + muw[,notOther] } if( length(corCols) > 0 ){ wss <- w*0 css <- .cov2Cor(sg[notOther,notOther]) muss <- x%*%alpha if(RANDOM)muss <- muss + groupRandEff ypred <- yPredict ypred[,notOther] <- rmvnormRcpp(n,rep(0,length(notOther)),css) + muss[,notOther] yPredict[,corCols] <- ypred[,corCols] } FCgroups <- attr(typeNames,'FCgroups') CCgroups <- attr(typeNames,'CCgroups') CATgroups <- attr(typeNames,'CATgroups') for(k in allTypes){ wk <- which(typeCols == k) nk <- length(wk) wo <- which(wk %in% notOther) wu <- which(typeCols[notOther] == k) wp <- w[, wk, drop=F] yq <- yPredict[, wk, drop=F] if( typeFull[wk[1]] %in% c('presenceAbsence','ordinal') ) { wss[,notOther] <- .sqrtMatrix(w[,notOther],sg[notOther,notOther], DIVIDE=T) llist <- list(ws = wss[,notOther], mus = muss[,notOther], sgs = css, wkk = wu, lo = plo[,notOther], hi = phi[,notOther], sampW = sampW, indexW = indexW) wp[,wo] <- .gjamWLoop( llist )[,wu] if( holdoutN > 0 ){ if( holdoutN < n ){ llist <- list(ws = wss[drop=F,holdoutIndex,notOther], mus = muss[drop=F,holdoutIndex,notOther], sgs = css, wkk = wu, lo = ploHold[drop=F,,notOther], hi = phiHold[drop=F,,notOther], sampW = sampleWhold[,notOther], indexW=wo) wHold[,wo] <- .gjamWLoop( llist )[,wu] } wp[holdoutIndex,wo] <- yq[holdoutIndex,wo] } } if( typeFull[wk[1]] == 'categorical' ){ wss[,notOther] <- .sqrtMatrix(w[,notOther],sg[notOther,notOther], DIVIDE=T) if(holdoutN > 0)yy[holdoutIndex,] <- yq[holdoutIndex,] tmp <- .gjamWcatLoop2(yy, ws = wss, mus = muss, sgs = css, notOther, plo, phi, groups = CATgroups) wp <- tmp$w[,wk] plo <- tmp$plo phi <- tmp$phi if(holdoutN > 0){ if(holdoutN < n){ wHold[,wk] <- .gjamWcatLoop2(yq[drop=F,holdoutIndex,], wss[drop=F,holdoutIndex,], muss[drop=F,holdoutIndex,], sgs = css, notOther, ploHold, phiHold, groups = CATgroups)$w[,wk] } wp[holdoutIndex,wo] <- yq[holdoutIndex,wo] } } if( !typeFull[wk[1]] %in% c('presenceAbsence','ordinal','categorical') ){ llist <- list(ws = w[,notOther], mus = muw[,notOther], sgs = sg[notOther,notOther], wkk = wu, lo = plo[,notOther], hi = phi[,notOther],sampW = sampW, indexW = indexW, byCol= byCol, byRow = byRow) wp[,wo] <- .gjamWLoop( llist )[,wu] if(holdoutN > 0){ if(holdoutN < n){ llist <- list(ws = w[drop=F,holdoutIndex,notOther], mus = muw[drop=F,holdoutIndex,notOther], sgs = sg[notOther,notOther], wkk = wu, lo = ploHold[drop=F,,notOther], hi = phiHold[drop=F,,notOther], sampW = sampleWhold[,notOther], indexW = wo, byCol = byCol, byRow = byRow) wHold[,wo] <- .gjamWLoop( llist )[,wu] if( typeFull[wk[1]] != "countComp")wp[holdoutIndex,wo] <- yq[holdoutIndex,wo] } } } groups <- NULL if(typeFull[wk[1]] == 'countComp') groups <- CCgroups[wk] if(typeFull[wk[1]] == 'fracComp') groups <- FCgroups[wk] if(typeFull[wk[1]] == 'categorical')groups <- CATgroups[wk] glist <- list(wo = wo, type = typeFull[wk[1]], yy = y[,wk,drop=F], wq = wp, yq = yq, cutg = cutg, censor = censor, censorCA = censorCA, censorDA = censorDA, censorCON = censorCON, eff = effMat[rows,wk,drop=F], groups = groups, k = k, typeCols = typeCols, notOther = notOther, wk = wk, sampW = sampleW[,wk]) tmp <- .gjamWLoopTypes( glist ) w[,wk] <- tmp[[1]] yPredict[,wk] <- tmp[[2]] yPredict[,wk] <- .censorValues(censor, y, yPredict)[,wk] } if(!is.null(sampleW))w[sampleW[rows,] == 0] <- y[sampleW[rows,] == 0] list(w = w, wHold = wHold, yp = yPredict, plo = plo, phi = phi ) } } } .binaryScore <- function(p, x){ a <- mean((x - p)^2) b <- -mean( x*log(p) + (1 - x)*log(1 - p)) list(brierScore = a, logScore = b) } .betaWrapper <- function(REDUCT, TIME, notOther, betaLim=50){ if(REDUCT){ function(X, Y, sig, beta, PRIOR, lo, hi, rows=NULL, pattern=NULL, ...){ SS <- ncol(Y) w0 <- which(colSums(X) == 0) if(length(w0) > 0){ X <- X[,-w0] beta <- beta[-w0,] rows[rows %in% w0] <- NA } tiny <- 1e-5 XX <- crossprod(X) diag(XX) <- diag(XX)*(1 + tiny) IXX <- try( solve(XX), T ) if( inherits(IXX,'try-error') ){ diag(XX) <- diag(XX) + 1.001*diag(XX) IXX <- solve(XX) } omega <- sig*IXX muB <- t(omega%*%crossprod((1/sig)*X, Y)) if( !PRIOR ){ B <- rmvnormRcpp( SS, rep(0,nrow(omega)), omega) + muB ws <- which(abs(B) > betaLim, arr.ind=T) if(length(ws) > 0){ ws <- unique(ws[,1]) bs <- B[drop=F,ws,] B[ws,] <- .tnormMVNmatrix(avec = bs, muvec = muB[drop=F,ws,], smat = omega, lo = bs*0 - betaLim, hi = bs*0 + betaLim) } return(t(B)) } if(!TIME){ tmp <- .tnormMVNmatrix( avec = t(beta), muvec = muB, smat = omega, lo = t(lo), hi = t(hi) ) return( t(tmp) ) } B <- t(beta) QX <- ncol(X) for(k in 1:nrow(pattern)){ krow <- rows[k,] krow <- krow[is.finite(krow)] notk <- c(1:QX)[-krow] if(length(notk) == 1){ M1 <- omega[krow,notk, drop=F]/omega[notk,notk] }else{ OI <- try( solve(omega[notk,notk]), T) if( inherits(OI,'try-error') ){ OI <- diag(1/diag(omega[notk,notk])) } M1 <- omega[krow,notk, drop=F]%*%OI } pk <- pattern[k,] pk <- pk[is.finite(pk)] muk <- muB[pk, krow, drop=F] - muB[pk,notk]%*%t(M1) Mk <- omega[krow,krow] - M1%*%omega[notk,krow] if(length(Mk) == 1){ B[pk,krow] <- .tnorm(length(pk),lo[krow,pk],hi[krow,pk],muk,sqrt(Mk)) } else { ll <- t(lo)[pk,krow,drop=F] hh <- t(hi)[pk,krow,drop=F] test <- try( .tnormMVNmatrix( avec=muk, muvec=muk, smat=Mk, lo=ll, hi=hh), T) if( inherits(test,'try-error') ){ mm <- diag(Mk) mm[mm < tiny] <- tiny test <- .tnorm(length(ll),ll,hh,muk,sqrt(mm)) } B[pk,krow] <- test } } return( t(B) ) } }else{ function(X, Y, sig, beta, PRIOR, lo, hi, rows = NULL, pattern = NULL, sinv = NULL, wF, ...){ if( !PRIOR ){ XX <- crossprod(X) IXX <- chol2inv(chol( XX ) ) WX <- crossprod(X,Y) WIX <- IXX%*%WX bg <- matrix( .rMVN(1,as.vector(WIX), kronecker(sig, IXX)),nrow(IXX),ncol(WIX) ) return(bg) } wc <- which(!is.na(lo) & lo < hi) wp <- c(1:length(lo))[-wc] XX <- crossprod(X) IXX <- chol2inv(chol( XX ) ) WX <- crossprod(X,Y) MU <- IXX%*%WX MM <- kronecker(sig,IXX) if( length(wp) > 0 ){ smat <- MM WIX <- MU if( length(wp) > length(wc) ){ if(is.null(sinv))sinv <- solveRcpp(sig) CC <- kronecker( sinv, XX) MM <- solveRcpp(CC[wc,wc]) IM <- CC[wp,wp] - CC[wp,wc]%*%MM%*%CC[wc,wp] MU <- t( WIX[wc] - smat[wc,wp]%*%IM%*%WIX[wp] ) }else{ M1 <- smat[wc,wp]%*%solve(smat[wp,wp]) MU <- t( WIX[wc] - M1%*%WIX[wp] ) MM <- smat[wc,wc] - M1%*%smat[wp,wc] } } beta[wc] <- .tnormMVNmatrix(avec = matrix(beta[wc],1), muvec = matrix(MU,1), smat = MM, lo = matrix(lo[wc],1), hi = matrix(hi[wc],1)) return(beta) } } } .paramWrapper <- function(REDUCT, inSamples,SS){ if(REDUCT){ function( X, beta, Y, otherpar ){ N <- otherpar$N r <- otherpar$r D <- otherpar$D Z <- otherpar$Z sigmaerror <- otherpar$sigmaerror K <- otherpar$K pvec <- otherpar$pvec alpha.DP <- otherpar$alpha.DP tmp <- .getPars(X = X, N = N, r = r, Y = Y, B = t(beta), D = D, Z = Z, sigmaerror = sigmaerror, K = K, pvec = pvec, alpha.DP = alpha.DP, inSamples = inSamples, SELECT = F) sg <- with(tmp, .expandSigma(sigma = tmp$sigmaerror, SS, Z = tmp$Z, K = tmp$K, REDUCT=T)) otherpar <- list(A = tmp$A, N = N, r = r, D = tmp$D, Z = tmp$Z, sigmaerror = tmp$sigmaerror, pvec = tmp$pvec, K = tmp$K, alpha.DP = alpha.DP) return(list(sg = sg, rndEff = tmp$rndEff, otherpar = otherpar)) } } else { function(x, beta,Y,otherpar){ sigmaDf <- otherpar$sigmaDf XX <- crossprod(x[inSamples,]) IXX <- solveRcpp(XX) WX <- crossprod(x[inSamples,], Y[inSamples,]) WIX <- IXX%*%WX sg <- .updateWishartNoPrior( x[drop=F,inSamples,], Y[inSamples,], sigmaDf, beta = beta, IXX = IXX, WX = WX, WIX = WIX, TRYPRIOR = T)$sigma otherpar=list(Z = NA, K = NA, sigmaDf = sigmaDf) return(list(sg = sg, otherpar = otherpar)) } } } .rwish <- function(df,SS){ z <- matrix(rnorm(df*nrow(SS)),df,nrow(SS))%*%chol(SS) crossprod(z) } .riwish <- function(df,S){ solveRcpp(.rwish(df,solveRcpp(S))) } .expandSigmaChains <- function(snames, sgibbs, otherpar, simIndex = sample(nrow(sgibbs),50,replace=T), sigErrGibbs, kgibbs=NULL, REDUCT=F, CHAINSONLY=F, verbose){ tiny <- 1e-8 S <- otherpar$S K <- otherpar$K N <- otherpar$N r <- otherpar$r if(length(simIndex) > 1000)simIndex <- sample(simIndex,1000) ns <- length(simIndex) xnames <- otherpar$xnames if( CHAINSONLY & !REDUCT ){ imat <- matrix(1:(S*S),S,S) jmat <- matrix(1:(S*S),S,S,byrow=T) tmp <- matrix(NA,nrow(sgibbs),S*S) sindex <- imat[lower.tri(imat,diag=T)] tmp[,sindex] <- sgibbs sindex <- jmat[lower.tri(imat,diag=T)] tmp[,sindex] <- sgibbs sMu <- matrix( colMeans(tmp),S,S) sSe <- matrix( apply(tmp,2,sd),S,S) chainList <- list(cchain = NULL, schain = tmp, kchain = NULL) return( list(chainList = chainList, rMu = NULL, rSe = NULL, sMu = sMu, sSe = sSe) ) } other <- grep('other',snames) notOther <- c(1:S) if(length(other) > 0)notOther <- notOther[-other] Kindex <- which(lower.tri( diag(S),diag=T ) ) kchain <- NULL schain <- cchain <- matrix(0,ns,length(Kindex)) colnames(schain) <- colnames(cchain) <- .multivarChainNames(snames,snames)[Kindex] if( REDUCT ){ kchain <- matrix(0, ns, ncol(kgibbs)) if( verbose )cat('\nexpanding covariance chains\n') } snames <- otherpar$snames s1 <- diag(S)*0 s2 <- r1 <- r2 <- s1 pbar <- txtProgressBar(min=1,max=ns,style=1) sinvPlus <- sinvMinus <- matrix(0,S,S) k <- 1 for(j in simIndex){ if(REDUCT){ Z <- matrix(sgibbs[j,],N,r) ss <- .expandSigma(sigErrGibbs[j], S, Z = Z, kgibbs[j,], REDUCT = TRUE) si <- invWbyRcpp(sigErrGibbs[j], Z[kgibbs[j,],]) cc <- .cov2Cor(ss) dc <- diag(sqrt(diag(ss))) ci <- dc%*%si%*%dc } else { ss <- .expandSigma(sgibbs[j,], S = S, REDUCT = FALSE) si <- ci <- diag(1,S) si[notOther,notOther] <- solveRcpp(ss[notOther,notOther]) cc <- .cov2Cor(ss) ci[notOther,notOther] <- solveRcpp(cc[notOther,notOther]) } s1 <- s1 + ss s2 <- s2 + ss^2 r1 <- r1 + cc r2 <- r2 + cc^2 schain[k,] <- ss[Kindex] cchain[k,] <- cc[Kindex] if(REDUCT)kchain[k,] <- kgibbs[j,] sinvPlus[si > 0] <- sinvPlus[si > 0] + 1 sinvMinus[si < 0] <- sinvMinus[si < 0] + 1 setTxtProgressBar(pbar,k) k <- k + 1 } diag(sinvPlus) <- diag(sinvMinus) <- 0 sigInvPos <- which(sinvPlus > .95*length(simIndex),arr.ind=T) sigInvNeg <- which(sinvMinus > .95*length(simIndex),arr.ind=T) ssi <- sort( unique(c( sigInvPos[,1], sigInvNeg[,1]) ) ) sMu <- s1/ns vv <- s2/ns - sMu^2 vv[vv < tiny] <- tiny sSe <- sqrt( vv ) rMu <- r1/ns vv <- r2/ns - rMu^2 vv[vv < tiny] <- tiny rSe <- sqrt( vv ) rownames(sMu) <- colnames(sMu) <- snames rownames(sSe) <- colnames(rSe) <- snames colnames(cchain) <- colnames(schain) chainList <- list(cchain = cchain, schain = schain, kchain = kchain) list(chainList = chainList, rMu = rMu, rSe = rSe, sMu = sMu, sSe = sSe) } .expandSigma <- function(sigma, S, Z = NULL, K = NULL, REDUCT = F){ if(REDUCT) return( sigma*diag(S) + tcrossprod(Z[K,]) ) ss <- diag(S) ss[lower.tri(ss,diag=T)] <- sigma ss[upper.tri(ss)] <- t(ss)[upper.tri(ss)] ss } .ordTraitsFromWts <- function(yWt,ordTraits){ if(!is.matrix(ordTraits))ordTraits <- matrix(ordTraits) n <- nrow(yWt) s <- ncol(yWt) ii <- rep(c(1:n),s) omat <- matrix(NA,n,ncol(ordTraits)) for(j in 1:ncol(ordTraits)){ PLUS <- F oj <- ordTraits[,j] if(min(oj) < 0)stop('ordinal scores cannot be < 0') if(min(oj) == 0){ PLUS <- T oj <- oj + 1 } rj <- range(oj, na.rm=T) mm <- matrix(0, n, rj[2] ) jj <- as.vector( matrix(oj, n, s, byrow=T) ) tmp <- .byGJAM(as.vector(yWt),ii,jj,mm,mm,fun='sum') w0 <- which( apply(tmp,1,sum) == 0) m1 <- apply(tmp,1,which.max) m1 <- (rj[1]:rj[2])[m1] if(PLUS)m1 <- m1 - 1 omat[,j] <- m1 if(length(w0) > 0)omat[w0,j] <- 0 } colnames(omat) <- colnames(ordTraits) omat } .incidence2Grid <- function(specs, lonLat, nx = NULL, ny = NULL, dx = NULL, dy = NULL, predGrid = NULL, effortOnly=TRUE){ ngrid <- length(predGrid) mapx <- range(lonLat[,1]) mapy <- range(lonLat[,2]) specs <- as.character(specs) ynames <- sort(unique(specs)) nspec <- length(ynames) jj <- match(specs,ynames) if(ngrid == 0){ if(!is.null(dx)){ xseq <- seq(mapx[1], mapx[2], by = dx) yseq <- seq(mapy[1], mapy[2], by = dy) } else { xseq <- seq(mapx[1], mapx[2], length = nx) yseq <- seq(mapy[1], mapy[2], length = ny) } predGrid <- as.matrix( expand.grid(lon = xseq, lat = yseq) ) ngrid <- nrow(predGrid) } ii <- RANN::nn2(predGrid, lonLat, k = 1 )$nn.idx mm <- matrix(0, ngrid, nspec ) gridBySpec <- .byGJAM(ii*0 + 1, ii, jj, mm, mm, fun='sum') colnames(gridBySpec) <- ynames effort <- rowSums(gridBySpec) if(effortOnly){ wk <- which(effort > 0) effort <- effort[wk] gridBySpec <- gridBySpec[wk,] predGrid <- predGrid[wk,] } list(gridBySpec = gridBySpec, predGrid = predGrid) } .spec2Trait <- function(pbys, sbyt, tTypes){ n <- nrow(pbys) S <- ncol(pbys) M <- ncol(sbyt) ttt <- numeric(0) y2t <- match(colnames(pbys),rownames(sbyt)) y2tf <- which(is.finite(y2t)) t2y <- match(rownames(sbyt),colnames(pbys)) t2yf <- which(is.finite(t2y)) if(is.data.frame(pbys))pbys <- as.matrix(pbys) ywt <- sweep(pbys,1,rowSums(pbys,na.rm=T),'/') ywt[is.na(ywt)] <- 0 newTypes <- character(0) tmat <- ttt <- numeric(0) wf <- which( !tTypes %in% c('OC','CAT') ) if(length(wf) > 0){ newTypes <- tTypes[wf] ttt <- sbyt[ y2t, wf, drop=F] tmat <- ywt%*%as.matrix( sbyt[y2t, wf, drop=F] ) } ordNames <- which(tTypes == 'OC') if(length(ordNames) > 0){ ordTraits <- as.matrix( round(sbyt[y2t[y2tf],ordNames],0) ) ordCols <- .ordTraitsFromWts(ywt,ordTraits) if(is.null(colnames(ordCols)))colnames(ordCols) <- colnames(ordTraits) <- colnames(sbyt)[ordNames] ttt <- cbind(ttt, ordTraits ) tmat <- cbind(tmat,ordCols) newTypes <- c(newTypes,tTypes[ordNames]) } censor <- NULL mcol <- ncol(tmat) if(is.null(mcol))mcol <- 0 xx <- numeric(0) FCgroups <- rep(0,mcol) wf <- numeric(0) for(j in 1:ncol(sbyt))if(is.factor(sbyt[,j]))wf <- c(wf,j) wf <- union(wf,which(tTypes %in% 'CAT')) if(length(wf) > 0){ xx <- sbyt[,wf,drop=F] xc <- numeric(0) kg <- 0 for(kk in 1:length(wf)){ xkk <- xx[,kk] xtab <- table(xkk) if(length(xtab) == 1){ stop( paste('CAT trait _',names(xx)[kk], '_ has only 1 level, need at least 2',sep='') ) } xtab <- xtab[order(xtab)] xkk <- relevel(xkk,ref=names(xtab)[1]) cont <- contrasts(xkk,contrasts = F) xk <- cont[xkk,,drop=F] tmp <- ywt[,t2y]%*%xk[t2y,] if(ncol(tmp) == 2){ mc <- mcol + 1 ktype <- 'CA' tmp <- tmp[,1,drop=F] gk <- 0 tc <- gjamCensorY( values = c(0,1), intervals = cbind( c(-Inf,0), c(1,Inf) ), y = tmp) ttt <- cbind(ttt,xk[,1,drop=F]) if(is.null(censor)){ censor <- c(censor, tc$censor) censor$CA$columns <- mc } else { censor$CA$columns <- c(censor$CA$columns,mc) } } else { mc <- ncol(tmp) cname <- colnames(tmp) cname[1] <- 'other' cname <- paste(colnames(xx)[kk],cname,sep='') colnames(tmp) <- colnames(xk) <- cname ttt <- cbind(ttt,xk) ktype <- rep('FC',ncol(tmp)) kg <- kg + 1 gk <- rep(kg,mc) } mcol <- mcol + ncol(tmp) FCgroups <- c(FCgroups,gk) xc <- cbind(xc,tmp) newTypes <- c(newTypes,ktype) } tmat <- cbind(tmat,xc) } colnames(tmat) <- colnames(ttt) attr(newTypes,'FCgroups') <- FCgroups list(plotByCWM = tmat, traitTypes = newTypes, censor = censor, specByTrait = ttt) } .boxplotQuant <- function( xx, ..., boxfill=NULL ){ pars <- list(...) tmp <- boxplot( xx, ..., plot=F) if(!'stats' %in% names(pars)){ ss <- apply( xx, 2, quantile, pnorm(c(-1.96,-1,0,1,1.96)) ) tmp$stats <- ss }else{ tmp$stats <- pars$stats } if( 'col' %in% names(pars) )boxfill <- pars$col bxp( tmp, ..., boxfill = boxfill ) tmp } .gjamOrd <- function( output, SPECLABS, col, cex, PLOT, method ){ ematrix <- output$parameters$ematrix ematAlpha <- output$modelList$ematAlpha whConZero <- output$fit$whConZero whichZero <- output$fit$whichZero y <- output$inputs$y S <- SO <- ncol(y) snames <- colnames(y) if(is.null(col))col <- rep('black',S) other <- output$inputs$other notOther <- output$inputs$notOther SO <- length(notOther) plab <- c('Axis I', 'Axis II', 'Axis III') if (method == 'NMDS') { tmp <- isoMDS(.cov2Dist(ematrix[notOther,notOther]), k = 3) eVecs <- tmp$points colnames(eVecs) <- paste('NMDS',c(1:3),sep = '_') eValues <- lambda <- cl <- NULL } else { tmp <- eigen(ematrix[notOther,notOther]) eVecs <- tmp$vectors eValues <- tmp$values lambda <- eValues/sum(eValues) cl <- cumsum(lambda) clab <- paste(' (',round(100*lambda,0),'%)',sep='') plab <- paste(plab, clab, sep='') } rownames(eVecs) <- snames[notOther] if(!PLOT) return( list(eVecs = eVecs, eValues = eValues) ) cbord <- .getColor(col[notOther],.6) par(mfcol=c(2,2), bty='n', cex = cex, mar=c(4,4,1,1)) plot(eVecs[,1],eVecs[,2],cex=1,col=cbord, bg = cbord, pch=16, xlab=plab[1], ylab = plab[2]) abline(h=0,col=.getColor('black',.3),lwd=2,lty=2) abline(v=0,col=.getColor('black',.3),lwd=2,lty=2) if(length(SPECLABS) > 0){ mmm <- match(SPECLABS,rownames(eVecs)) text(eVecs[mmm,2],eVecs[mmm,3],SPECLABS,col=cbord[notOther][mmm]) } plot(eVecs[,1],eVecs[,3],cex=1,col=cbord, bg = cbord, pch=16, xlab=plab[1], ylab = plab[3]) abline(h=0,col=.getColor('black',.3),lwd=2,lty=2) abline(v=0,col=.getColor('black',.3),lwd=2,lty=2) if(length(SPECLABS) > 0){ mmm <- match(SPECLABS,rownames(eVecs)) text(eVecs[mmm,2],eVecs[mmm,3],SPECLABS,col=cbord[notOther][mmm]) } plot(eVecs[,2],eVecs[,3],cex=1,col=cbord, bg = cbord, pch=16, xlab=plab[2], ylab = plab[3]) abline(h=0,col=.getColor('black',.3),lwd=2,lty=2) abline(v=0,col=.getColor('black',.3),lwd=2,lty=2) if(length(SPECLABS) > 0){ mmm <- match(SPECLABS,rownames(eVecs)) text(eVecs[mmm,2],eVecs[mmm,3],SPECLABS,col=cbord[notOther][mmm]) } if(method == 'PCA'){ plot(cl,type='s',xlab='Rank',ylab='Proportion of variance',xlim=c(.9,S), ylim=c(0,1),log='x',lwd=2) lines(c(.9,1),c(0,cl[1]),lwd=2,type='s') for(j in 1:length(lambda))lines(c(j,j),c(0,cl[j]),col='grey') lines(cl,lwd=2,type='s') abline(h=1,lwd=2,col=.getColor('grey',.5),lty=2) } list(eVecs = eVecs, eValues = eValues) } columnSplit <- function(vec, sep='_', ASFACTOR = F, ASNUMERIC=F, LASTONLY=F){ vec <- as.character(vec) nc <- length( strsplit(vec[1], sep)[[1]] ) mat <- matrix( unlist( strsplit(vec, sep) ), ncol=nc, byrow=T ) if(LASTONLY & ncol(mat) > 2){ rnn <- mat[,1] for(k in 2:(ncol(mat)-1)){ rnn <- columnPaste(rnn,mat[,k]) } mat <- cbind(rnn,mat[,ncol(mat)]) } if(ASNUMERIC){ mat <- matrix( as.numeric(mat), ncol=nc ) } if(ASFACTOR){ mat <- data.frame(mat) } mat } columnPaste <- function(c1, c2, sep='-', NOSPACE = FALSE){ c1 <- as.character(c1) c2 <- as.character(c2) if(NOSPACE){ c1 <- .replaceString(c1, ' ', '') c2 <- .replaceString(c2, ' ', '') } c12 <- apply( cbind(c1, c2) , 1, paste0, collapse=sep) c12 }
setGeneric("masking", function(r, m, RGB = c(1,0,0)) standardGeneric("masking")) .masking <- function(red, green, blue, m, RGB) { red[!m] <- RGB[1] green[!m] <- RGB[2] blue[!m] <- RGB[3] stack(red, green, blue) } setMethod("masking", signature(r = "RasterLayer"), function (r, m, RGB) { .check_if_r_was_normalized(r) compareRaster(r, m) red = green = blue <- r .masking(red, green, blue, m, RGB) } ) setMethod("masking", signature(r = "RasterStackBrick"), function (r, m, RGB) { .check_if_r_was_normalized(r) stopifnot(raster::nlayers(r) == 3) red <- raster::subset(r, 1) green <- raster::subset(r, 2) blue <- raster::subset(r, 3) .masking(red, green, blue, m, RGB) } )
memory_beta <- function(endpoint){ x <- .mb_portals if(endpoint == "portals") return(x) ep <- strsplit(endpoint, "/")[[1]] if(ep[1] %in% x$id){ d <- mb_category_pages(ep[1], x$url[x$id == ep[1]], c(".category-page__members", ".category-page__pagination")) } else { stop("Invalid endpoint: portal ID.", call. = FALSE) } if(length(ep) == 1) return(d) mb_select(d, ep[-1], ep[1]) } mb_article <- function(url, content_format = c("xml", "character"), content_nodes = c("h2", "h3", "h4", "p", "b", "ul", "dl", "table"), browse = FALSE){ content_format <- match.arg(content_format) url <- mb_base_add(url) tryCatch( x <- xml2::read_html(url), error = function(e) stop("Article not found.", call. = FALSE) ) title <- rvest::html_node(x, ".page-header__title") %>% mb_text() cats <- mb_article_categories(x) x <- rvest::html_nodes(x, ".WikiaArticle > aside <- mb_article_aside(x) content <- x[which(rvest::html_name(x) %in% content_nodes & !grepl("<aside.*aside>", x))] if(content_format == "character") content <- gsub("\\[edit.*", "", mb_text(content)) if(browse) utils::browseURL(url) dplyr::tibble(title = title, content = list(content), metadata = list(aside), categories = list(cats)) } mb_search <- function(text, browse = FALSE){ url <- paste0(mb_base_add("Special:Search?query="), gsub("\\s+", "+", text)) x <- xml2::read_html(url) %>% rvest::html_node(".unified-search__results") x <- rvest::html_nodes(x, "li article") %>% mb_text() %>% strsplit("(\n|\t)+") if(browse) utils::browseURL(url) dplyr::tibble(title = sapply(x, "[", 1), text = sapply(x, "[", 2), url = sapply(x, "[", 3)) } mb_image <- function(url, file, keep = FALSE){ url <- gsub(",", "%2C", url) file0 <- gsub("^File:|,", "", url) url2 <- xml2::read_html(mb_base_add(url)) %>% rvest::html_nodes("a img") %>% rvest::html_attr("src") url2 <- url2[grepl("^http", url2)] idx <- grep(file0, url2) if(!length(idx)) stop("Source file not accessible.", call. = FALSE) url2 <- url2[idx[1]] url2 <- gsub("latest/scale-to-width-down/\\d+\\?", "latest?", url2) if(missing(file)) file <- gsub(" ", "_", file0) file <- gsub("jpeg$", "jpg", file) downloader::download(url2, destfile = file, quiet = TRUE, mode = "wb") x <- jpeg::readJPEG(file) if(!keep) unlink(file, recursive = TRUE, force = TRUE) asp <- dim(x)[1] / dim(x)[2] x <- grid::rasterGrob(x, interpolate = TRUE) ggplot2::ggplot(geom = "blank") + ggplot2::annotation_custom(x, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) + ggplot2::theme(aspect.ratio = asp) }
post.pred <- function(z,fun=NULL) { x.n.new <- sapply(as.list(1:z$iter),function(g) distr(z$input$n,z$input$dist,z$sims[g,],'r')) if(!is.null(fun)) return(apply(x.n.new,2,fun)) else return(x.n.new) }
L1prop <- function(x, n, p.hypoth, pLset = 0.05) { L <- function(p, x, n) { p^x * (1 - p)^(n - x) } lL <- function(p, x, n) { x * log(p) + (n - x) * log(1 - p) } nL <- function(p, x, n) { (p^x * (1 - p)^(n - x))/((x/n)^x * (1 - (x/n))^(n - x)) } cat("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n") cat(" Likelihood analysis of one sample Binomial data\n") cat("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n") p <- x/n pies <- seq(0, 1, 0.001) nLpies <- nL(pies, x, n) inint <- pies[nLpies > pLset] low <- min(inint) high <- max(inint) Lratio <- L(p.hypoth, x, n)/L(x/n, x, n) pval <- 1 - pchisq(-2 * log(Lratio), 1) cat("Likelihood ratio for hypothesized prob.:", round(Lratio, 3), "\n", "with approximate p-value for these data:", round(pval, 3), "\n") plot(pies, nLpies, type = "l", ylab = "Normed likelihood", xlab = expression(hat(pi))) segments(low, 0, high, 0, lwd = 5) title(paste("Normed likelihood and", deparse(substitute(pLset)), "% likelihood interval")) abline(v = p.hypoth, col = "red") cat("MLE of p for these data:", round(x/n, 3), "\n") cat(pLset, "% likelihood interval: [", low, ",", high, "]\n") }
.noharm.tanaka <- function( noharmout1 ){ i1 <- grep( "Tanaka", noharmout1 ) tanaka <- as.numeric( strsplit( paste(noharmout1[i1]), split="=" )[[1]][2] ) return(tanaka) } .noharm.rmsr <- function( noharmout1 ){ i1 <- grep( "Root mean square of residuals", noharmout1 ) RMSR <- as.numeric( strsplit( paste(noharmout1[i1]), split="=" )[[1]][2] ) return(RMSR) } .noharm.itemlevel <- function( noharmout1, itemlevel.type, I=I,dat=dat){ i1 <- grep( itemlevel.type, noharmout1 ) VV <- floor(I/9)+1 * ( I/9 !=floor( I/9) ) uniquevar <- noharmout1[ seq( i1+5, i1 + 5 + 4*(VV-1), 4 ) ] uniquevar <- uniquevar[ substring( uniquevar, 1, 1 )==" " ] uniquevar <- paste( uniquevar, collapse=" " ) uniquevar <- strsplit( uniquevar, split=" " )[[1]] uniquevar <- as.numeric( paste( uniquevar[ uniquevar !="" ] ) ) uniquevar <- uniquevar[1:I] names(uniquevar) <- colnames(dat) return( uniquevar ) } .noharm.loadings <- function( noharmout1, type1, type2, dimensions=dimensions, I=I, dat=dat){ i1 <- grep( type1, noharmout1 )[1] i2 <- grep( type2, noharmout1 )[1] rows <- seq( i1+2, i2-4 ) if ( ( dimensions==1 ) & ( type1=="Factor Loadings" ) ){ rows <- seq(i1+2, i2-6 ) } r1 <- intersect( which( noharmout1=="" ), rows ) VV <- length(r1)/2 r2 <- stats::aggregate( r1, list(rep( 1:VV, each=2 )), mean ) colnames(r2) <- c("index", "index.row" ) index.m <- data.frame( r2, "begin"=r2[,2] + 2, "end"=c( r2[,2][-1] - 2, i2-4 ) ) if ( dimensions==1 & type1=="Factor Loadings"){ index.m$end <- i2 - 6 } loading.matrix <- matrix(0,I,dimensions) rownames(loading.matrix) <- colnames(dat) colnames(loading.matrix) <- paste( "F", 1:dimensions, sep="") for (vv in 1:VV){ ind.vv.col <- noharmout1[ index.m$index.row[vv] ] ind.vv.col <- strsplit( ind.vv.col, split=" " )[[1]] ind.vv.col <- as.numeric( ind.vv.col[ ind.vv.col !="" ] ) ind.vv <- seq( index.m$begin[vv], index.m$end[vv] ) loading.vv <- noharmout1[ ind.vv ] loading.vv <- sapply( loading.vv, FUN=function(ll){ ll1 <- strsplit( paste(ll), split=" " )[[1]] as.numeric( ll1[ ll1 !=ll1[1] ] ) } ) loading.vv <- as.matrix( loading.vv ) ind.vv.row <- as.vector( loading.vv[1,] ) loading.vv <- loading.vv[-1,] loading.matrix[ ind.vv.row, ind.vv.col ] <- t(loading.vv) } return( loading.matrix ) } .noharm.correlations <- function( noharmout1, type1="Factor Correlations", type2="Residual Matrix", dimensions=dimensions, dat=dat ){ i1 <- grep( type1, noharmout1 )[1] i2 <- grep( type2, noharmout1 )[1] rows <- seq( i1+2, i2-4 ) r1 <- intersect( which( noharmout1=="" ), rows ) VV <- length(r1)/2 r2 <- stats::aggregate( r1, list(rep( 1:VV, each=2 )), mean ) colnames(r2) <- c("index", "index.row" ) index.m <- data.frame( r2, "begin"=r2[,2] + 2, "end"=c( r2[,2][-1] - 2, i2-4 ) ) correlation.matrix <- matrix(NA,dimensions,dimensions) rownames(correlation.matrix) <- colnames(correlation.matrix) <- paste( "F", 1:dimensions, sep="") for (vv in 1:VV){ ind.vv.col <- noharmout1[ index.m$index.row[vv] ] ind.vv.col <- strsplit( ind.vv.col, split=" " )[[1]] ind.vv.col <- as.numeric( ind.vv.col[ ind.vv.col !="" ] ) ind.vv <- seq( index.m$begin[vv], index.m$end[vv] ) correlation.vv <- noharmout1[ ind.vv ] correlation.vv <- sapply( correlation.vv, FUN=function(ll){ ll1 <- strsplit( paste(ll), split=" " )[[1]] as.vector( as.numeric( ll1[ ll1 !="" ] )) } ) if ( is.list( correlation.vv ) ){ ind.vv.row <- as.vector(unlist( lapply( correlation.vv, FUN=function(ll){ ll[1] } ) )) correlation.vv <- lapply( correlation.vv, FUN=function(ll){ ll[-1] } ) } else { correlation.vv <- as.vector( correlation.vv ) ind.vv.row <- correlation.vv[1] correlation.vv <- as.list( correlation.vv[-1] ) } RVV <- length(correlation.vv) for (rvv in 1:RVV){ correlation.vv.rvv <- correlation.vv[[rvv]] i1.rvv <- ind.vv.row[rvv] i2.rvv <- ind.vv.col[ seq( 1, length(correlation.vv.rvv)) ] correlation.matrix[ i2.rvv, i1.rvv ] <- correlation.matrix[ i1.rvv, i2.rvv ] <- correlation.vv.rvv } } correlation.matrix } .noharm.residuals <- function(noharmout1, I=I, dat=dat ){ i1 <- grep( "Residual Matrix", noharmout1 ) i2 <- grep( "Sum of squares of residuals", noharmout1 ) rows <- seq( i1+2, i2-4 ) r1 <- intersect( which( noharmout1=="" ), rows ) VV <- length(r1)/2 r2 <- stats::aggregate( r1, list(rep( 1:VV, each=2 )), mean ) colnames(r2) <- c("index", "index.row" ) index.m <- data.frame( r2, "begin"=r2[,2] + 2, "end"=c( r2[,2][-1] - 2, i2-3 ) ) resid.matrix <- matrix(0,I,I) rownames(resid.matrix) <- colnames(resid.matrix) <- colnames(dat) for (vv in 1:VV){ ind.vv.col <- noharmout1[ index.m$index.row[vv] ] ind.vv.col <- strsplit( ind.vv.col, split=" " )[[1]] ind.vv.col <- as.numeric( ind.vv.col[ ind.vv.col !="" ] ) ind.vv <- seq( index.m$begin[vv], index.m$end[vv] ) resid.vv <- noharmout1[ ind.vv ] resid.vv <- sapply( resid.vv, FUN=function(ll){ ll1 <- strsplit( paste(ll), split=" " )[[1]] as.numeric( ll1[ ll1 !="" ] ) } ) if (is.list( resid.vv)){ gh1 <- lapply( resid.vv, FUN=function(ll){ length(ll) } ) ind1 <- which (gh1==0) if ( length(ind1) > 0 ){ for (ii in ind1 ){ resid.vv[[ii]] <- NULL } } ind.vv.row <- as.vector(unlist( lapply( resid.vv, FUN=function(ll){ ll[1] } ) )) resid.vv <- lapply( resid.vv, FUN=function(ll){ ll[-1] } ) } else { resid.vv <- as.vector(resid.vv) ind.vv.row <- resid.vv[1] resid.vv <- as.list( resid.vv[-1] ) } RVV <- length(resid.vv) for (rvv in 1:RVV){ resid.vv.rvv <- resid.vv[[rvv]] i1.rvv <- ind.vv.row[rvv] i2.rvv <- ind.vv.col[ seq( 1, length(resid.vv.rvv)) ] resid.matrix[ i2.rvv, i1.rvv ] <- resid.matrix[ i1.rvv, i2.rvv ] <- resid.vv.rvv } } return( resid.matrix ) }
GraphLimits=function(infile) { maxlat=max(infile$Latitude) minlat=min(infile$Latitude) maxlong=max(infile$Longitude) minlong=min(infile$Longitude) ratio=cos((maxlat+minlat)/2/360*2*pi) if(((maxlong-minlong)*ratio) > (maxlat-minlat)) { miny=minlat-((maxlong-minlong)*ratio)/2-0.025*(maxlong-minlong)*ratio; maxy=maxlat+((maxlong-minlong)*ratio)/2+0.025*(maxlong-minlong)*ratio; minx=minlong-0.025*(maxlong-minlong); maxx=maxlong+0.025*(maxlong-minlong); }else{ miny=minlat-0.025*(maxlat-minlat); maxy=maxlat+0.025*(maxlat-minlat); minx=minlong-((maxlat-minlat)-((maxlong-minlong)*ratio))/2-0.025*(maxlat-minlat)/ratio; maxx=maxlong+((maxlat-minlat)-((maxlong-minlong)*ratio))/2-0.025*(maxlat-minlat)/ratio; } return=list(miny=miny,maxy=maxy,minx=minx,maxx=maxx) }
.getPutVals <- function(obj, field, n, mask) { if (mask) { return( data.frame(v=rep(1, length=n)) ) } else if (missing(field)) { if (.hasSlot(obj, 'data')) { putvals <- obj@data cn <- validNames(c('ID', colnames(putvals))) cn[1] <- 'ID' putvals <- data.frame(ID=1:nrow(putvals), putvals) colnames(putvals) <- cn } else { putvals <- data.frame(v=as.integer(1:n)) } return(putvals) } else if (isTRUE (is.na(field))) { return( data.frame(v=rep(NA, n)) ) } else if (is.character(field) ) { if (.hasSlot(obj, 'data')) { nms <- names(obj) if (length(field) <= length(nms)) { m <- match(field, nms) if (!all(is.na(m))) { m <- stats::na.omit(m) return(obj@data[, m, drop=FALSE]) } } } } if (NROW(field) == n) { if (is.null(nrow(field))) { return(data.frame(field, stringsAsFactors=FALSE)) } else { return(field) } } if (is.numeric(field)) { putvals <- rep(field, length.out=n) return(data.frame(field=putvals)) } stop('invalid value for field') } .intersectSegments <- function(x1, y1, x2, y2, x3, y3, x4, y4) { denom <- ((y4 - y3) * (x2 - x1)) - ((x4 - x3) * (y2 - y1)) ua_num <- ((x4 - x3) *(y1 - y3)) - ((y4 - y3) * (x1 - x3)) ub_num <- ((x2 - x1) *(y1 - y3)) - ((y2 - y1) * (x1 - x3)) if ( denom == 0 ) { if (ua_num == 0 & ub_num == 0) { xmin <- max(x1, x3) if (xmin==x1) {ymin <- y1} else {ymin <- y3} xmax <- min(x2, x4) if (xmax==x2) {ymax <- y2} else {ymax <- y4} return(rbind(c(xmin, ymin), c(xmax, ymax))) } } else { ua <- round(ua_num / denom, 12) ub <- round(ub_num / denom, 12) if ((ua >= 0 & ua <= 1) & (ub >= 0 & ub <= 1) ) { x <- x1 + ua * (x2 - x1) y <- y1 + ua * (y2 - y1) return(c(x, y)) } } return(c(NA, NA)) } .intersectLinePolygon <- function(line, poly) { resxy <- matrix(NA, ncol=2, nrow=0) miny <- min(line[,2]) maxy <- max(line[,2]) xyxy <- cbind(poly, rbind(poly[-1,], poly[1,])) xyxy <- subset(xyxy, !( (xyxy[,2] > maxy & xyxy[,4] > maxy ) | (xyxy[,2] < miny & xyxy[,4] < miny)) ) if (nrow(xyxy) == 0) { return(resxy) } for (i in 1:nrow(xyxy)) { xy <- .intersectSegments(xyxy[i,1], xyxy[i,2], xyxy[i,3], xyxy[i,4], line[1,1], line[1,2], line[2,1], line[2,2] ) if (!is.na(xy[1])) { resxy <- rbind(resxy, xy) } } return((resxy)) } .polygonsToRaster <- function(p, rstr, field, fun='last', background=NA, mask=FALSE, update=FALSE, updateValue="all", getCover=FALSE, filename="", silent=TRUE, faster=TRUE, ...) { npol <- length(p@polygons) pvals <- .getPutVals(p, field, npol, mask) putvals <- pvals[,1] if (ncol(pvals) > 1) { rstr@data@isfactor <- TRUE rstr@data@attributes <- list(pvals) if (!is.character(fun)) { stop('when rasterizing multiple fields you must use "fun=first" or "fun=last"') } else if (!(fun %in% c('first', 'last'))) { stop('when rasterizing multiple fields you must use "fun=first" or "fun=last"') } } if (getCover) { nc <- ncell(rstr) fctr <- ifelse(nc < 5, 100, ifelse(nc < 17, 20, 10)) rstr <- disaggregate(raster(rstr), fctr) r <- .fasterize(p, rstr, rep(1, npol), background=0, datatype="INT1U") return( aggregate(r, fctr, mean, na.rm=TRUE, filename=filename, ...) ) } if (is.character(fun) && (ncol(pvals) == 1) && faster) { if (fun == "last") { if (mask || update) { if (mask && update) stop("either use 'mask' OR 'update'") background = NA r <- .fasterize(p, rstr, pvals[,1], background) if (! hasValues(r)) { if (mask) { warning('there are no values to mask') } else { warning('there are no values to update') } return(r) } if (mask) { r <- mask(rstr, r) } else { if (updateValue[1]=="all") { r <- cover(r, rstr) } else if (updateValue[1]=="NA") { r <- cover(rstr, r, ...) } else if (updateValue[1]=="!NA") { r <- mask(cover(r, rstr), rstr, ...) } else { s <- stack(r, rstr) r <- overlay(rstr, r, fun=function(x,y){ i = (x %in% updateValue & !is.na(y)); x[i] <- y[i]; x }, ... ) } } return(r) } else { return( .fasterize(p, rstr, pvals[,1], background, filename, ...) ) } } } leftColFromX <- function ( object, x ) { colnr <- (x - xmin(object)) / xres(object) i <- colnr %% 1 == 0 colnr[!i] <- trunc(colnr[!i]) + 1 colnr[colnr <= 0] <- 1 colnr } rightColFromX <- function ( object, x ) { colnr <- trunc((x - xmin(object)) / xres(object)) + 1 colnr[ colnr > ncol(object) ] <- object@ncols colnr } if (! inherits(p, 'SpatialPolygons') ) { stop('The first argument should be an object of the "SpatialPolygons*" lineage') } filename <- trim(filename) if (!canProcessInMemory(rstr, 3) && filename == '') { filename <- rasterTmpFile() } if (mask & update) { stop('use either "mask" OR "update"') } else if (mask) { oldraster <- rstr } else if (update) { oldraster <- rstr if (!is.numeric(updateValue)) { if (is.na(updateValue)) { updateValue <- 'NA' } else if (!(updateValue == 'NA' | updateValue == '!NA' | updateValue == 'all')) { stop('updateValue should be either "all", "NA", "!NA"') } } } rstr <- raster(rstr) if (!is.na(projection(p))) { projection(rstr) <-.getCRS(p) } spbb <- sp::bbox(p) rsbb <- bbox(rstr) if (spbb[1,1] >= rsbb[1,2] | spbb[1,2] <= rsbb[1,1] | spbb[2,1] >= rsbb[2,2] | spbb[2,2] <= rsbb[2,1]) { return( init(rstr, function(x) NA) ) } npol <- length(p@polygons) pvals <- .getPutVals(p, field, npol, mask) putvals <- pvals[,1] if (ncol(pvals) > 1) { rstr@data@isfactor <- TRUE rstr@data@attributes <- list(pvals) if (!is.character(fun)) { stop('when rasterizing multiple values you must use "fun=first" or "fun=last"') } else if (!(fun %in% c('first', 'last'))) { stop('when rasterizing multiple values you must use "fun=first" or "fun=last"') } } if (is.character(fun)) { if (fun=='first') { fun <- function(x, ...){ stats::na.omit(x)[1] } } else if (fun=='last') { fun <- function(x, ...){ rev(stats::na.omit(x))[1] } } else if (fun == 'count') { fun <- function(x, ...){ sum(!is.na(x)) } field <- 1 } } polinfo <- data.frame(matrix(NA, nrow=npol * 2, ncol=6)) colnames(polinfo) <- c('part', 'miny', 'maxy', 'value', 'hole', 'object') addpol <- polinfo[rep(1, 500), ] rownames(addpol) <- NULL pollist <- list() cnt <- 0 for (i in 1:npol) { nsubpol <- length(p@polygons[[i]]@Polygons) for (j in 1:nsubpol) { cnt <- cnt + 1 if (cnt > dim(polinfo)[1]) { polinfo <- rbind(polinfo, addpol) } polinfo[cnt, 1] <- cnt polinfo[cnt, 2] <- min(p@polygons[[i]]@Polygons[[j]]@coords[,2]) polinfo[cnt, 3] <- max(p@polygons[[i]]@Polygons[[j]]@coords[,2]) polinfo[cnt, 4] <- putvals[i] if ( p@polygons[[i]]@Polygons[[j]]@hole ) { polinfo[cnt, 5] <- 1 } else { polinfo[cnt, 5] <- 0 } polinfo[cnt, 6] <- i pollist[[cnt]] <- p@polygons[[i]]@Polygons[[j]] } } if (! silent) { message('Found ', npol, ' region(s) and ', cnt, ' polygon(s)') } polinfo <- subset(polinfo, polinfo[,1] <= cnt, drop=FALSE) lxmin <- min(spbb[1,1], rsbb[1,1]) - xres(rstr) lxmax <- max(spbb[1,2], rsbb[1,2]) + xres(rstr) adj <- 0.5 * xres(rstr) if (filename == "") { v <- matrix(NA, ncol=nrow(rstr), nrow=ncol(rstr)) } else { rstr <- writeStart(rstr, filename=filename, ...) } rxmn <- xmin(rstr) rxmx <- xmax(rstr) rv1 <- rep(NA, ncol(rstr)) holes1 <- rep(0, ncol(rstr)) pb <- pbCreate(nrow(rstr), label='rasterize', ...) for (r in 1:nrow(rstr)) { vals <- NULL holes <- holes1 ly <- yFromRow(rstr, r) myline <- rbind(c(lxmin,ly), c(lxmax,ly)) subpol <- subset(polinfo, !(polinfo[,2] > ly | polinfo[,3] < ly), drop=FALSE) if (length(subpol[,1]) > 0) { updateHoles <- FALSE lastpolnr <- subpol[1,6] rvtmp <- rv1 for (i in 1:nrow(subpol)) { if (i == nrow(subpol)) { updateHoles <- TRUE } else if (subpol[i+1,6] > lastpolnr) { updateHoles <- TRUE lastpolnr <- subpol[i+1,6] } mypoly <- pollist[[subpol[i,1]]] intersection <- .intersectLinePolygon(myline, mypoly@coords) x <- sort(intersection[,1]) if (length(x) > 0) { if ((nrow(intersection) %% 2 == 1) || ( sum(x[-length(x)] == x[-1]) > 0 )) { spPnts <- sp::SpatialPoints(xyFromCell(rstr, cellFromRowCol(rstr, rep(r, ncol(rstr)), 1:ncol(rstr)))) spPol <- sp::SpatialPolygons(list(sp::Polygons(list(mypoly), 1))) over <- sp::over(spPnts, spPol) if ( subpol[i, 5] == 1 ) { holes[!is.na(over)] <- holes[!is.na(over)] - 1 } else { rvtmp[!is.na(over)] <- subpol[i,4] holes[!is.na(over)] <- holes[!is.na(over)] + 1 } } else { for (k in 1:round(nrow(intersection)/2)) { l <- (k * 2) - 1 x1 <- x[l] x2 <- x[l+1] x1a <- x1 + adj x2a <- x2 - adj if (x1a > rxmx) { next } if (x2a < rxmn) { next } x1a <- min(rxmx, max(rxmn, x1a)) x2a <- min(rxmx, max(rxmn, x2a)) col1 <- leftColFromX(rstr, x1a) col2 <- rightColFromX(rstr, x2a) if (col1 > col2) { spPnts <- sp::SpatialPoints(xyFromCell(rstr, cellFromRowCol(rstr, rep(r, ncol(rstr)), 1:ncol(rstr)))) spPol <- sp::SpatialPolygons(list(sp::Polygons(list(mypoly), 1))) over <- sp::over(spPnts, spPol) if ( subpol[i, 5] == 1 ) { holes[!is.na(over)] <- holes[!is.na(over)] - 1 } else { rvtmp[!is.na(over)] <- subpol[i,4] holes[!is.na(over)] <- holes[!is.na(over)] + 1 } next } if ( subpol[i, 5] == 1 ) { holes[col1:col2] <- holes[col1:col2] - 1 } else { rvtmp[col1:col2] <- subpol[i,4] holes[col1:col2] <- holes[col1:col2] + 1 } } } } if (updateHoles) { updateHoles <- FALSE rvtmp[holes < 1] <- NA vals <- cbind(vals, rvtmp) rvtmp <- rv1 holes <- holes1 } } } rrv <- rv1 if (!is.null(vals)) { u <- which(rowSums(is.na(vals)) < ncol(vals)) if (length(u) > 0) { if (mask) { rrv[u] <- 1 } else { rrv[u] <- apply(vals[u, ,drop=FALSE], 1, fun, na.rm=TRUE) } } } if (mask) { oldvals <- getValues(oldraster, r) ind <- which(is.na(rrv)) oldvals[ind] <- NA rrv <- oldvals } else if (update) { oldvals <- getValues(oldraster, r) if (is.numeric(updateValue)) { ind <- which(oldvals == updateValue & !is.na(rrv)) } else if (updateValue == "all") { ind <- which(!is.na(rrv)) } else if (updateValue == "NA") { ind <- which(is.na(oldvals)) } else { "!NA" ind <- which(!is.na(oldvals) & !is.na(rrv)) } oldvals[ind] <- rrv[ind] rrv <- oldvals } else { rrv[is.na(rrv)] <- background } if (filename == "") { v[,r] <- rrv } else { rstr <- writeValues(rstr, rrv, r) } pbStep(pb, r) } pbClose(pb) if (filename == "") { rstr <- setValues(rstr, as.vector(v)) } else { rstr <- writeStop(rstr) } return(rstr) } .Old_polygoncover <- function(rstr, filename, polinfo, lxmin, lxmax, pollist, ...) { polinfo[, 4] <- 1 bigraster <- raster(rstr) rxmn <- xmin(bigraster) rxmx <- xmax(bigraster) f <- 10 adj <- 0.5 * xres(bigraster)/f nc <- ncol(bigraster) * f rv1 <- rep(0, nc) holes1 <- rep(0, nc) prj <-.getCRS(bigraster) hr <- 0.5 * yres(bigraster) vv <- matrix(ncol=f, nrow=nc) if (filename == "") { v <- matrix(NA, ncol=nrow(bigraster), nrow=ncol(bigraster)) } else { bigraster <- writeStart(bigraster, filename=filename, ...) } pb <- pbCreate(nrow(bigraster), label='rasterize', ...) for (rr in 1:nrow(bigraster)) { y <- yFromRow(bigraster, rr) yn <- y - hr yx <- y + hr rstr <- raster(xmn=rxmn, xmx=rxmx, ymn=yn, ymx=yx, ncols=nc, nrows=f, crs=prj) subpol <- subset(polinfo, !(polinfo[,2] > yx | polinfo[,3] < yn), drop=FALSE) for (r in 1:f) { rv <- rv1 ly <- yFromRow(rstr, r) myline <- rbind(c(lxmin,ly), c(lxmax,ly)) holes <- holes1 if (length(subpol[,1]) > 0) { updateHoles <- FALSE lastpolnr <- subpol[1,6] rvtmp <- rv1 for (i in 1:length(subpol[,1])) { if (i == length(subpol[,1])) { updateHoles <- TRUE } else if (subpol[i+1,6] > lastpolnr) { updateHoles <- TRUE lastpolnr <- subpol[i+1,6] } mypoly <- pollist[[subpol[i,1]]] intersection <- .intersectLinePolygon(myline, mypoly@coords) x <- sort(intersection[,1]) if (length(x) > 0) { if ( sum(x[-length(x)] == x[-1]) > 0 ) { spPnts <- sp::SpatialPoints(xyFromCell(rstr, cellFromRowCol(rstr, rep(r, ncol(rstr)), 1:ncol(rstr)))) spPol <- sp::SpatialPolygons(list(sp::Polygons(list(mypoly), 1))) over <- sp::over(spPnts, spPol) if ( subpol[i, 5] == 1 ) { holes[!is.na(over)] <- holes[!is.na(over)] - 1 } else { rvtmp[!is.na(over)] <- subpol[i,4] holes[!is.na(over)] <- holes[!is.na(over)] + 1 } } else { for (k in 1:round(nrow(intersection)/2)) { l <- (k * 2) - 1 x1 <- x[l] x2 <- x[l+1] if (x1 > rxmx) { next } if (x2 < rxmn) { next } x1a <- x1 + adj x2a <- x2 - adj x1a <- min(rxmx, max(rxmn, x1a)) x2a <- min(rxmx, max(rxmn, x2a)) col1 <- colFromX(rstr, x1a) col2 <- colFromX(rstr, x2a) if (col1 > col2) { next } if ( subpol[i, 5] == 1 ) { holes[col1:col2] <- holes[col1:col2] - 1 } else { rvtmp[col1:col2] <- subpol[i,4] holes[col1:col2] <- holes[col1:col2] + 1 } } } if (updateHoles) { holes <- holes < 1 rvtmp[holes] <- 0 holes <- holes1 updateHoles <- FALSE rv <- pmax(rv, rvtmp) } } } } vv[,r] <- rv } av <- colSums( matrix( rowSums(vv), nrow=f) ) if (filename == "") { v[,rr] <- av } else { bigraster <- writeValues(bigraster, av, rr) } pbStep(pb, rr) } pbClose(pb) if (filename == "") { bigraster <- setValues(bigraster, as.vector(v)) } else { bigraster <- writeStop(bigraster) } return(bigraster) } .polygonsToRaster2 <- function(p, raster, field=0, filename="", ...) { filename <- trim(filename) raster <- raster(raster) spbb <- sp::bbox(p) rsbb <- bbox(raster) if (spbb[1,1] > rsbb[1,2] | spbb[2,1] > rsbb[2,2]) { stop('polygon and raster have no overlapping areas') } if (class(p) == 'SpatialPolygons' | field == 0) { putvals <- 1:length(p@polygons) } else { putvals <- as.vector(p@data[,field]) if (class(putvals) == 'character') { stop('selected field is charater type') } } if (filename == "") { v <- vector(length=0) } else { raster <- writeStart(raster, filename=filename, ...) } rowcol <- cbind(0, 1:ncol(raster)) firstrow <- rowFromY(raster, spbb[2,2]) lastrow <- rowFromY(raster, spbb[2,1]) for (r in 1:nrow(raster)) { if (r < firstrow | r > lastrow) { vals <- rep(NA, times=ncol(raster)) } else { rowcol[,1] <- r sppoints <- xyFromCell(raster, cellFromRowCol(raster, rowcol[,1], rowcol[,2]), TRUE) over <- sp::over(sppoints, p) vals <- putvals[over] } if (filename == "") { v <- c(v, vals) } else { raster <- writeValues(raster, vals) } } if (filename == "") { raster <- setValues(raster, v) } else { raster <- writeStop(raster) } return(raster) }
test_that("complete_terms 1 iteration", { mcmc <- as_mcmc(nlist(beta = matrix(1:4, nrow = 2))) expect_identical(complete_terms(mcmc), mcmc) mcmc[, "beta[2,2]"] <- NA expect_identical(complete_terms(mcmc), mcmc) mcmc2 <- mcmc mcmc2 <- mcmc2[, -4,drop = FALSE] expect_identical(complete_terms(mcmc2), mcmc) }) test_that("complete_terms 2 iterations", { mcmc <- as_mcmc(nlists(nlist(beta = matrix(1:4, nrow = 2)), nlist(beta = matrix(1:4, nrow = 2)))) expect_identical(complete_terms(mcmc), mcmc) mcmc[, "beta[2,2]"] <- NA expect_identical(complete_terms(mcmc), mcmc) mcmc2 <- mcmc mcmc2 <- mcmc2[, -4] expect_identical(complete_terms(mcmc2), mcmc) }) test_that("complete_terms mcmc 1 digit", { mcmc <- as_mcmc(nlists(nlist(x = 1), nlist(x = 2))) colnames(mcmc) <- "1" expect_warning(complete_terms(mcmc)) })
as_httr_req <- function(entry, quiet=TRUE) { req <- entry$request req$headers <- purrr::map(req$headers, "value") %>% setNames(map_chr(req$headers, "name")) ml <- getOption("deparse.max.lines") options(deparse.max.lines=10000) template <- "httr::VERB(verb = '%s', url = '%s' %s%s%s%s%s%s)" hdrs <- enc <- bdy <- ckies <- auth <- verbos <- cfg <- "" if (length(req$headers) > 0) { ct_idx <- which(grepl("content-type", names(req$headers), ignore.case=TRUE)) if (length(ct_idx) > 0) { ct <- req$headers[[ct_idx]] req$headers[[ct_idx]] <- NULL if (stringi::stri_detect_regex(ct, "multipart")) { enc <- ", encode = 'multipart'" } else if (stringi::stri_detect_regex(ct, "form")) { enc <- ", encode = 'form'" } else if (stringi::stri_detect_regex(ct, "json")) { enc <- ", encode = 'json'" } else { enc <- "" } } hdrs <- paste0(capture.output(dput(req$headers, control=NULL)), collapse="") hdrs <- sub("^list", ", httr::add_headers", hdrs) } if (length(req$data) > 0) { bdy_bits <- paste0(capture.output(dput(parse_query(req$data), control=NULL)), collapse="") bdy <- sprintf(", body = %s", bdy_bits) } if (length(req$url_parts$username) > 0) { auth <- sprintf(", httr::authenticate(user='%s', password='%s')", req$url_parts$username, req$url_parts$password) } if (length(req$verbose) > 0) { verbos <- ", httr::verbose()" } if (length(req$cookies) > 0) { ckies <- paste0(capture.output(dput(req$cookies, control=NULL)), collapse="") ckies <- sub("^list", ", httr::set_cookies", ckies) } REQ_URL <- req$url out <- sprintf(template, toupper(req$method), REQ_URL, auth, verbos, hdrs, ckies, bdy, enc) fil <- tempfile(fileext=".R") on.exit(unlink(fil)) formatR::tidy_source(text=out, width.cutoff=30, indent=4, file=fil) tmp <- paste0(readLines(fil), collapse="\n") if (!quiet) cat(tmp, "\n") f <- function() {} formals(f) <- NULL environment(f) <- parent.frame() body(f) <- as.expression(parse(text=tmp)) options(deparse.max.lines=ml) return(f) }
regmixEM.loc=function (y, x, lambda = NULL, beta = NULL, sigma = NULL, k = 2, addintercept = TRUE, kern.l = c("Gaussian", "Beta", "Triangle", "Cosinus", "Optcosinus"), epsilon = 1e-08, maxit = 10000, kernl.g = 0, kernl.h = 1, verb = FALSE) { diff <- 1 iter <- 0 x.1 <- cbind(1, x) n <- length(y) kern.l <- match.arg(kern.l) out.EM <- regmixEM.lambda(y, x, lambda = lambda, beta = beta, sigma = sigma, k = k, epsilon = epsilon, maxit = maxit) ll = out.EM$loglik restarts <- 0 while (diff > epsilon && iter < maxit) { old.l.x = out.EM$lambda old.loglik = out.EM$loglik l.x = matrix(nrow = n, ncol = (k - 1)) for (i in 1:(k - 1)) { l.x[, i] <- c((cbind(rep(1,n),0)*t(apply(matrix(x, ncol = 1), 1, lambda, z = out.EM$post[, i], xi = x, kernel = kern.l, g = kernl.g, h = kernl.h)))[,1]) l.x[,i]=apply(cbind(l.x[,i]),1,max,0) l.x[,i]=apply(cbind(l.x[,i]),1,min,1) } l.x <- cbind(l.x, 1 - apply(l.x, 1, sum)) out.EM.loc <- regmixEM.lambda(y, x, beta = out.EM$beta, sigma = out.EM$sigma, lambda = l.x, k = k) loglik.loc <- out.EM.loc$loglik out.EM.old <- regmixEM.lambda(y, x, beta = out.EM$beta, sigma = out.EM$sigma, lambda = old.l.x, k = k) loglik.old <- out.EM.old$loglik if (loglik.loc > old.loglik) { out.EM <- out.EM.loc } else out.EM <- out.EM.old loglik.chosen <- out.EM$loglik ll <- c(ll, loglik.chosen) diff <- loglik.chosen - old.loglik if (diff < 0) { cat("Generating new starting values...", "\n") out.EM <- regmixEM.lambda(y, x, lambda = lambda, beta = beta, sigma = sigma, k = k, epsilon = epsilon, maxit = maxit) restarts <- restarts + 1 if (restarts > 15) stop("Too many tries!") iter <- 0 diff <- 1 } else { iter <- iter + 1 if (verb) { cat("iteration=", iter, "diff=", diff, "log-likelihood", loglik.chosen, "\n") } } } if (iter == maxit) { cat("WARNING! NOT CONVERGENT!", "\n") } cat("number of overall iterations=", iter, "\n") a = list(x = x, y = y, lambda.x = out.EM$lambda, beta = out.EM$beta, sigma = out.EM$sigma, loglik = loglik.chosen, posterior = out.EM$post, all.loglik = ll, restarts = restarts, ft = "regmixEM.loc") class(a) = "mixEM" a }
MPSep_consumerrisk <- function(n, cvec, pivec, Rvec){ sum1 <- rep(NA, length(1:dim(pivec)[1])) sum2 <- rep(NA, length(1:dim(pivec)[1])) for(i in 1:dim(pivec)[1]){ sum2[i] <- MPSep_core(n, cvec, pivec[i,]) sum1[i] <- sum2[i] * MP_Indicator(pivec[i,], Rvec) } return(1 - (sum(sum1) / sum(sum2))) }
app <- setRefClass( 'HelloWorld', methods = list( call = function(env){ list( status=200, headers = list( 'Content-Type' = 'text/html' ), body = paste('<h1>Hello World!</h1>') ) } ) )$new()
require(bvpSolve) Troesch <- function (t, y, pars) { list( c(y[2], mu*sinh(mu*y[1])) ) } mu <- 5 x <- seq(0, 1, len = 12) Sol <- bvptwp(yini = c(y = 0, dy = NA), yend = c(1, NA), x = x, fun = Troesch) plot(Sol)
caffPlot <- function(caffConcTimeData, log = FALSE){ caffConcTime <- caffConcTimeData p <- ggplot(caffConcTime, aes(x=Time, y=Conc)) + xlab("Time (hour)") + ylab("Concentration (mg/L)") + scale_x_continuous(breaks = seq(from = 0, to = 24, by = 4)) + geom_line(aes(group = Subject, colour = Conc)) + stat_summary(fun.y = "mean", colour = " geom_hline(yintercept = 80, colour="red") + geom_hline(yintercept = 40, colour="blue") + geom_hline(yintercept = 10, colour="green") + theme_linedraw() if (log == TRUE) p <- p + scale_y_log10() return(p) } caffPlotMulti <- function(caffConcTimeMultiData, log = FALSE){ caffConcTimeMulti <- caffConcTimeMultiData p <- ggplot(caffConcTimeMulti, aes(x=Time, y=Conc)) + xlab("Time (hour)") + ylab("Concentration (mg/L)") + scale_x_continuous(breaks = seq(0, 96, 12)) + geom_line(aes(group = Subject, colour = Conc)) + stat_summary(fun.y = "mean", colour = " geom_hline(yintercept = 80, colour="red") + geom_hline(yintercept = 40, colour="blue") + geom_hline(yintercept = 10, colour="green") + theme_linedraw() if (log == TRUE) p <- p + scale_y_log10() return(p) }
plot.competing.risk.rfsrc <- function (x, plots.one.page = FALSE, ...) { if (is.null(x)) { stop("object x is empty!") } if (sum(inherits(x, c("rfsrc", "grow"), TRUE) == c(1, 2)) != 2 & sum(inherits(x, c("rfsrc", "predict"), TRUE) == c(1, 2)) != 2) { stop("This function only works for objects of class `(rfsrc, grow)' or '(rfsrc, predict)'.") } if (x$family != "surv-CR") { stop("this function only supports competing risk settings") } matPlot <- function(matx, ylab = "", legend = "", pos = 1) { m <- dim(cbind(matx))[2] if (m > 1) legend <- paste(legend, 1:m, " ") matplot(x$time.interest, matx, xlab = "Time", ylab = ylab, type = "l", col = (1:m), lty = 1, lwd = 3) legend(c("topright", "bottomright")[pos], legend = legend, col = (1:m), lty = 1, lwd = 3) } opar <- par(no.readonly = TRUE) on.exit(par(opar)) if (plots.one.page) par(mfrow = c(1,1)) else par(mfrow = c(2,2)) if (!is.null(x$chf.oob)) { cschf <- apply(x$chf.oob, c(2, 3), mean, na.rm = TRUE) cif <- apply(x$cif.oob, c(2, 3), mean, na.rm = TRUE) } else { cschf <- apply(x$chf, c(2, 3), mean, na.rm = TRUE) cif <- apply(x$cif, c(2, 3), mean, na.rm = TRUE) } cpc <- do.call(cbind, lapply(1:ncol(cif), function(j) { cif[, j] / (1 - rowSums(cif[, -j, drop = FALSE])) })) matPlot(cschf, "Cause-Specific CHF", "CSCHF", pos = 2) matPlot(100 * cif, "Probability (%)", "CIF", 2) matPlot(100 * cpc, "Probability (%)", "CPC", 2) } plot.competing.risk <- plot.competing.risk.rfsrc
locate_footcite_punctuation <- function(parsed_doc = NULL, singular = TRUE, tex_lines = NULL) { if (is.null(parsed_doc)) { parsed_doc <- parse_tex(tex_lines) } chars <- .subset2(parsed_doc, "char") v_match <- function(needle, haystack, nomatch = 0L, singular = TRUE) { sieved <- which(haystack == needle[1L]) for (i in seq.int(1L, length(needle) - 1L)) { sieved <- sieved[haystack[sieved + i] == needle[i + 1L]] } if (singular) { sieved <- sieved[haystack[sieved + i + 1L] != "s"] } sieved } if (singular) { footcite_starts <- v_match(strsplit("\\footcite", split = "", fixed = TRUE)[[1L]], chars) } else { footcite_starts <- v_match(strsplit("\\footcites", split = "", fixed = TRUE)[[1L]], chars) } L <- lapply(footcite_starts, function(i) { j <- i + 9L s <- chars[j] TeX_group <- 0L opt_TeX_group <- 0L while (OR(s != "}" || TeX_group || opt_TeX_group, if (singular) { FALSE } else { OR(chars[j + 1L] == "{", chars[j + 1L] == "[") })) { if (opt_TeX_group) { switch(s, "{" = { TeX_group <- TeX_group + 1L }, "}" = { TeX_group <- TeX_group - 1L }, "[" = { opt_TeX_group <- opt_TeX_group + 1L }, "]" = { opt_TeX_group <- opt_TeX_group - 1L }) } else { switch(s, "[" = { opt_TeX_group <- opt_TeX_group + 1L }, "]" = { opt_TeX_group <- opt_TeX_group - 1L }) } j <- j + 1L s <- chars[j] } for (k in 1:200) { if (k > 1L && chars[j + k] == "-") { return(NULL) } if (k == 1L && chars[j + k] %fin% punctuation) { break } if (grepl("\\s", chars[j + k])) { next } return(NULL) } list(start = i, char_no = j + k) }) bound <- rbindlist(L) setattr(bound, "sorted", "char_no") column <- NULL parsed_doc[bound, on = "char_no"][column > 1L] }
cfReadBrewTemplate = function(template.file) { assertFileExists(template.file, "r") tmpl = readLines(template.file) if (length(tmpl) == 0L) stopf("Error reading template '%s' or empty template", template.file) collapse(tmpl, "\n") } cfBrewTemplate = function(conf, template, rscript, extension) { assertEnvironment(conf) assertString(template) assertString(rscript) assertString(extension) if (conf$debug) { outfile = sub("\\.R$", sprintf(".%s", extension), rscript) } else { outfile = tempfile("template") } pf = parent.frame() old = getOption("show.error.messages") on.exit(options(show.error.messages = old)) options(show.error.messages = FALSE) z = suppressAll(try(brew(text = template, output = outfile, envir = pf), silent = TRUE)) if (is.error(z)) stopf("Error brewing template: %s", as.character(z)) waitForFiles(outfile, conf$fs.timeout) return(outfile) } cfHandleUnknownSubmitError = function(cmd, exit.code, output) { assertString(cmd) exit.code = asInt(exit.code) assertCharacter(output, any.missing = FALSE) msg = sprintf("%s produced exit code %i; output %s", cmd, exit.code, collapse(output, sep = "\n")) makeSubmitJobResult(status = 101L, batch.job.id = NA_character_, msg = msg) } cfKillBatchJob = function(cmd, batch.job.id, max.tries = 3L) { assertString(cmd) assertString(batch.job.id) max.tries = asCount(max.tries) assertCount(max.tries) for (tmp in seq_len(max.tries)) { res = runOSCommandLinux(cmd, batch.job.id, stop.on.exit.code = FALSE) if (res$exit.code == 0L) return() Sys.sleep(1) } stopf("Really tried to kill job, but could not do it. batch job id is %s.\nMessage: %s", batch.job.id, collapse(res$output, sep = "\n")) }
register_class("tsibble", "tbl_ts") ts_tsibble_dts <- function(x) { stopifnot(requireNamespace("tsibble")) cid <- dts_cname(x)$id ctime <- dts_cname(x)$time x <- dts_rm(x) if (length(cid) > 0){ z <- tsibble::as_tsibble(x, key = !! cid, index = !! ctime) } else { z <- tsibble::as_tsibble(x, index = !! ctime) } z } ts_dts.tbl_ts <- function(x) { stopifnot(requireNamespace("tsibble")) z <- as.data.table(x) cid <- tsibble::key_vars(x) measures <- tsibble::measured_vars(x) ctime <- setdiff(names(z), c(measures, cid)) setnames(z, ctime, "time") if (class(z$time)[1] %in% c("yearmonth", "yearquarter", "yearweek")) { z$time <- as.Date(z$time) } is.non.num <- vapply(z[, measures, with = FALSE], is.numeric, TRUE) measures.non.num <- measures[!is.non.num] if (length(measures.non.num) > 0) { message( "Ignoring non-numeric measure vars (", paste(measures.non.num, collapse = ", "), ")." ) z[, (measures.non.num) := NULL] } cvalue <- setdiff(names(z), c("time", cid)) if (inherits(z$time, "Date")) { z$time <- as.Date(z$time) } if (inherits(z$time, "POSIXct")) { z$time <- as.POSIXct(z$time) } if (length(cvalue) > 1) { z <- melt( z, id.vars = c(cid, "time"), measure.vars = cvalue, variable.name = "id" ) cvalue <- "value" } setcolorder(z, c(setdiff(names(z), c("time", cvalue)), "time", cvalue)) setnames(z, "time", ctime) ts_dts(z) } ts_tsibble <- function(x) { stopifnot(ts_boxable(x)) if (relevant_class(x) == "tsibble") return(x) ts_tsibble_dts(ts_dts(x)) }
orcid_bio <- function(orcid, format = "application/json", ...) { stats::setNames( lapply(orcid, orcid_prof_helper, path = "biography", ctype = format, ...), orcid ) }
.trapz <- function(x,y){ n <- length(x) return(sum((y[1:(n-1)]+y[2:n])/2*(x[2:n]-x[1:(n-1)]))) } .intersection_onecolumn <- function(alpha, SSN1, SSN2, nrow_S1, nrow_S2, Ncol, .quantile_intersection){ SP_inters <- .quantile_intersection(vec1 = SSN1, vec2 = SSN2, a = alpha/2, b = 1 - alpha/2, n = nrow_S1) vol_intersect <- (SP_inters[6]) vol_B <- (SP_inters[3]) r <- 1 if (min(SP_inters[4] == SP_inters[1]) == 0 | min(SP_inters[5] == SP_inters[2]) == 0){ if (vol_intersect < vol_B) {r <- vol_intersect/vol_B} if (vol_B == 0) {r <- 0} } return(r) } .intersection_severalcol <- function(alpha,SSN1,SSN2,nrow_S1,nrow_S2,Ncol, .quantile_intersection){ SP_inters<-mapply(.quantile_intersection, vec1 = SSN1, vec2 = SSN2, MoreArgs = list(a=((1-(1-alpha)^(1/ncol(SSN1)))/2), b=(1-(1-(1-alpha)^(1/ncol(SSN1)))/2),n=nrow_S1)) product<-prod(SP_inters[6,]) vol_intersect<-c(product,mean(SP_inters[6,]),product^{1/length(SP_inters[6,])}) product<-prod(SP_inters[3,]) vol_B<-c(product,mean(SP_inters[3,]),product^{1/length(SP_inters[3,])}) r<-c(1,1,1) if(min(SP_inters[4,]==SP_inters[1,])==0 | min(SP_inters[5,]==SP_inters[2,])==0){ r[vol_intersect<vol_B]<-vol_intersect[vol_intersect<vol_B]/vol_B[vol_intersect<vol_B] r[vol_B==0]<-0 } return(r) } .portionAinB_coordinates_full <- function(S1,S2,steps=101 ){ nt<-ncol(S1) integral_coord<-rep(0,length=nt) portionAinB_function<-function(x1,x2,steps){ r<-.portionAinB_full_onecolumn(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps ) return(r$integral_approx) } portionAinB_function2<-function(x1,x2,steps){ r<-.portionAinB_full_onecolumn(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps ) return(r$overlap) } integral_coord<-mapply(portionAinB_function, x1=S1, x2=S2, MoreArgs =list(steps=steps)) plot_data_overlap<-mapply(portionAinB_function2, x1=S1, x2=S2, MoreArgs =list(steps=steps)) alpha_grid<-seq(0,1,length=steps)[1:(steps-1)] erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_data_overlap=plot_data_overlap) return(erg) } .portionAinB_coordinates_full_dim1 <- function(S1,S2,steps=101 ){ nt<-1 integral_coord<-rep(0,length=nt) r<-.portionAinB_full_onecolumn(data.frame(v1=S1) ,data.frame(v1=S2),steps=steps ) integral_coord<-r$integral_approx plot_data_overlap<-r$overlap alpha_grid<-seq(0,1,length=steps)[1:(steps-1)] erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_data_overlap=plot_data_overlap) return(erg) } .portionAinB_full_onecolumn <- function (S1, S2, steps = 101) { S <- rbind(S1, S2) Ncol <- ncol(S1) alpha_grid <- seq(0, 1, length = steps) Spans <- data.frame(trait_nr = 1:Ncol, min = min(S, na.rm = TRUE), max = max(S, na.rm = TRUE)) ab <- Spans$max - Spans$min SSN <- (S - Spans$min)/(ab) SSN[, ab == 0] <- 0.5 nrow_S1 <- nrow(S1) nrow_S2 <- nrow(S2) z <- mapply(.intersection_onecolumn, alpha = alpha_grid, MoreArgs = list(SSN1 = SSN[1:nrow_S1, ], SSN2 = SSN[(nrow_S1 + 1):(nrow_S1 + nrow_S2), ], nrow_S1 = nrow_S1, nrow_S2 = nrow_S2, Ncol = Ncol, .quantile_intersection = .quantile_intersection)) integral_approx <- c(prod = .trapz(alpha_grid, z)) erg <- list(alpha_grid = alpha_grid, overlap = z, integral_approx = integral_approx) return(erg) } .portionAinB2_full <- function(S1,S2,steps=101,alpha_grid){ steps0<-steps alpha_grid0<-alpha_grid .portionAinB2_full_severalcol(S1,S2,steps=steps0,alpha_grid=alpha_grid0) } .portionAinB2_full_dim1 <- function(S1,S2,steps=101,alpha_grid){ steps0<-steps alpha_grid0<-alpha_grid .portionAinB2_full_severalcol_dim1(S1,S2,steps=steps0,alpha_grid=alpha_grid0) } .portionAinB2_full_severalcol_dim1 <- function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)[1:(steps-1)]){ S<-c(S1,S2) alpha_grid<-seq(0,1,length=steps) Ncol<-1 ab<-max(S)-min(S) SSN<-t((t(S)-min(S))/(ab)) SSN[,ab==0]<-0.5 SSN<-as.data.frame(SSN) nrow_S1<-length(S1) nrow_S2<-length(S2) z<-mapply(.intersection_onecolumn, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow_S1,], SSN2=SSN[(nrow_S1+1):(nrow_S1+nrow_S2),],nrow_S1=nrow_S1,nrow_S2=nrow_S2,Ncol=Ncol,.quantile_intersection=.quantile_intersection)) integral_approx<-c(prod=.trapz(seq(0,1,length=steps), z),mean=.trapz(seq(0,1,length=steps),z),gmean=.trapz(seq(0,1,length=steps),z)) plot_data_prod<-z erg<-list(alpha_grid=seq(0,1,length=steps)[1:(steps-1)],overlap=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod) return(erg) } .portionAinB2_full_severalcol <- function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)[1:(steps-1)]){ S<-rbind(S1,S2) alpha_grid<-seq(0,1,length=steps) Ncol<-ncol(S1) Spans<-data.frame(trait_nr=1:Ncol,min=matrix(mapply(min, S, MoreArgs = list(na.rm = TRUE))),max=matrix(mapply(max, S, MoreArgs = list(na.rm = TRUE)))) ab<-Spans$max-Spans$min SSN<-t((t(S)-Spans$min)/(ab)) SSN[,ab==0]<-0.5 SSN<-as.data.frame(SSN) nrow_S1<-nrow(S1) nrow_S2<-nrow(S2) z<-mapply(.intersection_severalcol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow_S1,], SSN2=SSN[(nrow_S1+1):(nrow_S1+nrow_S2),],nrow_S1=nrow_S1,nrow_S2=nrow_S2,Ncol=Ncol,.quantile_intersection=.quantile_intersection)) integral_approx<-c(prod=.trapz(seq(0,1,length=steps), z[1,]),mean=.trapz(seq(0,1,length=steps),z[2,]),gmean=.trapz(seq(0,1,length=steps),z[3,])) plot_data_prod<-z[1,] erg<-list(alpha_grid=seq(0,1,length=steps)[1:(steps-1)],overlap=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod) return(erg) } .quantile_intersection <- function(vec1,vec2,a,b,n){ x<-c( quantile(vec1, probs = c(a,b), na.rm = TRUE), quantile(vec2, probs = c(a,b), na.rm = TRUE) ) x<-c(x,x[4]-x[3]) x[5]<-ifelse(x[5]<=0,0,x[5]) r<-c(max(x[c(1,3)]),min(x[c(2,4)])) r<-c(x[3:5],r,r[2]-r[1]) r[6]<-ifelse(r[6]<=0,0,r[6]) return(r) } .volume_onecol <- function(alpha,SSN1){ SP1<-quantile(SSN1,probs=c(alpha/2,1-alpha/2),na.rm = TRUE) vol<-(SP1[2]-SP1[1]) return(vol) } .volume_severalcol <- function(alpha,SSN1){ alpha<-(1-(1-alpha)^(1/ncol(SSN1))) a<-alpha/2 b<-1-alpha/2 SP1<-mapply(quantile, SSN1, MoreArgs = list(probs=c(a,b),na.rm=TRUE)) product<-prod(SP1[2,]-SP1[1,]) vol<-c(prod=product,mean=mean(SP1[2,]-SP1[1,]),gmean=product^{1/length(SP1[2,]-SP1[1,])}) return(vol) } .volumeA_coordinates_full_dim1 <- function(S1,S2,steps=101 ){ nt<-1 names(S2)<-"v1" r<-.volumeA_full_onecol(data.frame(v1=S1), data.frame(v1=S2), steps=steps) integral_coord<-r$integral_approx plot_volume<-r$volume alpha_grid<-seq(0,1,length=steps) erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_volume=plot_volume) return(erg) } .volumeA_coordinates_full <- function(S1,S2,steps=101 ){ nt<-ncol(S1) volumeA_function<-function(x1,x2,steps){ r<-.volumeA_full_onecol(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps ) return(r$integral_approx) } volumeA_function2<-function(x1,x2,steps){ r<-.volumeA_full_onecol(data.frame(v1=x1) ,data.frame(v1=x2),steps=steps ) return(r$volume) } integral_coord<-mapply(volumeA_function, x1=S1, x2=S2, MoreArgs =list(steps=steps)) plot_volume<-mapply(volumeA_function2, x1=S1, x2=S2, MoreArgs =list(steps=steps)) alpha_grid<-seq(0,1,length=steps) erg<-list(alpha_grid=alpha_grid,integral_coord=integral_coord,plot_volume=plot_volume) return(erg) } .volumeA_full_onecol <- function(S1,S2,steps=101){ S<-rbind(S1,S2) Ncol<-ncol(S1) alpha_grid<-seq(0,1,length=steps) Spans<-data.frame(trait_nr=1:Ncol,min=min(S,na.rm = TRUE),max=max(S,na.rm = TRUE)) ab<-Spans$max-Spans$min SSN<-(S-Spans$min)/(ab) SSN[,ab==0]<-0.5 z<-mapply(.volume_onecol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow(S1),])) z<-1/(1-alpha_grid[-length(alpha_grid)])*z[-length(alpha_grid)] z <- ifelse(z <= 1, z, 1) integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z)) erg<-list(alpha_grid=alpha_grid,volume=z,integral_approx=integral_approx) return(erg) } .volumeA2_full <- function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){ steps0<-steps alpha0_grid<-alpha_grid .volumeA2_full_severalcol(S1,S2,steps=steps0,alpha_grid=alpha0_grid ) } .volumeA2_full_dim1 <- function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){ steps0<-steps alpha0_grid<-alpha_grid .volumeA2_full_severalcol_dim1(S1,S2,steps=steps0,alpha_grid=alpha0_grid ) } .volumeA2_full_severalcol_dim1 <- function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){ S<-c(S1,S2) Ncol<-1 ab<-max(S)-min(S) SSN<-t((t(S)-min(S))/(ab)) SSN[,ab==0]<-0.5 SSN<-as.data.frame(SSN) z<-mapply(.volume_onecol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN)) z<-rbind(1/(1-alpha_grid[-length(alpha_grid)])*z[-length(alpha_grid)]) z <- ifelse(z <= 1, z, 1) integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z),mean=.trapz(alpha_grid[-length(alpha_grid)],z),gmean=.trapz(alpha_grid[-length(alpha_grid)],z)) plot_data_prod<-z erg<-list(alpha_grid=seq(0,1,length=steps),volume=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod) return(erg) } .volumeA2_full_severalcol <- function(S1,S2,steps=101,alpha_grid=seq(0,1,length=steps)){ S<-rbind(S1,S2) Ncol<-ncol(S1) Spans<-data.frame(trait_nr=1:Ncol,min=matrix(mapply(min, S, MoreArgs = list(na.rm = TRUE))),max=matrix(mapply(max, S, MoreArgs = list(na.rm = TRUE)))) ab<-Spans$max-Spans$min SSN<-t((t(S)-Spans$min)/(ab)) SSN[,ab==0]<-0.5 SSN<-as.data.frame(SSN) z<-mapply(.volume_severalcol, alpha = alpha_grid, MoreArgs = list(SSN1=SSN[1:nrow(S1),])) z<-rbind(1/(1-alpha_grid[-length(alpha_grid)])*z[1,][-length(alpha_grid)],1/(1-alpha_grid[-length(alpha_grid)])*z[2,][-length(alpha_grid)],1/(1-alpha_grid[-length(alpha_grid)])*z[3,][-length(alpha_grid)]) z <- ifelse(z <= 1, z, 1) integral_approx<-c(prod=.trapz(alpha_grid[-length(alpha_grid)], z[1,]),mean=.trapz(alpha_grid[-length(alpha_grid)],z[2,]),gmean=.trapz(alpha_grid[-length(alpha_grid)],z[3,])) plot_data_prod<-z[1,] erg<-list(alpha_grid=seq(0,1,length=steps),volume=z,integral_approx=integral_approx,plot_data_prod=plot_data_prod) return(erg) } .trpca <- function(data, va){ PCA <- prcomp(data[,-1]) vars <- apply(PCA$x, 2, var) prop <- cumsum(vars / sum(vars)) k <- which(prop >= va)[1] k <- ifelse(k==1, 2, k) data1 <- data.frame(data[,1], PCA$x[,1:k]) colnames(data1)[1] <- "Species" return(data1) } .getVarianceEstimate <-function(x,y){ x_smallerM = x[1:round(length(x)/2 + 0.1)] x_greaterM = x[round(length(x)/2+1.1):length(x)] n = as.numeric(length(x)) k = as.numeric(length(x_smallerM)) x_smallerM_ranks = rank(x_smallerM) x_greaterM_ranks = rank(x_greaterM) y_smallerM = y[1:round(length(y)/2 +0.1)] y_greaterM = y[round(length(y)/2+1.1):length(y)] m = as.numeric(length(y)) l = as.numeric(length(y_smallerM)) y_smallerM_ranks = rank(y_smallerM) y_greaterM_ranks = rank(y_greaterM) xy_smallerM_ranks = rank(c(x_smallerM,y_smallerM))[1:k] yx_smallerM_ranks = rank(c(y_smallerM,x_smallerM))[1:l] xy_greaterM_ranks = rank(c(x_greaterM,y_greaterM))[1:(n-k)] yx_greaterM_ranks = rank(c(y_greaterM,x_greaterM))[1:(m-l)] s2_X1 = 1/(l^2*(k-1)) * sum((xy_smallerM_ranks - x_smallerM_ranks - mean(xy_smallerM_ranks) + (k+1)/2)^2) s2_X2 = 1/((m-l)^2*(n-k-1)) * sum((xy_greaterM_ranks - x_greaterM_ranks - mean(xy_greaterM_ranks) + (n-k+1)/2)^2) s2_Y1 = 1/(k^2*(l-1)) * sum((yx_smallerM_ranks - y_smallerM_ranks - mean(yx_smallerM_ranks) + (l+1)/2)^2) s2_Y2 = 1/((n-k)^2*(m-l-1)) * sum((yx_greaterM_ranks - y_greaterM_ranks - mean(yx_greaterM_ranks) + (m-l+1)/2)^2) s2_2 = (l+k)*(s2_X1/k + s2_Y1/l) + (n+m-l-k)*(s2_X2/(n-k) + s2_Y2/(m-l)) return(s2_2) } .getRankedSingleOverlapIndex <- function(x,y){ x_length = as.numeric(length(x)) if(round(x_length/2)==x_length/2){ k=x_length/2 }else{ k=(x_length+1)/2 } y_length = as.numeric(length(y)) x = sort(x) xy_ranks = rank(c(x,y)) x_rank = xy_ranks[1:x_length] y_rank = xy_ranks[(x_length+1):(x_length+y_length)] rank_gtm = sum(x_rank[(k+1) : x_length]) rank_stm = sum(x_rank[1:k]) K= sum(rank(x)[1:k]) c = 2/((x_length)*(y_length)) * ( - x_length*(x_length+1) + K*4) overlap_ranked = 2*(rank_gtm - rank_stm)/((x_length)*(y_length)) + c/2 return(overlap_ranked) } .geo.mean <- function (x){ n<-length(x) mittelwert<-prod(x)^(1/n) return (mittelwert) }
setGeneric("moduleMetadata", function(sim, module, path = getOption("spades.modulePath", NULL), defineModuleListItems = c( "name", "description", "keywords", "childModules", "authors", "version", "spatialExtent", "timeframe", "timeunit", "citation", "documentation", "reqdPkgs", "parameters", "inputObjects", "outputObjects" )) { standardGeneric("moduleMetadata") }) setMethod( "moduleMetadata", signature = c(sim = "missing", module = "character", path = "character"), definition = function(module, path, defineModuleListItems) { filename <- paste(path, "/", module, "/", module, ".R", sep = "") if (!file.exists(filename)) { stop(paste(filename, "does not exist. This was created by putting", "modulePath with the module name as a folder and filename. ", "Please correct the modulePath or module name in", "the simInit() call.")) } metadata <- lapply(defineModuleListItems, function(xx) { pmp <- .parseModulePartial(filename = file.path(path, module, paste0(module, ".R")), defineModuleElement = xx) out2 <- suppressMessages(try(eval(pmp), silent = TRUE)) if (is(out2, "try-error")) { inner2 <- lapply(pmp, function(yyy) { out4 <- try(eval(yyy), silent = TRUE) if (is(out4, "try-error")) { yyy <- lapply(yyy, function(yyyyy) { out5 <- try(eval(yyyyy), silent = TRUE) if (is(out5, "try-error")) yyyyy <- deparse(yyyyy) return(yyyyy) }) } if (is.list(yyy)) yyy <- as.call(yyy) return(yyy) }) out2 <- as.call(inner2) } aa <- capture.output(type = "message", {bb <- eval(out2)}) return(bb) }) names(metadata) <- defineModuleListItems metadata <- rmExtraSpacesEOLList(metadata) return(metadata) }) setMethod( "moduleMetadata", signature = c(sim = "missing", module = "character", path = "missing"), definition = function(module, defineModuleListItems) { moduleMetadata(module = module, path = getOption("spades.modulePath"), defineModuleListItems = defineModuleListItems) }) setMethod( "moduleMetadata", signature = c(sim = "ANY", module = "ANY", path = "ANY"), definition = function(sim, module, path, defineModuleListItems) { if (is.character(sim)) { message("Assuming sim is a module name") if (missing(path)) { metadataList <- moduleMetadata(module = sim, defineModuleListItems = defineModuleListItems) } else { metadataList <- moduleMetadata(module = sim, path = path, defineModuleListItems = defineModuleListItems) } } else { if (!missing(path)) message("path not used with sim provided") if (missing(module)) { module <- unlist(modules(sim)) } numModules <- length(module) metadata <- sim@depends@dependencies[module] sn <- slotNames(".moduleDeps") names(sn) <- sn metadataList <- lapply(metadata, function(mod) { lapply(sn, function(element) { slot(mod, name = element) }) }) metadataList <- lapply(metadataList, function(moduleMetadata) { rmExtraSpacesEOLList(moduleMetadata) }) if (numModules == 1) metadataList <- metadataList[[module]] } return(metadataList) }) setGeneric("moduleVersion", function(module, path, sim, envir = NULL) { standardGeneric("moduleVersion") }) setMethod( "moduleVersion", signature = c(module = "character", path = "character", sim = "missing", envir = "ANY"), definition = function(module, path, envir) { v <- .parseModulePartial(filename = file.path(path, module, paste0(module, ".R")), defineModuleElement = "version", envir = envir) if (is.null(names(v))) { as.numeric_version(v) } else { as.numeric_version(v[[module]]) } }) setMethod( "moduleVersion", signature = c(module = "character", path = "missing", sim = "missing", envir = "ANY"), definition = function(module, envir) { moduleVersion(module = module, path = getOption("spades.modulePath"), envir = envir) }) setMethod( "moduleVersion", signature = c(module = "character", path = "missing", sim = "simList", envir = "ANY"), definition = function(module, sim, envir) { v <- .parseModulePartial(sim = sim, modules = list(module), defineModuleElement = "version", envir = envir) %>% `[[`(module) if (is.null(names(v))) { as.numeric_version(v) } else { as.numeric_version(v[[module]]) } }) setGeneric("moduleParams", function(module, path) { standardGeneric("moduleParams") }) setMethod( "moduleParams", signature = c(module = "character", path = "character"), definition = function(module, path) { md <- suppressWarnings(moduleMetadata(module = module, path = path)) md[["parameters"]][["paramDesc"]] <- rmExtraSpacesEOL(md[["parameters"]][["paramDesc"]]) md[["parameters"]] }) setGeneric("moduleInputs", function(module, path) { standardGeneric("moduleInputs") }) setMethod( "moduleInputs", signature = c(module = "character", path = "character"), definition = function(module, path) { md <- suppressWarnings(moduleMetadata(module = module, path = path)) md[["inputObjects"]][["desc"]] <- rmExtraSpacesEOL(md[["inputObjects"]][["desc"]]) md[["inputObjects"]] }) setGeneric("moduleOutputs", function(module, path) { standardGeneric("moduleOutputs") }) setMethod( "moduleOutputs", signature = c(module = "character", path = "character"), definition = function(module, path) { md <- suppressWarnings(moduleMetadata(module = module, path = path)) md[["outputObjects"]][["desc"]] <- rmExtraSpacesEOL(md[["outputObjects"]][["desc"]]) md[["outputObjects"]] }) rmExtraSpacesEOL <- function(x) gsub(" +|[ *\n]+", " ", x) rmExtraSpacesEOLList <- function(xx) { toRmESEOL <- grepl(c("parameters|inputObjects|outputObjects"), names(xx)) xx[toRmESEOL] <- lapply(xx[toRmESEOL], function(elem) { if (any(grepl("desc", tolower(names(elem))))) { whCol <- grep("desc", tolower(names(elem))) elem[[whCol]] <- rmExtraSpacesEOL(elem[[whCol]]) elem } else { elem } }) xx } rmExtraSpacesEOLCollapse <- function(lis, useOnlyUnnamed = TRUE) { if (isTRUE(useOnlyUnnamed)) if (!is.null(names(lis))) { lis <- lis[!nzchar(names(lis))] } lis <- unlist(lis) lis <- paste(lis, collapse = "") lis <- rmExtraSpacesEOL(lis) }
layout_tbl_graph_dendrogram <- function(graph, circular = FALSE, offset = pi / 2, height = NULL, length = NULL, repel = FALSE, ratio = 1, direction = 'out') { height <- enquo(height) length <- enquo(length) reverse_dir <- if (direction == 'out') 'in' else 'out' if (quo_is_null(height)) { if (quo_is_null(length)) { height <- NA } else { length <- eval_tidy(length, .E()) full_lengths <- distances(graph, to = node_is_root(), weights = length, mode = reverse_dir) full_lengths[is.infinite(full_lengths)] <- 0 height <- unname(apply(full_lengths, 1, max)) height <- abs(height - max(height)) } } else { height <- eval_tidy(height, .N()) } nodes <- new_data_frame(list( x = rep(NA_real_, gorder(graph)), y = height, leaf = degree(graph, mode = direction) == 0 )) if (all(is.na(nodes$y))) { nodes$y <- vapply(seq_len(gorder(graph)), function(i) { max(bfs(graph, i, direction, unreachable = FALSE, order = FALSE, dist = TRUE)$dist, na.rm = TRUE) }, numeric(1)) } if (repel) { pad <- min(nodes$y[nodes$y != 0]) / 2 } else { pad <- 0 } startnode <- which(degree(graph, mode = reverse_dir) == 0) if (length(startnode) < 1) stop('No root nodes in graph') recurse_layout <- function(gr, node, layout, direction, offset = 0) { children <- as.numeric(neighbors(gr, node, direction)) if (length(children) == 0) { layout$x[node] <- offset layout } else { children_missing <- children[is.na(layout$x[children])] for (i in children_missing) { layout <- recurse_layout(gr, i, layout, direction, offset) offset <- if (repel) { max(layout$x[layout$leaf], na.rm = TRUE) + (layout$y[node] + pad) * ratio } else { max(layout$x[layout$leaf], na.rm = TRUE) + 1 + pad } } layout$x[node] <- mean(range(layout$x[children])) layout } } offset <- 0 for (i in startnode) { nodes <- recurse_layout(graph, i, nodes, direction = direction, offset) offset <- max(nodes$x[nodes$leaf], na.rm = TRUE) + 1 } graph <- add_direction(graph, nodes) if (circular) { radial <- radial_trans( r.range = rev(range(nodes$y)), a.range = range(nodes$x), offset = offset ) coords <- radial$transform(nodes$y, nodes$x) nodes$x <- coords$x nodes$y <- coords$y } extra_data <- as_tibble(graph, active = 'nodes') warn_dropped_vars(nodes, extra_data) nodes <- cbind(nodes, extra_data[, !names(extra_data) %in% names(nodes), drop = FALSE]) nodes$circular <- circular attr(nodes, 'graph') <- graph nodes }
basepkgs = installed.packages(priority="base")[, "Package"] switchDeps = c(basepkgs, "switchr", "RCurl", "bitops", "BiocInstaller", "BiocManager", "RJSONIO") switchrDontUnload = function(value, add=TRUE) { if(missing(value)){ if(is.null(switchrOpts$dontunload)) switchrOpts$dontunload = switchDeps switchrOpts$dontunload } else { value = .dodepsourselves(value, incl_pkgs = TRUE) if(add) value = unique(c(switchrDontUnload(), value)) switchrOpts$dontunload = value } } .dodepsourselves = function(pkg, av = available.packages(contrib.url(defaultRepos())), incl_pkgs = TRUE) { if(nrow(av) == 0) av = installed.packages() deps = .innerdodeps(pkg, av) done = pkg remaining = deps while(length(remaining) > 0) { d = remaining[1] newdeps = .innerdodeps(d, av, done = done) done = c(done, d) deps = c(deps, newdeps) remaining = unique(c(remaining[-1], newdeps)) } if(incl_pkgs) deps = unique(c(pkg, deps)) deps } .innerdodeps = function(pkg, av, done = character() ) { deps = av[pkg, c("Depends", "Imports")] deps = unlist(as.vector(deps)) deps = deps[!is.na(deps)] if(length(deps) >0) { deps = unlist(strsplit(deps, "[[:space:]]*,[[:space:]]*")) deps = gsub("[[:space:]]*([\\._[:alnum:]]*).*", "\\1", deps) deps = deps[deps!= "R"] deps = unique(deps) deps = deps[!deps %in% c(done, basepkgs)] } deps } switchrNoUnload = function(value) { if(missing(value)){ if(is.null(switchrOpts$noflush)) switchrOpts$noflush = FALSE switchrOpts$noflush } else { if(is.na(value)) value = FALSE if(!is(value, "logical")) stop("The no unload option must be a logical value") switchrOpts$noflush = value } } flushSession = function(dontunload = switchrDontUnload()) { atched = names(sessionInfo()$otherPkgs) if(is.null(atched)) atched = character() sapply(atched[!atched %in% dontunload], function(x) { pkg = paste("package", x, sep=":") detach(pkg, character.only = TRUE) }) lded = rev(names(sessionInfo()$loadedOnly)) lded = lded[!lded %in% dontunload] lded2 = lded cnt = 1 while(length(lded) && cnt < 1000) { sapply(lded, function(x) { res = tryCatch(unloadNamespace(getNamespace(x)), error = function(e) e) if(!is(res, "error")) { } }) lded = rev(names(sessionInfo()$loadedOnly)) lded = lded[!lded %in% dontunload] cnt = cnt +1 } if(cnt == 1000) warning("Unable to unload all namespaces") pkgs = unique(c(atched, lded2)) pkgs = pkgs[! pkgs %in% dontunload] sapply(pkgs, function(x) { dll = getLoadedDLLs()[[x]] if(!is.null(dll)) tryCatch(library.dynam.unload(x, dirname(dirname(dll[["path"]]))), error = function(e) NULL) }) NULL }
COPY_biglasso <- function(X, y.train, ind.train, covar.train, family = c("gaussian", "binomial"), alpha = 1, lambda.min = `if`(nrow(X) > ncol(X), .001, .01), nlambda = 100, lambda.log.scale = TRUE, lambda, eps = 1e-7, max.iter = 1000, dfmax = p + 1, penalty.factor = NULL, warn = TRUE, verbose = FALSE) { family <- match.arg(family) lambda.min <- max(lambda.min, 1e-6) n <- length(ind.train) if (is.null(covar.train)) covar.train <- matrix(0, n, 0) assert_lengths(y.train, ind.train, rows_along(covar.train)) p <- ncol(X) + ncol(covar.train) if (is.null(penalty.factor)) penalty.factor <- rep(1, p) if (p != length(penalty.factor)) stop("'penalty.factor' has an incompatible length.") if (alpha == 1) { penalty <- "lasso" } else if (alpha < 1 && alpha > 1e-6) { penalty <- "enet" } else { stop("alpha must be between 1e-6 and 1 for elastic net penalty.") } if (nlambda < 2) stop("nlambda must be at least 2") if (any(is.na(y.train))) stop(paste("Missing data (NA's) detected. Take actions", "(e.g., removing cases, removing features, imputation)", "to eliminate missing data before fitting the model.")) if (class(y.train) != "numeric") tryCatch(y.train <- as.numeric(y.train), error = function(e) stop("y.train must numeric or able to be coerced to numeric")) if (family == "binomial") { yy <- transform_levels(y.train) } else if (family == "gaussian") { yy <- y.train - mean(y.train) } else { stop("Current version only supports Gaussian or Binominal response!") } if (missing(lambda)) { user.lambda <- FALSE lambda <- rep(0, nlambda); } else { nlambda <- length(lambda) user.lambda <- TRUE } if (verbose) printf("\nStart biglasso: %s\n", format(Sys.time())) if (family == "gaussian") { res <- COPY_cdfit_gaussian_hsr(X, yy, ind.train, covar.train, lambda, nlambda, lambda.log.scale, lambda.min, alpha, user.lambda | any(penalty.factor == 0), eps, max.iter, penalty.factor, dfmax, verbose) a <- rep(mean(y.train), nlambda) b <- Matrix(res[[1]], sparse = TRUE) center <- res[[2]] scale <- res[[3]] lambda <- res[[4]] loss <- res[[5]] iter <- res[[6]] rejections <- res[[7]] col.idx <- res[[8]] } else if (family == "binomial") { res <- COPY_cdfit_binomial_hsr(X, yy, ind.train, covar.train, lambda, nlambda, lambda.log.scale, lambda.min, alpha, user.lambda | any(penalty.factor == 0), eps, max.iter, penalty.factor, dfmax, warn, verbose) a <- res[[1]] b <- Matrix(res[[2]], sparse = TRUE) center <- res[[3]] scale <- res[[4]] lambda <- res[[5]] loss <- res[[6]] iter <- res[[7]] rejections <- res[[8]] col.idx <- res[[9]] } else { stop("Current version only supports Gaussian or Binominal response!") } if (verbose) printf("\nEnd biglasso: %s\n", format(Sys.time())) col.idx <- col.idx + 1 ind <- !is.na(iter) a <- a[ind] b <- b[, ind, drop = FALSE] iter <- iter[ind] lambda <- lambda[ind] loss <- loss[ind] if (warn & any(iter == max.iter)) warning("Algorithm failed to converge for some values of lambda") beta <- Matrix(0, nrow = p, ncol = length(lambda), sparse = TRUE) bb <- b / scale[col.idx] beta[col.idx, ] <- bb aa <- a - as.numeric(crossprod(center[col.idx], bb)) names(aa) <- colnames(beta) <- round(lambda, digits = 4) structure(list( intercept = aa, beta = beta, iter = iter, lambda = lambda, penalty = penalty, family = family, alpha = alpha, loss = loss, penalty.factor = penalty.factor, n = n, p = p, center = center, scale = scale, y = yy, col.idx = col.idx, rejections = rejections ), class = "big_sp") } big_spLinReg <- function(X, y.train, ind.train = rows_along(X), covar.train = NULL, ...) { check_args() COPY_biglasso(X, y.train, ind.train, covar.train, family = "gaussian", ...) } big_spLogReg <- function(X, y01.train, ind.train = rows_along(X), covar.train = NULL, ...) { check_args() COPY_biglasso(X, y01.train, ind.train, covar.train, family = "binomial", ...) }
aggregate_positions <- function(tau_x, type = "sum") { if (!inherits(tau_x, "Matrix") & !is.matrix(tau_x)) { stop("tau_x must be a matrix") } if (type == "sum") { return(rowSums(tau_x)) } else if (type == "prod") { return(apply(tau_x, 1, prod)) } else if (type == "mean") { return(rowMeans(tau_x)) } else if (type == "max") { return(apply(tau_x, 1, max)) } else if (type == "min") { return(apply(tau_x, 1, min)) } else if (type == "invsum") { return(rowSums(tau_x)^-1) } else if (type == "self") { diag(tau_x) } else { stop(paste("type =", type, "is not supported. See function details for options.")) } }
GetPermanentTraffic <- function(reportsuite.ids) { request.body <- c() request.body$rsid_list <- reportsuite.ids request.body$locale <- unbox(AdobeAnalytics$SC.Credentials$locale) request.body$elementDataEncoding <- unbox("utf8") response <- ApiRequest(body=toJSON(request.body),func.name="ReportSuite.GetPermanentTraffic") if(length(response$permanent_traffic[[1]]) == 0) { return(print("Permanent Traffic Not Enabled For This Report Suite")) } accumulator <- data.frame() permanent_traffic_list <- response$permanent_traffic response$permanent_traffic <- NULL for(i in 1:nrow(response)){ permanent_traffic_df <- as.data.frame(permanent_traffic_list[[i]]) if(nrow(permanent_traffic_df) == 0){ temp <- response[i,] } else { temp <- cbind(response[i,], permanent_traffic_df, row.names = NULL) } accumulator <- rbind.fill(accumulator, temp) } return(accumulator) }
readALSLAS = function(files, select = "*", filter = "") { do_no_read_lascluster(files) las <- readLAS(files, select, filter) las@index <- LIDRALSINDEX return(las) } readTLSLAS = function(files, select = "*", filter = "") { do_no_read_lascluster(files) las <- readLAS(files, select, filter) las@index <- LIDRTLSINDEX return(las) } readUAVLAS = function(files, select = "*", filter = "") { do_no_read_lascluster(files) las <- readLAS(files, select, filter) las@index <- LIDRUAVINDEX return(las) } readDAPLAS = function(files, select = "*", filter = "") { do_no_read_lascluster(files) las <- readLAS(files, select, filter) las@index <- LIDRDAPINDEX return(las) } readMSLAS = function(files1, files2, files3, select = "*", filter = "") { if (missing(files2) && missing(files3)) { las <- readLAS(files1, select, filter) las@index <- LIDRMLSINDEX return(las) } las <- readLAS(c(files1, files2, files3), select, filter) if (!"ScannerChannel" %in% names(las@data)) { tmp <- readLAS(files1, "", filter) n1 <- npoints(tmp) tmp <- readLAS(files2, "", filter) n2 <- npoints(tmp) las@data[["ScannerChannel"]] <- 1L las@data[["ScannerChannel"]][(n1+1):(n1+n2)] <- 2L las@data[["ScannerChannel"]][(n1+n2+1):npoints(las)] <- 3L las@header@PHB[["Point Data Format ID"]] <- 6L las@header@PHB[["Version Minor"]] <- 4L message("Multispectral data read from point format < 6 with no ScannerChannel attribute. The LAS object has been upgraded to LAS 1.4 prf 6 with a ScannerChannel.") } else { n <- fast_countequal(las@data[["ScannerChannel"]], 0L) if (n > 0 && n < npoints(las)) warning("Some points have a ScannerChannel of 0 meaning they come from single source sensor.", call. = FALSE) if (n == npoints(las)) { tmp <- readLAS(files1, "", filter) n1 <- npoints(tmp) tmp <- readLAS(files2, "", filter) n2 <- npoints(tmp) las@data[["ScannerChannel"]] <- 1L las@data[["ScannerChannel"]][(n1+1):(n1+n2)] <- 2L las@data[["ScannerChannel"]][(n1+n2+1):npoints(las)] <- 3L message("ScannerChannel was not populated. The ScannerChannel of the LAS object has been automatically populated.") } } las@index <- LIDRMLSINDEX return(las) } do_no_read_lascluster = function(x) { if (is(x, "LAScluster")) stop("Use readLAS() to read a LAScluster object not one of readXXXLAS(). A LAScluster object already contains metadata about the point cloud type.", call. = FALSE) }
library(checkargs) context("isNumberOrNanOrInfScalarOrNull") test_that("isNumberOrNanOrInfScalarOrNull works for all arguments", { expect_identical(isNumberOrNanOrInfScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNumberOrNanOrInfScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNumberOrNanOrInfScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNumberOrNanOrInfScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNumberOrNanOrInfScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNumberOrNanOrInfScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNumberOrNanOrInfScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
bfastpp<- function(data, order = 3, lag = NULL, slag = NULL, na.action = na.omit, stl = c("none", "trend", "seasonal", "both"), decomp = c("stl", "stlplus"), sbins = 1) { decomp <- match.arg(decomp) stl <- match.arg(stl) if (stl != "none" && decomp == "stlplus" && !requireNamespace("stlplus", quietly = TRUE)) stop("Please install the stlplus package or set decomp = 'stl' or stl = 'none'.") if(!is.ts(data)) data <- as.ts(data) stl <- match.arg(stl) if(stl != "none") { stl_adjust <- function(x) { x_stl <- if (decomp=="stlplus") { stlplus::stlplus(x, s.window = "periodic")$data } else { stats::stl(x, s.window = "periodic")$time.series } switch(stl, "trend" = x - x_stl[, "trend"], "seasonal" = x - x_stl[, "seasonal"], "both" = x - x_stl[, "trend"] - x_stl[, "seasonal"]) } if(NCOL(data) > 1L) { for(i in 1:NCOL(data)) data[,i] <- stl_adjust(data[,i]) } else { data <- stl_adjust(data) } } if(NCOL(data) > 1L) { x <- coredata(data)[, -1L] y <- data[, 1L] } else { x <- NULL y <- data } rval <- data.frame( time = as.numeric(time(y)), response = y, trend = 1:NROW(y), season = cut(cycle(y), if (sbins > 1) sbins else frequency(y)*sbins, ordered_result = TRUE) ) freq <- frequency(y) order <- min(freq, order) harmon <- outer(2 * pi * as.vector(time(y)), 1:order) harmon <- cbind(apply(harmon, 2, cos), apply(harmon, 2, sin)) colnames(harmon) <- if(order == 1) { c("cos", "sin") } else { c(paste("cos", 1:order, sep = ""), paste("sin", 1:order, sep = "")) } if((2 * order) == freq) harmon <- harmon[, -(2 * order)] rval$harmon <- harmon nalag <- function(x, k) c(rep(NA, k), head(x, -k)) if(!is.null(lag)) { rval$lag <- sapply(lag, function(k) nalag(as.vector(y), k)) colnames(rval$lag) <- lag } if(!is.null(slag)) { rval$slag <- sapply(slag * freq, function(k) nalag(as.vector(y), k)) colnames(rval$slag) <- slag } rval$xreg <- x rval <- na.action(rval) return(rval) }
calc_kel_single_tdm <- function ( dose = 1000, V = 50, t = 10, dv = 10, tau = 12, t_inf = 1, kel_init = 0.1, n_iter = 25 ) { t_next_dose <- tau - (t %% tau) kel <- kel_init for(i in 1:n_iter) { cpeak <- clinPK::pk_1cmt_inf_cmax_ss( dose = dose, CL = kel * V, V = V, tau = tau, t_inf = t_inf ) cpred <- clinPK::pk_1cmt_inf_ss( t = t, dose = dose, CL = kel * V, V = V, tau = tau, t_inf = t_inf) kel <- (cpred$dv/dv) * kel } return(kel) }
setClass("SDMXCodelists", contains = "SDMX", representation( codelists = "list" ), prototype = list(), validity = function(object){ return(TRUE); } )
fluidRow( column( width = 3, radioButtons( "sampler_warmup", label = h5("Warmup"), choices = list(Omit = "omit", Include = "include"), inline = TRUE ) ), column( width = 4, radioButtons( "sampler_report", label = h5("Statistic"), choices = list( Mean = "average", SD = "sd", Max = "maximum", Min = "minimum" ), inline = TRUE ) ), column( width = 2, numericInput( "sampler_digits", label = h5("Decimals"), value = 4, min = 0, max = 10, step = 1 ) ) )
expected <- c(3L, 0L, 0L, 3L, 0L, 0L) test(id=8, code={ argv <- structure(list(x = complex(real=Inf, imaginary=Inf)), .Names = "x") do.call('format.info', argv); }, o = expected);
calculate_score <- function(string, keywords, case = FALSE) { if(case == FALSE) { score <- stringr::str_match_all(stringr::str_to_lower(string), stringr::str_to_lower(keywords)) %>% purrr::flatten() %>% length() } else if (case == TRUE) { score <- stringr::str_match_all(string, keywords) %>% purrr::flatten() %>% length() } return(score) }
predict.tvgarch <- function (object, n.ahead = 10, newxtv = NULL, newxreg = NULL, newindex = NULL, n.sim = 5000, as.zoo = TRUE, verbose = FALSE, ...) { n <- length(object$y) if (!is.null(object$order.g) && object$order.g[1] != 0) { coefs.h <- as.numeric(coef.tvgarch(object = object, spec = "garch")) } if (is.null(object$order.g) || object$order.g[1] == 0) { coefs.h <- as.numeric(coef.tvgarch(object = object, spec = "sigma2")) } interceptCoef <- coefs.h[1] archCoef <- coefs.h[(1+1):(1+object$order.h[2])] if (object$order.h[1] != 0) { garchCoef <- coefs.h[(1+object$order.h[2]+1):(1+sum(object$order.h[1:2]))] } if (object$order.h[1] == 0) garchCoef <- NULL if (object$order.h[3] != 0) { asymCoef <- coefs.h[(1+sum(object$order.h[1:2])+1):(1+sum(object$order.h))] } if (object$order.h[3] == 0) asymCoef <- NULL if (!is.null(object$xreg)) xregCoef <- coefs.h[-(1:(1+sum(object$order.h)))] if (is.null(object$xreg)) xregCoef <- NULL backcast.values <- list() if (max(object$order.h) > 0) { backcast.values$innovations <- tail(as.numeric(object$residuals), n = max(object$order.h)) backcast.values$z2 <- backcast.values$innovations^2 backcast.values$Ineg <- as.numeric(backcast.values$innovations < 0) backcast.values$sigma2 <- tail(as.numeric(object$h), n = max(object$order.h)) if (!is.null(object$xreg)) { backcast.values$xreg <- tail(as.numeric(object$xreg%*%xregCoef), n = max(object$order.h)) } } xreg <- NULL if (!is.null(object$xreg)) { if ((NROW(newxreg) != n.ahead)) { stop("NROW(newxreg) is unequal to n.ahead") } xreg <- cbind(newxreg) %*% xregCoef } etahat <- coredata(object$residuals) draws <- runif(n.ahead*n.sim, min = 0.5+1e-09, max = length(etahat)+0.5-1e-09) draws <- round(draws, digits = 0) innovations <- matrix(etahat[draws], n.ahead, n.sim) predictions.h <- matrix(NA, n.ahead, n.sim) for (i in 1:n.sim) { predictions.h[,i] <- garchxSim(n = n.ahead, intercept = interceptCoef, arch = archCoef, garch = garchCoef, asym = asymCoef, xreg = xreg, innovations = innovations[,i], backcast.values = backcast.values, verbose = TRUE, as.zoo = FALSE)[,"sigma2"] } if (!is.null(object$order.g) && object$order.g[1] != 0) { coefs.g <- as.numeric(coef.tvgarch(object = object, spec = "tv")) if (!is.null(newxtv)) { if ((NROW(newxtv) != n.ahead)) { stop("NROW(newxtv) is unequal to n.ahead") } newxtv <- as.matrix(newxtv) predictions.g <- tvObj(par.g = coefs.g, fixed.par.g = NULL, xtv = newxtv, opt = object$opt, order.g = object$order.g, fixed.h = NULL, y = NULL, iter0 = TRUE, flag = 2) } if (is.null(newxtv)) predictions.g <- rep(coefs.g[1], n.ahead) result <- as.matrix(rowMeans(predictions.h)*predictions.g) if (verbose == TRUE) { result <- cbind(result, as.vector(predictions.g), predictions.h) colnames(result) <- c("p_sigma2", "p_g", paste("p_h", 1:NCOL(predictions.h), sep = "_")) } } if (is.null(object$order.g) || object$order.g[1] == 0) { result <- as.matrix(rowMeans(predictions.h)) if (verbose == TRUE) { result <- cbind(result, predictions.h) colnames(result) <- c("p_sigma2", paste("p_h", 1:NCOL(predictions.h), sep = "_")) } } if (is.null(newindex)) { newindex <- 1:n.ahead } if (as.zoo == TRUE) { result <- zoo(result, order.by = newindex) } return(result) }
stat_summarise <- function(mapping = NULL, data = NULL, geom = "bar", position = "identity", ..., fun = NULL, args = list(), show.legend = NA, inherit.aes = TRUE){ layer(geom = geom, stat = StatSummarise, data = data, mapping = mapping, position = position, params = list(fun = fun, args = args, ...), inherit.aes = inherit.aes, show.legend = show.legend) } stat_summarize <- stat_summarise StatSummarise <- ggplot2::ggproto("StatSummarise", Stat, required_aes = c("domain"), compute_panel = function(self, data, scales, domain = NULL, fun = NULL, args = list()) { if (empty(data)) return(new_data_frame()) if(is.null(fun)) { warn("fun is NULL, using length as default") fun <- length } groups <- split(data, data$group) stats <- lapply(groups, function(group){ self$compute_group(data = group, fun = fun, args = args) }) rbind_dfs(stats) }, compute_group = function(self, data, scales, fun = NULL, args = args){ call_f <- function(fun = fun, x) { if (is.null(fun)) return(NA_real_) fun <- as_function(fun) do.call(fun, c(list(quote(x)), args)) } data <- unique(transform(data, summarise = call_f(fun, domain), domain = NULL)) data[['summarize']] <- data[['summarise']] data }, compute_layer = function(self, data, params, layout) { check_required_aesthetics( self$required_aes, c(names(data), names(params)), snake_class(self) ) required_aes <- intersect( names(data), unlist(strsplit(self$required_aes, "|", fixed = TRUE)) ) data <- remove_missing(data, params$na.rm, c(required_aes, self$non_missing_aes), snake_class(self), finite = FALSE ) params <- params[intersect(names(params), self$parameters())] args <- c(list(data = quote(data), scales = quote(scales)), params) dapply(data, "PANEL", function(data) { scales <- layout$get_scales(data$PANEL[1]) tryCatch(do.call(self$compute_panel, args), error = function(e) { warn(glue("Computation failed in `{snake_class(self)}()`:\n{e$message}")) new_data_frame() }) }) }) StatSummarize <- ggplot2::ggproto("StatSummarize", Stat, required_aes = c("domain"), compute_panel = function(self, data, scales, domain = NULL, fun = NULL, args = list()) { if (empty(data)) return(new_data_frame()) if(is.null(fun)) { warn("fun is NULL, using length as default") fun <- length } groups <- split(data, data$group) stats <- lapply(groups, function(group){ self$compute_group(data = group, fun = fun, args = args) }) rbind_dfs(stats) }, compute_group = function(self, data, scales, fun = NULL, args = args){ call_f <- function(fun = fun, x) { if (is.null(fun)) return(NA_real_) fun <- as_function(fun) do.call(fun, c(list(quote(x)), args)) } data <- unique(transform(data, summarise = call_f(fun, domain), domain = NULL)) data[['summarize']] <- data[['summarise']] data }, compute_layer = function(self, data, params, layout) { check_required_aesthetics( self$required_aes, c(names(data), names(params)), snake_class(self) ) required_aes <- intersect( names(data), unlist(strsplit(self$required_aes, "|", fixed = TRUE)) ) data <- remove_missing(data, params$na.rm, c(required_aes, self$non_missing_aes), snake_class(self), finite = FALSE ) params <- params[intersect(names(params), self$parameters())] args <- c(list(data = quote(data), scales = quote(scales)), params) dapply(data, "PANEL", function(data) { scales <- layout$get_scales(data$PANEL[1]) tryCatch(do.call(self$compute_panel, args), error = function(e) { warn(glue("Computation failed in `{snake_class(self)}()`:\n{e$message}")) new_data_frame() }) }) })
testthat::context("SlideDeck") testthat::test_that("Testing the introduction presentation", { fname <- system.file("Introduction.plain", package = "REPLesentR", mustWork = TRUE) file.copy(fname, tfname <- tempfile(fileext = ".plain")) rawText <- Read()$auto(tfname, quiet = TRUE) slideDeck <- SlideDeck()$new(rawText) testthat::expect_true(length(slideDeck) == 10) lapply(slideDeck, function(slide) { testthat::expect_true(all(c("content", "format", "number") %in% names(slide))) }) })
simfam <- function(N.fam, design="pop", variation="none", interaction=FALSE, depend=NULL, base.dist="Weibull", frailty.dist=NULL, base.parms, vbeta, allelefreq=c(0.02, 0.2), dominant.m=TRUE, dominant.s=TRUE, mrate=0, hr=0, probandage=c(45, 2), agemin = 20, agemax = 100) { if(!is.element(variation, c("none", "frailty", "secondgene"))) stop("Unrecognized variation; variation should be one of none, frailty, or secondgene") if(agemin > 70) warning("agemin should be less than 70.") if(agemin >= agemax) stop("agemax should be greater than agemin.") if(!is.element(base.dist, c("Weibull", "loglogistic", "Gompertz", "lognormal", "logBurr"))) stop("Unrecognized base.dist; base.dist should be one of \"Weibull\", \"loglogistic\", \"Gompertz\", \"lognormal\", or \"logBurr\". ") if(variation=="frailty"){ if(!any(frailty.dist==c("lognormal", "gamma"))) stop("Unrecognized frailty distribution; frailty.dist should be either \"gamma\" or \"lognormal\". ") if(is.null(depend)) stop("depend should be specified.") if(depend <= 0) stop("depend should be > 0") } else{ if(any(frailty.dist==c("lognormal", "gamma")) ) stop("Variation should be specified as variation = \"frailty\".") if(!is.null(frailty.dist) ) stop("frailty.dist should be specified only with variation=\"frailty\" ") if(!is.null(depend)) stop("depend should be specified only with variation=\"frailty\" ") } if(!is.element(design, c("pop","pop+","cli","cli+","twostage"))) stop("Unrecognized design; should be one of pop, pop+, cli, cli+ or twostage") nvbeta = 2+(variation=="secondgene")+interaction if(length(vbeta) != nvbeta) stop(paste("vbeta should be a vector of length", nvbeta)) if(base.dist=="logBurr" & length(base.parms)!=3) stop("parms should be a vector of length 3") else if(base.dist!="logBurr" & length(base.parms)!=2) stop("parms should be a vector of length 2") if(design=="pop") {affectnum=1; m.carrier=0} if(design=="pop+"){affectnum=1; m.carrier=1} if(design=="cli") {affectnum=3; m.carrier=0} if(design=="cli+"){affectnum=3; m.carrier=1} if(design=="twostage"){ affectnum = 2 m.carrier = 0 if(hr==0) stop("Please specify the sampling rate of high risk families (0 < hr < 1)") else if(hr>1 | hr <0) stop("hr should be between 0 and 1 (0 < hr < 1)") } dat <- data.frame(familyDesign(n=N.fam, affectnum=affectnum, m.carrier=m.carrier, base.dist=base.dist, frailty.dist=frailty.dist, dominant.m=dominant.m, dominant.s=dominant.s, interaction=interaction, depend=depend, vbeta=vbeta, parms=base.parms, variation=variation, allelefreq=allelefreq, mrate=mrate, probandage=probandage, agemin=agemin, agemax=agemax)) if(hr==0) dat$weight <- 1 else { if(design!="twostage") stop ("hr can be used only with twostage design" ) en.hr <- round(hr*N.fam) en.lr <- N.fam - en.hr datp <- dat[dat$proband==1,] n.hr <- sum(datp$naff>2) fam.id <- datp$famID lfam.id <- fam.id[datp$naff<3] hfam.id <- fam.id[datp$naff>2] if(length(lfam.id) < en.lr) id <- lfam.id else id <- sample(lfam.id, en.lr, replace=FALSE) n.more <- ifelse(en.hr < n.hr, 0, en.hr-n.hr) dat1 <- dat[is.element(dat$famID, c(id, hfam.id)), ] dat2 <- data.frame(familyDesign(n=n.more, affectnum=3, m.carrier=m.carrier, base.dist=base.dist, frailty.dist=frailty.dist, dominant.m=dominant.m, dominant.s=dominant.s, interaction=interaction, depend=depend, vbeta=vbeta, parms=base.parms, variation=variation, allelefreq=allelefreq, mrate=mrate, probandage=probandage, agemin=agemin, agemax=agemax)) dat <- rbind(dat1, dat2) samrate <- en.lr/(N.fam-n.hr)/(en.hr/n.hr) dat$weight <- ifelse(dat$naff>2, 1, samrate) } class(dat)<-c("simfam","data.frame") attr(dat, "design") <- design attr(dat, "variation") <- variation attr(dat, "interaction") <- interaction attr(dat, "frailty.dist") <- frailty.dist attr(dat, "base.dist") <- base.dist attr(dat, "base.parms") <- base.parms attr(dat, "vbeta") <- vbeta attr(dat, "n.fam") <- N.fam attr(dat, "agemin") <- agemin return(dat) }
library(xts) library(qrmtools) library(qrmdata) data(SP500) data(VIX) plot(SP500) plot(VIX) X1 <- returns(SP500)['1990-01-01/'] X2 <- returns(VIX/100, method = "diff")['1990-01-01/'] X. <- merge(X1, X2) any(is.na(X.)) X <- as.matrix(na.fill(X., fill = "extend")) colnames(X) <- c("SP500", "VIX") plot(X) T <- 1 K <- 100 S <- 100 r <- 0.03 sigma <- 0.25 Delta.t <- 1/250 V.t0 <- Black_Scholes(0, S = S, r = r, sigma = sigma, K = K, T = T, type = "call") V.t1 <- Black_Scholes(Delta.t, S = exp(log(S) + X[,"SP500"]), r = r, sigma = exp(log(sigma) + X[,"VIX"]), K = K, T = T, type = "call") L <- -(V.t1 - V.t0) hist(L, probability = TRUE); box() (Greeks <- Black_Scholes_Greeks(0, S = S, r = r, sigma = sigma, K = K, T = T)) L.Delta <- -(Greeks[["delta"]] * X[,"SP500"] * S + Greeks[["theta"]] * Delta.t + Greeks[["vega"]] * X[,"VIX"] * sigma) plot(L, L.Delta) abline(0, 1, col = "royalblue3") L.Delta.Gamma <- L.Delta - 0.5 * (Greeks[["gamma"]] * (X[,"SP500"] * S)^2 + 2 * Greeks[["vanna"]] * X[,"SP500"] * X[,"VIX"] * S * sigma + Greeks[["vomma"]] * (X[,"VIX"] * sigma)^2) plot(L, L.Delta.Gamma) abline(0, 1, col = "royalblue3") S <- 70 V.t0 <- Black_Scholes(0, S = S, r = r, sigma = sigma, K = K, T = T, type = "call") V.t1 <- Black_Scholes(Delta.t, S = exp(log(S) + X[,"SP500"]), r = r, sigma = exp(log(sigma) + X[,"VIX"]), K = K, T = T, type = "call") L <- -(V.t1 - V.t0) (Greeks <- Black_Scholes_Greeks(0, S = S, r = r, sigma = sigma, K = K, T = T)) L.Delta <- -(Greeks[["delta"]] * X[,"SP500"] * S + Greeks[["theta"]] * Delta.t + Greeks[["vega"]] * X[,"VIX"] * sigma) plot(L, L.Delta) abline(0, 1, col = "royalblue3") L.Delta.Gamma <- L.Delta - 0.5 * (Greeks[["gamma"]] * (X[,"SP500"] * S)^2 + 2 * Greeks[["vanna"]] * X[,"SP500"] * X[,"VIX"] * S * sigma + Greeks[["vomma"]] * (X[,"VIX"] * sigma)^2) plot(L, L.Delta.Gamma) abline(0, 1, col = "royalblue3") t <- 0 T <- 1 K <- 100 S <- 110 r <- 0.02 sigma <- 0.2 delta.S <- 0.05 delta.sig <- 0.02 Delta.t <- 1/250 Delta.rho <- 0.001 (Greeks <- Black_Scholes_Greeks(0, S = S, r = r, sigma = sigma, K = K, T = T)) V.t0 <- S * Greeks[["delta"]] - Black_Scholes(t, S = S, r = r, sigma = sigma, K = K, T = T) S.new <- exp(log(S) + delta.S) V.t1 <- S.new * Greeks[["delta"]] - Black_Scholes(t + Delta.t, S = S.new, r = r, sigma = sigma + delta.sig, K = K, T = T) L <- -(V.t1 - V.t0) delta.term <- Greeks[["delta"]] * S * delta.S vega.term <- Greeks[["vega"]] * delta.sig theta.term <- Greeks[["theta"]] * Delta.t rho.term <- Greeks[["rho"]] * Delta.rho (L.Delta <- theta.term + vega.term) gamma.term <- 0.5 * Greeks[["gamma"]] * S^2 * delta.S^2 vanna.term <- Greeks[["vanna"]] * S * delta.S * delta.sig vomma.term <- 0.5 * Greeks[["vomma"]] * delta.sig^2 L.Delta + gamma.term L.Delta + vanna.term (L.Delta.Gamma <- L.Delta + gamma.term + vanna.term + vomma.term) c(L, L.Delta, L.Delta.Gamma) abs(L - L.Delta)/abs(L) abs(L - L.Delta.Gamma)/abs(L)
context("partitioning") test_that("sdf_repartition works", { iris_tbl <- testthat_tbl("iris") expect_equal( iris_tbl %>% sdf_repartition(4L) %>% sdf_num_partitions(), 4L ) }) test_that("sdf_reparition: partitioning by column works", { test_requires_version("2.0.0", "partitioning by column requires spark 2.0+") iris_tbl <- testthat_tbl("iris") if (is_testing_databricks_connect()) { plan_type <- "analyzed" } else { plan_type <- "optimizedPlan" } expect_true( any(grepl( "RepartitionByExpression \\[Species, Petal_Width\\]", iris_tbl %>% sdf_repartition(partition_by = c("Species", "Petal_Width")) %>% sdf_query_plan(plan_type) %>% gsub(" )) ) expect_true( any(grepl( "RepartitionByExpression \\[Species, Petal_Width\\], 5", iris_tbl %>% sdf_repartition(5L, partition_by = c("Species", "Petal_Width")) %>% sdf_query_plan(plan_type) %>% gsub(" )) ) }) test_that("'sdf_partition' -- 'partitions' argument should take numeric ( test_requires_version("2.0.0", "partitioning by column requires spark 2.0+") iris_tbl <- testthat_tbl("iris") expect_equal( iris_tbl %>% sdf_repartition(6, partition_by = "Species") %>% sdf_num_partitions(), 6 ) }) test_that("'sdf_coalesce' works as expected", { iris_tbl <- testthat_tbl("iris") expect_equal( iris_tbl %>% sdf_repartition(5) %>% sdf_coalesce(1) %>% sdf_num_partitions(), 1 ) })
setpath.wrapper <- function(d1,d2,pathwaygenes,pathwaynames,M=1,transform=NULL,minalpha=NULL,normalize=TRUE,pvalue="chisq",npermutations=10000) { K = length(pathwaynames) results = matrix(NA,K,2*(M+1)+2) dimnames(results)[[1]] = pathwaynames dimnames(results)[[2]] = c("n.genes",paste("alpha.0",1:M,sep="."),"T.0",paste("alpha.0",1:M,sep="."),"T.0","pval") if(!identical(dimnames(d1)[[2]],dimnames(d2)[[2]])) { stop("d1 and d2 have different feature (column) names.") } for(k in 1:K) { missinggenes = setdiff(pathwaygenes[[k]],dimnames(d1)[[2]]) if(length(missinggenes)>0) { warning(c("The following pathway genes are missing from the dataset:",missinggenes)) pathwaygenes[[k]] = intersect(pathwaygenes[[k]],dimnames(d1)[[2]]) } temp = setpath(d1[,pathwaygenes[[k]]],d2[,pathwaygenes[[k]]],M=M,transform=transform,verbose=TRUE,minalpha=minalpha,normalize=normalize,pvalue=pvalue,npermutations=npermutations) results[k,] = c(length(pathwaygenes[[k]]),temp$stats[,1],temp$stats[,2],temp$pval) } return(results) }
NULL `<.bignum_vctr` <- function(e1, e2) { vec_compare_bignum(e1, e2) < 0 } `>.bignum_vctr` <- function(e1, e2) { vec_compare_bignum(e1, e2) > 0 } `<=.bignum_vctr` <- function(e1, e2) { vec_compare_bignum(e1, e2) <= 0 } `>=.bignum_vctr` <- function(e1, e2) { vec_compare_bignum(e1, e2) >= 0 } vec_proxy_compare.bignum_vctr <- function(x, ...) { stop_unsupported(x, "vec_proxy_compare") } vec_compare_bignum <- function(x, y, na_equal = FALSE) { vec_assert(x) vec_assert(y) vec_assert(na_equal, ptype = logical(), size = 1L) args <- vec_recycle_common(x, y) if ((is_biginteger(x) && is.double(y)) || (is_biginteger(y) && is.double(x))) { args <- allow_lossy_cast(vec_cast_common(!!!args, .to = new_bigfloat())) } else { args <- vec_cast_common(!!!args) } vec_compare_bignum2(args[[1]], args[[2]], na_equal) } vec_compare_bignum2 <- function(x, y, na_equal = FALSE) { UseMethod("vec_compare_bignum2") } vec_compare_bignum2.default <- function(x, y, na_equal = FALSE) { stop_unsupported(x, "vec_compare_bignum2") } vec_compare_bignum2.bignum_biginteger <- function(x, y, na_equal = FALSE) { c_biginteger_compare(x, y, na_equal) } vec_proxy_order.bignum_biginteger <- function(x, ...) { c_biginteger_rank(x) } vec_compare_bignum2.bignum_bigfloat <- function(x, y, na_equal = FALSE) { c_bigfloat_compare(x, y, na_equal) } vec_proxy_order.bignum_bigfloat <- function(x, ...) { c_bigfloat_rank(x) }
"or.midp" <- function(x, conf.level = 0.95, byrow = TRUE, interval = c(0, 1000)){ if(is.vector(x)){ if(!is.numeric(x)){stop("vector must be numeric")} if(length(x)!=4){stop("vector must be of length 4")} x <- matrix(x, 2, 2, byrow = byrow) } if(is.matrix(x)){ if(!is.numeric(x)){stop("matrix must be numeric")} if(nrow(x)!=2 || ncol(x)!=2){stop("must be 2 x 2 matrix")} a1 <- x[1,1]; a0 <- x[1,2]; b1 <- x[2,1]; b0 <- x[2,2] } else {stop("must be numeric vector of length=4 or 2x2 numeric matrix")} mue <- function(a1, a0, b1, b0, or){ mm <- matrix(c(a1,a0,b1,b0),2,2, byrow=TRUE) fisher.test(mm, or=or, alternative="l")$p-fisher.test(x=x, or=or, alternative="g")$p } midp <- function(a1, a0, b1, b0, or = 1){ mm <- matrix(c(a1,a0,b1,b0),2,2, byrow=TRUE) lteqtoa1 <- fisher.test(mm,or=or,alternative="l")$p.val gteqtoa1 <- fisher.test(mm,or=or,alternative="g")$p.val 0.5*(lteqtoa1-gteqtoa1+1) } alpha <- 1 - conf.level EST <- uniroot(function(or){ mue(a1, a0, b1, b0, or) }, interval = interval)$root LCL <- uniroot(function(or){ 1-midp(a1, a0, b1, b0, or)-alpha/2 }, interval = interval)$root UCL <- 1/uniroot(function(or){ midp(a1, a0, b1, b0, or=1/or)-alpha/2 }, interval = interval)$root rr <- list(x = x, estimate = EST, conf.int = c(LCL, UCL), conf.level = conf.level) attr(rr, "method") <- "median-unbiased estimate & mid-p exact CI" return(rr) }
tblHvrules <- function(x) { stopifnot(inherits(x, "tblBlocks")) nblk <- NROW(x) hvrules <- data.frame("id"=character(0), "direction"=character(0), "block"=character(0), "side"=character(0), "adjacent_blocks"=character(0), "arow1"=numeric(0), "arow2"=numeric(0), "acol1"=numeric(0), "acol2"=numeric(0), "enabled"=logical(0), stringsAsFactors=FALSE) if (nblk > 0) { adj <- adjacent_blocks(x) x$block <- x$id h1 <- within(x, { direction <- "hrule"; side <- "top" a <- arow1 - 0.5; arow1 <- a; arow2 <- a }) h1$adjacent_blocks <- vapply(adj[, "top"], paste, character(1), collapse=";", USE.NAMES=FALSE) h2 <- within(x, { direction <- "hrule"; side <- "bottom" a <- arow2 + 0.5; arow1 <- a; arow2 <- a }) h2$adjacent_blocks <- vapply(adj[, "bottom"], paste, character(1), collapse=";", USE.NAMES=FALSE) v1 <- within(x, { direction <- "vrule"; side <- "left" a <- acol1 - 0.5; acol1 <- a; acol2 <- a }) v1$adjacent_blocks <- vapply(adj[, "left"], paste, character(1), collapse=";", USE.NAMES=FALSE) v2 <- within(x, { direction <- "vrule"; side <- "right" a <- acol2 + 0.5; acol1 <- a; acol2 <- a }) v2$adjacent_blocks <- vapply(adj[, "right"], paste, character(1), collapse=";", USE.NAMES=FALSE) hv <- rbind(h1, h2, v1, v2) hv$id <- with(hv, paste(block, side, sep="_")) hv$adjacent_blocks <- trimws(hv$adjacent_blocks) hv$enabled <- rep(FALSE, nrow(hv)) hvrules <- hv[order(hv$direction, hv$block, hv$side), names(hvrules), drop=FALSE] } row.names(hvrules) <- hvrules$id class(hvrules) <- c("tblHvrules", "data.frame") hvrules }
vertmean <- function(depth, vari, level, top, bot, vol, total = FALSE) { idepth <- which(depth >= top & depth <= bot) ndepth <- c(depth[idepth]) nvari <- c(vari[idepth]) mdepth <- c(top, (ndepth[-1] + ndepth[-length(ndepth)])/2, bot) nvol <- vol(mdepth, level) dvol <- abs(diff(nvol)) ret <- sum(nvari * dvol) if (total) return(ret) else return(ret / sum(dvol)) }
bidiagpls.fit <- function (X, Y, ncomp, ...) { Y <- as.matrix(Y) dnX <- dimnames(X)[[2]] dnY <- dimnames(Y) nobj <- dim(X)[1] npred <- dim(X)[2] nresp <- dim(Y)[2] Xmeans <- colMeans(X) X <- X - rep(Xmeans, each = nobj) Ymean <- mean(Y) Y <- Y - Ymean A <- ncomp W <- matrix(0, ncol(X), A) TT <- matrix(0, nrow = nrow(X), ncol = A) D2 <- matrix(0, nrow = ncol(X), ncol = A) iD2 <- matrix(0, nrow = ncol(X), ncol = A) iB <- matrix(0, ncol(X), A) iPreds <- matrix(0, nrow(X), A) iResids <- matrix(0, nrow(X), A) tQ <- matrix(0, nrow = A, ncol = 1) out <- NULL W[, 1] <- crossprod(X, Y) W[, 1] <- W[, 1]/sqrt(c(crossprod(W[, 1]))) TT[, 1] <- X %*% W[, 1] D2[1, 1] <- sqrt(c(crossprod(TT[, 1]))) TT[, 1] <- TT[, 1]/D2[1, 1] iD2[1, 1] <- 1/D2[1, 1] q1 <- crossprod(TT[, 1], Y) tQ[1, ] <- q1 if (A == 1) { out <- list(W, D2[1, 1], TT, iD2[1, 1], tQ) } else if (A > 1) { for (a in 2:A) { W[, a] <- crossprod(X, TT[, a - 1]) - D2[a - 1, a - 1] * W[, a - 1] W[, a] <- W[, a] - W[, 1:(a - 1)] %*% crossprod(W[, 1:(a - 1)], W[, a]) D2[a - 1, a] <- -sqrt(c(crossprod(W[, a]))) W[, a] <- W[, a]/D2[a - 1, a] TT[, a] <- (X %*% W[, a]) - D2[a - 1, a] * TT[, a - 1] TT[, a] <- TT[, a] - TT[, 1:(a - 1)] %*% crossprod(TT[, 1:(a - 1)], TT[, a]) D2[a, a] <- sqrt(c(crossprod(TT[, a]))) TT[, a] <- TT[, a]/D2[a, a] iD2[a, a] <- 1/D2[a, a] iD2[1:(a - 1), a] <- iD2[1:(a - 1), a - 1] * (-D2[a - 1, a]/D2[a, a]) q1 <- crossprod(TT[, a], Y) tQ[a, ] <- q1 out <- list(W, D2[1:A, 1:A], TT, iD2[1:A, 1:A], tQ) } } W <- out[[1]] D2 <- as.matrix(out[[2]]) TT <- out[[3]] iD2 <- as.matrix(out[[4]]) tQ <- as.matrix(out[[5]]) P <- crossprod(X, TT) D2.b <- D2 diag(D2.b)[diag(D2.b) < .Machine$double.eps^0.5] <- 1 for (a in 1:A) { P[, a] <- P[, a]/D2.b[a, a] } R <- W %*% iD2 if (A == 1) { iB[, 1] <- W[, 1] * iD2[1, 1] * tQ[1, 1] out.iB <- iB } else { for (a in 2:A) { iB[, 1] <- W[, 1] * iD2[1, 1] * tQ[1, 1] iB[, a] <- R[, 1:a] %*% tQ[1:a, 1] out.iB <- iB } } Betas <- R %*% tQ fitted.pre <- X %*% Betas fitted <- fitted.pre + Ymean Yactual <- Y + Ymean Xdata <- as.data.frame(X) yloadings <- as.matrix(c(tQ)/diag(D2)) if (A == 1) { iPreds[, 1] <- X %*% W[, 1] * iD2[1, 1] * tQ[1, 1] + Ymean out.iPreds <- iPreds } else { for (a in 2:A) { iPreds[, 1] <- X %*% W[, 1] * iD2[1, 1] * tQ[1, 1] + Ymean iPreds[, a] <- X %*% R[, 1:a] %*% tQ[1:a, 1] + Ymean out.iPreds <- iPreds } } if (A == 1) { iResids[, 1] <- Y - (X %*% out.iB[, 1]) out.iResids <- iResids } else { for (a in 2:A) { iResids[, 1] <- Y - (X %*% out.iB[, 1]) iResids[, a] <- Y - (X %*% out.iB)[, a] out.iResids <- iResids } } colnames(out.iB) <- paste("ncomp", 1:A, sep = ".") colnames(out.iPreds) <- paste("ncomp", 1:A, sep = ".") colnames(out.iResids) <- paste("ncomp", 1:A, sep = ".") colnames(R) <- paste("ncomp", 1:A, sep = ".") class(TT) <- "scores" class(P) <- class(q1) <- class(yloadings) <- "loadings" class(W) <- "weights" class(out.iPreds) <- "predict" class(out.iB) <- "coefficients" class(Xmeans) <- "vector" row.names(P) <- dnX row.names(W) <- dnX row.names(out.iB) <- dnX row.names(Betas) <- dnX if (A == 1) { scores <- TT * (diag(D2)) } else { scores <- TT %*% diag(diag(D2)) } Outs <- list(loadings = P, weights = W, D2 = D2, iD2 = iD2, Ymean = Ymean, Xmeans = Xmeans, coefficients = out.iB, y.loadings = yloadings, scores = scores, R = R, Y = Y, Yactual = Yactual, fitted = fitted, residuals = out.iResids, Xdata = Xdata, iPreds = out.iPreds, y.loadings2 = tQ) }
export_table <- function(x, sep = " | ", header = "-", empty_line = NULL, digits = 2, protect_integers = TRUE, missing = "", width = NULL, format = NULL, title = NULL, caption = title, subtitle = NULL, footer = NULL, align = NULL, group_by = NULL, zap_small = FALSE, table_width = NULL, verbose = TRUE) { if (is.null(format)) { format <- "text" } if (format == "md") { format <- "markdown" } if (is.null(x) || (is.data.frame(x) && nrow(x) == 0) || .is_empty_object(x)) { if (isTRUE(verbose)) { message(paste0("Can't export table to ", format, ", data frame is empty.")) } return(NULL) } if (identical(format, "html") && !is.data.frame(x) && is.list(x)) { x <- do.call(rbind, lapply(x, function(i) { attr_name <- .check_caption_attr_name(i) i$Component <- attr(i, attr_name)[1] i })) } indent_groups <- attributes(x)$indent_groups indent_rows <- attributes(x)$indent_rows if (is.data.frame(x)) { if (!is.null(title)) { caption <- title } if (is.null(caption)) { attr_name <- .check_caption_attr_name(x) caption <- attributes(x)[[attr_name]] } if (is.null(subtitle)) { subtitle <- attributes(x)$table_subtitle } if (is.null(footer)) { footer <- attributes(x)$table_footer } out <- .export_table( x = x, sep = sep, header = header, digits = digits, protect_integers = protect_integers, missing = missing, width = width, format = format, caption = caption, subtitle = subtitle, footer = footer, align = align, group_by = group_by, zap_small = zap_small, empty_line = empty_line, indent_groups = indent_groups, indent_rows = indent_rows, table_width = table_width ) } else if (is.list(x)) { l <- .compact_list(x) tmp <- lapply(1:length(l), function(element) { i <- l[[element]] t_footer <- attributes(i)$table_footer if (element == length(l) && is.null(attributes(i)$table_footer) && !is.null(footer) && !is.list(footer)) { t_footer <- footer } if (is.null(t_footer) && !is.null(footer) && is.list(footer) && length(footer) == length(l)) { t_footer <- footer[[element]] } attr_name <- .check_caption_attr_name(i) if (!is.null(title) && is.null(caption)) { caption <- title } t_title <- attributes(i)[[attr_name]] if (element == 1 && is.null(attributes(i)[[attr_name]]) && !is.null(caption) && !is.list(caption)) { t_title <- caption } if (is.null(t_title) && !is.null(caption) && is.list(caption) && length(caption) == length(l)) { t_title <- caption[[element]] } .export_table( x = i, sep = sep, header = header, digits = digits, protect_integers = protect_integers, missing = missing, width = width, format = format, caption = t_title, subtitle = attributes(i)$table_subtitle, footer = t_footer, align = align, group_by = group_by, zap_small = zap_small, empty_line = empty_line, indent_groups = indent_groups, indent_rows = indent_rows, table_width = table_width ) }) out <- c() if (format == "text") { for (i in 1:length(tmp)) { out <- paste0(out, tmp[[i]], "\n") } out <- substr(out, 1, nchar(out) - 1) } else if (format == "markdown") { for (i in 1:length(tmp)) { out <- c(out, tmp[[i]], "") } out <- out[1:(length(out) - 1)] } } else { return(NULL) } if (format == "markdown") { attr(out, "format") <- "pipe" class(out) <- c("knitr_kable", "character") } else if (format == "text") { class(out) <- c("insight_table", class(out)) } out } .check_caption_attr_name <- function(x) { attr_name <- "table_caption" if (is.null(attr(x, attr_name, exact = TRUE)) && !is.null(attr(x, "table_title", exact = TRUE))) { attr_name <- "table_title" } attr_name } .export_table <- function(x, sep = " | ", header = "-", digits = 2, protect_integers = TRUE, missing = "", width = NULL, format = NULL, caption = NULL, subtitle = NULL, footer = NULL, align = NULL, group_by = NULL, zap_small = FALSE, empty_line = NULL, indent_groups = NULL, indent_rows = NULL, table_width = NULL) { df <- as.data.frame(x) if (is.null(width) || length(width) == 1) { col_width <- width } else { col_width <- NULL } col_names <- names(df) df <- as.data.frame(sapply(df, function(i) { if (is.numeric(i)) { format_value(i, digits = digits, protect_integers = protect_integers, missing = missing, width = col_width, zap_small = zap_small ) } else { i } }, simplify = FALSE), stringsAsFactors = FALSE) df <- as.data.frame(sapply(df, as.character, simplify = FALSE), stringsAsFactors = FALSE) names(df) <- col_names df[is.na(df)] <- as.character(missing) if (identical(format, "html")) { out <- .format_html_table( df, caption = caption, subtitle = subtitle, footer = footer, align = align, group_by = group_by, indent_groups = indent_groups, indent_rows = indent_rows ) } else { df <- rbind(colnames(df), df) aligned <- format(df, justify = "right") col_align <- rep("right", ncol(df)) first_row <- as.character(aligned[1, ]) for (i in 1:length(first_row)) { aligned[1, i] <- format(trimws(first_row[i]), width = nchar(first_row[i]), justify = "right") } final <- as.matrix(aligned) if (!is.numeric(x[, 1])) { final[, 1] <- format(trimws(final[, 1]), justify = "left") col_align[1] <- "left" } if (format == "text") { out <- .format_basic_table( final, header, sep, caption = caption, subtitle = subtitle, footer = footer, align = align, empty_line = empty_line, indent_groups = indent_groups, indent_rows = indent_rows, col_names = col_names, col_width = width, col_align = col_align, table_width = table_width ) } else if (format == "markdown") { out <- .format_markdown_table( final, x, caption = caption, subtitle = subtitle, footer = footer, align = align, indent_groups = indent_groups, indent_rows = indent_rows ) } } out } .format_basic_table <- function(final, header, sep, caption = NULL, subtitle = NULL, footer = NULL, align = NULL, empty_line = NULL, indent_groups = NULL, indent_rows = NULL, col_names = NULL, col_width = NULL, col_align = NULL, table_width = NULL) { if (!is.null(align) && length(align) == 1) { for (i in 1:ncol(final)) { align_char <- "" if (align %in% c("left", "right", "center", "firstleft")) { align_char <- "" } else { align_char <- substr(align, i, i) } if (align == "left" || (align == "firstleft" && i == 1) || align_char == "l") { final[, i] <- format(trimws(final[, i]), justify = "left") col_align[i] <- "left" } else if (align == "right" || align_char == "r") { final[, i] <- format(trimws(final[, i]), justify = "right") col_align[i] <- "right" } else { final[, i] <- format(trimws(final[, i]), justify = "centre") col_align[i] <- "centre" } } } if (!is.null(indent_groups) && any(grepl(indent_groups, final[, 1], fixed = TRUE))) { final <- .indent_groups(final, indent_groups) } else if (!is.null(indent_rows) && any(grepl(" final <- .indent_rows(final, indent_rows) } if (!is.null(col_width) && length(col_width) > 1 && !is.null(names(col_width))) { matching_columns <- stats::na.omit(match(names(col_width), col_names)) if (length(matching_columns)) { for (i in matching_columns) { w <- as.vector(col_width[col_names[i]]) final[, i] <- format(trimws(final[, i]), width = w, justify = col_align[i]) } } } final2 <- NULL final3 <- NULL if (identical(table_width, "auto") || (!is.null(table_width) && is.numeric(table_width))) { if (is.numeric(table_width)) { line_width <- table_width } else { line_width <- options()$width } row_width <- nchar(paste0(final[1, ], collapse = sep)) if (row_width > line_width) { i <- 1 while (nchar(paste0(final[1, 1:i], collapse = sep)) < line_width) { i <- i + 1 } if (i > 2 && i < ncol(final)) { final2 <- final[, c(1, i:ncol(final))] final <- final[, 1:(i - 1)] } } row_width <- nchar(paste0(final2[1, ], collapse = sep)) if (row_width > line_width) { i <- 1 while (nchar(paste0(final2[1, 1:i], collapse = sep)) < line_width) { i <- i + 1 } if (i > 2 && i < ncol(final2)) { final3 <- final2[, c(1, i:ncol(final2))] final2 <- final2[, 1:(i - 1)] } } } rows <- .table_parts(c(), final, header, sep, empty_line) if (!is.null(final2)) { rows <- .table_parts(paste0(rows, "\n"), final2, header, sep, empty_line) } if (!is.null(final3)) { rows <- .table_parts(paste0(rows, "\n"), final3, header, sep, empty_line) } if (!is.null(caption) && caption[1] != "") { if (length(caption) == 2 && .is_valid_colour(caption[2])) { caption <- .colour(caption[2], caption[1]) } if (!is.null(subtitle)) { if (length(subtitle) == 2 && .is_valid_colour(subtitle[2])) { subtitle <- .colour(subtitle[2], subtitle[1]) } } else { subtitle <- "" } title_line <- .trim(paste0(caption[1], " ", subtitle[1])) title_line <- gsub(" ", " ", title_line, fixed = TRUE) rows <- paste0(title_line, "\n\n", rows) } if (!is.null(footer)) { if (is.list(footer)) { for (i in footer) { rows <- .paste_footers(i, rows) } } else { rows <- .paste_footers(footer, rows) } } rows } .table_parts <- function(rows, final, header, sep, empty_line) { for (row in 1:nrow(final)) { final_row <- paste0(final[row, ], collapse = sep) if (!is.null(empty_line) && all(nchar(trimws(final[row, ])) == 0)) { rows <- paste0(rows, paste0(rep_len(empty_line, nchar(final_row)), collapse = ""), sep = "\n") } else { rows <- paste0(rows, final_row, sep = "\n") } if (row == 1) { if (!is.null(header)) { rows <- paste0(rows, paste0(rep_len(header, nchar(final_row)), collapse = ""), sep = "\n") } } } rows } print.insight_table <- function(x, ...) { cat(x) invisible(x) } .paste_footers <- function(footer, rows) { if (.is_empty_string(footer)) { return(rows) } if (length(footer) == 2 && .is_valid_colour(footer[2])) { footer <- .colour(footer[2], footer[1]) } paste0(rows, footer[1]) } .indent_groups <- function(final, indent_groups) { whitespace <- sprintf("%*s", nchar(indent_groups), " ") grps <- grep(indent_groups, final[, 1], fixed = TRUE) grp_rows <- seq(grps[1], nrow(final)) grp_rows <- grp_rows[!grp_rows %in% grps] final[grp_rows, 1] <- paste0(whitespace, final[grp_rows, 1]) final[, 1] <- gsub(indent_groups, "", final[, 1], fixed = TRUE) final[, 1] <- trimws(final[, 1], which = "right") final[, 1] <- format(final[, 1], justify = "left", width = max(nchar(final[, 1]))) final } .indent_rows <- function(final, indent_rows, whitespace = " ") { grp_rows <- indent_rows + 1 final[grp_rows, 1] <- paste0(whitespace, final[grp_rows, 1]) non_grp_rows <- 1:nrow(final) non_grp_rows <- non_grp_rows[!non_grp_rows %in% grp_rows] final[non_grp_rows, 1] <- paste0(final[non_grp_rows, 1], whitespace) grps <- grep(" final[, 1] <- gsub(" final[grps, 1] <- format(final[grps, 1], justify = "left", width = max(nchar(final[, 1]))) final } .indent_rows_html <- function(final, indent_rows, whitespace = "") { grp_rows <- indent_rows + 1 final[grp_rows, 1] <- paste0(whitespace, final[grp_rows, 1]) non_grp_rows <- 1:nrow(final) non_grp_rows <- non_grp_rows[!non_grp_rows %in% grp_rows] final[, 1] <- gsub(" final } .format_markdown_table <- function(final, x, caption = NULL, subtitle = NULL, footer = NULL, align = NULL, indent_groups = NULL, indent_rows = NULL) { column_width <- nchar(final[1, ]) n_columns <- ncol(final) first_row_leftalign <- (!is.null(align) && align == "firstleft") header <- "|" if (!is.null(indent_rows) || !is.null(indent_groups)) { column_width[1] <- column_width[1] + 2 } for (i in 1:n_columns) { line <- paste0(rep_len("-", column_width[i]), collapse = "") align_char <- "" if (!is.null(align)) { if (align %in% c("left", "right", "center", "firstleft")) { align_char <- "" } else { align_char <- substr(align, i, i) } } if (is.null(align)) { if (grepl("^\\s", final[2, i])) { line <- paste0(line, ":") final[, i] <- format(final[, i], width = column_width[i] + 1, justify = "right") } else { line <- paste0(":", line) final[, i] <- format(final[, i], width = column_width[i] + 1, justify = "left") } } else if (align == "left" || (first_row_leftalign && i == 1) || align_char == "l") { line <- paste0(":", line) final[, i] <- format(final[, i], width = column_width[i] + 1, justify = "left") } else if (align == "right" || align_char == "r") { line <- paste0(line, ":") final[, i] <- format(final[, i], width = column_width[i] + 1, justify = "right") } else { line <- paste0(":", line, ":") final[, i] <- format(final[, i], width = column_width[i] + 2, justify = "centre") } header <- paste0(header, line, "|") } if (!is.null(indent_groups) && any(grepl(indent_groups, final[, 1], fixed = TRUE))) { final <- .indent_groups(final, indent_groups) } else if (!is.null(indent_rows) && any(grepl(" final <- .indent_rows(final, indent_rows) } rows <- c() for (row in 1:nrow(final)) { final_row <- paste0("|", paste0(final[row, ], collapse = "|"), "|", collapse = "") rows <- c(rows, final_row) if (row == 1) { rows <- c(rows, header) } } if (!is.null(caption)) { if (!is.null(subtitle)) { caption[1] <- paste0(caption[1], " ", subtitle[1]) } rows <- c(paste0("Table: ", .trim(caption[1])), "", rows) } if (!is.null(footer)) { if (is.list(footer)) { for (i in footer) { if (!.is_empty_string(i)) { rows <- c(rows, i[1]) } } } else if (!.is_empty_string(footer)) { rows <- c(rows, footer[1]) } } rows } .format_html_table <- function(final, caption = NULL, subtitle = NULL, footer = NULL, align = "center", group_by = NULL, indent_groups = NULL, indent_rows = NULL) { check_if_installed("gt") if (is.null(align)) { align <- "firstleft" } group_by_columns <- c(intersect(c("Group", "Response", "Effects", "Component"), names(final)), group_by) if (!length(group_by_columns)) { group_by_columns <- NULL } else { for (i in group_by_columns) { if (.n_unique(final[[i]]) <= 1) { final[[i]] <- NULL } } } if (!is.null(indent_rows) && any(grepl(" final <- .indent_rows_html(final, indent_rows) } tab <- gt::gt(final, groupname_col = group_by_columns) header <- gt::tab_header(tab, title = caption, subtitle = subtitle) footer <- gt::tab_source_note(header, source_note = footer) out <- gt::cols_align(footer, align = "center") if (!is.null(out[["_boxhead"]]) && !is.null(out[["_boxhead"]]$column_align)) { if (align == "firstleft") { out[["_boxhead"]]$column_align[1] <- "left" } else { col_align <- c() for (i in 1:nchar(align)) { col_align <- c(col_align, switch(substr(align, i, i), "l" = "left", "r" = "right", "center" )) } out[["_boxhead"]]$column_align <- col_align } } out }
NULL methods::setMethod("cutpoints", methods::signature(object = "glmdisc"), function(object) { cutpoints <- list() for (j in which(object@parameters$types_data == "factor")) { cutpoints[[j]] <- apply(prop.table([email protected]$bestLinkFunction[[j]], 2), 2, which.max) } for (j in which(object@parameters$types_data == "numeric")) { data_disc <- data.frame(disc = [email protected][, j], cont = [email protected][, j], stringsAsFactors = TRUE) cut1 <- stats::aggregate(cont ~ disc, data = data_disc, min) cut2 <- stats::aggregate(cont ~ disc, data = data_disc, max) cut1 <- cut1[order(cut1$cont), ] cut2 <- cut2[order(cut2$cont), ] cut1 <- cut1[-1, ] cut2 <- cut2[-nrow(cut2), ] cutpoints[[j]] <- rowMeans(cbind(cut1$cont, cut2$cont)) } names(cutpoints) <- colnames([email protected])[-ncol([email protected])] return(cutpoints) })
context("Test results of cs_per() function") cs.per_result1 <- cs_per(x = seq(0, 1, by = 0.001), knots = 5) cs.per_result2 <- cs_per(seq(0, 1, by = 0.001), knots = 8) set.seed(12345) cs.per_result3 <- cs_per(runif(1000), knots = 5) test_that("cs.per_result1 is as expected", { expect_equal_to_reference(cs.per_result1, file = "cs.per_result1.rds") }) test_that("cs.per_result2 is as expected", { expect_equal_to_reference(cs.per_result2, file = "cs.per_result2.rds") }) test_that("cs.per_result3 is as expected", { expect_equal_to_reference(cs.per_result3, file = "cs.per_result3.rds") })
tar_test("create tar_resources_aws object", { x <- resources_aws_init(bucket = "bucket_name") expect_silent(resources_validate(x)) }) tar_test("prohibit empty tar_resources_aws object", { x <- resources_aws_init(bucket = "", prefix = NULL) expect_error(resources_validate(x), class = "tar_condition_validate") }) tar_test("print tar_resources_aws object", { x <- resources_aws_init(bucket = "bucket_name") out <- utils::capture.output(print(x)) expect_true(any(grepl("tar_resources_aws", out))) })
linequad <- function(X, Y, ..., eps=NULL, nd=1000, random=FALSE) { epsgiven <- !is.null(eps) if(is.lpp(X)) { coo <- coords(X) mapXY <- coo$seg tp <- coo$tp Xproj <- as.ppp(X) if(!missing(Y) && !is.null(Y)) warning("Argument Y ignored when X is an lpp object") Y <- as.psp(X) } else if(is.ppp(X)) { stopifnot(is.psp(Y)) v <- project2segment(X, Y) Xproj <- v$Xproj mapXY <- v$mapXY tp <- v$tp } else stop("X should be an object of class lpp or ppp") ismulti <- is.multitype(X) if(is.marked(X) && !ismulti) stop("Not implemented for marked patterns") if(ismulti) { marx <- marks(X) flev <- factor(levels(marx)) } win <- as.owin(Y) len <- lengths_psp(Y) nseg <- length(len) if(is.null(eps)) { stopifnot(is.numeric(nd) && length(nd) == 1L & is.finite(nd) && nd > 0) eps <- sum(len)/nd } else stopifnot(is.numeric(eps) && length(eps) == 1L && is.finite(eps) && eps > 0) if(is.lpp(X) && spatstat.options('Clinequad')) { L <- as.linnet(X) W <- Frame(L) V <- vertices(L) nV <- npoints(V) coordsV <- coords(V) coordsX <- coords(X) nX <- npoints(X) ooX <- order(coordsX$seg) ndumeach <- ceiling(len/eps) + 1L ndummax <- sum(ndumeach) maxdataperseg <- max(table(factor(coordsX$seg, levels=1:nsegments(L)))) maxscratch <- max(ndumeach) + maxdataperseg if(!ismulti) { if(!random) { z <- .C(SL_Clinequad, ns = as.integer(nseg), from = as.integer(L$from-1L), to = as.integer(L$to-1L), nv = as.integer(nV), xv = as.double(coordsV$x), yv = as.double(coordsV$y), eps = as.double(eps), ndat = as.integer(nX), sdat = as.integer(coordsX$seg[ooX]-1L), tdat = as.double(coordsX$tp[ooX]), wdat = as.double(numeric(nX)), ndum = as.integer(integer(1L)), xdum = as.double(numeric(ndummax)), ydum = as.double(numeric(ndummax)), sdum = as.integer(integer(ndummax)), tdum = as.double(numeric(ndummax)), wdum = as.double(numeric(ndummax)), maxscratch = as.integer(maxscratch), PACKAGE="spatstat.linnet") } else { z <- .C(SL_ClineRquad, ns = as.integer(nseg), from = as.integer(L$from-1L), to = as.integer(L$to-1L), nv = as.integer(nV), xv = as.double(coordsV$x), yv = as.double(coordsV$y), eps = as.double(eps), ndat = as.integer(nX), sdat = as.integer(coordsX$seg[ooX]-1L), tdat = as.double(coordsX$tp[ooX]), wdat = as.double(numeric(nX)), ndum = as.integer(integer(1L)), xdum = as.double(numeric(ndummax)), ydum = as.double(numeric(ndummax)), sdum = as.integer(integer(ndummax)), tdum = as.double(numeric(ndummax)), wdum = as.double(numeric(ndummax)), maxscratch = as.integer(maxscratch), PACKAGE="spatstat.linnet") } seqdum <- seq_len(z$ndum) dum <- with(z, ppp(xdum[seqdum], ydum[seqdum], window=W, check=FALSE)) wdum <- z$wdum[seqdum] wdat <- numeric(nX) wdat[ooX] <- z$wdat dat <- as.ppp(X) } else { ntypes <- length(flev) ndummax <- ntypes * (ndummax + nX) maxscratch <- ntypes * maxscratch if(!random) { z <- .C(SL_ClineMquad, ns = as.integer(nseg), from = as.integer(L$from-1L), to = as.integer(L$to-1L), nv = as.integer(nV), xv = as.double(coordsV$x), yv = as.double(coordsV$y), eps = as.double(eps), ntypes = as.integer(ntypes), ndat = as.integer(nX), xdat = as.double(coordsX$x), ydat = as.double(coordsX$y), mdat = as.integer(as.integer(marx)-1L), sdat = as.integer(coordsX$seg[ooX]-1L), tdat = as.double(coordsX$tp[ooX]), wdat = as.double(numeric(nX)), ndum = as.integer(integer(1L)), xdum = as.double(numeric(ndummax)), ydum = as.double(numeric(ndummax)), mdum = as.integer(integer(ndummax)), sdum = as.integer(integer(ndummax)), tdum = as.double(numeric(ndummax)), wdum = as.double(numeric(ndummax)), maxscratch = as.integer(maxscratch), PACKAGE="spatstat.linnet") } else { z <- .C(SL_ClineRMquad, ns = as.integer(nseg), from = as.integer(L$from-1L), to = as.integer(L$to-1L), nv = as.integer(nV), xv = as.double(coordsV$x), yv = as.double(coordsV$y), eps = as.double(eps), ntypes = as.integer(ntypes), ndat = as.integer(nX), xdat = as.double(coordsX$x), ydat = as.double(coordsX$y), mdat = as.integer(as.integer(marx)-1L), sdat = as.integer(coordsX$seg[ooX]-1L), tdat = as.double(coordsX$tp[ooX]), wdat = as.double(numeric(nX)), ndum = as.integer(integer(1L)), xdum = as.double(numeric(ndummax)), ydum = as.double(numeric(ndummax)), mdum = as.integer(integer(ndummax)), sdum = as.integer(integer(ndummax)), tdum = as.double(numeric(ndummax)), wdum = as.double(numeric(ndummax)), maxscratch = as.integer(maxscratch), PACKAGE="spatstat.linnet") } seqdum <- seq_len(z$ndum) marques <- factor(z$mdum[seqdum] + 1L, labels=flev) dum <- with(z, ppp(xdum[seqdum], ydum[seqdum], marks=marques, window=W, check=FALSE)) wdum <- z$wdum[seqdum] wdat <- numeric(nX) wdat[ooX] <- z$wdat dat <- as.ppp(X) } } else { dat <- dum <- ppp(numeric(0), numeric(0), window=win) wdat <- wdum <- numeric(0) if(ismulti) marks(dat) <- marks(dum) <- marx[integer(0)] YY <- as.data.frame(Y) for(i in 1:nseg) { leni <- len[i] nwhole <- floor(leni/eps) if(leni/eps - nwhole < 0.5 && nwhole > 2) nwhole <- nwhole - 1 rump <- (leni - nwhole * eps)/2 brks <- c(0, rump + (0:nwhole) * eps, leni) nbrks <- length(brks) sdum <- (brks[-1L] + brks[-nbrks])/2 x <- with(YY, x0[i] + (sdum/leni) * (x1[i]-x0[i])) y <- with(YY, y0[i] + (sdum/leni) * (y1[i]-y0[i])) newdum <- list(x=x, y=y) ndum <- length(sdum) IDdum <- 1:ndum relevant <- (mapXY == i) newdat <- Xproj[relevant] sdat <- leni * tp[relevant] IDdat <- findInterval(sdat, brks, rightmost.closed=TRUE, all.inside=TRUE) w <- countingweights(id=c(IDdum, IDdat), areas=diff(brks)) wnewdum <- w[1:ndum] wnewdat <- w[-(1:ndum)] if(!ismulti) { dat <- superimpose(dat, newdat, W=win, check=FALSE) dum <- superimpose(dum, newdum, W=win, check=FALSE) wdat <- c(wdat, wnewdat) wdum <- c(wdum, wnewdum) } else { marks(newdat) <- marx[relevant] dat <- superimpose(dat, newdat, W=win, check=FALSE) wdat <- c(wdat, wnewdat) newdum <- as.ppp(newdum, W=win, check=FALSE) for(k in seq_len(length(flev))) { le <- flev[k] avoid <- (marks(newdat) != le) dum <- superimpose(dum, newdum %mark% le, newdat[avoid] %mark% le, W=win, check=FALSE) wdum <- c(wdum, wnewdum, wnewdat[avoid]) } } } } dmethod <- paste("Equally spaced along each segment at spacing eps =", signif(eps, 4), summary(unitname(X))$plural) if(!epsgiven) dmethod <- paste0(dmethod, "\nOriginal parameter nd = ", nd) wmethod <- "Counting weights based on segment length" param <- list(dummy = list(method=dmethod), weight = list(method=wmethod)) Qout <- quad(dat, dum, c(wdat, wdum), param=param) attr(Qout, "lines") <- Y return(Qout) }
test_that("check slide selection", { x <- read_pptx() x <- add_slide(x, "Title and Content", "Office Theme") x <- ph_with(x, "Hello world 1", location = ph_location_type(type = "body")) x <- add_slide(x, "Title and Content", "Office Theme") x <- ph_with(x, "Hello world 2", location = ph_location_type(type = "body")) x <- add_slide(x, "Title and Content", "Office Theme") x <- ph_with(x, "Hello world 3", location = ph_location_type(type = "body")) x <- on_slide(x, index = 1) sm <- slide_summary(x) expect_equal(sm[1,]$text, "Hello world 1") x <- on_slide(x, index = 2) sm <- slide_summary(x) expect_equal(sm[1, ]$text, "Hello world 2") x <- on_slide(x, index = 3) sm <- slide_summary(x) expect_equal(sm[1, ]$text, "Hello world 3") }) test_that("check errors", { x <- read_pptx() expect_error(slide_summary(x), "presentation contains no slide") expect_error(remove_slide(x), "presentation contains no slide to delete") expect_error(on_slide(x, index = 1), "presentation contains no slide") x <- add_slide(x, "Title and Content", "Office Theme") x <- ph_with(x, "Hello world", location = ph_location_type(type = "body")) x <- ph_with(x, "my title", location = ph_location_type(type = "title")) x <- add_slide(x, "Title and Content", "Office Theme") x <- ph_with(x, "Hello world", location = ph_location_type(type = "body")) x <- ph_with(x, "my title 2", location = ph_location_type(type = "title")) expect_error(on_slide(x, index = 3), "unvalid index 3") expect_error(remove_slide(x, index = 3), "unvalid index 3") expect_error(slide_summary(x, index = 3), "unvalid index 3") }) test_that("get shape id", { doc <- read_pptx() doc <- add_slide(doc, "Title and Content", "Office Theme") doc <- ph_with(doc, "hello", location = ph_location_type(type = "body")) expect_equal(officer:::get_shape_id(doc, type = "body", id = 1), "2") expect_equal(officer:::get_shape_id(doc, ph_label = "Content Placeholder 2", id = 1), "2") expect_error(officer:::get_shape_id(doc, type = "body", id = 4) ) }) unlink("*.pptx")
.packageName<-"argosfilter" internal.angles<-function(lat, lon) { bn<-bearingTrack(lat,lon) bn[1:10] bn<-c(bn,0) bp2<-bearingTrack(rev(lat),rev(lon)) bp<-rev(bp2) bp<-c(0,bp) bp[1:10] ang<-numeric(length(lat)) for (i in 2:(length(lat)-1)) { if (lat[i]==lat[i+1]&lon[i]==lon[i+1] | lat[i]==lat[i-1]&lon[i]==lon[i-1]) ang[i]<-180 else { ang[i]<-abs(bp[i]-bn[i]) if (ang[i]>180) ang[i]<-(360-ang[i]) else ang[i]<-ang[i] } } ang[1:10] ang }
data_template <- function(x = NULL, read_fun = "read.csv", read_args = NULL) { if(is.null(x)) { x <- data.frame( matrix(rep("", 100), ncol = 10, nrow = 10, dimnames = list(1:10, paste0("V", 1:10))), stringsAsFactors = FALSE, check.names = FALSE ) } else if(is.null(dim(x))) { if(is.numeric(x)) { x <- rep(x, length.out = 2) x <- data.frame( structure( rep(list(rep("", x[1])), x[2]), names = paste0("V", seq_len(x[2])) ), stringsAsFactors = FALSE, check.names = FALSE ) } else if(is.character(x)) { if(length(x) == 1 & nzchar(file_ext(x[1]))) { x <- do.call( read_fun, c( list(x), read_args ) ) } else { x <- data.frame( structure( rep(list(""), length(x)), names = x ), stringsAsFactors = FALSE ) } } } if(is.null(rownames(x))) { rownames(x) <- seq_len(nrow(x)) } return(x) } data_format <- function(data, data_class = NULL, col_factor = FALSE) { if(!is.null(data)) { if(!nzchar(trimws(colnames(data)[1]))) { new_row_names <- data[, 1] ind <- which(is.na(new_row_names)) if(length(ind) > 0) { new_row_names[ind] <- rev( seq( nrow(data), nrow(data) - length(ind) + 1, -1 ) ) } if (length(unique(new_row_names)) != length(new_row_names)) { message("Storing non-unique row names in the first column of data.") colnames(data)[1] <- "rownames" } else { rownames(data) <- new_row_names data <- data[, -1, drop = FALSE] } } else { } if("matrix" %in% data_class) { data <- as.matrix(data) } else { for (z in colnames(data)) { data[, z] <- type.convert(data[, z], as.is = !col_factor) } } } return(data) } data_bind_cols <- function(data = NULL, col_bind = NULL) { if(!is.null(data)) { if (!is.null(col_bind)) { if (is.null(dim(col_bind))) { if (class(col_bind) == "list") { if (is.null(names(col_bind))) { names(col_bind) <- paste0("V", length(col_bind)) } ind <- which(!unlist(lapply(col_bind, length)) == nrow(data)) if (length(ind) > 0) { for (z in ind) { col_bind[[z]] <- rep(col_bind[[z]], nrow(data)) } } col_bind <- do.call("cbind", col_bind) } else { col_bind <- matrix(rep("", nrow(data) * length(col_bind)), ncol = length(col_bind), dimnames = list( rownames(data), col_bind ) ) } } data <- cbind( data, col_bind[1:nrow(data), , drop = FALSE] ) } } return(data) } data_bind_rows <- function(data = NULL, row_bind = NULL) { if(!is.null(data)) { if (!is.null(row_bind)) { if (is.null(dim(row_bind))) { if (class(row_bind) == "list") { ind <- which(!unlist(lapply(row_bind, length)) == ncol(data)) if (length(ind) > 0) { for (z in ind) { row_bind[[z]] <- rep(row_bind[[z]], ncol(data)) } } row_bind <- do.call("rbind", row_bind) } else { row_bind <- matrix(rep("", ncol(data) * length(row_bind)), nrow = length(row_bind), dimnames = list( row_bind, colnames(data) ) ) } } data <- rbind(data, row_bind[, 1:ncol(data)]) } } return(data) }
"fevd.svecest" <- function(x, n.ahead=10, ...){ if(!(class(x)=="svecest")){ stop("\nPlease provide an object of class 'svecest', generated by 'SVEC()'.\n") } n.ahead <- abs(as.integer(n.ahead)) ifelse(is.null(x$call$r), r <- 1, r <- x$call$r) varlevel <- vec2var(x$var, r = r) K <- varlevel$K p <- varlevel$p ynames <- colnames(varlevel$datamat[, 1 : K]) msey <- .fecovsvec(x, n.ahead = n.ahead, K = K) Phi <- Phi(x, nstep = n.ahead) mse <- matrix(NA, nrow = n.ahead, ncol = K) Omega <- array(0, dim = c(n.ahead, K, K)) for(i in 1 : n.ahead){ mse[i, ] <- diag(msey[, , i]) temp <- matrix(0, K, K) for(j in 1 : i){ temp <- temp + Phi[ , , j]^2 } temp <- temp / mse[i, ] for(j in 1 : K){ Omega[i, ,j] <- temp[j, ] } } result <- list() for(i in 1 : K){ result[[i]] <- matrix(Omega[, , i], nrow = n.ahead, ncol = K) colnames(result[[i]]) <- ynames } names(result) <- ynames class(result) <- "varfevd" return(result) }
mkM2U <- function(df, vN, low, high, delta, alpha=2, ...) { ii <- df[[vN]] if (missing(low)) low <- min(df$time) if (missing(high)) high <- max(df$time) if (missing(delta)) { iii <- sort(diff(sort(unique(ii)))) delta <- min(iii[iii>=diff(range(iii))/1000]) rm(iii) } iiD <- c(min(df[[vN]])-.Machine$double.eps, max(df[[vN]])+.Machine$double.eps) iiRef <- ii[low <= df$time & df$time <= high] rm(df,ii,low,high) iiB <- seq(iiD[1],iiD[2]+delta,delta) iiH <- as.data.frame(hist(iiRef,breaks=iiB,plot=FALSE)[c("mids","counts")]) names(iiH) <- c("x","counts") riiD <- range(iiH$x)+delta*c(-1,1)/2 ii.fit <- ssden(~x, data=iiH, domain=data.frame(x=riiD), weights=iiH$counts,alpha=alpha, ... ) rm(iiH,iiB,iiRef,iiD) mn <- min(ii.fit$domain) mx <- max(ii.fit$domain) Z <- integrate(function(x) dssden(ii.fit,x),mn,mx,subdivisions=1000)$value dFct <- function(x) { result <- numeric(length(x)) good <- mn <= x & x <= mx if (any(good)) result[good] <- dssden(ii.fit,x[good])/Z result } Q <- seq(mn,mx,len=101) P <- numeric(101) for (i in 2:101) P[i] <- P[i-1] + integrate(dFct,Q[i-1],Q[i])$value result <- function(q,...) { order.q <- rank(q) p <- q <- sort(q) q.dup <- duplicated(q) p[q <= mn] <- 0 p[q >= mx] <- 1 kk <- (1:length(q))[q > mn & q < mx] p.dup <- 0 for (i in kk) { if (q.dup[i]) { p[i] <- p.dup next } idx <- findInterval(q[i],Q) lwr <- Q[idx] if (q[i]-lwr < 1e-5) { p[i] <- P[idx]+(P[idx+1]-P[idx])/(Q[idx+1]-lwr)*(q[i]-lwr) } else { p[i] <- integrate(dFct, lower = lwr, upper = q[i], ...)$value + P[idx] p.dup <- p[i] } } p[order.q] } qFct <- function(p,...) { q <- p <- sort(p) p.dup <- duplicated(p) q[p<=0] <- mn q[p>=1] <- mx kk <- (1:length(p))[p > 0 & p < 1] for (i in kk) { if (p.dup[i]) { q[i] <- q[i-1] } else { idx <- findInterval(p[i],P) if (identical(p[i],P[idx])) { q[i] <- Q[idx] } else { q[i] <- uniroot(function(x) result(x) - p[i],Q[idx:(idx+1)],...)$root } } } q } attr(result,"qFct") <- qFct attr(result,"dFct") <- dFct attr(result,"range") <- riiD attr(result,"call") <- match.call() result } mkAR <- function(df, low, high, max.order, selfName="lN.1", ... ) { if (missing(low)) low <- min(df$time) - .Machine$double.eps if (missing(high)) high <- max(df$time) + .Machine$double.eps vNames <- paste("i",1:max.order,sep="") vNames2 <- paste("i",1:max.order,"t",sep="") for (i in 1:max.order) df[[vNames[i]]] <- isi(df,lag=i) df <- df[complete.cases(df),] m2uL <- mkM2U(df,selfName,low,high,...) m2uI <- mkM2U(df,"i1",low,high,...) df <- within(df, est <- m2uL(lN.1)) for (i in 1:max.order) df[[vNames2[i]]] <- m2uI(df[[vNames[i]]]) for (i in 1:max.order) df[[vNames[i]]] <- NULL fmla <- as.formula(paste("event ~ est+", paste(vNames2, collapse= "+"))) attr(df,"fmla") <- fmla attr(df,"m2uL") <- m2uL attr(df,"m2uI") <- m2uI attr(df,"call") <- match.call() df } changeScale <- function(obj, xFct, yFct ) { if (!inherits(obj,"quickPredict")) stop("obj should be a quickPredict object.") if (missing(xFct)) xFct <- function(x) x if (missing(yFct)) yFct <- function(y) y est.mean <- obj$est.mean if (!is.null(obj$est.sd)) { est.sd <- obj$est.sd } else { est.sd <- NULL } theCall <- match.call() theCall[["obj"]] <- obj$call xx <- xFct(obj$xx) n <- length(xx) equal2min <- sum(abs(xx-min(xx)) <= .Machine$double.eps) equal2max <- sum(abs(xx-max(xx)) <= .Machine$double.eps) goodX <- !logical(n) if (equal2min > 1) goodX[1:(equal2min-1)] <- FALSE if (equal2max > 1) goodX[(n-equal2max+2):n] <- FALSE est.mean <- est.mean[goodX,] if (!is.null(est.sd)) est.sd <- est.sd[goodX,] xx <- xx[goodX] goodX <- !duplicated(xx) xx <- xx[goodX] est.mean <- est.mean[goodX,] if (!is.null(est.sd)) est.sd <- est.sd[goodX,] yy <- yFct(obj$yy) equal2min <- sum(abs(yy-min(yy)) <= .Machine$double.eps) equal2max <- sum(abs(yy-max(yy)) <= .Machine$double.eps) goodY <- !logical(n) if (equal2min > 1) goodY[1:(equal2min-1)] <- FALSE if (equal2max > 1) goodY[(n-equal2max+2):n] <- FALSE est.mean <- est.mean[,goodY] if (!is.null(est.sd)) est.sd <- est.sd[,goodY] yy <- yy[goodY] goodY <- !duplicated(yy) yy <- yy[goodY] est.mean <- est.mean[,goodY] if (!is.null(est.sd)) est.sd <- est.sd[,goodY] result <- list(xx=xx, yy=yy, call=theCall, include=obj$include, est.mean=est.mean, est.sd=est.sd) class(result) <- "quickPredict" result }
setClass("AffineTransformation", representation(), contains = "Cartesian2DCoordinateTransformation", validity = function(object) { if (length(object@parameters) == 0){ if (nrow(object@controlPoints) < 3) stop("At least 3 control points (rows in the data.frame 'controlPoints') are required for the affine transformation") } else if (length(object@parameters) != 6){ stop("Affine transformations require 6 parameters!") } return(TRUE) } )
"UserGS"
model.frame.dyn <- function (formula, data = NULL, ...) { if (!inherits(formula, "formula")) { if (nargs() == 1) return(NextMethod("model.frame", formula)) return(NextMethod("model.frame", formula, data = data, ...)) } class(formula) <- "formula" if (is.null(data)) data <- parent.frame() env <- environment(formula) .Class <- if (is.environment(data) || is.list(data)) class(eval(as.list(formula)[[2]], data, env)) else class(data) mf <- NextMethod("model.frame", formula, data = data, ...) attr(mf, ".Class") <- .Class predvars <- attr(attr(mf, "terms"), "predvars") attr(mf, "series") <- eval(predvars, as.list(data), env) for(i in seq(mf)) if (!inherits(mf[[i]], "factor")) mf[[i]] <- coredata(mf[[i]]) mf } model.frame.zooreg <- model.frame.ts <- model.frame.irts <- model.frame.its <- model.frame.zoo <- function (formula, data = NULL, ...) { if (is.environment(data)) formula <- terms(formula, data = data) else { data <- as.list(data) data1 <- as.data.frame(lapply(data, "[", 1)) names(data1) <- names(data) formula <- terms(formula, data = data1) } cl <- attr(formula, "variables") cl[[1]] <- as.name("merge.zoo") cl$retclass <- "data.frame" cl$retclass <- "list" cl$all <- TRUE attr(formula, "predvars") <- as.call(cl) NextMethod("model.frame", formula, data = data, ...) } model.matrix.dyn <- function(object, ...) { model.matrix(terms(object), model.frame(object), ...) }
rxodeTest({ if (requireNamespace("units", quietly = TRUE)) { context("tad family of functions with odes") library(units) test_that("tad family works with ode", { mod1 <- RxODE({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 C2 <- centr / V2 C3 <- peri / V3 d / dt(depot) <- -KA * depot d / dt(centr) <- KA * depot - CL * C2 - Q * C2 + Q * C3 d / dt(peri) <- Q * C2 - Q * C3 d / dt(eff) <- Kin - Kout * (1 - C2 / (EC50 + C2)) * eff tad <- tad() dosen <- dosenum() tl <- tlast() tafd <- tafd() tfirst <- tfirst() tl <- tlast() tadd <- tad(depot) tfirstd <- tfirst(depot) tlastd <- tlast(depot) tafdd <- tafd(depot) tadp <- tad(peri) tafdp <- tafd(peri) tfirstp <- tfirst(peri) tlastp <- tlast(peri) }) ev <- et(amountUnits = "mg", timeUnits = "hours") %>% et(time = 1, amt = 10000, addl = 9, ii = 12, cmt = "depot") %>% et(time = 120, amt = 2000, addl = 4, ii = 14, cmt = "depot") %>% et(time = 122, amt = 2000, addl = 4, ii = 14, cmt = "peri") %>% et(0, 240, by = 3) r1 <- rxSolve(mod1, ev, addDosing = TRUE) expect_equal(r1$dosen, c( 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 14, 15, 16, 16, 16, 16, 16, 17, 17, 18, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 )) expect_equal( r1$tad, c( NA, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 0, 0, 0, 1, 4, 7, 10, 0, 1, 0, 2, 5, 8, 11, 0, 0, 0, 3, 6, 9, 0, 0, 0, 1, 4, 7, 10, 0, 1, 0, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62 ) ) expect_equal(r1$tafd, c( NA, 0, 2, 5, 8, 11, 12, 14, 17, 20, 23, 24, 26, 29, 32, 35, 36, 38, 41, 44, 47, 48, 50, 53, 56, 59, 60, 62, 65, 68, 71, 72, 74, 77, 80, 83, 84, 86, 89, 92, 95, 96, 98, 101, 104, 107, 108, 110, 113, 116, 119, 119, 121, 122, 125, 128, 131, 133, 134, 135, 137, 140, 143, 146, 147, 149, 149, 152, 155, 158, 161, 161, 163, 164, 167, 170, 173, 175, 176, 177, 179, 182, 185, 188, 191, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 230, 233, 236, 239 )) expect_equal( r1$tadd, c( NA, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 11, 0, 2, 5, 8, 0, 0, 2, 3, 6, 9, 12, 0, 1, 2, 4, 7, 10, 13, 0, 2, 2, 5, 8, 11, 0, 0, 2, 3, 6, 9, 12, 0, 1, 2, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64 ) ) expect_equal(r1$tafdd, c( NA, 0, 2, 5, 8, 11, 12, 14, 17, 20, 23, 24, 26, 29, 32, 35, 36, 38, 41, 44, 47, 48, 50, 53, 56, 59, 60, 62, 65, 68, 71, 72, 74, 77, 80, 83, 84, 86, 89, 92, 95, 96, 98, 101, 104, 107, 108, 110, 113, 116, 119, 119, 121, 122, 125, 128, 131, 133, 134, 135, 137, 140, 143, 146, 147, 149, 149, 152, 155, 158, 161, 161, 163, 164, 167, 170, 173, 175, 176, 177, 179, 182, 185, 188, 191, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 230, 233, 236, 239 )) expect_equal( r1$tadp, c( NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0, 1, 4, 7, 10, 12, 13, 0, 2, 5, 8, 11, 12, 0, 0, 3, 6, 9, 12, 12, 0, 1, 4, 7, 10, 12, 13, 0, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62 ) ) expect_equal(r1$tfirst[1], NA_real_) expect_true(all(r1$tfirst[-1] == 1)) expect_equal( r1$tl, c( NA, 1, 1, 1, 1, 1, 13, 13, 13, 13, 13, 25, 25, 25, 25, 25, 37, 37, 37, 37, 37, 49, 49, 49, 49, 49, 61, 61, 61, 61, 61, 73, 73, 73, 73, 73, 85, 85, 85, 85, 85, 97, 97, 97, 97, 97, 109, 109, 109, 109, 120, 120, 122, 122, 122, 122, 122, 134, 134, 136, 136, 136, 136, 136, 148, 150, 150, 150, 150, 150, 162, 162, 164, 164, 164, 164, 164, 176, 176, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178 ) ) expect_equal( r1$tfirstd, c( NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ) ) expect_equal( r1$tlastd, c( NA, 1, 1, 1, 1, 1, 13, 13, 13, 13, 13, 25, 25, 25, 25, 25, 37, 37, 37, 37, 37, 49, 49, 49, 49, 49, 61, 61, 61, 61, 61, 73, 73, 73, 73, 73, 85, 85, 85, 85, 85, 97, 97, 97, 97, 97, 109, 109, 109, 109, 120, 120, 120, 120, 120, 120, 120, 134, 134, 134, 134, 134, 134, 134, 148, 148, 148, 148, 148, 148, 162, 162, 162, 162, 162, 162, 162, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176 ) ) expect_equal( r1$tlastp, c( NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 122, 122, 122, 122, 122, 122, 122, 136, 136, 136, 136, 136, 136, 150, 150, 150, 150, 150, 150, 150, 164, 164, 164, 164, 164, 164, 164, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178, 178 ) ) expect_equal( r1$tfirstp, c( NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122 ) ) }) test_that("test parsing of ode", { expect_error(RxODE({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 C2 <- centr / V2 C3 <- peri / V3 f <- tad(eff) d / dt(depot) <- -KA * depot d / dt(centr) <- KA * depot - CL * C2 - Q * C2 + Q * C3 d / dt(peri) <- Q * C2 - Q * C3 d / dt(eff) <- Kin - Kout * (1 - C2 / (EC50 + C2)) * eff })) .rxWithOptions(list(RxODE.syntax.require.ode.first = FALSE), { expect_error(RxODE({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 C2 <- centr / V2 C3 <- peri / V3 f <- tad(eff) d / dt(depot) <- -KA * depot d / dt(centr) <- KA * depot - CL * C2 - Q * C2 + Q * C3 d / dt(peri) <- Q * C2 - Q * C3 d / dt(eff) <- Kin - Kout * (1 - C2 / (EC50 + C2)) * eff }), NA) }) }) context("tad family of functions with linCmt()") test_that("lincmt solution tad family", { sol.1c.ka <- RxODE({ KA <- 2 V <- 20 CL <- 25 C2 <- linCmt(V, CL, KA) tad <- tad() tafd <- tafd() tadd <- tad(depot) tafdd <- tafd(depot) tadc <- tad(central) tafdc <- tafd(central) }) et <- eventTable() %>% add.dosing(dose = 3, nbr.doses = 6, dosing.interval = 8) %>% add.dosing( dose = 6, nbr.doses = 6, dosing.interval = 8, start.time = 2, dosing.to = "central" ) %>% add.sampling(seq(0, 48, length.out = 200)) s1 <- rxSolve(sol.1c.ka, et) sol.1c.ka <- RxODE({ KA <- 2 V <- 20 CL <- 25 C2 <- linCmt(V, CL, KA) tad <- tad() tafd <- tafd() tadc <- tad(central) tafdc <- tafd(central) }) s2 <- rxSolve(sol.1c.ka, et) expect_equal(s2$tad, s1$tad) expect_equal(s2$tafd, s1$tafd) expect_equal(s2$tadc, s1$tadc) expect_equal(s2$tafdc, s1$tafdc) expect_error(RxODE({ V <- 20 CL <- 25 C2 <- linCmt(V, CL) tad <- tad() tafd <- tafd() tadd <- tad(depot) tafdd <- tafd(depot) tadc <- tad(central) tafdc <- tafd(central) })) one.cmt <- RxODE({ V <- 20 CL <- 25 C2 <- linCmt(V, CL) tad <- tad() tafd <- tafd() tadc <- tad(central) tafdc <- tafd(central) }) et <- eventTable() %>% add.dosing(dose = 3, nbr.doses = 6, dosing.interval = 8) %>% add.sampling(seq(0, 48, length.out = 200)) s <- rxSolve(one.cmt, et) expect_equal(s$tad, s$tadc) expect_equal(s$tafd, s$tafdc) }) context("tad family of functions with linCmt()/ode mix") test_that("ode mixed", { mod3 <- RxODE({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin0 <- 1 Kout <- 1 EC50 <- 200 C2 <- linCmt() Tz <- 8 amp <- 0.1 eff(0) <- 1 Kin <- Kin0 + amp * cos(2 * pi * (ctime - Tz) / 24) d / dt(eff) <- Kin - Kout * (1 - C2 / (EC50 + C2)) * eff tadd <- tad(depot) tad <- tad() tade <- tad(eff) }) ev <- eventTable(amount.units = "mg", time.units = "hours") %>% add.dosing(dose = 10000, nbr.doses = 1, dosing.to = 1) %>% add.sampling(seq(0, 48, length.out = 100)) ev$ctime <- (ev$time + set_units(8, hr)) %% 24 x <- rxSolve(mod3, ev) expect_equal(x$tad, x$tadd) expect_true(all(is.na(x$tade))) ev <- eventTable(amount.units = "mg", time.units = "hours") %>% add.dosing(dose = 10000, nbr.doses = 1, dosing.to = 1) %>% add.dosing(dose = -1, start.time = 6, nbr.doses = 1, dosing.to = 3) %>% add.sampling(seq(0, 48, length.out = 20)) ev$ctime <- (ev$time + set_units(8, hr)) %% 24 x <- rxSolve(mod3, ev, addDosing = TRUE) expect_false(isTRUE(all.equal(x$tad, x$tadd))) expect_false(isTRUE(all.equal(x$tad, x$tade))) }) } })
options(width=60)
xpose.write <- function(object, file = "xpose.ini" ) { prefs <- matrix(1:150, ncol=2) prefs[1,] <- c("Miss", object@Prefs@Miss) prefs[2,] <- c("Cat.levels", object@[email protected]) prefs[3,] <- c("DV.Cat.levels", object@[email protected]) prefs[4,] <- c("type", object@[email protected]$type) prefs[5,] <- c("cex", object@[email protected]$cex) prefs[6,] <- c("lty", object@[email protected]$lty) prefs[7,] <- c("lwd", object@[email protected]$lwd) prefs[8,] <- c("col", object@[email protected]$col) prefs[9,] <- c("pch", object@[email protected]$pch) prefs[10,] <- c("grid", object@[email protected]$grid) prefs[11,] <- c("aspect", object@[email protected]$aspect) prefs[12,] <- c("byordfun", object@[email protected]$byordfun) prefs[13,] <- c("shingnum", object@[email protected]$shingnum) prefs[14,] <- c("shingol", object@[email protected]$shingol) prefs[15,] <- c("ablcol", object@[email protected]$ablcol) prefs[16,] <- c("abllty", object@[email protected]$abllty) prefs[17,] <- c("abllwd", object@[email protected]$abllwd) prefs[18,] <- c("lmcol", object@[email protected]$lmcol) prefs[19,] <- c("lmlty", object@[email protected]$lmlty) prefs[20,] <- c("lmlwd", object@[email protected]$lmlwd) prefs[21,] <- c("smooth", object@[email protected]$smooth) prefs[22,] <- c("smcol", object@[email protected]$sucol) prefs[23,] <- c("smlty", object@[email protected]$sulty) prefs[24,] <- c("smlwd", object@[email protected]$sulwd) prefs[25,] <- c("smspan", object@[email protected]$suspan) prefs[26,] <- c("smdegr", object@[email protected]$sudegr) prefs[27,] <- c("sucol", object@[email protected]$sucol) prefs[28,] <- c("sulty", object@[email protected]$sulty) prefs[29,] <- c("sulwd", object@[email protected]$sulwd) prefs[30,] <- c("suspan", object@[email protected]$suspan) prefs[31,] <- c("sudegr", object@[email protected]$sudegr) prefs[32,] <- c("ids", object@[email protected]$ids) prefs[33,] <- c("idsext", object@[email protected]$idsext) prefs[34,] <- c("idscex", object@[email protected]$idscex) prefs[35,] <- c("idsdir", object@[email protected]$idsdir) prefs[36,] <- c("dilfrac", object@[email protected]$dilfrac) prefs[37,] <- c("dilci", object@[email protected]$dilci) prefs[38,] <- c("PIuplty", object@[email protected]$PIuplty) prefs[39,] <- c("PIdolty", object@[email protected]$PIdolty) prefs[40,] <- c("PImelty", object@[email protected]$PImelty) prefs[41,] <- c("PIuptyp", object@[email protected]$PIuptyp) prefs[42,] <- c("PIdotyp", object@[email protected]$PIdotyp) prefs[43,] <- c("PImetyp", object@[email protected]$PImetyp) prefs[44,] <- c("PIupcol", object@[email protected]$PIupcol) prefs[45,] <- c("PIdocol", object@[email protected]$PIdocol) prefs[46,] <- c("PImecol", object@[email protected]$PImecol) prefs[47,] <- c("PIuplwd", object@[email protected]$PIuplwd) prefs[48,] <- c("PIdolwd", object@[email protected]$PIdolwd) prefs[49,] <- c("PImelwd", object@[email protected]$PImelwd) prefs[50,] <- c("PIuplimit", object@[email protected]$PIlimits[2]) prefs[51,] <- c("PIdolimit", object@[email protected]$PIlimits[1]) prefs[52,] <- c("PIarcol", object@[email protected]$PImelwd) prefs[53,] <- c("bwhoriz", object@[email protected]$bwhoriz) prefs[54,] <- c("bwratio", object@[email protected]$bwratio) prefs[55,] <- c("bwvarwid", object@[email protected]$bwvarwid) prefs[56,] <- c("bwdotpch", object@[email protected]$bwdotpch) prefs[57,] <- c("bwdotcol", object@[email protected]$bwdotcol) prefs[58,] <- c("bwdotcex", object@[email protected]$bwdotcex) prefs[59,] <- c("bwrecfill", object@[email protected]$bwrecfill) prefs[60,] <- c("bwreccol", object@[email protected]$bwreccol) prefs[61,] <- c("bwreclty", object@[email protected]$bwreclty) prefs[62,] <- c("bwreclwd", object@[email protected]$bwreclwd) prefs[63,] <- c("bwumbcol", object@[email protected]$bwumbcol) prefs[64,] <- c("bwumblty", object@[email protected]$bwumblty) prefs[65,] <- c("bwumblwd", object@[email protected]$bwumblwd) prefs[66,] <- c("bwoutpch", object@[email protected]$bwoutpch) prefs[67,] <- c("bwoutcol", object@[email protected]$bwoutcol) prefs[68,] <- c("bwoutcex", object@[email protected]$bwoutcex) prefs[69,] <- c("hiborder", object@[email protected]$hiborder) prefs[70,] <- c("hicol", object@[email protected]$hicol) prefs[71,] <- c("hilty", object@[email protected]$hilty) prefs[72,] <- c("hilwd", object@[email protected]$hilwd) prefs[73,] <- c("hidcol", object@[email protected]$hidcol) prefs[74,] <- c("hidlty", object@[email protected]$hidlty) prefs[75,] <- c("hidlwd", object@[email protected]$hidlwd) for (i in 1:nrow(prefs)) { if (prefs[i,1] == prefs[i,2]) { prefs[i,2] = "NULL" } } write.table(prefs, file = file, sep = "\t", col.names = FALSE, row.names=FALSE, quote=FALSE) }
semPlotModel.regsem <- semPlotModel.regsemplot <- function(object,...){ object1 <- object$lav.model@ParTable object2 <- object$lav.model@Model@dimNames varnames <- unique(c(object1$lhs, object1$rhs)) mannames <- object2[[1]][1] names(mannames) <- 'manifest' '%!in%' <- function(x,y)!('%in%'(x,y)) namelist <- strsplit(names(object$out$pars)," ") inout <- data.frame(1,2) for(i in 1:length(namelist)){ inout[i,1] <- namelist[[i]][1] inout[i,2] <- namelist[[i]][3] } int <- data.frame(1,2) for(i in 1:length(object1$lhs)){ int[i,1] <- ifelse(object1$op[i]=="~"|object1$op[i]=="~1",object1$rhs[i],object1$lhs[i]) int[i,2] <- ifelse(object1$op[i]=="~"|object1$op[i]=="~1",object1$lhs[i],object1$rhs[i]) } pinout <- with(inout, paste0(X1, X2)) pint <- with(int, paste0(X1, X2)) counter <- 0 for(i in 1:length(pint)){ if(pint[i] %!in% pinout){ object1$regest[i] <- 1 counter <- counter + 1 } else { object1$regest[i] <- object$out$pars[i - counter] } } semModel <- new("semPlotModel") semModel@Pars <- data.frame( label = rep("", length(object1$id)), lhs = ifelse(object1$op=="~"|object1$op=="~1",object1$rhs,object1$lhs), edge = "--", rhs = ifelse(object1$op=="~"|object1$op=="~1",object1$lhs,object1$rhs), est = object1$regest, std = NA, group = object1$group, fixed = object1$free == 0, par = object1$free, stringsAsFactors=FALSE) row.names(semModel@Pars) <- 1:length(object1$id) semModel@Pars$edge[object1$op=="~~"] <- "<->" semModel@Pars$edge[object1$op=="~*~"] <- "<->" semModel@Pars$edge[object1$op=="~"] <- "~>" semModel@Pars$edge[object1$op=="=~"] <- "->" semModel@Pars$edge[object1$op=="~1"] <- "int" semModel@Pars$edge[grepl("\\|",object1$op)] <- "|" semModel@Pars <- semModel@Pars[!object$op%in%c(':=','<','>','==','|','<', '>'),] semModel@Vars <- data.frame( name = varnames, manifest = varnames[1:length(varnames)] %in% mannames$manifest[1:length(mannames$manifest)], exogenous = NA, stringsAsFactors = FALSE ) semModel@Thresholds <- data.frame() semModel@ObsCovs <- list() semModel@ImpCovs <- list() semModel@Computed <- FALSE semModel@Original <- list(object) return(semModel) }
makeWFG8Function = function(n.objectives, k, l) { assertInt(n.objectives, lower = 2L) force(n.objectives) if (missing(k)) { if (n.objectives == 2L) { k = 4L } else { k = 2L * (n.objectives - 1L) } } assertInt(k, lower = n.objectives - 1L) assertTRUE(k %% (n.objectives - 1L) == 0L) force(k) if (missing(l)) { l = 20L } assertInt(l, lower = 1L) force(l) dimensions = k + l fn = function(x) { assertNumeric(x, len = k + l, any.missing = FALSE, all.missing = FALSE) return(mof_WFG_8(z = x, M = n.objectives, k = k)) } makeMultiObjectiveFunction( name = "WFG8 function", id = sprintf("WFG8-%id-%io", dimensions, n.objectives), description = "WFG8 function", fn = fn, par.set = makeNumericParamSet( len = dimensions, id = "x", lower = rep(0, dimensions), upper = 2L * seq_len(dimensions), vector = TRUE ), minimize = rep(TRUE, n.objectives), n.objectives = n.objectives ) } class(makeWFG8Function) = c("function", "smoof_generator") attr(makeWFG8Function, "name") = c("WFG8") attr(makeWFG8Function, "type") = c("multi-objective") attr(makeWFG8Function, "tags") = c("multi-objective")
difLRT<-function (Data, group, focal.name, alpha = 0.05, purify = FALSE, nrIter = 10, p.adjust.method=NULL,save.output = FALSE, output = c("out", "default")) { internalLRT <- function() { if (length(group) == 1) { if (is.numeric(group)) { gr <- Data[, group] DATA <- Data[, (1:ncol(Data)) != group] colnames(DATA) <- colnames(Data)[(1:ncol(Data)) != group] } else { gr <- Data[, colnames(Data) == group] DATA <- Data[, colnames(Data) != group] colnames(DATA) <- colnames(Data)[colnames(Data) != group] } } else { gr <- group DATA <- Data } Group <- rep(0, nrow(DATA)) Group[gr == focal.name] <- 1 if (!purify) { STATS <- LRT(DATA, Group) PVAL<-1-pchisq(STATS,1) if (max(STATS) <= qchisq(1 - alpha, 1)) DIFitems <- "No DIF item detected" else DIFitems <- (1:ncol(DATA))[STATS > qchisq(1 - alpha, 1)] RES <- list(LRT = STATS, p.value=PVAL,alpha = alpha, thr = qchisq(1 - alpha, 1), DIFitems = DIFitems, p.adjust.method = p.adjust.method, adjusted.p = NULL,purification = purify, names = colnames(DATA), save.output = save.output, output = output) } else { nrPur <- 0 noLoop <- FALSE stats1 <- LRT(DATA, Group) if (max(stats1) <= qchisq(1 - alpha, 1)) { DIFitems <- "No DIF item detected" noLoop <- TRUE } else { dif <- (1:ncol(DATA))[stats1 > qchisq(1 - alpha, 1)] nodif <- NULL for (i in 1:ncol(DATA)) { if (sum(i == dif) == 0) nodif <- c(nodif, i) } repeat { if (nrPur >= nrIter) break else { nrPur <- nrPur + 1 dat <- DATA[, nodif] stats2 <- LRT(dat, Group) stats1[nodif] <- stats2 if (max(stats2) <= qchisq(1 - alpha, 1)) { noLoop <- TRUE break } else { ind2 <- (1:ncol(dat))[stats2 > qchisq(1 - alpha, 1)] noind2 <- (1:ncol(dat))[stats2 <= qchisq(1 - alpha, 1)] dif <- c(dif, nodif[ind2]) nodif <- nodif[noind2] } } } DIFitems <- (1:ncol(DATA))[stats1 > qchisq(1 - alpha, 1)] } PVAL<-1-pchisq(stats1,1) RES <- list(LRT = stats1, p.value=PVAL,alpha = alpha, thr = qchisq(1 - alpha, 1), DIFitems = DIFitems, p.adjust.method = p.adjust.method, adjusted.p = NULL, purification = purify, nrPur = nrPur, convergence = noLoop, names = colnames(DATA), save.output = save.output, output = output) } if (!is.null(p.adjust.method)) { pval <- 1 - pchisq(RES$LRT, 1) RES$adjusted.p <- p.adjust(pval, method = p.adjust.method) if (min(RES$adjusted.p, na.rm = TRUE) > alpha) RES$DIFitems <- "No DIF item detected" else RES$DIFitems <- which(RES$adjusted.p < alpha) } class(RES) <- "LRT" return(RES) } resToReturn <- internalLRT() if (save.output) { if (output[2] == "default") wd <- paste(getwd(), "/", sep = "") else wd <- output[2] fileName <- paste(wd, output[1], ".txt", sep = "") capture.output(resToReturn, file = fileName) } return(resToReturn) } plot.LRT<-function(x,pch=8,number=TRUE,col="red", save.plot=FALSE,save.options=c("plot","default","pdf"),...) { internalLRT<-function(){ res <- x if (!number) { plot(res$LRT,xlab="Item",ylab="Likelihood Ratio statistic",ylim=c(0,max(c(res$LRT,res$thr)+1)),pch=pch,main="Likelihood Ratio Test") points(res$DIFitems,res$MH[res$DIFitems],pch=pch,col=col) } else { plot(res$LRT,xlab="Item",ylab="Likelihood Ratio statistic",ylim=c(0,max(c(res$LRT,res$thr)+1)),col="white",main="Likelihood Ratio Test") text(1:length(res$LRT),res$LRT,1:length(res$LRT)) if (!is.character(res$DIFitems)) text(res$DIFitems,res$LRT[res$DIFitems],res$DIFitems,col=col) } abline(h=res$thr) } internalLRT() if (save.plot){ plotype<-NULL if (save.options[3]=="pdf") plotype<-1 if (save.options[3]=="jpeg") plotype<-2 if (is.null(plotype)) cat("Invalid plot type (should be either 'pdf' or 'jpeg').","\n","The plot was not captured!","\n") else { if (save.options[2]=="default") wd<-paste(getwd(),"/",sep="") else wd<-save.options[2] fileName<-paste(wd,save.options[1],switch(plotype,'1'=".pdf",'2'=".jpg"),sep="") if (plotype==1){ { pdf(file=fileName) internalLRT() } dev.off() } if (plotype==2){ { jpeg(filename=fileName) internalLRT() } dev.off() } cat("The plot was captured and saved into","\n"," '",fileName,"'","\n","\n",sep="") } } else cat("The plot was not captured!","\n",sep="") } print.LRT<-function (x, ...) { res <- x cat("\n") cat("Detection of Differential Item Functioning using Likelihood Ratio Test", "\n") if (res$purification) pur <- "with " else pur <- "without " cat(pur, "item purification", "\n", "\n", sep = "") if (res$purification) { if (res$nrPur <= 1) word <- " iteration" else word <- " iterations" if (!res$convergence) { cat("WARNING: no item purification convergence after ", res$nrPur, word, "\n", sep = "") cat("WARNING: following results based on the last iteration of the purification", "\n", "\n") } else cat("Convergence reached after ", res$nrPur, word, "\n", "\n", sep = "") } if (is.null(res$p.adjust.method)) cat("No p-value adjustment for multiple comparisons", "\n", "\n") else { pAdjMeth <- switch(res$p.adjust.method, bonferroni = "Bonferroni", holm = "Holm", hochberg = "Hochberg", hommel = "Hommel", BH = "Benjamini-Hochberg", BY = "Benjamini-Yekutieli") cat("Multiple comparisons made with", pAdjMeth, "adjustement of p-values", "\n", "\n") } cat("Likelihood Ratio statistic:", "\n", "\n") pval <- round(1 - pchisq(res$LRT, 1), 4) if (is.null(res$p.adjust.method)) symb <- symnum(pval, c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", "**", "*", ".", "")) else symb <- symnum(res$adjusted.p, c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", "**", "*", ".", "")) m1 <- cbind(round(res$LRT, 4), pval) if (!is.null(res$p.adjust.method)) m1<-cbind(m1,round(res$adjusted.p,4)) m1 <- noquote(cbind(format(m1, justify = "right"), symb)) if (!is.null(res$names)) rownames(m1) <- res$names else { rn <- NULL for (i in 1:nrow(m1)) rn[i] <- paste("Item", i, sep = "") rownames(m1) <- rn } con <- c("Stat.", "P-value") if (!is.null(res$p.adjust.method)) con <- c(con, "Adj. P", "") else con <- c(con, "") colnames(m1) <- con print(m1) cat("\n") cat("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ", "\n") cat("\n", "Detection threshold: ", round(res$thr, 4), " (significance level: ", res$alpha, ")", "\n", "\n", sep = "") if (is.character(res$DIFitems) == TRUE) cat("Items detected as DIF items:", res$DIFitems, "\n", "\n") else { cat("Items detected as DIF items:", "\n") m2 <- cbind(rownames(m1)[res$DIFitems]) rownames(m2) <- rep("", nrow(m2)) colnames(m2) <- "" print(m2, quote = FALSE) cat("\n") } if (!x$save.output) cat("Output was not captured!", "\n") else { if (x$output[2] == "default") wd <- paste(getwd(), "/", sep = "") else wd <- x$output[2] fileName <- paste(wd, x$output[1], ".txt", sep = "") cat("Output was captured and saved into file", "\n", " '", fileName, "'", "\n", "\n", sep = "") } }
expected <- eval(parse(text="c(\"0\", \"25\", \"50\", \"75\", \"100\")")); test(id=0, code={ argv <- eval(parse(text="list(c(0, 25, 50, 75, 100), \"double\", 1, 7L, \"fg\", \"\", c(16L, 15L, 15L, 15L, 15L))")); .Internal(`formatC`(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]])); }, o=expected);
taxfac <- function(lookup) { output <- matrix(ncol = ncol(lookup), nrow = nrow(lookup)) for (i in seq_len(ncol(lookup))) output[, i] <- as.numeric(as.factor(as.character(lookup[, i]))) row.names(output) <- lookup[, 1] colnames(output) <- colnames(lookup) output - 1 }
makeOperator = function( operator, supported = getAvailableRepresentations()) { assertFunction(operator) assertSubset(supported, choices = getAvailableRepresentations(), empty.ok = FALSE) operator = setAttribute(operator, "supported", supported) operator = addClasses(operator, c("ecr_operator")) return(operator) } isEcrOperator = function(obj) { return(inherits(obj, "ecr_operator")) } print.ecr_operator = function(x, ...) { catf("ECR2 OPERATOR:") catf("Supported representations: %s", collapse(getSupportedRepresentations(x))) } print.ecr_recombinator = function(x, ...) { print.ecr_operator(x) catf("Number of returned children: %i", attr(x, "n.parents")) } print.ecr_selector = function(x, ...) { print.ecr_operator(x) catf("Supported } getSupportedRepresentations = function(operator) { UseMethod("getSupportedRepresentations") } getSupportedRepresentations.ecr_operator = function(operator) { attr(operator, "supported") } is.supported = function(operator, representation) { UseMethod("is.supported") } is.supported.ecr_operator = function(operator, representation) { return (representation %in% getSupportedRepresentations(operator)) }
utility.gen <- function(object, data, ...) UseMethod("utility.gen") utility.gen.default <- function(object, ...) stop("No compare method associated with class ", class(object), call. = FALSE) utility.gen.data.frame <- utility.gen.list <- function(object, data, not.synthesised = NULL, cont.na = NULL, method = "cart", maxorder = 1, k.syn = FALSE, tree.method = "rpart", max.params = 400, print.stats = c("pMSE", "S_pMSE"), resamp.method = NULL, nperms = 50, cp = 1e-3, minbucket = 5, mincriterion = 0, vars = NULL, aggregate = FALSE, maxit = 200, ngroups = NULL, print.flag = TRUE, print.every = 10, digits = 6, print.zscores = FALSE, zthresh = 1.6, print.ind.results = FALSE, print.variable.importance = FALSE, ...) { if (is.null(data)) stop("Requires parameter 'data' to give name of the real data.\n\n", call. = FALSE) if (is.null(object)) stop("Requires parameter 'object' to give name of the synthetic data.\n\n", call. = FALSE) if (is.list(object) & !is.data.frame(object)) m <- length(object) else if (is.data.frame(object)) m <- 1 else stop("object must be a data frame or a list of data frames.\n", call. = FALSE) cna <- cont.na cont.na <- as.list(rep(NA, length(data))) names(cont.na) <- names(data) if (!is.null(cna)) { if (!is.list(cna) | any(names(cna) == "") | is.null(names(cna))) stop("Argument 'cont.na' must be a named list with names of selected variables.", call. = FALSE) if (any(!names(cna) %in% names(data))) stop("Names of the list cont.na must be variables in data.\n", call. = FALSE) for (i in 1:length(cna)) { j <- (1:length(data))[names(cna)[i] == names(data)] cont.na[[j]] <- unique(c(NA,cna[[i]])) } } syn.method = rep("ok", length(data)) if (!is.null(not.synthesised)) { if (!is.null(not.synthesised) && !all(not.synthesised %in% names(data))) stop("not.synthesised must be names of variables in data.\n", call. = FALSE) syn.method[names(data) %in% not.synthesised] <- "" } object <- list(syn = object, m = m, strata.syn = NULL, method = syn.method, cont.na = cont.na) class(object ) <- "synds" res <- utility.gen.synds(object = object, data = data, method = method, maxorder = maxorder, k.syn = k.syn, tree.method = tree.method, max.params = max.params, print.stats = print.stats, resamp.method = resamp.method, nperms = nperms, cp = cp, minbucket = minbucket, mincriterion = mincriterion, vars = vars, aggregate = aggregate, maxit = maxit, ngroups = ngroups, print.flag = print.flag, print.every = print.every, digits = digits, print.zscores = print.zscores, zthresh = zthresh, print.ind.results = print.ind.results, print.variable.importance = print.variable.importance) res$call <- match.call() return(res) } utility.gen.synds <- function(object, data, method = "cart", maxorder = 1, k.syn = FALSE, tree.method = "rpart", max.params = 400, print.stats = c("pMSE", "S_pMSE"), resamp.method = NULL, nperms = 50, cp = 1e-3, minbucket = 5, mincriterion = 0, vars = NULL, aggregate = FALSE, maxit = 200, ngroups = NULL, print.flag = TRUE, print.every = 10, digits = 6, print.zscores = FALSE, zthresh = 1.6, print.ind.results = FALSE, print.variable.importance = FALSE, ...) { m <- object$m if (is.null(method) || length(method) != 1 || is.na(match(method, c("cart", "logit")))) stop("Invalid 'method' type - must be either 'logit' or 'cart'.\n", call. = FALSE) if (is.null(print.stats) || any(is.na(match(print.stats, c("pMSE", "SPECKS", "PO50", "U", "S_pMSE", "S_SPECKS", "S_PO50", "S_U", "all"))))) stop("Invalid 'print.stats'. Can only include 'pMSE', 'SPECKS', 'PO50', 'U', 'S_pMSE', 'S_SPECKS', 'S_PO50', 'S_U'.\nAternatively it can be set to 'all'.\n", call. = FALSE) if (!is.null(resamp.method) && is.na(match(resamp.method, c("perm", "pairs", "none")))) stop("Invalid 'resamp.method' type - must be NULL, 'perm', 'pairs' or 'none'.\n", call. = FALSE) if (aggregate == TRUE & method != "logit") stop("Aggregation only works for 'logit' method.\n", call. = FALSE) if (is.null(data)) stop("Requires parameter 'data' to give name of the real data.\n", call. = FALSE) if (!class(object) == "synds") stop("Object must have class 'synds'.\n", call. = FALSE) if (k.syn & !is.null(resamp.method) && resamp.method == "pairs") stop('\nresamp.method = "pairs" will give the wrong answer when k.syn is TRUE.\n', call. = FALSE) if (is.null(tree.method) || length(tree.method) != 1 || is.na(match(tree.method, c("rpart", "ctree")))) stop("Invalid 'tree.method' - must be either 'rpart' or 'ctree'.\n", call. = FALSE) if (!(is.null(vars))) { if (is.numeric(vars)){ if (!(all(vars %in% 1:length(data)))) stop("Column indices of 'vars' must be in 1 to length(data).\n", call. = FALSE) } else if (!(all(vars %in% names(data)))) stop("Some 'vars' specified not in data.\n", call. = FALSE) data <- data[, vars, drop = FALSE] if (m == 1) { if (!all(vars %in% names(object$syn))) stop("Some 'vars' specified not in synthetic data.\n", call. = FALSE) else object$syn <- object$syn[, vars, drop = FALSE ] } else { if (!all(vars %in% names(object$syn[[1]]))) stop("Some 'vars' specified not in synthetic data.\n", call. = FALSE) else object$syn <- lapply(object$syn, "[", vars) } } else { if (m == 1) vars <- names(object$syn) else vars <- names(object$syn[[1]]) if (!all(vars %in% names(data))) stop("Some variables in synthetic data not in original data.\n", call. = FALSE) else data <- data[, vars] } if (!is.null(object$strata.syn)) { cna <- object$cont.na[1,] syn.method <- object$method[1,] } else { cna <- object$cont.na syn.method <- object$method } cna <- cna[names(cna) %in% vars] for ( i in 1:length(cna)) { nm <- names(cna)[i] vals <- unique(cna[[i]][!is.na(cna[[i]])]) if (length(vals) > 0){ for (j in 1:length(vals)) n_cna <- sum(vals[j] == data[,nm] & !is.na(data[,nm])) if (n_cna == 0) stop("\nValue ", vals[j], " identified as denoting a special or missing in cont.na for ",nm, " is not in data.\n",sep = "", call. = FALSE) else if (n_cna < 10 & print.flag) cat ("\nWarning: Only ",n_cna ," record(s) in data with value ",vals[j]," identified as denoting a missing value in cont.na for ",nm, "\n\n", sep = "") } } incomplete <- FALSE nsynthd <- length(vars) unsyn.vars <- names(syn.method)[syn.method == ""] if (any(vars %in% unsyn.vars) & !is.null(unsyn.vars)) { notunsyn <- vars[!vars %in% unsyn.vars] if (!all(unsyn.vars %in% vars)) stop("Unsynthesised variables must be a subset of variables contributing to the utility measure.\n", call. = FALSE) if ( all(vars %in% unsyn.vars)) stop("Utility measure impossible if all in vars are unsynthesised.\n", call. = FALSE) incomplete <- TRUE } if (is.null(resamp.method)) { if ("S_SPECKS" %in% print.stats || "S_PO50" %in% print.stats || "S_U" %in% print.stats || incomplete) { resamp.method <- "pairs" cat('Resampling method set to "pairs" because S_SPECKS or S_PO50 or S_U in print.stats or incomplete = TRUE.\n') } else if (method == "cart") resamp.method <- "perm" } else { if (incomplete & resamp.method == "perm") stop('Incomplete synthesis requires resamp.method = "pairs".\n', call. = FALSE) if (any(c("S_SPECKS", "S_PO50", "S_U") %in% print.stats) & resamp.method == "perm") stop('Stat SPECKS, PO50, and U requires resamp.method = "pairs" to get S_SPECKS, S_PO50, and S_U respectively.\n', call. = FALSE) if (resamp.method == "pairs" & m == 1) stop('resamp.method = "pairs" needs a synthesis with m > 1, m = 10 suggested.\n', call. = FALSE) } leneq1 <- function(x) length(table(as.numeric(x[!is.na(x)]), useNA = "ifany")) %in% (0:1) dchar <- sapply(data,is.character) if (any(dchar == TRUE)) for ( i in 1:dim(data)[2]) if (dchar[i] == TRUE) data[,i] <- factor(data[,i]) dout <- sapply(data,leneq1) if (m == 1) sout <- sapply(object$syn,leneq1) else sout <- sapply(object$syn[[1]],leneq1) dout <- dout & sout if (any(dout == TRUE) & print.flag) { cat("Some columns with single values or all missing values in original and synthetic\nexcluded from utility comparisons (excluded variables: ", paste(names(data)[dout], collapse = ", "), ").\n", sep = "") data <- data[,!dout] if (m == 1) object$syn <- object$syn[, !dout, drop = FALSE] else object$syn <- lapply(object$syn, "[", !dout) } numvars <- (1:dim(data)[2])[sapply(data, is.numeric)] names(numvars) <- names(data)[numvars] data0 <- data if (!is.null(ngroups)) { for (i in numvars) { if (m == 1) { groups <- group_num(data[,i], object$syn[,i], object$syn[,i], ngroups, cont.na = cna, ...) data[,i] <- groups[[1]] object$syn[,i] <- groups[[2]] } else { syn0 <- c(sapply(object$syn, '[[', i)) for (j in 1:m) { groups <- group_num(data0[,i], object$syn[[j]][,i], syn0, ngroups, cont.na = cna[[i]], ...) data[,i] <- groups[[1]] object$syn[[j]][,i] <- groups[[2]] } } } } catvars <- (1:dim(data)[2])[sapply(data, is.factor)] for (i in catvars) { data[,i] <- factor(data[,i]) if (m == 1) object$syn[,i] <- factor(object$syn[,i]) else for (j in 1:m) object$syn[[j]][,i] <- factor(object$syn[[j]][,i]) if (any(is.na(data[,i]))) { data[,i] <- addNA(data[,i]) if (m == 1) object$syn[,i] <- addNA(object$syn[,i]) else for (j in 1:m) object$syn[[j]][,i] <- addNA(object$syn[[j]][,i]) } } for (i in numvars) { if (anyNA(data[,i]) & is.null(ngroups)) { newname <- paste(names(data)[i], "NA", sep = "_") data <- data.frame(data, 1*(is.na(data[,i]))) names(data)[length(data)] <- newname data[is.na(data[,i]), i] <- 0 if (m == 1) { object$syn <- data.frame(object$syn, 1*(is.na(object$syn[,i]))) names(object$syn)[length(object$syn)] <- newname object$syn[is.na(object$syn[,i]), i] <- 0 } else { for (j in 1:m) { object$syn[[j]] <- data.frame(object$syn[[j]], 1*(is.na(object$syn[[j]][,i]))) names(object$syn[[j]])[length(object$syn[[j]])] <- newname object$syn[[j]][is.na(object$syn[[j]][,i]),i] <- 0 } } } if (any(!is.na(cna[[i]])) & is.null(ngroups)) { cna[[i]] <- cna[[i]][!is.na(cna[[i]])] for (j in 1:length(cna[[i]])) { newname <- paste(names(data)[i], "cna",j, sep = "_") data <- data.frame(data, 1*(data[,i] == cna[[i]][j])) data[data[,i] == cna[[i]][j], i] <- 0 names(data)[length(data)] <- newname } if (m == 1) { for (j in 1:length(cna[[i]])) { newname <- paste(names(object$syn)[i], "cna",j, sep = "_") object$syn <- data.frame(object$syn, 1*(object$syn[,i] == cna[[i]][j])) object$syn[object$syn[,i] == cna[[i]][j], i] <- 0 names(object$syn)[length(object$syn)] <- newname } } else { for (k in 1:m) { for (j in 1:length(cna[[i]])) { newname <- paste(names(object$syn[[k]])[i], "cna",j, sep = "_") object$syn[[k]] <- data.frame(object$syn[[k]], 1*(object$syn[[k]][,i] == cna[[i]][j])) object$syn[[k]][object$syn[[k]][,i] == cna[[i]][j], i] <- 0 names(object$syn[[k]])[length(object$syn[[k]])] <- newname } } } } } propcalcs <- function(syndata, data) { n1 <- dim(data)[1] n2 <- dim(syndata)[1] N <- n1 + n2 cc <- n2 / N if (k.syn) cc <- 0.5 df.prop <- rbind(syndata, data) df.prop <- data.frame(df.prop, t = c(rep(1,n2), rep(0,n1))) catvars <- (1:(dim(df.prop)[2]))[sapply(df.prop,is.factor)] for (i in catvars) { if (any(table(df.prop[,i]) == 0)) { df.prop[,i] <- as.factor(as.character(df.prop[,i])) if (print.flag) cat("Empty levels of factor(s) for variable ", names(df.prop)[i]," removed.\n" ) } } if (aggregate == TRUE) { aggdat <- aggregate(df.prop[,1], by = df.prop, FUN = length) wt <- aggdat$x aggdat <- aggdat[, -dim(aggdat)[2]] } if (method == "logit" ) { if (maxorder >= dim(data)[2]) stop("maxorder cannot be greater or equal to the number of variables.\n", call. = FALSE) levs <- sapply(data, function(x) length(levels(x))) levs[levs == 0] <- 2 tt1 <- apply(combn(length(levs), 1), 2, function(x) {prod(levs[x] - 1)}) if (maxorder == 0) nparams <- 1 + sum(tt1) else { tt2 <- apply(combn(length(levs), 2), 2, function(x) {prod(levs[x] - 1)}) if (maxorder == 1) nparams <- 1 + sum(tt1) + sum(tt2) else { tt3 <- apply(combn(length(levs), 3), 2, function(x) {prod(levs[x] - 1)}) if (maxorder == 2) nparams <- 1 + sum(tt1) + sum(tt2) + sum(tt3) else { tt4 <- apply(combn(length(levs), 4), 2, function(x) {prod(levs[x] - 1)}) if (maxorder == 3) nparams <- 1 + sum(tt1) + sum(tt2) + sum(tt3) + sum(tt4) else { tt5 <- apply(combn(length(levs), 5), 2, function(x) {prod(levs[x] - 1)}) if (maxorder == 4) nparams <- 1 + sum(tt1) + sum(tt2) + sum(tt3) + sum(tt4) + sum(tt5) } } } } if (nparams > max.params) stop("You will be fitting a large model with ", nparams, " parameters that may take a long time and fail to converge. Have you selected variables with vars? You can try again, if you really want to, by increasing max.params.\n", sep = "", call. = FALSE) else if (nparams > dim(data)[[1]]/5) cat("You will be fitting a large model with ", nparams, " parameters and only ", dim(data)[[1]], " records that may take a long time and fail to converge. Have you selected variables with vars?\n") if (maxorder >= 1) logit.int <- as.formula(paste("t ~ .^", maxorder + 1)) else logit.int <- as.formula(paste("t ~ .")) if (aggregate == TRUE) fit <- glm(logit.int, data = aggdat, family = "binomial", control = list(maxit = maxit), weights = wt) else fit <- suppressWarnings(glm(logit.int, data = df.prop, family = "binomial", control = list(maxit = maxit))) score <- predict(fit, type = "response") if (incomplete == FALSE) km1 <- length(fit$coefficients[!is.na(fit$coefficients)]) - 1 else { namescoef <- names(fit$coefficients) coefOK <- rep(FALSE, length(namescoef)) for (nn in notunsyn) coefOK[grepl(nn, namescoef)] <- TRUE km1 <- sum(coefOK & print.flag) if (m == 1 || (m > 1 & j == 1)) cat("Expectation of utility uses only coefficients involving synthesised variables: ", km1, " from ", length(fit$coefficients) - 1, "\n", sep = "") } if (k.syn) km1 <- km1 + 1 if (aggregate == TRUE) { pMSE <- (sum(wt*(score - cc)^2, na.rm = T)) / N KSt <- suppressWarnings(ks.test(rep(score[aggdat$t == 1], wt[aggdat$t == 1]), rep(score[aggdat$t == 0], wt[aggdat$t == 0]))) SPECKS <- KSt$statistic PO50 <- sum(wt[(score > 0.5 & df.prop$t == 1) | ( score <= 0.5 & df.prop$t == 0)])/N*100 - 50 U <- suppressWarnings(wilcox.test(rep(score[aggdat$t == 1], wt[aggdat$t == 1]), rep(score[aggdat$t == 0], wt[aggdat$t == 0]))$statistic) } else { pMSE <- (sum((score - cc)^2, na.rm = T)) / N KSt <- suppressWarnings(ks.test(score[df.prop$t == 1], score[df.prop$t == 0])) SPECKS <- KSt$statistic PO50 <- sum((score > 0.5 & df.prop$t == 1) | ( score <= 0.5 & df.prop$t == 0))/N*100 - 50 U <- suppressWarnings(wilcox.test(score[df.prop$t == 1], score[df.prop$t == 0])$statistic) } pMSEExp <- km1 * (1 - cc)^2 * cc / N S_pMSE <- pMSE / pMSEExp fit$data <- NULL } else if (method == "cart") { km1 <- NA if (tree.method == "rpart") { fit <- rpart(t ~ ., data = df.prop, method = 'class', control = rpart.control(cp = cp, minbucket = minbucket)) score <- predict(fit)[, 2] } else if (tree.method == "ctree") { fit <- ctree(t ~ ., data = df.prop, controls = ctree_control(mincriterion = mincriterion, minbucket = minbucket)) score <- predict(fit) } pMSE <- sum((score - cc)^2, na.rm = T) / N KSt <- suppressWarnings(ks.test(score[df.prop$t == 1], score[df.prop$t == 0])) SPECKS <- KSt$statistic PO50 <- sum((score > 0.5 & df.prop$t == 1) | ( score <= 0.5 & df.prop$t == 0))/N*100 - 50 U <- suppressWarnings(wilcox.test(score[df.prop$t == 1], score[df.prop$t == 0])$statistic) } if (!is.null(resamp.method) && resamp.method == "none") S_pMSE <- NA else if (!is.null(resamp.method) && resamp.method == "perm") { S_pMSE <- rep(NA, m) simpMSE <- rep(0, nperms) if (m == 1) j <- 1 if (j == 1 & print.flag) { if (print.every == 0 | print.every >= nperms) cat("Running ", nperms, " permutations to get NULL utilities.", sep = "") else cat("Running ", nperms, " permutations to get NULL utilities and printing every ", print.every, "th.", sep = "") } if (print.flag) cat("\nsynthesis ", j, " ", sep = "") for (i in 1:nperms) { if (print.every > 0 & nperms > print.every & floor(i/print.every) == i/print.every & print.flag) cat(i, " ", sep = "") pdata <- df.prop if (!k.syn) pdata$t <- sample(pdata$t) else pdata$t <- rbinom(N, 1, 0.5) if (method == "cart") { if (tree.method == "rpart") { sfit <- rpart(t ~ ., data = pdata, method = 'class', control = rpart.control(cp = cp, minbucket = minbucket)) score <- predict(sfit)[,2] } else if (tree.method == "ctree") { sfit <- ctree(t ~ ., data = pdata, controls = ctree_control(mincriterion = mincriterion, minbucket = minbucket)) score <- predict(sfit) } simpMSE[i] <- (sum((score - cc)^2, na.rm = T)) / N / 2 } else if (method == "logit") { if (maxorder >= 1) logit.int <- as.formula(paste("t ~ .^", maxorder + 1)) else logit.int <- as.formula(paste("t ~ .")) if (aggregate == TRUE) { aggdat1 <- aggregate(pdata[,1], by = pdata, FUN = length) wt <- aggdat1$x aggdat1 <- aggdat1[, -dim(aggdat1)[2]] sfit <- glm(logit.int, data = aggdat1, family = "binomial", control = list(maxit = maxit), weights = wt) } else sfit <- glm(logit.int, data = pdata, family = "binomial", control = list(maxit = maxit)) if (sfit$converged == FALSE & print.flag) cat("Warning: Logistic model did not converge in ", maxit, " iterations.\nYou could try increasing parameter 'maxit'.\n", sep = "") score <- predict(sfit, type = "response") if (aggregate == TRUE) { simpMSE[i] <- sum(wt*(score - cc)^2, na.rm = T) / N / 2 } else { simpMSE[i] <- sum((score - cc)^2, na.rm = T) / N / 2 } } } nnosplits <- c(sum(simpMSE < 1e-8), length(simpMSE)) S_pMSE <- pMSE/mean(simpMSE) } if (!is.null(resamp.method) && resamp.method == "pairs") res.ind <- list(pMSE = pMSE, SPECKS = SPECKS, PO50 = PO50, U = U, S_pMSE= NA, S_SPECKS = NA, S_PO50 = NA, S_U = NA, fit = fit, nnosplits = NA, df = NA) else if (!is.null(resamp.method) && resamp.method == "perm") res.ind <- list(pMSE = pMSE, SPECKS = SPECKS, PO50 = PO50,U = U, S_pMSE= S_pMSE, S_SPECKS = NA, S_PO50 = NA, S_U = NA, fit = fit, nnosplits = nnosplits, df = NA) else res.ind <- list(pMSE = pMSE, SPECKS = SPECKS, PO50 = PO50, U =U, S_pMSE = S_pMSE, S_SPECKS = NA, S_PO50 = NA, S_U = NA, fit = fit, nnosplits = NA, df = km1) return(res.ind) } n1 <- nrow(data) if (m == 1) { n2 <- nrow(object$syn) res.ind <- propcalcs(object$syn, data) res <- list(call = match.call(), m = m, method = method, tree.method = tree.method, resamp.method = resamp.method, maxorder = maxorder, vars = vars, k.syn = k.syn, aggregate = aggregate, maxit = maxit, ngroups = ngroups, mincriterion = mincriterion, nperms = nperms, df = res.ind$df, incomplete = incomplete, pMSE = res.ind$pMSE, S_pMSE = res.ind$S_pMSE, S_SPECKS = res.ind$S_SPECKS, S_PO50 = res.ind$S_PO50,S_U = res.ind$S_U, SPECKS = res.ind$SPECKS, PO50 = res.ind$PO50, U = res.ind$U, print.stats = print.stats, fit = res.ind$fit, nnosplits = res.ind$nnosplits, digits = digits, print.ind.results = print.ind.results, print.zscores = print.zscores, zthresh = zthresh, print.variable.importance = print.variable.importance) } else { n2 <- nrow(object$syn[[1]]) pMSE <- SPECKS <- PO50 <- U <- S_pMSE <- S_SPECKS <- S_PO50 <- S_U <- rep(NA, m) fit <- nnosplits <- as.list(1:m) if (!is.null(resamp.method) && !(resamp.method == "none") && resamp.method == "pairs") { kk <- 0 simpMSE <- simKS <- simPO50 <- simU <- rep(NA, m*(m - 1)/2) } for (j in 1:m) { res.ind <- propcalcs(object$syn[[j]], data) pMSE[j] <- res.ind$pMSE SPECKS[j] <- res.ind$SPECKS PO50[j] <- res.ind$PO50 U[j] <- res.ind$U fit[[j]] <- res.ind$fit if (resamp.method == "none" || (method == "logit" & (is.null(resamp.method)))) { if (j == 1 & print.flag) cat("Fitting syntheses: ") if (print.flag) { cat(j, " ", sep = "") if (res.ind$fit$converged == FALSE) cat("Convergence failed.\n") } if (j == m ) cat("\n") S_pMSE[j] <- res.ind$S_pMSE } if (!is.null(resamp.method) && resamp.method == "pairs") { if (j == 1 & print.flag) { if (print.every == 0 | m*(m - 1)/2 <= print.every) cat("Simulating NULL pMSE from ", m*(m - 1)/2, " pair(s).", sep = "") else cat("Simulating NULL pMSE from ", m*(m - 1)/2, " pairs, printing every ", print.every, "th:\n", sep = "") if (m*(m - 1)/2 < 6 ) cat("\nNumber of pairs too low, we suggest increasing number of syntheses (m).\n") } if (j < m) { for (jj in (j + 1):(m)) { kk <- kk + 1 if (print.every > 0 & print.every < m*(m - 1)/2 & floor(kk/print.every) == kk/print.every & print.flag) cat(kk," ",sep = "") simvals <- propcalcs(object$syn[[j]], object$syn[[jj]]) simpMSE[kk] <- simvals$pMSE simKS[kk] <- simvals$SPECKS simPO50[kk] <- simvals$SPECKS simU[kk] <- simvals$U } } nnosplits<- c(sum(simpMSE < 1e-8), length(simpMSE)) for (j in 1:m) { S_pMSE[j] <- pMSE[j] *2 /mean(simpMSE) S_SPECKS[j] <- SPECKS[j] *2 /mean(simKS) S_PO50[j] <- PO50[j] *2 /mean(simPO50) S_U[j] <- U[j] *2 /mean(simU) } } else { nnosplits[[j]] <- res.ind$nnosplits S_pMSE[j] <- res.ind$S_pMSE S_SPECKS[j] <- res.ind$S_SPECKS S_PO50[j] <- res.ind$S_PO50 S_U[j] <- res.ind$S_U } } res <- list(call = match.call(), m = m, method = method, tree.method = tree.method, resamp.method = resamp.method, maxorder = maxorder, vars = vars, k.syn = k.syn, aggregate = aggregate, maxit = maxit, ngroups = ngroups, mincriterion = mincriterion, nperms = nperms, df = res.ind$df, incomplete = incomplete, pMSE = pMSE, S_pMSE = S_pMSE, S_SPECKS = S_SPECKS, S_PO50 = S_PO50, S_U = S_U, SPECKS = SPECKS, PO50 = PO50, U = U, print.stats = print.stats, fit = fit, nnosplits = nnosplits, digits = digits, print.ind.results = print.ind.results, print.zscores = print.zscores, zthresh = zthresh, print.variable.importance = print.variable.importance) } class(res) <- "utility.gen" res$call <- match.call() return(res) } utility.tab <- function(object, data, ...) UseMethod("utility.tab") utility.tab.default <- function(object, ...) stop("No compare method associated with class ", class(object), call. = FALSE) utility.tab.data.frame <- utility.tab.list <- function(object, data, vars = NULL, cont.na = NULL, ngroups = 5, useNA = TRUE, max.table = 1e6, print.tables = length(vars) < 4, print.stats = c("pMSE", "S_pMSE", "df"), print.zdiff = FALSE, print.flag = TRUE, digits = 4, k.syn = FALSE, ...) { if (is.null(data)) stop("Requires parameter 'data' to give name of the real data.\n", call. = FALSE) if (is.null(object)) stop("Requires parameter 'object' to give name of the synthetic data.\n", call. = FALSE) if (is.list(object) & !is.data.frame(object)) m <- length(object) else if (is.data.frame(object)) m <- 1 else stop("object must be a data frame or a list of data frames.\n", call. = FALSE) cna <- cont.na cont.na <- as.list(rep(NA, length(data))) names(cont.na) <- names(data) if (!is.null(cna)) { if (!is.list(cna) | any(names(cna) == "") | is.null(names(cna))) stop("Argument 'cont.na' must be a named list with names of selected variables.", call. = FALSE) if (any(!names(cna) %in% names(data))) stop("Names of the list cont.na must be variables in data.\n", call. = FALSE) for (i in 1:length(cna)) { j <- (1:length(data))[names(cna)[i] == names(data)] cont.na[[j]] <- unique(c(NA,cna[[i]])) } } object <- list(syn = object, m = m, cont.na = cont.na) class(object ) <- "synds" res <- utility.tab.synds(object = object, data = data, vars = vars, ngroups = ngroups, useNA = useNA, print.tables = print.tables, print.stats = print.stats, print.zdiff = print.zdiff, print.flag = print.flag, digits = digits, k.syn = k.syn, ...) return(res) } utility.tab.synds <- function(object, data, vars = NULL, ngroups = 5, useNA = TRUE, max.table = 1e6, print.tables = length(vars) < 4, print.stats = c("pMSE", "S_pMSE", "df"), print.zdiff = FALSE, print.flag = TRUE, digits = 4, k.syn = FALSE, ...) { vars <- unique(vars) if (is.null(data)) stop("Requires parameter 'data' to give name of the real data.\n", call. = FALSE) if (!is.data.frame(data)) stop("Data must have class 'data.frame'.\n", call. = FALSE) if (!class(object) == "synds") stop("Object must have class 'synds'.\n", call. = FALSE) if (is.null(vars)) stop("You need to set variables with vars parameter.\n", call. = FALSE) else if (!(all(vars %in% names(data)))) stop("Unrecognized variable(s) in vars parameter: ", paste(vars[!(vars %in% names(data))], collapse = ", "), call. = FALSE) if (!all(print.stats %in% c("VW", "FT", "JSD", "SPECKS", "WMabsDD", "U", "G", "pMSE", "PO50", "MabsDD", "dBhatt","S_VW", "S_FT", "S_JSD", "S_WMabsDD", "S_G", "S_pMSE", "df", "dfG", "all"))) stop('print.stats must be set to "all" or selected from "VW", "FT", "JSD", "SPECKS", "WMabsDD", "U", "G", "pMSE", "PO50", "MabsDD", "dBhatt", "S_VW", "S_FT", "S_JSD", "S_WMabsDD", "S_G", "S_pMSE", "df" or "dfG".\n', call. = FALSE) data <- data[, vars, drop = FALSE] nvars <- ncol(data) data.orig <- data if (!is.null(object$strata.syn)) { cna <- object$cont.na[1, ] } else { cna <- object$cont.na } cna <- cna[vars] m <- object$m if (m == 1) syndata <- list(object$syn) else syndata <- object$syn syndata <- lapply(syndata, '[', vars) pMSE <- S_pMSE <- df <- dfG <- VW <- S_VW <- FT <- S_FT <- G <- S_G <- JSD <- U <- S_JSD <- MabsDD <- WMabsDD <- S_WMabsDD <- SPECKS <- dBhatt <- PO50 <- nempty <- vector("numeric", m) tab.syn <- tab.obs <- tab.zdiff <- vector("list", m) syn.mvar <- vector("list", nvars) for (j in 1:nvars) { if (is.numeric(syndata[[1]][, j])) syn.mvar[[j]] <- c(sapply(syndata, '[[', j)) } for (i in 1:m) { data <- data.orig for (j in 1:nvars) { if (is.numeric(data[, j])) { grpd <- group_num(data[, j], syndata[[i]][, j], syn.mvar[[j]], n = ngroups, cont.na = cna[[j]], ...) data[, j] <- grpd[[1]]; syndata[[i]][, j] <- grpd[[2]] } else if (is.character(data[, j])) { data[, j] <- factor(data[, j]) syndata[[i]][, j] <- factor(syndata[[i]][, j], levels = levels(data[, j])) } if (any(is.na(data[, j])) & useNA) { data[, j] <- addNA(data[, j]) syndata[[i]][, j] <- addNA(syndata[[i]][, j]) } } table.size <- prod(sapply(data, function(x) length(levels(x)))) if (table.size > max.table) stop("Table size ", round(table.size), " exceeds max.table limit of ", round(max.table),".", "\nYou could try increasing max.table but memory problems are likely.\n", call. = FALSE) else if (i == 1 & table.size > dim(data)[1]/2 & print.flag) cat("Warning: You are creating tables with ", table.size, " cells from ", dim(data)[1], " observations.\nResults from sparse tables may be unreliable.\n", sep = "") if (useNA){ tab.obs[[i]] <- table(data, useNA = "ifany", deparse.level = 0) tab.syn[[i]] <- table(syndata[[i]], useNA = "ifany", deparse.level = 0) } else { tab.obs[[i]] <- table(data, useNA = "no", deparse.level = 0) tab.syn[[i]] <- table(syndata[[i]], useNA = "no", deparse.level = 0) } nempty[i] <- sum(tab.obs[[i]] + tab.syn[[i]] == 0) td <- tab.obs[[i]][tab.obs[[i]] + tab.syn[[i]] > 0] ts <- tab.syn[[i]][tab.obs[[i]] + tab.syn[[i]] > 0] totcells <- length(td) if (!k.syn) df[i] <- totcells - 1 else df[i] <- totcells cc <- sum(ts) / sum(ts + td) N <- sum(ts + td) sumos <- ts + td expect <- sumos * cc diff <- ts - td * cc / (1 - cc) VW[i] <- sum(diff^2 / expect) FT[i] <- 4*sum((ts^(0.5) - (cc / (1 - cc) * td)^(0.5))^2) S_FT[i] <- FT[i] / df[i] S_VW[i] <- S_pMSE[i] <- VW[i] / df[i] pMSE[i] <- VW[i] * cc * (1 - cc)^2 / N tab.zdiff[[i]] <- suppressWarnings((tab.syn[[i]] - tab.obs[[i]] * cc/(1-cc)) / sqrt((tab.syn[[i]] + tab.obs[[i]]) * cc)) ptabd <- td / sum(td) ptabs <- ts / sum(ts) phalf <- (ptabd + ptabs) *0.5 JSD[i] <- sum((ptabd * log2(ptabd/phalf))[ptabd > 0])/2 + sum((ptabs * log2(ptabs/phalf))[ptabs > 0])/2 S_JSD[i] <- JSD[i]*2*N/df[i]/log(2) sok <- ts[ts > 1e-8 & td > 1e-8] dok <- td[ts > 1e-8 & td > 1e-8] if (!k.syn) dfG[i] <- length(dok) - 1 else dfG[i] <- length(dok) G[i] <- 2 *sum(sok*log(sok/sum(sok)/dok*sum(dok))) S_G[i] <- G[i] / dfG[i] score <- ts / (ts + td) kst <- suppressWarnings(ks.test(rep(score, ts), rep(score, td))) SPECKS[i] <- kst$statistic Ut <- suppressWarnings(wilcox.test(rep(score, ts), rep(score, td))) U[i] <- Ut$statistic predsyn <- (ptabs > ptabd) PO50[i] <- (sum(ts[predsyn]) + sum(td[!predsyn])) / (sum(ts) + sum(td)) * 100 - 50 MabsDD[i] <- sum(abs(diff))/sum(ts) WMabsDD[i] <- sum(abs(diff)/sqrt(expect))/sqrt(2/pi) S_WMabsDD[i] <- WMabsDD[i]/df[i] dBhatt[i] <- sqrt(1 - sum(sqrt(ptabd*ptabs))) } tab.obs <- tab.obs[[1]] if (m == 1) { tab.syn <- tab.syn[[1]] tab.zdiff <- tab.zdiff[[1]] } res <- list(m = m, VW = VW, FT = FT, JSD = JSD, SPECKS = SPECKS, WMabsDD = WMabsDD, U = U, G = G, pMSE = pMSE, PO50 = PO50, MabsDD = MabsDD, dBhatt = dBhatt, S_VW = S_VW, S_FT = S_FT, S_JSD = S_JSD, S_WMabsDD = S_WMabsDD, S_G = S_G, S_pMSE = S_pMSE, df = df, dfG = dfG, nempty = unlist(nempty), tab.obs = tab.obs, tab.syn = tab.syn, tab.zdiff = tab.zdiff, digits = digits, print.stats = print.stats, print.zdiff = print.zdiff, print.tables = print.tables, n = sum(object$n), k.syn = k.syn) class(res) <- "utility.tab" return(res) } group_num <- function(x1, x2, xsyn, n = 5, style = "quantile", cont.na = NA, ...) { if (!is.numeric(x1) | !is.numeric(x2) | !is.numeric(xsyn)) stop("x1, x2, and xsyn must be numeric.\n", call. = FALSE) x1nm <- x1[!(x1 %in% cont.na) & !is.na(x1)] x2nm <- x2[!(x2 %in% cont.na) & !is.na(x2)] xsynnm <- xsyn[!(xsyn %in% cont.na) & !is.na(xsyn)] my_breaks <- unique(suppressWarnings(classIntervals(c(x1nm, xsynnm), n = n, style = style, ...))$brks) my_levels <- c(levels(cut(x1nm, breaks = my_breaks, dig.lab = 8, right = FALSE, include.lowest = TRUE)), cont.na[!is.na(cont.na)]) x1[!(x1 %in% cont.na) & !is.na(x1)] <- as.character(cut(x1nm, breaks = my_breaks, dig.lab = 8, right = FALSE, include.lowest = TRUE)) x2[!(x2 %in% cont.na) & !is.na(x2)] <- as.character(cut(x2nm, breaks = my_breaks, dig.lab = 8, right = FALSE, include.lowest = TRUE)) x1 <- factor(x1, levels = my_levels) x2 <- factor(x2, levels = my_levels) return(list(x1,x2)) }
getBestShiftConfiguration <- function(x, expectedNumberOfShifts , threshold = 5){ if (inherits(x, 'bammdata')) { x <- credibleShiftSet(x, expectedNumberOfShifts, threshold, set.limit = 0.95); } else if (inherits(x, 'credibleshiftset')) { } else { stop("Argument x must be of class bammdata or credibleshiftset\n"); } class(x) <- 'bammdata'; subb <- subsetEventData(x, index = x$indices[[1]]); coreshifts <- c((length(x$tip.label) + 1), x$coreshifts); coreshifts <- intersect(subb$eventData[[1]]$node, coreshifts); for (i in 1:length(subb$eventData)) { if (i == 1) { ff <- subb$eventData[[i]]; } ff <- rbind(ff, subb$eventData[[i]]); } xn <- numeric(length(coreshifts)); xc <- character(length(coreshifts)); if (x$type == 'diversification') { dff <- data.frame(generation = xn, leftchild=xc, rightchild=xc, abstime=xn, lambdainit=xn, lambdashift=xn, muinit = xn, mushift = xn, stringsAsFactors=F); for (i in 1:length(coreshifts)) { if (coreshifts[i] <= length(x$tip.label)) { dset <- c(x$tip.label[coreshifts[i]], NA) }else{ tmp <- extract.clade(as.phylo(x), node= coreshifts[i]); dset <- tmp$tip.label[c(1, length(tmp$tip.label))]; } tmp2 <- ff[ff$node == coreshifts[i], ]; dff$leftchild[i] <- dset[1]; dff$rightchild[i] <- dset[2]; dff$abstime[i] <- mean(tmp2$time); dff$lambdainit[i] <- mean(tmp2$lam1); dff$lambdashift[i] <- mean(tmp2$lam2); dff$muinit[i] <- mean(tmp2$mu1); dff$mushift[i] <- mean(tmp2$mu2); } best_ed <- getEventData(as.phylo(x), eventdata=dff); } else if (x$type == 'trait') { dff <- data.frame(generation = xn, leftchild=xc, rightchild=xc, abstime=xn, betainit=xn, betashift=xn, stringsAsFactors=F); for (i in 1:length(coreshifts)) { if (coreshifts[i] <= length(x$tip.label)) { dset <- c(x$tip.label[coreshifts[i]], NA) } else { tmp <- extract.clade(as.phylo(x), node= coreshifts[i]); dset <- tmp$tip.label[c(1, length(tmp$tip.label))]; } tmp2 <- ff[ff$node == coreshifts[i], ]; dff$leftchild[i] <- dset[1]; dff$rightchild[i] <- dset[2]; dff$abstime[i] <- mean(tmp2$time); dff$betainit[i] <- mean(tmp2$lam1); dff$betashift[i] <- mean(tmp2$lam2); } best_ed <- getEventData(as.phylo(x), eventdata=dff, type = 'trait'); } else { stop("error in getBestShiftConfiguration; invalid type"); } return(best_ed); }
library(geobr) library(magrittr) library(sf) library(dplyr) library(data.table) library(mapview) library(sfheaders) library(furrr) library(future) library(pbapply) source("./prep_data/prep_functions.R") update <- 2010 destdir <- paste0("./neighborhood/", update) dir.create(destdir, recursive =T) tracts <- geobr::read_census_tract(code_tract = 'all', year= update, simplified = F) head(tracts) tracts <- use_encoding_utf8(tracts) tracts <- st_cast(tracts, to="MULTIPOLYGON") future::plan(future::multiprocess) nei <- subset(tracts, !is.na(name_neighborhood)) all_muni_part1 <- unique(nei$code_muni) temp_list1 <- furrr::future_map(.x = all_muni_part1, .progress = TRUE, .f = function(X){dissolve_polygons( mysf = subset(nei, code_muni== X), group_column = 'code_neighborhood')} ) part_1_neighborhood <- do.call('rbind', temp_list1) temp_nei <- select(nei, code_muni, name_muni, name_neighborhood, code_neighborhood, code_subdistrict, name_subdistrict, code_district, name_district ) temp_nei$geom <- NULL temp_nei <- unique(temp_nei) part_1_neighborhood_final <- left_join(part_1_neighborhood, temp_nei) part_1_neighborhood_final$reference_geom <- 'neighborhood' part_1_neighborhood_final %<>% group_by(code_muni) %>% mutate(count=n()) %>% ungroup() table(part_1_neighborhood_final$count) part_1_neighborhood_final <- subset(part_1_neighborhood_final, count > 1) part_1_neighborhood_final$count <- NULL df_subdistrict <- subset(tracts, is.na(name_neighborhood) & !is.na(name_subdistrict)) df_subdistrict <- subset(df_subdistrict, !(code_muni %in% all_muni_part1)) all_muni_part <- unique(df_subdistrict$code_muni) temp_list2 <- furrr::future_map(.x = all_muni_part2, .progress = TRUE, .f = function(X){dissolve_polygons( mysf = subset(df_subdistrict, code_muni== X), group_column = 'code_subdistrict')} ) part_2_subdistrict <- do.call('rbind', temp_list2) temp_subdistrict <- select(df_subdistrict, code_muni, name_muni, code_subdistrict, name_subdistrict, code_district, name_district ) temp_subdistrict$geom <- NULL temp_subdistrict <- unique(temp_subdistrict) part_2_subdistrict_final <- left_join(part_2_subdistrict, temp_subdistrict) part_2_subdistrict_final$reference_geom <- 'subdistrict' part_2_subdistrict_final %<>% group_by(code_muni) %>% mutate(count=n()) %>% ungroup() table(part_2_subdistrict_final$count) part_2_subdistrict_final <- subset(part_2_subdistrict_final, count > 5) part_2_subdistrict_final$count <- NULL df_district <- subset(tracts, is.na(name_neighborhood) & is.na(name_subdistrict) & !is.na(name_district)) df_district <- subset(df_district, !(code_muni %in% all_muni_part1)) df_district <- subset(df_district, !(code_muni %in% all_muni_part2)) all_muni_part3 <- unique(df_district$code_muni) temp_list3 <- furrr::future_map(.x = all_muni_part3, .progress = TRUE, .f = function(X){dissolve_polygons( mysf = subset(df_district, code_muni== X), group_column = 'code_district')} ) part_3_district <- do.call('rbind', temp_list3) temp_district <- select(df_district, code_muni, name_muni, code_district, name_district ) temp_district$geom <- NULL temp_district <- unique(temp_district) part_3_district_final <- left_join(part_3_district, temp_district) part_3_district_final$reference_geom <- 'district' part_3_district_final %<>% group_by(code_muni) %>% mutate(count=n()) %>% ungroup() table(part_3_district_final$count) part_3_district_final <- subset(part_3_district_final, count > 15) part_3_district_final$count <- NULL intersect(part_1_neighborhood_final$code_muni, part_2_subdistrict_final$code_muni) intersect(part_1_neighborhood_final$code_muni, part_3_district_final$code_muni) intersect(part_3_district_final$code_muni, part_2_subdistrict_final$code_muni) names(part_1_neighborhood_final) names(part_2_subdistrict_final) names(part_3_district_final) ncol(part_1_neighborhood_final) ncol(part_2_subdistrict_final) ncol(part_3_district_final) part_2_subdistrict_final$name_neighborhood <- NA part_2_subdistrict_final$code_neighborhood <- NA part_3_district_final$name_neighborhood <- NA part_3_district_final$code_neighborhood <- NA part_3_district_final$code_subdistrict <- NA part_3_district_final$name_subdistrict <- NA setcolorder(part_1_neighborhood_final, c("code_muni", "name_muni", "name_neighborhood", "code_neighborhood", "code_subdistrict", "name_subdistrict", "code_district", "name_district", "reference_geom", "geometry")) setcolorder(part_2_subdistrict_final, c("code_muni", "name_muni", "name_neighborhood", "code_neighborhood", "code_subdistrict", "name_subdistrict", "code_district", "name_district", "reference_geom", "geometry")) setcolorder(part_3_district_final, c("code_muni", "name_muni", "name_neighborhood", "code_neighborhood", "code_subdistrict", "name_subdistrict", "code_district", "name_district", "reference_geom", "geometry")) brazil <- rbind(part_1_neighborhood_final, part_2_subdistrict_final, part_3_district_final) head(brazil) nrow(brazil) brazil <- add_state_info(brazil) setcolorder(brazil, c("code_muni", "name_muni", "name_neighborhood", "code_neighborhood", "code_subdistrict", "name_subdistrict", "code_district", "name_district", "code_state", "abbrev_state", "reference_geom", "geometry")) head(brazil) brazil %<>% group_by(code_muni) %>% mutate(count=n()) %>% ungroup() table(brazil$count) brazil <- subset(brazil, count > 1) brazil$count <- NULL brazil <- harmonize_projection(brazil) brazil <- to_multipolygon(brazil) brazil_simp <- simplify_temp_sf(brazil, tolerance=10) as.numeric(object.size(brazil_simp)) / as.numeric(object.size(brazil)) sf::st_write(brazil, dsn= paste0(destdir, "/neighborhoods_", update, ".gpkg")) sf::st_write(brazil_simp, dsn= paste0(destdir, "/neighborhoods_", update,"_simplified", ".gpkg"))
new_record_update <- function(dimension, old, new) { update <- list(dimension = dimension, old = old, new = new) structure(update, class = "record_update") }
library(ump) ns <- seq(10, 40, 10) alphas <- ps <- seq(0, 1, 0.025) epsilon <- 1e-9 for (n in ns) { x <- seq(0, n) save <- array(NA, c(length(x), length(ps), length(alphas))) for (p in ps) { for (alpha in alphas) { px <- dbinom(x, n, p) phix <- umpu.binom(x, n, p, alpha) save[ , ps == p, alphas == alpha] <- phix foo <- sum(phix * px) bar <- sum(x * phix * px) if (p == 0 & alpha > 0 & alpha < 1) { fred <- phix[1:2] == alpha sally <- phix[- (1:2)] == 1 if ((! all(fred)) | (! all(sally))) cat("n =", n, ": p =", p, ": alpha =", alpha, ": fred =", fred, ": sally =", sally, "\n") } else if (p == 1 & alpha > 0 & alpha < 1) { fred <- rev(phix)[1:2] == alpha sally <- rev(phix)[- (1:2)] == 1 if ((! all(fred)) | (! all(sally))) cat("n =", n, ": p =", p, ": alpha =", alpha, ": fred =", fred, ": sally =", sally, "\n") } else { if (abs(foo - alpha) > epsilon) cat("n =", n, ": p =", p, ": alpha =", alpha, ": foo =", foo, "\n") if (abs(bar - n * p * alpha) > epsilon) cat("n =", n, ": p =", p, ": alpha =", alpha, ": bar =", bar, ": n * p * alpha =", n * p * alpha, "\n") } } } xs <- seq(0, n) for (x in xs) for (p in ps) { phix <- umpu.binom(x, n, p, alphas) phix.too <- save[xs == x, ps == p, ] if (! all.equal(phix, phix.too)) cat("oopsie!\n") } for (x in xs) for (alpha in alphas) { phix <- umpu.binom(x, n, ps, alpha) phix.too <- save[xs == x, , alphas == alpha] if (! all.equal(phix, phix.too)) cat("oopsie!\n") } }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) Sys.setenv("TESTTHAT" = "true") options(pins.quiet = FALSE) library(pins) board <- board_temp() mtcars <- tibble::as_tibble(mtcars) board %>% pin_write(mtcars, "mtcars") board %>% pin_read("mtcars") board %>% pin_meta("mtcars") board %>% pin_write(mtcars, description = "Data extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).", metadata = list( source = "Henderson and Velleman (1981), Building multiple regression models interactively. Biometrics, 37, 391–411." ) ) board %>% pin_meta("mtcars") board2 <- board_temp(versioned = TRUE) board2 %>% pin_write(1:5, name = "x", type = "rds") board2 %>% pin_write(2:6, name = "x", type = "rds") board2 %>% pin_write(3:7, name = "x", type = "rds") board2 %>% pin_versions("x") board2 %>% pin_read("x") paths <- file.path(tempdir(), c("mtcars.csv", "alphabet.txt")) write.csv(mtcars, paths[[1]]) writeLines(letters, paths[[2]]) board %>% pin_upload(paths, "example") board %>% pin_download("example") board %>% pin_read("example") board %>% pin_download("mtcars") my_data <- board_url(c( "penguins" = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/master/inst/extdata/penguins_raw.csv" )) my_data %>% pin_download("penguins") %>% read.csv(check.names = FALSE) %>% tibble::as_tibble()
context("assert_that") test_that("assert_that handles long false assertions gracefully", { expect_error( assert_that(isTRUE(10 + sqrt(25) + sum(1:10) + sqrt(25) + sum(11:20) + sqrt(25) + sum(21:30) + sqrt(25) + sum(31:40) + sqrt(25) + sum(41:50))), "^isTRUE\\(.* [.]{3} is not TRUE$" ) }) test_that("assert_that handles has_name failures with multiple missing names", { x <- list(a = TRUE, b = "hello") expect_error( assert_that(has_name(x, c("a", "f", "g"))), regexp = "x does not have all of these name" ) })
puchwein <- function(X, pc = 0.95, k = 0.2, min.sel = 5, details = FALSE, .center = TRUE, .scale = FALSE) { if (ncol(X) < 2) { stop("X should have at least 2 columns") } if (min.sel >= nrow(X)) { stop("min.sel should be lower than nrow(X)") } if (!is.data.frame(X)) { X <- as.data.frame(X) } pca <- prcomp(X, center = .center, scale = .scale) if (pc < 1) { pvar <- pca$sdev^2 / sum(pca$sdev^2) pcsum <- cumsum(pvar) < pc if (any(pcsum)) { pc <- max(which(pcsum)) + 1 } else { pc <- 1 } } X <- sweep(pca$x[, 1:pc, drop = FALSE], 2, pca$sdev[1:pc], "/") H <- fastDistV(X, colMeans(X), "euclid") lsel <- list() x <- data.frame(ID = 1:nrow(X), H) ord <- order(H, decreasing = TRUE) d <- fastDist(X, X, "euclid")[ord, ord] x <- x[ord, ] d.ini <- k * max((ncol(X) - 2), 1) m <- 1 repeat { Dm <- m * d.ini minD <- d[1, ] <= Dm sel <- x$ID[1] for (i in 1:nrow(x)) { if (!i %in% which(minD)) { sel <- c(sel, x$ID[i]) minD <- minD | d[i, ] <= Dm } } lsel[[m]] <- sel if (length(sel) <= min.sel) { break } m <- m + 1 } lsel[[length(lsel)]] <- NULL left <- sapply(lsel, length) sel <- nrow(x) - left x.mat <- as.matrix(X) L <- diag(x.mat %*% solve(t(x.mat) %*% x.mat) %*% t(x.mat)) oL <- sapply(lsel, function(x) sum(L[x])) tL <- (sum(L) / length(L)) * left res2 <- data.frame(loop = 1:(m - 1), removed = sel, obs = oL, theor = tL, diff = oL - tL) loop.optimal <- which.max(oL - tL) model <- lsel[[loop.optimal]] if (details) { return(list(model = model, test = (1:nrow(X))[-model], pc = X, loop.optimal = loop.optimal, leverage = res2, details = lsel)) } else { return(list(model = model, test = (1:nrow(X))[-model], pc = X, loop.optimal = loop.optimal, leverage = res2)) } }
metric.degree.max <- function(g) { if (!is.list(g)) stop("Parameter 'g' must be a list",call. = FALSE) max(lengths(g)) }
EMI_2d <- function(x, model, type = "UK", critcontrol = NULL, paretoFront = NULL, r = 0){ if(is.null(paretoFront)){ observations <- Reduce(cbind, lapply(model, slot, "y")) paretoFront <- t(nondominated_points(t(observations))) } if (is.unsorted(paretoFront[,1])){ paretoFront <- paretoFront[order(paretoFront[,1]),] } if(checkPredict(x, model, type = type, distance = critcontrol$distance, threshold = critcontrol$threshold)){ return(-1) } tmp <- data.frame(t(x)) colnames(tmp) <- colnames(model[[1]]@X) pred <- predict_kms(model, newdata=tmp, type=type, checkNames = FALSE, light.return = TRUE, cov.compute = FALSE) y <- as.numeric(pred$mean) s <- as.numeric(pred$sd) res <- sum(apply(expand.grid(1:2, 1:nrow(paretoFront)), 1, EMI_ij, paretoFront = paretoFront, y = y, s = s, r = r)) if(is.nan(res)) return(-1) return(res) } EMI_ij <- function(ij, paretoFront, y, s, r){ return(Int1(ij[1], ij[2], paretoFront, y, s, r) + Int2(ij[1], ij[2], paretoFront, y, s, r) + Int3(ij[1], ij[2], paretoFront, y, s, r)) } k_S <- function(a){ if(a == 1){ return(2) } if(a == 2){ return(1) } } h_S <- function(i, j){ if(i == 1){ return(j - 1); } if(i == 2){ return(j + 1); } } d_S <- function(i, j, P, y){ if(i == 1 & j == (nrow(P)+1)){ return(Inf) } if(i == 2 & j == 0){ return(Inf) } return(P[j,i] - y[i]) } u_S <- function(i, j, P, y, s){ pnorm(d_S(i, j, P, y)/s[i]) } v_S <- function(i, j, P, y, s, r){ if(j == 0){ return(Inf) } if(j ==(nrow(P)+1)){ return(Inf) } return(y[i]/s[i]^2 + (P[j,2] - d_S(k_S(i), j, P, y) + r * s[k_S(i)] * y[i] / s[i]) / sqrt((1-r^2)*s[k_S(i)]^2)) } q_S <- function(i, j, P, y, s, r){ (1 - r^2) * s[k_S(i)]^2 * s[i]^2 / (s[i]^2 + s[k_S(i)]^2 - 2 * r * s[i] * s[k_S(i)]) } Int1 <- function(i, j, P, y, s, r){ return( s[i] * dnorm(d_S(i,j, P, y) / s[i]) * ( pnorm((-d_S(k_S(i), j, P, y) + r * s[k_S(i)] * d_S(i,j, P, y) / s[i]) / sqrt((1 - r^2) * s[k_S(i)]^2)) - pnorm((-d_S(k_S(i), h_S(i, j), P, y) + r * s[k_S(i)] * d_S(i,j, P, y) / s[i]) / sqrt((1 - r^2) * s[k_S(i)]^2)) ) ) } Int2 <- function(i, j, P, y, s, r){ aa <- q_S(i, j, P, y, s, r) a1 <- sqrt(aa) * (s[i] - s[k_S(i)] * r) / sqrt(2 * pi * (1 - r^2) * s[k_S(i)]^2) a2 <- exp(-1/2 * (y[i]^2 / s[i]^2 + (P[j,i] - d_S(k_S(i), j, P, y) + r * s[k_S(i)] * y[i] / s[i])^2 / sqrt(1 - r^2) * s[k_S(i)]^2)) * exp(1/2 * aa * v_S(i, j, P, y, s, r)^2) * pnorm((P[j,i] - aa * v_S(i, j, P, y, s, r)) / sqrt(aa)) a3 <- exp(-1/2 * (y[i]^2 / s[i]^2 + (P[j,i] - d_S(k_S(i), h_S(i,j), P, y) + r * s[k_S(i)] * y[i] / s[i])^2 / sqrt(1-r^2)*s[k_S(i)]^2)) * exp(1/2 * aa * v_S(i, h_S(i, j), P, y, s, r)^2) * pnorm((P[j,i] - aa * v_S(i, h_S(i,j), P, y, s, r)) / sqrt(aa)) if(is.nan(a2)) a2 <- 0 if(is.nan(a3)){ a3 <- 0 } return(a1 * (a2 - a3)) } ftmp1 <- function(w, i, j, P, y, s, r){ return( pnorm((d_S(i, j, P, y) - d_S(k_S(i), j, P, y) + (s[k_S(i)]*r - s[i])*qnorm(w))/sqrt((1-r^2)*s[k_S(i)]^2)) ) } ftmp2 <- function(w, i, j, P, y, s, r){ return( pnorm((d_S(i, j, P, y) - d_S(k_S(i), h_S(i, j), P, y) + (s[k_S(i)]*r - s[i])*qnorm(w))/sqrt((1-r^2)*s[k_S(i)]^2)) ) } Int3 <- function(i, j, P, y, s, r){ a1 <- d_S(i, j, P, y) b1 <- u_S(i, j, P, y, s) if(b1 < 1e-5){ return(0) } a2 <- integrate(ftmp1, 0, b1, i=i, j=j, P=P, y=y, s=s, r=r, stop.on.error = FALSE)$value a3 <- integrate(ftmp2, 0, b1, i=i, j=j, P=P, y=y,s=s, r=r, stop.on.error = FALSE)$value return(a1 * (a2 - a3)) }
ji_fisher <- function(x) { x <- unlist(strsplit(x, "")) x <- purrr::map_chr(x, get_emoji) structure( paste0(x, collapse = ""), class = "emoji") } get_emoji <- function(x) { emojis <- emo::fisher_lst[[tolower(x)]] if (length(emojis) == 0L) { return(x) } sample(emojis, 1) } "fisher_lst" print.fisher_alphabet <- function(x, ...){ letters <- names(x) emojis <- map_chr( x, paste, collapse = " ") writeLines( paste( letters, " : ", emojis) ) invisible(x) }
`PLTpicks` <- function(picks, labs=NA, cols=NA) { if(missing(labs)) { labs = rep(NA, length(picks)) } if(missing(cols)) { cols = rep(NA, length(picks)) } u=par("usr") pyt=u[4]-0.05*(u[4]-u[3]) if(length(cols)<length(picks)) {cols = rep( cols[1],length(picks)) } if(length(labs)<length(picks)) {labs = rep( labs[1],length(picks)) } for(i in 1:length(picks)) { if(!is.na(cols[i])) { col=cols[i] } else { col = 1 } abline(v=picks[i], col=col, lty=3) if(!is.na(labs[i])) { text( picks[i], pyt, labs[i], adj=0, col=col) } } }
logisticbyx <- function (distance, x, models, beta, point){ xlist <- as.list(x) xlist$distance <- distance xmat <- expand.grid(xlist) if(!point){ return(g0(beta, setcov(xmat, models$g0model))) }else{ return(g0(beta, setcov(xmat, models$g0model))*2*distance) } }
shiny::tabPanel( title = "Update nodes/edges data", fluidRow( column( width = 4, actionButton("goUpdate", "Update data"), actionButton("goRemove", "Remove data") ), column( width = 8, visNetworkOutput("network_proxy_update", height = "400px") ) ), verbatimTextOutput("code_proxy_update") )
library(miRetrieve) library(testthat) set.seed(42) toy_df <- data.frame("miRNA_" = sample(c("miR-24", "miR-25", "miR-26"), size = 20, replace = TRUE), "PMID" = seq(1:20)) subset_df <- subset_mir(toy_df, mir.retain = "miR-24", col.mir = miRNA_) test_that("Tests subsetting data.frames for miRNAs", { expect_equal(nrow(subset_df), 9) }) subset_df_abs <- subset_mir_threshold(toy_df, col.mir = miRNA_, threshold = 9) subset_df_rel <- subset_mir_threshold(toy_df, col.mir = miRNA_, threshold = 0.3) test_that("Tests subsetting data.frames for a miRNA threshold", { expect_equal(nrow(subset_df_abs), 9) expect_equal(nrow(subset_df_rel), 15) })
context("test-gapDer") test_that("gapDer works", { nirdata <- data("NIRsoil") X_gapDer <- gapDer(NIRsoil$spc, m = 1, w = 3) expect_is(X_gapDer, "matrix") expect_true(round(max(abs(X_gapDer[1, ])), 5) == 0.00517) })
add_pwa_deps <- function(tag) { pwa_deps <- htmlDependency( name = "pwa-utils", version = packageVersion("shinyMobile"), src = c(file = "shinyMobile-0.9.1"), head = "<link rel=\"manifest\" href=\"manifest.webmanifest\" /> <link rel=\"icon\" type=\"image/png\" href=\"icons/icon-144.png\" sizes=\"144x144\" /> <link rel=\"apple-touch-icon\" href=\"icons/apple-touch-icon.png\" /> <link rel=\"icon\" href=\"icons/favicon.png\"/> ", package = "shinyMobile", ) tagList(tag, pwa_deps) }
skip_on_cran() test_that("modify_column_alignment() works", { expect_error( lm(age ~ marker + grade, trial) %>% tbl_regression() %>% modify_column_alignment(columns = everything(), align = "left"), NA ) })
NULL read_CensoEscolar <- function(ft,i,harmonize_varnames=F,root_path=NULL, file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ if (harmonize_varnames==T) { var_translator <- read_var_translator('CensoEscolar','escola') read_data("CensoEscolar", ft, i, var_translator = var_translator, root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) } else { read_data(dataset = "CensoEscolar",ft, i,root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) } } read_CensoEducacaoSuperior<- function(ft,i,root_path=NULL, file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ metadata <- read_metadata('CensoEducacaoSuperior') data<-read_data(dataset = "CensoEducacaoSuperior",ft, i,root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_ENEM<- function(ft,i,root_path=NULL, file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ metadata <- read_metadata('ENEM') data<-read_data(dataset = "ENEM",ft, i,root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_CENSO<- function(ft,i,root_path = NULL, file = NULL, vars_subset = NULL, UF = NULL, nrows = -1L, source_file_mark = F){ metadata <- read_metadata('CENSO') if(is.null(file)){ if(!is.null(UF)){ UF <- paste0("(",paste(UF, collapse = "|"),")") metadata[, grep("^ft_", names(metadata))] <- lapply(metadata[, grep("^ft_", names(metadata))], function(x) gsub(x = x, pattern = "&", replacement = paste0("&",UF,"/"))) } } data<-read_data(dataset = "CENSO", ft = ft, metadata = metadata, i = i, root_path = root_path,file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_RAIS<- function(ft, i,root_path = NULL,file = NULL, vars_subset = NULL,UF = NULL, nrows = -1L, source_file_mark = F){ metadata <- read_metadata('RAIS') if(!is.null(UF)){ UF <- paste0("(",paste(UF, collapse = "|"),")") metadata$ft_vinculos <- metadata$ft_vinculos %>% gsub(pattern = "[A-Z]{2}", replacement = UF, fixed = TRUE)} data <- read_data(dataset = "RAIS",ft = ft, i = i, metadata = metadata, root_path = root_path,file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_CAGED<- function(ft,i,root_path = NULL,file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ data<- read_data(dataset = "CAGED",ft = ft, i = i, root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_PNAD<- function(ft,i,root_path=NULL,file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ data<-read_data(dataset = "PNAD", ft, i, root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_PME <- function(ft,i, root_path = NULL,file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ if(!is.character(i)|!grepl(pattern = "^[0-9]{4}-[0-9]{2}m$", x = i)){ stop(paste0("The argument 'i' must be a character in the format 2014-01m.")) } data<- read_data(dataset = "PME", ft = ft,i = i, root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_POF <- function(ft,i, root_path = NULL,file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ if(i %in% c(1987,1995,1997)){ metadata <- read_metadata("POF") data_path <- paste(c(root_path, metadata[metadata$period == i, "path"], metadata[metadata$period == i, "data_folder"], ""), collapse = "/") uf<-list.files(data_path) tudo<-NULL for(j in uf){ dados <- readLines(paste0(data_path,j)) tudo <-c(tudo,dados) } casas <- substr(dados,1,2) out <- split( dados , f = casas ) invisible( lapply(seq_along(out), function(i) write.table(out[[i]],paste0(data_path,names(out)[[i]],".txt"),quote = FALSE,row.names = FALSE, col.names = FALSE) ) ) invisible(file.remove(paste0(data_path,names(out),".txt"))) } data <- read_data(dataset= "POF", ft = ft,i = i, root_path = root_path,file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_PNADcontinua<- function(ft,i,root_path=NULL,file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ data<-read_data(dataset = "PnadContinua",ft, i,root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) } read_PNS<- function(ft,i,root_path=NULL,file = NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){ data<-read_data(dataset = "PNS",ft, i,root_path = root_path, file = file, vars_subset = vars_subset, nrows = nrows, source_file_mark = source_file_mark) return(data) }
outogk<-function(x,sigmamu=taulc,v=gkcov,op=TRUE,SEED=FALSE, beta=max(c(.95,min(c(.99,1/nrow(x)+.94)))),n.iter=1,plotit=TRUE,...){ if(!is.matrix(x))stop("x should be a matrix") x<-elimna(x) if(!op){ temp<-ogk.pairwise(x,sigmamu=sigmamu,v=v,beta=beta,n.iter=n.iter,...) vals<-hard.rejection(temp$distances,p=ncol(x),beta=beta,...) flag<-(vals==1) vals<-c(1:nrow(x)) outid<-vals[!flag] keep<-vals[flag] if(is.matrix(x)){ if(ncol(x)==2 && plotit){ plot(x[,1],x[,2],xlab="X", ylab="Y",type="n") points(x[flag,1],x[flag,2]) if(sum(!flag)>0)points(x[!flag,1],x[!flag,2],pch="o") }}} if(op){ temp<-out(x,cov.fun=ogk,beta=beta,plotit=plotit,SEED=SEED) outid<-temp$out.id keep<-temp$keep } list(out.id=outid,keep=keep,distances=temp$dis) }