code
stringlengths
1
13.8M
library(hexSticker) library(magick) library(magrittr) img <- image_read(here::here("man", "figures", "lasso-img.jpg")) res <- img %>% image_convert("png") %>% image_resize("1080 x 200") %>% image_fill(color = "none") %>% image_annotate("bolasso", size = 10, degrees = 35, location = "+85+147", color="black") res <- sticker(filename = here::here("man", "figures", "logo.png"), white_around_sticker = FALSE, res, package = "", s_x = 0.97, s_y = 1.04, s_width = 1.7, s_height = 14, h_fill = " h_color = " save_sticker(sticker = res, filename = here::here("man", "figures", "logo.png"))
qdc.zsc <- function(results) { nstat <- results$brief$nstat nfactors <- results$brief$nfactors zsc <- results$zsc if (sum(is.na(colSums(zsc)))>0) { zsc <- results$zsc[,!is.na(colSums(zsc))>0] nfactors <- sum(!is.na(colSums(zsc))) } dac <- results$qdc$dist.and.cons names(dac) <- rownames(results$qdc) qdc.zsc <- matrix(NA, nrow=nrow(zsc), ncol=ncol(zsc), dimnames=dimnames(zsc)) for (i in 1:nfactors) { qdc.zsc[grep(paste0("all|f", i), dac), i] <- zsc[grep(paste0("all|f", i), dac), i] } if (nfactors==2) { for (i in 1:nfactors) { qdc.zsc[grep("Distinguishing", dac), i] <- zsc[grep("Distinguishing", dac), i] } } return(qdc.zsc) }
"lyme.svs.eco0.dat"
checkVal_fgpm <- function(env){ if (all(!is.null(env$sIn), !is.null(env$fIn))) { if (length(unique(c(nrow(env$sIn), as.numeric(sapply(env$fIn, nrow)), length(env$sOut)))) > 1) { stop("Inconsistent number of points. Please check that sIn, sOut and each matrix in fIn have all the same number of rows.") } if (!is.null(env$f_pdims)) { if (length(env$f_pdims) != length(env$fIn)) { stop(paste("Inconsistent number of projection dimensions. The functional input list has", length(env$fIn), "elements, but", length(env$f_pdims), "projection dimensions were specified.")) } } if (!is.null(env$ls_s.hyp)) { if (length(env$ls_s.hyp) != ncol(env$sIn)) { stop(paste("Inconsistent number of length-scale parameters. Please check that the vector ls_s.hyp has as many elements as the number\n ", "of columns in sIn., or leave this argument empty and the scalar length-scale parameters will be estimated from the data.")) } } if (!is.null(env$ls_f.hyp)) { od <- sapply(env$fIn, ncol) pd <- env$f_pdims zrs <- which(pd == 0) pd[zrs] <- od[zrs] sumdims <- sum(sapply(seq_along(pd), function(i) if(env$f_disType[i] == "L2_bygroup") return(1) else return(pd[i]))) if (length(env$ls_f.hyp) != sumdims) { stop(paste("Inconsistent number of length-scale parameters. Please check that the vector ls_f.hyp has as many elements as effective", "dimensions.\n Consider checking ?fgpm for details. Yoy can also leave this argument empty and the functional length-scale", "parameters will be\n estimated from the data.")) } } } else if(!is.null(env$fIn)) { if (length(unique(c(as.numeric(sapply(env$fIn, nrow)), length(env$sOut)))) > 1) { stop("Inconsistent number of points. Please check that sOut and each matrix in fIn have all the same number of rows.") } if (!is.null(env$f_pdims)) { if (length(env$f_pdims) != length(env$fIn)) { if (length(env$f_pdims) == 1) { stop(paste("Inconsistent number of projection dimensions. The functional input list has", length(env$fIn), "elements, but only", length(env$f_pdims), "projection dimension was specified.")) } else { stop(paste("Inconsistent number of projection dimensions. The functional input list has", length(env$fIn), "elements, but", length(env$f_pdims), "projection dimensions were specified.")) } } } if (!is.null(env$ls_f.hyp)) { od <- sapply(env$fIn, ncol) pd <- env$f_pdims zrs <- which(pd == 0) pd[zrs] <- od[zrs] sumdims <- sum(sapply(seq_along(pd), function(i) if(env$f_disType[i] == "L2_bygroup") return(1) else return(pd[i]))) if (length(env$ls_f.hyp) != sumdims) { stop(paste("Inconsistent number of length-scale parameters. Please check that the vector ls_f.hyp has as many elements as effective", "dimensions.\n Consider checking ?fgpm for details. Yoy can also leave this argument empty and the functional length-scale", "parameters will be\n estimated from the data.")) } } } else if(!is.null(env$sIn)) { if (nrow(env$sIn) != length(env$sOut)) { stop("Inconsistent number of points. Please check that sIn and sOut have the same number of rows.") } if (!is.null(env$ls_s.hyp)) { if (length(env$ls_s.hyp) != ncol(env$sIn)) { stop(paste("Inconsistent number of length-scale parameters. Please check that the vector ls_s.hyp has as many elements as the number\n ", "of columns in sIn., or leave this argument empty and the scalar length-scale parameters will be estimated from the data.")) } } } if (!is.numeric(env$nugget)) { stop("The nugget should be numeric.") } else if (env$nugget < 0) { stop("The nugget should be a nonnegative number.") } if (!is.numeric(env$n.starts)) { stop("The argument n.starts should be numeric.") } else if (!check.int(env$n.starts)) { stop("The argument n.starts should be an integer value.") } else if (env$n.starts <= 0) { stop("The argument n.starts should be a positive integer.") } if (!is.numeric(env$n.presample)) { stop("The argument n.presample should be numeric.") } else if (!check.int(env$n.presample)) { stop("The argument n.presample should be an integer value.") } else if (env$n.presample <= 0) { stop("The argument n.presample should be a positive integer.") } } checkVal_pred_and_sim <- function(env){ model <- env$model if (all(is.null(env$sIn.sm), is.null(env$fIn.sm))) { if(!is.null(env$sIn.pr)) {sIn.ch <- env$sIn.pr; sName <- "sIn.pr"} else sIn.ch <- NULL if(!is.null(env$fIn.pr)) {fIn.ch <- env$fIn.pr; fName <- "fIn.pr"} else fIn.ch <- NULL taskName <- "prediction" } else { if(!is.null(env$sIn.sm)) {sIn.ch <- env$sIn.sm; sName <- "sIn.sm"} else sIn.ch <- NULL if(!is.null(env$fIn.sm)) {fIn.ch <- env$fIn.sm; fName <- "fIn.sm"} else fIn.ch <- NULL taskName <- "simulation" } if (model@type == "hybrid") { if (all(is.null(sIn.ch), is.null(fIn.ch))) { stop(paste("Invalid input. The model has both, scalar and functional inputs. Please provide valid scalar and\n ", "functional points to proceed with the ", taskName, ".")) } else if (is.null(fIn.ch)) { stop(paste("Inconsistent data structures. The model has both, scalar and functional inputs, but only scalar points\n ", "for ", taskName, " were specified. Please provide also valid new functional points to proceed with the ", taskName, ".")) } else if (is.null(sIn.ch)) { stop(paste("Inconsistent data structures. The model has both, scalar and functional inputs, but only functional points\n ", "for ", taskName, " were specified. Please provide also valid new scalar points to proceed with the ", taskName, ".")) } if (!all(nrow(sIn.ch) == sapply(fIn.ch, nrow))) { stop("Inconsistent number of points. Please check that ", sName, " and each matrix in ", fName, " have all the same number of rows.") } } else if(model@type == "functional") { if (all(!is.null(sIn.ch), !is.null(sIn.ch))) { stop(paste("Inconsistent data structures. The model has only functional inputs, but also scalar points\n ", "for ", taskName, " were specified. Please provide only new functional points to proceed with the ", taskName, ".")) } if (!is.null(sIn.ch)) { stop(paste("Inconsistent data structures. The model has only functional inputs, but scalar points\n ", "for ", taskName, " were specified. Please provide new functional points instead to proceed with the ", taskName, ".")) } if (is.null(fIn.ch)) { stop(paste("Invalid input. The model has functional inputs. Please provide valid new functional points to proceed with\n ", "the ", taskName, ".")) } } else { if (all(!is.null(sIn.ch), !is.null(fIn.ch))) { stop(paste("Inconsistent data structures. The model has only scalar inputs, but also functional points\n ", "for ", taskName, " were specified. Please provide only new scalar points to proceed with the ", taskName, ".")) } if (!is.null(fIn.ch)) { stop(paste("Inconsistent data structures. The model has only scalar inputs, but functional points\n ", "for ", taskName, " were specified. Please provide new scalar points instead to proceed with the ", taskName, ".")) } if (is.null(sIn.ch)) { stop(paste("Invalid input. The model has scalar inputs. Please provide valid new scalar points to proceed with\n ", "the ", taskName, ".")) } } } check_del <- function(env) { model <- env$model if (any(duplicated(env$ind.dl))) { warning("Some elements in the deletion index vector ind.dl are duplicated. Duplicates are dropped.") env$ind.dl <- unique(env$ind.dl) } if (any(env$ind.dl < 1) || any(env$ind.dl > [email protected])) { stop("Some elements in the detelion index vector ind.dl are not in [1, [email protected]]. Please check your vector.") } if ([email protected] - length(env$ind.dl) < 2) { stop("The number of points to delete cannot exceed [email protected] - 2. Please check your vector.") } return(env$ind.dl) } check_subData <- function(env) { model <- env$model if (model@type == "hybrid") { if (!check_nrows_mlm(env$sIn.sb, env$fIn.sb, env$sOut.sb)) { stop("Inconsistent number of points. Please check that sIn.sb, each matrix in fIn.sb and sOut.sb have all the same number\n of rows.") } if (nrow(env$sIn.sb) != length(env$ind.sb)) { stop(paste("Inconsistent number of points in your replacement index vector ind.sb. Please check that it has the same number of\n ", "rows than sIn.sb, each matrix in fIn.sb and sOut.sb.", sep = "")) } } else if (model@type == "functional") { if (!check_nrows_lm(env$fIn.sb, env$sOut.sb)) { stop("Inconsistent number of points. Please check that each matrix in fIn.sb and sOut.sb have all the same number of rows.") } if (nrow(env$fIn.sb[[1]]) != length(env$ind.sb)) { stop(paste("Inconsistent number of points in your replacement index vector ind.sb. Please check that it has the same number of\n ", "rows than each matrix in fIn.sb and sOut.sb.", sep = "")) } } else { if (!check_nrows_mm(env$sIn.sb, env$sOut.sb)) { stop("Inconsistent number of points. Please check that sIn.sb and sOut.sb have the same number of rows.") } if (nrow(env$sIn.sb) != length(env$ind.sb)) { stop(paste("Inconsistent number of points in your replacement index vector ind.sb. Please check that it has the same number of\n ", "rows than sIn.sb and sOut.sb.", sep = "")) } } if (any(env$ind.sb %% 1 != 0)) { stop(paste(c("Replacement indices should be integer numbers. Please check the following positions of your ind.sb vector: ", which(env$ind.sb %% 1 != 0)), sep = "", collapse = " ")) } if (any(env$ind.dl < 1) || any(env$ind.dl > [email protected])) { stop(paste(c("Replacement indices shuold be integers in [1, [email protected]]. Please check the following positions of your ind.sb vector: ", which(!(env$ind.sb > 0 & env$ind.sb < [email protected]))), sep = "", collapse = " ")) } if (anyDuplicated(env$ind.sb)) { stop(paste(c("Replacement indices shuold be unique. Please check the following positions of your ind.sb vector: ", which(duplicated(env$ind.sb) | duplicated(env$ind.sb, fromLast = TRUE))), sep = "", collapse = " ")) } } check_add <- function(env) { model <- env$model if (model@type == "hybrid") { if (!check_nrows_mlm(env$sIn.nw, env$fIn.nw, env$sOut.nw)) { stop("Inconsistent number of points. Please check that sIn.nw, each matrix in fIn.nw and sOut.nw have all the same number\n of rows.") } } else if (model@type == "functional") { if (!check_nrows_lm(env$fIn.nw, env$sOut.nw)) { stop("Inconsistent number of points. Please check that each matrix in fIn.nw and sOut.nw have all the same number of rows.") } } else { if (!check_nrows_mm(env$sIn.nw, env$sOut.nw)) { stop("Inconsistent number of points. Please check that sIn.nw and sOut.nw have the same number of rows.") } } } check_subHypers <- function(env) { model <- env$model if (!is.null(env$var.sb)) if (env$var.sb <= 0) stop("The variance should be a positive real number. Please check your inputs.") if (model@type == "hybrid") { if (!is.null(env$ls_s.sb)) { if (length(model@kern@s_lsHyps) != length(env$ls_s.sb)) { stop(paste("The model has ", length(model@kern@s_lsHyps), " scalar length-scale parameters, but you provided", length(env$ls_s.sb), " instead for substitution. Please check your inputs.", sep = "")) } if (any(env$ls_s.sb <= 0)) stop("Length-scale parameters should be positive real numbers. Please check your ls_s.sb vector.") } if (!is.null(env$ls_f.sb)) { if (length(model@kern@f_lsHyps) != length(env$ls_f.sb)) { stop(paste("The model has ", length(model@kern@f_lsHyps), " functional length-scale parameters, but you provided", length(env$ls_f.sb), " instead for substitution. Please check your inputs.", sep = "")) } if (any(env$ls_f.sb <= 0)) stop("Length-scale parameters should be positive real numbers. Please check your ls_f.sb vector.") } } else if (model@type == "functional") { if (!is.null(env$ls_f.sb)) { if (length(model@kern@f_lsHyps) != length(env$ls_f.sb)) { stop(paste("The model has ", length(model@kern@f_lsHyps), " functional length-scale parameters, but you provided", length(env$ls_f.sb), " instead for substitution. Please check your inputs.", sep = "")) } if (env$ls_f.sb <= 0) stop("Length-scale parameters should be positive real numbers. Please check your ls_f.sb vector.") } } else { if (!is.null(env$ls_s.sb)) { if (length(model@kern@s_lsHyps) != length(env$ls_s.sb)) { stop(paste("The model has ", length(model@kern@s_lsHyps), " scalar length-scale parameters, but you provided", length(env$ls_s.sb), " instead for substitution. Please check your inputs.", sep = "")) } if (env$ls_s.sb <= 0) stop("Length-scale parameters should be positive real numbers. Please check your ls_s.sb vector.") } } } check_nrows_mlm <- function(M1, L, M2){ return(all(nrow(M1) == c(sapply(L, nrow), nrow(M2)))) } check_nrows_lm <- function(L, M){ return(all(nrow(M) == sapply(L, nrow))) } check_nrows_mm <- function(M1, M2){ return(nrow(M1) == nrow(M2)) } check_duplicates_SF <- function(sBench, fBench, sCand, fCand){ bchM <- cbind(sBench, do.call(cbind, fBench)) cndM <- cbind(sCand, do.call(cbind, fCand)) if (isTRUE(all.equal(bchM, cndM))) { ind.dp <- which(duplicated(bchM) | duplicated(bchM[nrow(bchM):1, ])[nrow(bchM):1]) } else { ind.dp <- which(tail(duplicated(rbind(bchM, cndM)), nrow(cndM))) } return(ind.dp) } check_duplicates_F <- function(fBench, fCand){ bchM <- do.call(cbind, fBench) cndM <- do.call(cbind, fCand) if (isTRUE(all.equal(bchM, cndM))) { ind.dp <- which(duplicated(bchM) | duplicated(bchM[nrow(bchM):1, ])[nrow(bchM):1]) } else { ind.dp <- which(tail(duplicated(rbind(bchM, cndM)), nrow(cndM))) } return(ind.dp) } check_duplicates_S <- function(sBench, sCand, oCand, iCand){ bchM <- sBench cndM <- sCand if (isTRUE(all.equal(bchM, cndM))) { ind.dp <- which(duplicated(bchM) | duplicated(bchM[nrow(bchM):1, ])[nrow(bchM):1]) } else { ind.dp <- which(tail(duplicated(rbind(bchM, cndM)), nrow(cndM))) } return(ind.dp) }
variableMetadata <- function(dataset) { varcat <- allVariables(dataset) extra <- crGET(shojiURL(dataset, "fragments", "table"))$metadata extra <- mapply(function(x, i) { x$id <- i if (length(x$subvariables)) { x$subvariables <- absoluteURL( paste0(i, "/subvariables/", unlist(x$subvariables), "/"), self(varcat) ) } return(x) }, x = extra, i = names(extra), SIMPLIFY = FALSE) names(extra) <- absoluteURL(paste0(names(extra), "/"), self(varcat)) extra <- modifyList(index(varcat), extra) index(varcat) <- extra return(varcat) } flattenVariableMetadata <- function(vm) { ind <- index(vm) extra <- lapply(urls(vm), function(u) { this <- ind[[u]] these.subs <- this$subvariables if (!is.null(these.subs)) { out <- structure(this$subreferences, .Names = these.subs) out <- lapply(out, function(x) { x$parent <- u x$parent_alias <- this$alias return(x) }) return(out) } else { return(NULL) } }) index(vm) <- c(ind, unlist(extra, recursive = FALSE)) return(vm) }
vtDecMap <- function(thetas, etas, prev.res=0, dec.cut=0.6) { stopifnot(get.const()$CLSPOST %in% class(thetas)); dec.cut <- rep(dec.cut, 3)[1:3]; cur.smp <- thetas; cur.dlt <- cur.smp[,3] + cur.smp[,4]; cur.res <- cur.smp[,2] + cur.smp[,4]; rst <- rep(0,4); rst[1] <- mean(cur.dlt >= etas[2]); rst[2] <- mean(cur.dlt < etas[2] & cur.res < prev.res); rst[3] <- mean(cur.dlt < etas[1] & cur.res >= prev.res); rst[4] <- 1 - sum(rst[1:3]); cond.prob <- rep(0,2); cond.prob[1] <- rst[2]/(1 - rst[1] + 1e-10); cond.prob[2] <- rst[3]/(1 - sum(rst[1:2]) + 1e-10); if (rst[1] > dec.cut[1]) { region <- 1; cond.prob[1:2] <- 0; } else if (cond.prob[1] > dec.cut[2]) { region <- 2; cond.prob[2] <- 0; } else if (cond.prob[2] > dec.cut[3]) { region <- 3; } else { region <- 4; } rst.dec <- list(prob = rst, region = region, ptox = mean(cur.dlt), pres = mean(cur.res), cond.prob = cond.prob, prev.res = mean(prev.res), etas = etas, dec.cut = dec.cut); class(rst.dec) <- get.const()$CLSDEC; rst.dec } vtInterim <- function(cur.obs.y, prev.obs.y = NULL, prev.res = NULL, etas = c(0.1,0.3), dec.cut = 0.65, priors = NULL, prob.mdl = c("NONPARA", "NONPARA+", "PARA", "PARA+"), seed = NULL, ...) { if (!is.null(seed)) { old_seed <- set.seed(seed); } prob.mdl <- match.arg(prob.mdl); post.smp <- vtPost(rbind(cur.obs.y), prob.mdl, priors, ...); if (!is.null(prev.obs.y)) { post.prev <- vtPost(rbind(prev.obs.y), prob.mdl, priors, ...); prev.res <- apply(post.prev[,c(2,4)],1,sum); } else if (is.null(prev.res)){ stop("Please provide either prev.obs.y or prev.res"); } rst.dec <- vtDecMap(post.smp, etas, prev.res=prev.res, dec.cut=dec.cut); if (!is.null(seed)) { set.seed(old_seed); } rst.dec } plot.VTDEC <- function(x, margin = 0.003, nms = c("TT", "NME", "SE", "UN"), col.reg = "pink", col.prob = "blue", cex.prob = 0.9, cex.nms = 1, ...) { f.reg <- function(x1, x2, y1, y2, labels, cols, tt = margin) { x1 <- x1 + tt; x2 <- x2 - tt; y1 <- y1 + tt; y2 <- y2 - tt; rect(x1, y1, x2, y2, col = cols[1], lwd = 1); text(x1+(x2-x1)/2, y1+(y2-y1)/2, labels = labels[1], col=cols[2], cex=cex.prob); text(x1+(x2-x1)/2, y1+(y2-y1)/2, labels = labels[2], col=cols[2], cex=cex.prob, pos = 1); text(x1+(x2-x1)/2, y2, labels = labels[3], cex=cex.nms, pos = 1); } etas <- x$etas; prev.res <- round(x$prev.res,2); probs <- x$prob * 100; cond.prob <- x$cond.prob * 100; col.regs <- rep("white", 4); col.ps <- rep("black", 4); col.regs[x$region] <- col.reg; col.ps[x$region] <- col.prob; par(xaxs="i", yaxs="i"); plot(NULL, xlim=c(0,1), ylim=c(0,1), xlab="DLT Risk", ylab="Immune Response Rate", axes=FALSE, ...); lbls <- c(sprintf("%.2f", probs[1]), "", nms[1]); f.reg(etas[2], 1, 0, 1, labels = lbls, cols=c(col.regs[1], col.ps[1])); if (prev.res > 0) { axis(2, at = prev.res); l2 <- ""; if (0 < cond.prob[1]) { l2 <- sprintf("(%.2f)", cond.prob[1]); } lbls <- c(sprintf("%.2f", probs[2]), l2, nms[2]); f.reg(0, etas[2], 0, prev.res, labels = lbls, cols=c(col.regs[2], col.ps[2])); } l2 <- ""; if (0 < cond.prob[2]) { l2 <- sprintf("(%.2f)", cond.prob[2]); } lbls <- c(sprintf("%.2f", probs[3]), l2, nms[3]); f.reg(0, etas[1], prev.res, 1, labels = lbls, cols=c(col.regs[3], col.ps[3])); lbls <- c(sprintf("%.2f", probs[4]), "", nms[4]); f.reg(etas[1], etas[2], prev.res, 1, labels = lbls, cols=c(col.regs[4], col.ps[4])); } vtTrack <- function(obs.all, cex.txt = 0.9, decision = 1, max.level = NULL, letters = c("E", "C", "S"), colors = c("green", "yellow", "red"), height = 0.5, end.width = 2, end.height = height, cex.roman = 0.9, cex.end = 0.9, ...) { f.rec <- function(x, y, width, height, ys, cex.txt, margin = 0.1) { width <- width/4; cys <- rbind(c(0,0), c(0,1), c(1,0), c(1,1)); for (i in 1:4) { cur.x <- x + width *(i-1); xleft <- cur.x; xright <- xleft + 0.5 * width; ytop <- y; ybottom <- ytop - 0.5 * height; if (1 == cys[i,1]) { r.txt <- "T"; r.col <- "gray80"; } else { r.txt <- "NoT"; r.col <- "white"; } rect(xleft, ybottom, xright, ytop, col=r.col, lwd=0.1); text(xleft + 0.25 * width, ytop - 0.25 * height, labels = r.txt, cex = 0.5 * cex.txt); xleft <- cur.x + 0.5 * width; xright <- xleft + 0.5 * width; ytop <- y; ybottom <- ytop - 0.5 * height; if (1 == cys[i,2]) { r.txt <- "R"; r.col <- "pink"; } else { r.txt <- "NoR"; r.col <- "white"; } rect(xleft, ybottom, xright, ytop, col=r.col, lwd=0.1); text(xleft + 0.25 * width, ytop - 0.25 * height, labels = r.txt, cex = 0.5 * cex.txt); xleft <- cur.x; xright <- xleft + width; ytop <- y - 0.5 * height; ybottom <- ytop - 0.5 * height; rect(xleft, ybottom, xright, ytop, lwd=0.1); text(xleft + 0.5 * width, ytop - 0.25 * height, labels = ys[i], cex = cex.txt); rect(cur.x, y - height, cur.x + width, y, lwd=1); } } f.arrow <- function(x, y, width, height, direction, labels = NULL) { end.xy <- switch(direction, "flat" = c(width, 0, 3), "up" = c(0, height, 2), "down" = c(0, -height, 4)); arrows(x, y, x + end.xy[1], y + end.xy[2], length = 0.1); text(x + end.xy[1]/2, y + end.xy[2]/2, labels = as.roman(labels), pos = end.xy[3], col = "brown", cex = cex.roman); } f.end <- function(x, y, width, height, letter, color) { rect(x - 0.5*width, y - 0.5*height, x + 0.5*width, y + 0.5*height, lwd = 1); rect(x - 0.45*width, y - 0.45*height, x + 0.45*width, y + 0.45*height, lwd = 1, col = color); text(x, y, labels = letter, cex = cex.end); } if (is.null(max.level)) max.level <- max(obs.all[,1]); tbl.level <- table(obs.all[,1]); x.tot <- 0; for (i in 1:length(tbl.level)) { x.tot <- x.tot + 4*tbl.level[i] + tbl.level[i] - 1; } x.tot <- x.tot - length(tbl.level) + 1; x.max <- (x.tot + 3) * 1; y.max <- max.level * 1; plot(NULL, NULL, xlim=c(0, x.max), ylim=c(height/2, y.max), axes = FALSE, xlab = "", ylab = "", ...); box(); last.level <- 0; cur.x <- 1; cur.y <- 1; inx <- 0; for (i in 1:nrow(obs.all)) { cur.level <- obs.all[i,1]; if (cur.level != last.level) { last.level <- cur.level; if (cur.level > 1) { inx <- inx + 1; f.arrow(cur.x + 3.5, cur.y, 0, 1-height, "up", labels = inx); cur.x <- cur.x + 3; cur.y <- cur.y + 1; } } else { inx <- inx + 1; f.arrow(cur.x + 4, cur.y - 0.5*height, 1, 0, "flat", labels = inx); cur.x <- cur.x + 5; } f.rec(cur.x, cur.y, 4, height = height, ys = obs.all[i, 2:5], cex.txt = cex.txt); } inx <- inx + 1; f.arrow(cur.x + 4, cur.y - 0.5*height, 1, 0, "flat", labels = inx); f.end(cur.x + 5 + end.width/2, cur.y - 0.5*height, width = end.width, height = end.height, letter = letters[decision], color = colors[decision]); }
cuminyear=function(data,coldate,colnum,start=1){ a=NULL data[colnum]=metools::col2num(data[colnum],1,1) n=start while(n<=nrow(data[coldate])){ if(lubridate::month(data[[coldate]][[n]])==1){a[n]=data[[colnum]][n]/data[[colnum]][n]-1} if(lubridate::month(data[[coldate]][[n]])==2){a[n]=data[[colnum]][n]/data[[colnum]][n-1]-1} if(lubridate::month(data[[coldate]][[n]])==3){a[n]=data[[colnum]][n]/data[[colnum]][n-2]-1} if(lubridate::month(data[[coldate]][[n]])==4){a[n]=data[[colnum]][n]/data[[colnum]][n-3]-1} if(lubridate::month(data[[coldate]][[n]])==5){a[n]=data[[colnum]][n]/data[[colnum]][n-4]-1} if(lubridate::month(data[[coldate]][[n]])==6){a[n]=data[[colnum]][n]/data[[colnum]][n-5]-1} if(lubridate::month(data[[coldate]][[n]])==7){a[n]=data[[colnum]][n]/data[[colnum]][n-6]-1} if(lubridate::month(data[[coldate]][[n]])==8){a[n]=data[[colnum]][n]/data[[colnum]][n-7]-1} if(lubridate::month(data[[coldate]][[n]])==9){a[n]=data[[colnum]][n]/data[[colnum]][n-8]-1} if(lubridate::month(data[[coldate]][[n]])==10){a[n]=data[[colnum]][n]/data[[colnum]][n-9]-1} if(lubridate::month(data[[coldate]][[n]])==11){a[n]=data[[colnum]][n]/data[[colnum]][n-10]-1} if(lubridate::month(data[[coldate]][[n]])==12){a[n]=data[[colnum]][n]/data[[colnum]][n-11]-1} n=n+1 } return(a) }
sim.brQCA<-function(qca.data, outcome="OUT", conditions=c(""), sim=10, ncut=2, type="crisp", inclcut = "", neg.out=FALSE, verbose=TRUE){ ptm <- proc.time() if (all(conditions == c(""))) { conditions <- names(qca.data[,!(names(qca.data) %in% outcome)]) } if (inclcut == ""){ inclcut<-seq(from=.5, to = 1, by=.01) } pop<-dim(qca.data)[1] rows<-sim*length(ncut)*length(inclcut)*length(pop)*2 out<-qca.data[,outcome] qca.data<-qca.data[,!(names(qca.data) %in% outcome)] data<-data.frame(CTH=0,CNTH=0,CPI=0,NTH=0,OUT=rep(NA,rows)) kk<-0 for (j in 1:sim) { for (k in 1:length(inclcut)){ for (n in ncut){ kk<-kk+1 data[kk,1]<-inclcut[k] data[kk,2]<-n data[kk,4]<-pop s.qca.data<-qca.data if (type=="crisp"){ for (i in 1:length(qca.data)){ prob<-c(sum(qca.data[,i]==0)/(dim(qca.data)[1]),sum(qca.data[,i]==1)/dim(qca.data)[1]) s.qca.data[,i]<-sample(c(0,1),pop,prob=prob,replace=TRUE)} prob<-c(sum(out==0)/(length(out)),sum(out==1)/length(out)) s.qca.data$OUT<-sample(c(0,1),pop,prob=prob,replace=TRUE) } if (type == "fuzzy"){ for (i in 1:length(qca.data)){ ranges<-seq(from=0.1, to=1, by=.1) prob<-hist(qca.data[,i])[[2]]/dim(qca.data)[1] s.qca.data[,i]<-sample(ranges,pop,prob=prob,replace=TRUE) } prob<-hist(out)[[2]]/length(out) s.qca.data$OUT<-sample(ranges,pop,prob=prob,replace=TRUE) } parsimonious <- tryCatch( minimize(s.qca.data, outcome=c("OUT"), n.cut=n, incl.cut=inclcut[k], include = "?", neg.out=neg.out, conditions= c(names(s.qca.data[,!(names(s.qca.data) %in% 'OUT')])),details = TRUE, show.cases = TRUE), error=function(e) e ) if(!inherits(parsimonious, "error")){ data[kk,5]<-1 data[kk,3]<-0 } if(inherits(parsimonious, "error")){ data[kk,5]<-0 data[kk,3]<-0 } kk<-kk+1 data[kk,1]<-inclcut[k] data[kk,2]<-n data[kk,4]<-pop complex <- tryCatch( minimize(s.qca.data, outcome=c("OUT"), n.cut=n, incl.cut=inclcut[k], neg.out=neg.out, conditions = c(names(s.qca.data[,!(names(s.qca.data) %in% 'OUT')])), details = TRUE, show.cases = TRUE), error=function(e) e ) if(!inherits(complex, "error")){ data[kk,5]<-1 data[kk,3]<-1 } if(inherits(complex, "error")){ data[kk,5]<-0 data[kk,3]<-1 } captureError<-tryCatch(truthTable(s.qca.data, outcome=c("OUT"), n.cut=n, incl.cut=inclcut[k], neg.out=neg.out, conditions= c(names(s.qca.data[,!(names(s.qca.data) %in% 'OUT')])),details = TRUE, show.cases = TRUE)[[1]][,1], error=function(e) e) if (verbose == T){ print(paste(round(100*kk/rows, digits=2),"% done", sep="")) print(proc.time()-ptm) flush.console()} }}} return(data) }
rowDist <- function(x, method) { MethOpts <- c("cosine", "euclidean", "maximum", "manhattan", "canberra", "binary", "pearson", "correlation", "spearman", "kendall", "abspearson", "abscorrelation") amapMeth <- MethOpts[-1] method <- match.arg(method, MethOpts) if (method %in% amapMeth) { if (!requireNamespace("amap", quietly = TRUE)) { stop("You need to install package amap to use this distance option") } distance <- amap::Dist(x, method = method) } if (method == "cosine") { distance <- as.dist(1 - (x %*% t(x) / (sqrt(rowSums(x^2) %*% t(rowSums(x^2)))))) } distance }
P.units <- function(units=NULL) { if(is.null(units)) return(get("thermo", CHNOSZ)$opt$P.units) units <- tolower(units) if(!units %in% c("bar","mpa")) stop("units of pressure must be either bar or MPa") if(units=="bar") with(CHNOSZ, thermo$opt$P.units <- "bar") if(units=="mpa") with(CHNOSZ, thermo$opt$P.units <- "MPa") message("changed pressure units to ", get("thermo", CHNOSZ)$opt$P.units) } T.units <- function(units=NULL) { if(is.null(units)) return(get("thermo", CHNOSZ)$opt$T.units) units <- tolower(units) if(!units %in% c("c","k")) stop("units of temperature must be either C or K") if(units=="c") with(CHNOSZ, thermo$opt$T.units <- "C") if(units=="k") with(CHNOSZ, thermo$opt$T.units <- "K") message("changed temperature units to ", get("thermo", CHNOSZ)$opt$T.units) } E.units <- function(units=NULL) { if(is.null(units)) return(get("thermo", CHNOSZ)$opt$E.units) units <- tolower(units) if(!units %in% c("cal","j")) stop("units of energy must be either cal or J") if(units=="cal") with(CHNOSZ, thermo$opt$E.units <- "cal") if(units=="j") with(CHNOSZ, thermo$opt$E.units <- "J") message("changed energy units to ", get("thermo", CHNOSZ)$opt$E.units) } convert <- function(value, units, T=298.15, P=1, pH=7, logaH2O=0) { if(is.list(value) & !is.data.frame(value)) { if(!isTRUE(value$fun %in% c("solubility", "solubilities"))) stop("'value' is a list but is not the output from solubility()") if(!is.character(units)) stop("please specify a character argument for the destination units (e.g. ppm or logppm)") element <- value$in.terms.of if(is.null(element)) element <- value$balance grams.per.mole <- mass(element) message(paste("solubility: converting to", units, "by weight using the mass of", element)) ppfun <- function(loga, units, grams.per.mole) { moles <- 10^loga grams <- moles * grams.per.mole ppx <- NULL if(grepl("ppt", units)) ppx <- grams * 1e0 if(grepl("ppm", units)) ppx <- grams * 1e3 if(grepl("ppb", units)) ppx <- grams * 1e6 if(is.null(ppx)) stop(paste("units", units, "not available for conversion")) if(grepl("log", units)) ppx <- log10(ppx) ppx } value$loga.balance <- ppfun(value$loga.balance, units, grams.per.mole) value$loga.equil <- lapply(value$loga.equil, ppfun, units = units, grams.per.mole = grams.per.mole) value$fun <- paste(value$fun, units, sep = ".") return(value) } if(is.null(value)) return(NULL) if(!is.character(units)) stop(paste('convert: please specify', 'a character argument for the destination units.\n', 'possibilities include (G or logK) (C or K) (J or cal) (cm3bar or calories) (Eh or pe)\n', 'or their lowercase equivalents.\n'),call.=FALSE) Units <- units units <- tolower(units) if(units %in% c('c','k')) { CK <- 273.15 if(units=='k') value <- value + CK if(units=='c') value <- value - CK } else if(units[1] %in% c('j','cal')) { Jcal <- 4.184 if(units=='j') value <- value * Jcal if(units=='cal') value <- value / Jcal } else if(units %in% c('g','logk')) { R <- 1.9872 if(units=='logk') value <- value / (-log(10) * R * T) if(units=='g') value <- value * (-log(10) * R * T) } else if(units %in% c('cm3bar','calories')) { if(units=='cm3bar') value <- convert(value,'J') * 10 if(units=='calories') value <- convert(value,'cal') / 10 } else if(units %in% c('eh','pe')) { R <- 0.00831470 F <- 96.4935 if(units=='pe') value <- value * F / ( log(10) * R * T ) if(units=='eh') value <- value * ( log(10) * R * T ) / F } else if(units %in% c('bar','mpa')) { barmpa <- 10 if(units=='mpa') value <- value / barmpa if(units=='bar') value <- value * barmpa } else if(units %in% c('e0','logfo2')) { supcrt.out <- suppressMessages(subcrt(c("H2O", "oxygen", "H+", "e-"), c(-1, 0.5, 2, 2), T=T, P=P, convert=FALSE)) if(units=='logfo2') value <- 2*(supcrt.out$out$logK + logaH2O + 2*pH + 2*(convert(value,'pe',T=T))) if(units=='e0') value <- convert(( -supcrt.out$out$logK - 2*pH + value/2 - logaH2O )/2, 'Eh',T=T) } else cat(paste('convert: no conversion to ',Units,' found.\n',sep='')) return(value) } outvert <- function(value,units) { units <- tolower(units) opt <- get("thermo", CHNOSZ)$opt if(units %in% c('c','k')) { if(units=='c' & opt$T.units=='K') return(convert(value,'k')) if(units=='k' & opt$T.units=='C') return(convert(value,'c')) } if(units %in% c('j','cal')) { if(units=='j' & opt$E.units=='Cal') return(convert(value,'cal')) if(units=='cal' & opt$E.units=='J') return(convert(value,'j')) } if(units %in% c('bar','mpa')) { if(units=='mpa' & opt$P.units=='bar') return(convert(value,'bar')) if(units=='bar' & opt$P.units=='MPa') return(convert(value,'mpa')) } return(value) } envert <- function(value,units) { if(!is.numeric(value[1])) return(value) units <- tolower(units) opt <- get("thermo", CHNOSZ)$opt if(units %in% c('c','k','t.units')) { if(units=='c' & opt$T.units=='K') return(convert(value,'c')) if(units=='k' & opt$T.units=='C') return(convert(value,'k')) } if(units %in% c('j','cal','e.units')) { if(units=='j' & opt$T.units=='Cal') return(convert(value,'j')) if(units=='cal' & opt$T.units=='J') return(convert(value,'cal')) } if(units %in% c('bar','mpa','p.units')) { if(units=='mpa' & opt$P.units=='bar') return(convert(value,'mpa')) if(units=='bar' & opt$P.units=='MPa') return(convert(value,'bar')) } return(value) }
"predict.obliqueRF" <- function(object, newdata, type="response", proximity=F, ...) { if (!inherits(object, "obliqueRF")) stop("object not of class obliqueRF") if (is.null(object$trees)) stop("No trees in the object") if ( object$type != "classification" ) stop("right now predict supports only (binary) classification") typeOK=switch(type,response="ok",prob="ok",votes="ok","notok"); if(typeOK=="notok") stop("specified type is not valid, choose one of \"prob\", \"votes\" or \"response\"; aborting..."); ntree=object$ntree; num_classes=object$num_classes num_samples=nrow(newdata); newdata_class_votes<-matrix(0, num_classes, num_samples); if(!is.matrix(newdata)) newdata<-as.matrix(newdata); if(proximity) proxM=matrix(NA,num_samples,ntree); for(currTree in 1:ntree) { tree=object$trees[[currTree]]; node_classIdx=tree$node_class+1; for(M in 1:num_samples) { curr_node=1; for(i in 1:(tree$total_nr_nodes)) { if(tree$node_status[curr_node]==-1) { newdata_class_votes[node_classIdx[curr_node],M]= newdata_class_votes[node_classIdx[curr_node],M]+1; if(proximity) proxM[M,currTree]<-curr_node break; } dset<-newdata[M, tree$best_vars[,curr_node]]; score=sum(tree$training_stats[,curr_node]*dset); if(score<tree$best_split_value[curr_node]) { curr_node=tree$treemap[1, curr_node] } else { curr_node=tree$treemap[2, curr_node]; } } } } totalVotes=ntree; pred=c(); if(type=="response") pred=object$class_names[1+((newdata_class_votes[2,]/totalVotes)>0.5)*1]; if(type=="prob"){ pred=t(newdata_class_votes/totalVotes); colnames(pred)<-object$class_names } if(type=="votes"){ pred=t(newdata_class_votes); colnames(pred)<-object$class_names } if(!proximity) { res<-pred; } else { node_counts<-matrix(0,num_samples,num_samples) for(op in 1:ntree){ tabl<-table(proxM[,op]) mults<-as.numeric(names(tabl)[tabl>1]) for(mi in mults){ wh<-which(proxM[,op]==mi) node_counts[wh, wh]<-node_counts[wh, wh] +1 } } node_counts<-node_counts/ntree; res<-list( pred=pred, proximity=node_counts); } return(res); }
mag2flux=function( mag, zero_pt=21.10, ABwave=F) { if(!missing(ABwave)) return(10^(-0.4*(mag + 2.406 + 5*log10(ABwave)))) else return(10^(-0.4*( mag + zero_pt))) }
define_searchrequest_custom <- function(request, negate, use_uid, esearch, handle) { if (isTRUE(esearch)) { esearch_string = "RETURN () " } else { esearch_string = NULL } if (isTRUE(use_uid)) { use_uid_string = "UID " } else { use_uid_string = NULL } if (isTRUE(negate)) { negate_string = "NOT " } else { negate_string = NULL } customrequest = paste0(use_uid_string, "SEARCH ", esearch_string, negate_string, "(", request, ")") tryCatch({ curl::handle_setopt( handle = handle, customrequest = customrequest) }, error = function(e){ stop("The connection handle is dead. Please, configure a new IMAP connection with ImapCon$new().") }) return(c(handle = handle, customrequest = customrequest)) }
length.rpqueue <- function(x) { return(length(x$l) + length(x$r)) }
context("utils-data-sampler") test_that("sampler's lenght", { x <- torch_randn(1000, 10) y <- torch_randn(1000) data <- tensor_dataset(x, y) sampler <- SequentialSampler$new(data) expect_length(sampler, 1000) sampler <- RandomSampler$new(data, num_samples = 10) expect_length(sampler, 10) sampler <- RandomSampler$new(data) expect_length(sampler, 1000) batch <- BatchSampler$new(sampler = sampler, batch_size = 32, drop_last = TRUE) expect_length(batch, 1000 %/% 32) batch <- BatchSampler$new(sampler = sampler, batch_size = 32, drop_last = FALSE) expect_length(batch, 1000 %/% 32 + 1) batch <- BatchSampler$new(sampler = sampler, batch_size = 100, drop_last = FALSE) expect_length(batch, 10) batch <- BatchSampler$new(sampler = sampler, batch_size = 1000, drop_last = FALSE) expect_length(batch, 1) batch <- BatchSampler$new(sampler = sampler, batch_size = 1001, drop_last = FALSE) expect_length(batch, 1) batch <- BatchSampler$new(sampler = sampler, batch_size = 1001, drop_last = TRUE) expect_length(batch, 0) }) test_that("Random sampler, replacement = TRUE", { x <- torch_randn(2, 10) y <- torch_randn(2) data <- tensor_dataset(x, y) x <- RandomSampler$new(data, replacement = TRUE) it <- x$.iter() for (i in 1:length(x)) { k <- it() expect_true(k <= 2 && k >= 1) } expect_equal(it(), coro::exhausted()) }) test_that("Batch sampler", { x <- torch_randn(100, 10) y <- torch_randn(2) data <- tensor_dataset(x, y) r <- RandomSampler$new(data, replacement = FALSE) x <- BatchSampler$new(r, 32, TRUE) it <- x$.iter() expect_length(it(), 32) expect_length(it(), 32) expect_length(it(), 32) expect_equal(it(), coro::exhausted()) })
rate_adjustment<-function(data = data){ rate <- function(T,temp_cmin,temp_cmax,ro){ro*T*(T-temp_cmin)*(temp_cmax-T)/(((temp_cmin+temp_cmax+sqrt((temp_cmin+temp_cmax)^2- 3*temp_cmin*temp_cmax))/3)*(((temp_cmin+temp_cmax+sqrt((temp_cmin+temp_cmax)^2-3*temp_cmin*temp_cmax))/3)-temp_cmin)* (temp_cmax-((temp_cmin+temp_cmax+sqrt((temp_cmin+temp_cmax)^2-3*temp_cmin*temp_cmax))/3)))} m <- nls2(data$R~rate(data$TA,temp_cmin,temp_cmax,ro),data=data,start=list(temp_cmin=10,temp_cmax=30,ro=0.2)) temp_cmin<- coefficients(m)[1] temp_cmax<- coefficients(m)[2] ro<-coefficients(m)[3] Top<- (temp_cmin+temp_cmax+sqrt((temp_cmin+temp_cmax)^2-3*temp_cmin*temp_cmax))/3 s<- seq(temp_cmin,temp_cmax) r<- ro*s*(s-temp_cmin)*(temp_cmax-s)/(((temp_cmin+temp_cmax+sqrt((temp_cmin+temp_cmax)^2- 3*temp_cmin*temp_cmax))/3)*(((temp_cmin+temp_cmax+sqrt((temp_cmin+temp_cmax)^2- 3*temp_cmin*temp_cmax))/3)-temp_cmin)*(temp_cmax-((temp_cmin+temp_cmax+ sqrt((temp_cmin+temp_cmax)^2-3*temp_cmin*temp_cmax))/3))) plot(s,r,xlab="Temperature", ylab="r(T)", main="Intrinsic growth rate", xlim = c(temp_cmin, temp_cmax), ylim = c(0, ro), type="l",lty=c(1),cex.axis=1.5, tcl=-0.7,las=0, cex.main=2,bty="n",cex=1.5,lwd=2,cex.lab=1.5,lwd.ticks=2) par(new=TRUE) plot(data$TA,data$R,xlab = "",ylab = "", xlim = c(temp_cmin, temp_cmax), ylim = c(0, ro), axes=FALSE,lwd=2) axis(side=1,at=c(-20,100),col="black",lwd=3) axis(side=2,at=c(-20,100),col="black",lwd=3) as.list(c(temp_cmin,temp_cmax,ro)) }
library(raster) library(usethis) nlcd_bbox = extent(c(1249650, 1270000, 1246800, 1260000)) nlcd_filepath = "your_path" augusta_nlcd = crop(raster(nlcd_filepath), nlcd_bbox) plot(augusta_nlcd) usethis::use_data(augusta_nlcd) ccilc_bbox = extent(c(22.23, 23.5, 52.8, 53.83)) ccilc_filepath = "your_path" podlasie_ccilc = crop(raster(ccilc_filepath, band = 24), ccilc_bbox) plot(podlasie_ccilc) usethis::use_data(podlasie_ccilc)
interlayer_callnextinterlayer <- function(next.interlayers, LL.params, LL.function.sum, ...){ all.other.args <- list(...) interlayer.call.args <- list(next.interlayers = next.interlayers[-1], LL.params = LL.params, LL.function.sum = LL.function.sum) interlayer.call.args <- modifyList(interlayer.call.args, all.other.args) return(do.call(what = next.interlayers[[1]], args = interlayer.call.args)) }
context("wbt_quantiles") test_that("Transforms raster values into quantiles", { skip_on_cran() skip_if_not(check_whitebox_binary()) dem <- system.file("extdata", "DEM.tif", package = "whitebox") ret <- wbt_quantiles(input = dem, output = "output.tif") expect_match(ret, "Elapsed Time") })
html_coefs <- function(x){ coefs <- coef(summary(x)) Signif <- symnum(coefs[, 'Pr(>|z|)'], corr = FALSE, na = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", "**", "*", ".", " "), legend = FALSE) df <- data.frame(Name = rownames(coefs), Value = coefs[, 'Estimate'], Level = Signif) rownames(df) <- NULL a <- print(xtable(df), type = "html", html.table.attributes = "class = 'table table-condensed'", include.rownames = FALSE, include.colnames = FALSE, print.results = FALSE) a <- gsub(' \\*\\*\\* ', '<span class="label label-table label-primary">0.1%</span>', a) a <- gsub(' \\*\\* ', '<span class="label label-table label-info">1%</span>', a) a <- gsub(' \\* ', '<span class="label label-table label-mint">5%</span>', a) a <- gsub(' \\. ', '<span class="label label-table label-default">10%</span>', a) a } html_stats <- function(x, digits = 5){ x <- summary(x) class(x) <- "seas" z <- list() if (!is.null(x$spc$seats)){ z <- c(z, list(c("Adjustment", "SEATS"))) } if (!is.null(x$spc$x11)){ z <- c(z, list(c("Adjustment", "X11"))) } z <- c(z, list( c("ARIMA", x$model$arima$model), c("Obs.", formatC(nobs(x), format = "d")), c("Transform", x$transform.function), c("AICc", formatC(unname(seasonal::udg(x, "aicc")), digits = digits)), c("BIC", formatC(BIC(x), digits = digits)) ) ) df <- data.frame(do.call(rbind, z)) a <- print(xtable(df), type = "html", html.table.attributes = "class = 'table table-condensed'", include.rownames = FALSE, include.colnames = FALSE, print.results = FALSE) a } html_tests <- function(x, digits = 4){ x <- summary(x) z <- list() qsv <- x$qsv qsstars <- symnum(as.numeric(qsv['p-val']), corr = FALSE, na = FALSE, legend = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", "**", "*", ".", " ")) z <- c(z, list(c("QS (H0: no seasonality in final series)", formatC(as.numeric(qsv['qs']), digits = digits), qsstars))) if (!is.null(x$resid)){ bltest <- Box.test(x$resid, lag = 24, type = "Ljung") blstars <- symnum(bltest$p.value, corr = FALSE, na = FALSE, legend = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", "**", "*", ".", " ")) z <- c(z, list(c("Box-Ljung (H0: no residual autocorrelation)", formatC(bltest$statistic, digits = digits), blstars))) swtest <- shapiro.test(x$resid) swstars <- symnum(swtest$p.value, corr = FALSE, na = FALSE, legend = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", "**", "*", ".", " ")) z <- c(z, list(c("Shapiro (H0: normal distr. of residuals)", formatC(swtest$statistic, digits = digits), swstars))) } df <- data.frame(do.call(rbind, z)) a <- print(xtable(df), type = "html", html.table.attributes = "class = 'table table-condensed'", include.rownames = FALSE, include.colnames = FALSE, print.results = FALSE) a <- gsub(' \\*\\*\\* ', '<span class="label label-table label-error">0.1%</span>', a) a <- gsub(' \\*\\* ', '<span class="label label-table label-error">1%</span>', a) a <- gsub(' \\* ', '<span class="label label-table label-warning">5%</span>', a) a <- gsub(' \\. ', '<span class="label label-table label-default">10%</span>', a) a <- gsub('\\(', '<br><small class="text-muted">', a) a <- gsub('\\)', '</small>', a) a }
testthat::test_that("a minimal LimeSurvey TSV file can be imported", { lsrv <- limonaid::ls_read_tsv( system.file( "extdata", "export-of-survey-with-one-question-as-tsv.txt", package = "limonaid" ) ); limonaid::ls_tsv_get_rows(lsrv, class = "S"); limonaid::ls_tsv_get_rows(lsrv, class = "SL")['name'] testthat::expect_equal(nrow(lsrv), 72); }) testthat::test_that("a minimal LimeSurvey TSV file in two languages can be imported", { lsrv <- limonaid::ls_read_tsv( system.file( "extdata", "export-of-en-and-nl-survey-with-one-question-as-tsv.txt", package = "limonaid" ) ); limonaid::ls_tsv_get_rows(lsrv, class = "S"); limonaid::ls_tsv_get_rows(lsrv, class = "SL") testthat::expect_equal(nrow(lsrv), 96); }) testthat::test_that("a more extensive LimeSurvey TSV file can be imported", { lsrv <- limonaid::ls_read_tsv( system.file( "extdata", "export-of-minimal-survey-as-tsv.txt", package = "limonaid" ) ); limonaid::ls_tsv_get_rows(lsrv, class = "S"); limonaid::ls_tsv_get_rows(lsrv, class = "SL")['name'] limonaid::ls_tsv_get_rows(lsrv, name = "nrOfDMQs") testthat::expect_equal(nrow(lsrv), 312); }) dontRun <- expression({ yourCOVID19riskPath <- "B:/Data/ABC/your-risk.com/your-covid-19-risk/operationalizations/limesurvey/during-development"; lsrv <- limonaid::ls_read_tsv( file.path(yourCOVID19riskPath, "test-of-survey-with-hidden-equation.txt") ); limonaid::ls_tsv_get_rows(lsrv, class = "Q"); })
bed.matrix.split.genomic.region = function( x, changeID=TRUE, genomic.region=NULL, split.pattern="," ) { if (is.null(genomic.region) & !("genomic.region" %in% colnames(x@snps))) stop("genomic.region should be provided or already in x@snps") if (!is.null(genomic.region)){ if(nrow(x@snps)!=length(genomic.region)) stop("genomic.region should have the same length as the number of markers in x") if("genomic.region" %in% colnames(x@snps)) warning("genomic.region was already in x@snps, x@snps will be replaced.\n") x@snps$genomic.region=genomic.region } if(is.factor(x@snps$genomic.region)) x@snps$genomic.region <- as.character(x@snps$genomic.region) genomic.region.split = strsplit(x@snps$genomic.region, split.pattern) n.genomic.regions = sapply(genomic.region.split,length) if (!any(n.genomic.regions>1)) warning("no any marker is annotated to multiple genomic regions") nn = unlist(mapply( 1:length(n.genomic.regions) , FUN=rep , n.genomic.regions )) bim = x@snps[nn,] ; row.names(bim)=NULL bim$genomic.region = factor(unlist(genomic.region.split), levels = unique(unlist(genomic.region.split))) if (changeID) { bim$id = paste(bim$chr,bim$pos,bim$A1,bim$A2,bim$genomic.region,sep=":") } y = as.bed.matrix( x=gaston::as.matrix(x)[,nn] , fam=x@ped , bim=bim ) return(y) }
expected <- eval(parse(text="structure(list(trace = 0, fnscale = 1, parscale = 1, ndeps = 0.001, maxit = 100L, abstol = -Inf, reltol = 1.49011611938477e-08, alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10), .Names = c(\"trace\", \"fnscale\", \"parscale\", \"ndeps\", \"maxit\", \"abstol\", \"reltol\", \"alpha\", \"beta\", \"gamma\", \"REPORT\", \"type\", \"lmm\", \"factr\", \"pgtol\", \"tmax\", \"temp\"))")); test(id=0, code={ argv <- eval(parse(text="list(trace = 0, fnscale = 1, parscale = 1, ndeps = 0.001, maxit = 100L, abstol = -Inf, reltol = 1.49011611938477e-08, alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10)")); do.call(`list`, argv); }, o=expected);
sim.GeometricAvg <- function(zm, q.ga,...){ results <- q.ga(zm,...) if(length(results)==7){ zm <- results[[5]] Y <- results[[7]] } else{ Y <- results[[1]] } cv.matrix = c() expectations = c() prodSt <- results[[4]] bs_asian_geom_results <- BS_Asian_geom(...) ti <- bs_asian_geom_results[[2]] d = length(ti) Z<-exp(-bs_asian_geom_results[[3]]*ti[d])*pmax(prodSt^(1/d)-bs_asian_geom_results[[4]],0) cv.matrix <- cbind(Z, cv.matrix) expectations <- c(bs_asian_geom_results[[1]], expectations) lm.matrix <- cbind(Y, cv.matrix) model <- lm(lm.matrix[,1]~., data = data.frame(lm.matrix[,-1])) coeffs <- model$coefficients[-1] Y = Y - (coeffs*(Z - expectations)) if(length(results)==7){ Y <- Y * results[[6]] results[[6]] <- 1 } results[[1]] <- Y return(results) }
get_s_to_ns <- function(Alist, Blist, seeds, nonseeds, perm = seq(sum(seeds))) { nns <- nrow(nonseeds) ns <- nrow(seeds) pmat <- Matrix::Diagonal(nns, )[perm, ] s_to_ns <- function(A,B){ Asn <- A[seeds$A,nonseeds$A] Ans <- A[nonseeds$A,seeds$A] Bsn <- B[seeds$B,nonseeds$B] %*% t(pmat) Bns <- pmat %*% B[nonseeds$B,seeds$B] tcrossprod(Ans, Bns) + crossprod(Asn, Bsn) } if (!is(Alist, "list")){ return(s_to_ns(Alist, Blist)) } nc <- length(Alist) s2ns <- Matrix(0, nrow = nns, ncol = nns) for (ch in 1:nc){ s2ns <- s2ns + s_to_ns(Alist[[ch]], Blist[[ch]]) gc() } s2ns }
as_grain <- function(x) { stopifnot(inherits(x, "bnc_bn")) if (is.null(x$.grain)) { compile_grain(params(x)) } else { x$.grain } } compute_grain_log_joint <- function(grain, dataset, class) { if (!requireNamespace("gRain", quietly = TRUE)) { stop("gRain needed for this function to work. Please install it.", call. = FALSE) } stopifnot(is_grain_compiled(grain)) check_dataset(dataset) stopifnot(nrow(dataset) > 0) if (class %in% colnames(dataset)) { dataset <- dataset[, setdiff(colnames(dataset), class), drop = FALSE] } cp <- t(apply(dataset, 1, compute_grain_log_joint_instance, grain, class)) rownames(cp) <- NULL cp } compute_grain_log_joint_instance <- function(instance, grain, class) { if (!requireNamespace("gRain", quietly = TRUE)) { stop("gRain needed for this function to work. Please install it.", call. = FALSE) } stopifnot(is.character(instance)) instance <- instance[!is.na(instance)] vars <- intersect(names(instance), grain_nodes(grain)) instance <- instance[vars] check_class(class) stopifnot(!(class %in% vars)) if (length(instance) > 0) { grain <- gRain::setEvidence(grain, nodes = vars, states = instance) } cp <- gRain::querygrain(grain, nodes = class, normalize = TRUE)[[class]] cp <- log(cp) if (length(vars) > 0) { cp <- cp + log(gRain::pEvidence(grain)) } cp } compile_grain <- function(cpts) { if (!requireNamespace("gRain", quietly = TRUE)) { stop("gRain needed for this function to work. Please install it.", call. = FALSE) } if (!requireNamespace("gRbase", quietly = TRUE)) { stop("gRbase needed for this function to work. Please install it.", call. = FALSE) } stopifnot(is.list(cpts)) pcpts <- lapply(cpts, gRbase::as.parray, normalize = "none", smooth = 0) all_eq <- mapply(equivalent_num, cpts, pcpts, SIMPLIFY = TRUE) stopifnot(vapply(all_eq, isTRUE, FUN.VALUE = logical(1))) gRain::grain.CPTspec(gRain::compileCPT(pcpts)) } is_grain_compiled <- function(g) { if (!requireNamespace("gRain", quietly = TRUE)) { stop("gRain needed for this function to work. Please install it.", call. = FALSE) } inherits(g, "grain") && g$isCompiled } grain_nodes <- function(g) { g$universe$nodes }
volcano <- function(x, ...){ UseMethod("volcano") } volcano.default <- function(x, pval, effect0 = 0, sig.level = 0.05, effect.low = NULL, effect.high = NULL, color.low = " xlab = "effect size", ylab = "-log10(p value)", title = "Volcano Plot", alpha = 1, shape = 19, ...){ effect <- x stopifnot(is.numeric(effect), is.numeric(pval)) stopifnot(all(pval > 0), all(pval <= 1)) stopifnot(length(effect0) == 1) stopifnot(length(sig.level) == 1) stopifnot(sig.level > 0, sig.level < 1) if(!is.null(effect.low) & !is.null(effect.high)) stopifnot(length(effect.low) == 1, length(effect.high) == 1, effect.low < effect.high) stopifnot(length(color.low) == 1, length(color.high) == 1) if(!is.null(effect.low)){ low <- effect < effect.low & pval < sig.level }else{ low <- logical(length(effect)) } if(!is.null(effect.high)){ high <- effect > effect.high & pval < sig.level }else{ high <- logical(length(effect)) } effect.color <- ifelse(low, "low", "normal") effect.color[high] <- "high" effect.color <- factor(effect.color, levels = c("low", "normal", "high")) effect.color <- factor(effect.color) DF <- data.frame(effect = effect, pval = pval, col = effect.color) if(is.null(effect.low) & is.null(effect.high)){ gg <- ggplot(DF, aes(x = effect, y = pval)) + geom_point(alpha = alpha, shape = shape) + scale_y_neglog10() + geom_vline(xintercept = effect0) + geom_vline(xintercept = c(effect.low, effect.high), color = c(color.low, color.high)) + geom_hline(yintercept = sig.level) + labs(x = xlab, y = ylab) + ggtitle(title) }else{ gg <- ggplot(DF, aes(x = effect, y = pval, color = col)) + geom_point(alpha = alpha, shape = shape) + scale_y_neglog10() + scale_color_manual(values = c("low" = color.low, "normal" = "black", "high" = color.high)) + geom_vline(xintercept = effect0) + geom_vline(xintercept = c(effect.low, effect.high), color = c(color.low, color.high)) + geom_hline(yintercept = sig.level) + labs(x = xlab, y = ylab) + ggtitle(title) } gg }
.zpss_mle <- function(par, values, freq, truncated = TRUE) { alpha <- par[1] lambda <- par[2] probs <- .panjerRecursion(max(values), alpha, lambda) if (truncated) { probs <- (probs) / (1 - probs[1]) probs <- probs[-1] return(- (sum(freq * log(probs[values])))) } return(- (sum(freq * log(probs[values+1])))) } zipfpssFit <- function(data, init_alpha = NULL, init_lambda = NULL, level=0.95, isTruncated = FALSE, ...){ Call <- match.call() if(is.null(init_alpha) || is.null(init_lambda)){ if(isTruncated){ model <- 'zt_zipfpss' } else { model <- 'zipfpss' } initValues <- getInitialValues(data, model = model) init_alpha <- initValues$init_alpha init_lambda <- initValues$init_lambda } if(!is.numeric(init_alpha) || !is.numeric(init_lambda)){ stop('Wrong intial values for the parameters.') } tryCatch({ res <- stats::optim(par = c(init_alpha, init_lambda), .zpss_mle, values = as.numeric(as.character(data[, 1])), freq = as.numeric(data[, 2]), truncated = isTruncated, hessian = TRUE, ...) estAlpha <- as.numeric(res$par[1]) estLambda <- as.numeric(res$par[2]) paramSD <- sqrt(diag(solve(res$hessian))) paramsCI <- .getConfidenceIntervals(paramSD, estAlpha, estLambda, level) structure(class = "zipfpssR", list(alphaHat = estAlpha, lambdaHat = estLambda, alphaSD = paramSD[1], lambdaSD = paramSD[2], alphaCI = c(paramsCI[1,1],paramsCI[1,2]), lambdaCI = c(paramsCI[2,1],paramsCI[2,2]), logLikelihood = -res$value, hessian = res$hessian, call = Call)) }, error = function(e){ print(c('Error', e)) }) } residuals.zipfpssR <- function(object, isTruncated = FALSE, ...){ dataMatrix <- get(as.character(object[['call']]$data)) dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1])) dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2])) fitted.values <- fitted(object, isTruncated) residual.values <- dataMatrix[, 2] - fitted.values return(residual.values) } fitted.zipfpssR <- function(object, isTruncated = FALSE, ...) { dataMatrix <- get(as.character(object[['call']]$data)) dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1])) dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2])) N <- sum(dataMatrix[, 2]) fitted.values <- N*sapply(dataMatrix[,1], dzipfpss, alpha = object[['alphaHat']], lambda = object[['lambdaHat']], isTruncated = isTruncated) return(fitted.values) } coef.zipfpssR <- function(object, ...){ estimation <- matrix(nrow = 2, ncol = 4) estimation[1, ] <- c(object[['alphaHat']], object[['alphaSD']], object[['alphaCI']][1], object[['alphaCI']][2]) estimation[2, ] <- c(object[['lambdaHat']], object[['lambdaSD']], object[['lambdaCI']][1], object[['lambdaCI']][2]) colnames(estimation) <- c("MLE", "Std. Dev.", paste0("Inf. ", "95% CI"), paste0("Sup. ", "95% CI")) rownames(estimation) <- c("alpha", "lambda") estimation } plot.zipfpssR <- function(x, isTruncated = FALSE, ...){ dataMatrix <- get(as.character(x[['call']]$data)) dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1])) dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2])) graphics::plot(dataMatrix[,1], dataMatrix[,2], log="xy", xlab="Observation", ylab="Frequency", main="Fitting Zipf-PSS Distribution", ...) graphics::lines(dataMatrix[,1], fitted(x, isTruncated), col="blue") graphics::legend("topright", legend = c('Observations', 'Zipf-PSS Distribution'), col=c('black', 'blue'), pch=c(21,NA), lty=c(NA, 1), lwd=c(NA, 2)) } print.zipfpssR <- function(x, ...){ cat('Call:\n') print(x[['call']]) cat('\n') cat('Initial Values:\n') cat(sprintf('Alpha: %s\n', format(eval(x[['call']]$init_alpha), digits = 3))) cat(sprintf('Lambda: %s\n', format(eval(x[['call']]$init_lambda), digits = 3))) cat('\n') cat('Coefficients:\n') print(coef(x)) cat('\n') cat('Metrics:\n') cat(sprintf('Log-likelihood: %s\n', logLik(x))) cat(sprintf('AIC: %s\n', AIC(x))) cat(sprintf('BIC: %s\n', BIC(x))) } summary.zipfpssR <- function(object, isTruncated = FALSE, ...){ print(object) cat('\n') cat('Fitted values:\n') print(fitted(object, isTruncated)) } logLik.zipfpssR <- function(object, ...){ if(!is.na(object[['logLikelihood']]) || !is.null(object[['logLikelihood']])){ return(object[['logLikelihood']]) } return(NA) } AIC.zipfpssR <- function(object, ...){ aic <- .get_AIC(object[['logLikelihood']], 2) return(aic) } BIC.zipfpssR <- function(object, ...){ dataMatrix <- get(as.character(object[['call']]$data)) dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1])) dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2])) bic <- .get_BIC(object[['logLikelihood']], 2, sum(dataMatrix[, 2])) return(bic) }
context("RequestPattern") test_that("RequestPattern: structure is correct", { expect_is(RequestPattern, "R6ClassGenerator") aa <- RequestPattern$new(method = "get", uri = "https://httpbin.org/get") expect_is(aa, "RequestPattern") expect_null(aa$body_pattern) expect_null(aa$headers_pattern) expect_is(aa$clone, "function") expect_is(aa$initialize, "function") expect_is(aa$matches, "function") expect_is(aa$method_pattern, "MethodPattern") expect_is(aa$to_s, "function") expect_is(aa$uri_pattern, "UriPattern") }) test_that("RequestPattern: behaves as expected", { aa <- RequestPattern$new(method = "get", uri = "https://httpbin.org/get") rs1 <- RequestSignature$new(method = "get", uri = "https://httpbin.org/get") rs2 <- RequestSignature$new(method = "post", uri = "https://httpbin.org/get") rs3 <- RequestSignature$new( method = "get", uri = "https:/httpbin.org/get", options = list(headers = list(`User-Agent` = "foobar", stuff = "things")) ) expect_true(aa$matches(rs1)) expect_false(aa$matches(rs2)) expect_false(aa$matches(rs3)) expect_is(aa$to_s(), "character") expect_match(aa$to_s(), "GET") expect_match(aa$to_s(), "httpbin.org/get") }) test_that("RequestPattern: uri_regex", { x <- RequestPattern$new(method = "get", uri_regex = ".+ossref.org") expect_is(x$uri_pattern, "UriPattern") expect_equal(x$uri_pattern$to_s(), "https?://.+ossref.org") expect_equal(x$to_s(), "GET https?://.+ossref.org") }) test_that("RequestPattern fails well", { expect_error(RequestPattern$new(), "one of uri or uri_regex is required") x <- RequestPattern$new(method = "get", uri = "https://httpbin.org/get") expect_error(x$matches(), "argument \"request_signature\" is missing") expect_error(x$matches("adfadf"), "request_signature must be of class RequestSignature") }) context("MethodPattern") test_that("MethodPattern: structure is correct", { expect_is(MethodPattern, "R6ClassGenerator") aa <- MethodPattern$new(pattern = "get") expect_is(aa, "MethodPattern") expect_is(aa$pattern, "character") expect_equal(aa$pattern, "get") expect_true(aa$matches(method = "get")) expect_false(aa$matches(method = "post")) expect_error( expect_is(aa$matches(), "function"), "argument \"method\" is missing" ) }) context("HeadersPattern") test_that("HeadersPattern: structure is correct", { expect_is(HeadersPattern, "R6ClassGenerator") aa <- HeadersPattern$new(pattern = list(a = 5)) expect_is(aa, "HeadersPattern") expect_is(aa$pattern, "list") expect_named(aa$pattern, "a") expect_true(aa$matches(headers = list(a = 5))) expect_false(aa$matches(headers = list(a = 6))) expect_false(aa$matches(list())) bb <- HeadersPattern$new(pattern = list()) expect_true(bb$matches(list())) expect_error( expect_is(aa$matches(), "function"), "argument \"headers\" is missing" ) expect_equal(aa$to_s(), "a=5") }) context("BodyPattern") test_that("BodyPattern: structure is correct", { expect_is(BodyPattern, "R6ClassGenerator") bb <- RequestSignature$new( method = "get", uri = "https:/httpbin.org/get", options = list( body = list(foo = "bar", a = 5) ) ) aa <- BodyPattern$new(pattern = list(foo = "bar")) expect_is(aa, "BodyPattern") expect_is(aa$pattern, "list") expect_named(aa$pattern, "foo") expect_false(aa$matches(bb$body)) aaa <- BodyPattern$new(pattern = list(foo = "bar", a = 5)) expect_true(aaa$matches(bb$body)) bb <- BodyPattern$new(pattern = list()) expect_true(bb$matches(list())) expect_error( aa$matches(), "argument \"body\" is missing" ) expect_equal(aa$to_s(), list(foo = "bar")) }) context("UriPattern") test_that("UriPattern: structure is correct", { expect_is(UriPattern, "R6ClassGenerator") aa <- UriPattern$new(pattern = "http://foobar.com") expect_is(aa, "UriPattern") expect_is(aa$pattern, "character") expect_false(aa$regex) expect_match(aa$pattern, "foobar") expect_true(aa$matches("http://foobar.com")) expect_true(aa$matches("http://foobar.com/")) expect_error( expect_is(aa$matches(), "function"), "argument \"uri\" is missing" ) z <- UriPattern$new(regex_pattern = ".+ample\\..") expect_is(z, "UriPattern") expect_is(z$pattern, "character") expect_true(z$regex) expect_true(z$matches("http://sample.org")) expect_true(z$matches("http://example.com")) expect_false(z$matches("http://tramples.net")) z <- UriPattern$new(pattern = "http://foobar.com") expect_equal(z$pattern, "http://foobar.com") z$add_query_params(list(pizza = "cheese", cheese = "cheddar")) expect_equal(z$pattern, "http://foobar.com?pizza=cheese&cheese=cheddar") z <- UriPattern$new(pattern = "http://foobar.com?pizza=cheese&cheese=cheddar") expect_equal(z$pattern, "http://foobar.com?pizza=cheese&cheese=cheddar") expect_false(z$matches("http://foobar.com?pizza=cheese&cheese=cheddar")) z$add_query_params() expect_true(z$matches("http://foobar.com?pizza=cheese&cheese=cheddar")) z <- UriPattern$new(pattern = "foobar.com") expect_equal(z$pattern, "http://foobar.com") expect_true(z$matches("http://foobar.com")) expect_false(z$matches("https://foobar.com")) z <- UriPattern$new(regex_pattern = "https://x.com/.+/order?fruit=apple") z$add_query_params() expect_is(z, "UriPattern") expect_is(z$pattern, "character") expect_true(z$regex) expect_true(z$matches("https://x.com/a/order?fruit=apple")) expect_true(z$matches("https://x.com/b/order?fruit=apple")) expect_false(z$matches("https://x.com/a?fruit=apple")) })
NULL NULL "cocktails" globalVariables(c('cocktails','votes','rating','cocktail','proportion','url','short_ingredient','unit', 'cocktail_id','coamount','amt', 'deno','deno2','rhoval', 'sum_cova','n','rat','tot_ingr','tot_has_ingr','tot_am','ncocktails', 'tstat','page_src','tst', 'has_or_must','has_and_must','has_not_must', 'matches_name','ingr_class','description', 'isfl', 'match_re_ing', 'has_ing','bad_ing', 'ck_ok', 'pct_amt', 'tot_amt','has_both','Other', 'ingredient','coingredient','cova','wts')) my_ui <- function(page_title='Drink Schnauzer') { utils::data("cocktails", package="cocktailApp") indat <- cocktails normo <- indat %>% dplyr::group_by(short_ingredient) %>% dplyr::summarize(tot_am=sum(proportion,na.rm=TRUE)) %>% dplyr::ungroup() %>% dplyr::mutate(ingr_class=cut(tot_am,breaks=c(-1,0,10,100,1000), labels=c('garnish','uncommon-spirit','common-spirit','base-spirit'))) %>% dplyr::arrange(tot_am,short_ingredient) %>% dplyr::mutate(ingr_class=forcats::fct_rev(ingr_class)) %>% dplyr::arrange(ingr_class,short_ingredient) ingr <- (split(normo$short_ingredient,normo$ingr_class)) sources <- indat %>% dplyr::select(url) %>% dplyr::mutate(url=gsub('^http://(www.)?(.+).com/.+$','\\2',url)) %>% dplyr::distinct(url) all_source <- unique(sources$url) if (!is.null(page_title)) { tp_bits <- titlePanel(page_title) } else { tp_bits <- tagList() } shinyUI( fluidPage(theme=shinytheme("spacelab"), tags$head( tags$script(src='test.js'), tags$style(".table .alignRight {color: black; text-align:right;}"), tags$link(rel="stylesheet", type="text/css", href="style.css") ), tp_bits, sidebarLayout( position="left", sidebarPanel( width=2, selectInput("must_have_ing","Must Have:",choices=ingr,selected=c(),multiple=TRUE), selectInput("logical_sense","Join by:",choices=c('OR','AND'),selected='OR',multiple=FALSE), selectInput("must_not_have_ing","Must Not Have:",choices=ingr,selected=c(),multiple=TRUE), selectInput("from_sources","Sources:",choices=all_source,selected=all_source[grepl('diffords|kindred',all_source)],multiple=TRUE), textInput("name_regex","Name Regex:",value='',placeholder='^sazerac'), textInput("ing_regex","Ingredient Regex:",value='',placeholder='^[Cc]hartreus'), helpText('Select for random cocktails:'), checkboxInput("hobsons","Hobson's Choice!",value=FALSE), hr(), sliderInput("max_ingr","Maximum Ingredients:",sep='',min=1,max=20,value=6), sliderInput("max_other_ingr","Maximum Unlisted Ingredients:",sep='',min=1,max=20,value=6), sliderInput("min_rating","Minimum Rating",min=1,max=5,value=3.5,step=0.5), sliderInput("min_tstat","Minimum T-Stat",min=1,max=100,value=2,step=0.25), sliderInput("t_zero","T-Stat Zero",min=1,max=5,value=2.5,step=0.25), hr(), helpText('data scraped from the web'), bookmarkButton('bookmark',title='bookmark page'), hr() ), mainPanel( width=9, tabsetPanel( tabPanel('drinks', helpText('Select rows from this table to see the recipe below', 'and also in the plot tab.'), DT::dataTableOutput('drinks_table'), hr(), helpText('Ingredients Table:'), tableOutput('ingredients_table') ), tabPanel('ternary', helpText('A ternary plot based on the first two Must Have ingredients selected.'), plotOutput('selected_ingredients_tern_plot',height='100%',width='100%') ), tabPanel('plots', helpText('A bar plot of ingredients in the selected cocktails.', 'If nothing appears here, select rows of the table in the "drinks" tab to populate.'), plotOutput('selected_ingredients_bar_plot') ), tabPanel('other', helpText('This is not well tested, but here one should find a table of common co-ingredients.', 'If you have selected ingredients in the "Must Have" input, other ingredients which', 'commonly co-occur should appear in this table.'), DT::dataTableOutput('suggestions_table') ) ) ) ) ) ) } .applylink <- function(title,url) { as.character(a(title,href=url,target="_blank")) } applylink <- function(title,url) { as.character(mapply(.applylink,title,url)) } .add_id <- function(recipe_df) { subs <- recipe_df %>% dplyr::distinct(cocktail,url) %>% tibble::rowid_to_column(var='cocktail_id') recipe_df %>% dplyr::left_join(subs,by=c('cocktail','url')) } .distill_info <- function(recipe_df) { cocktail_df <- recipe_df %>% dplyr::mutate(isfl=(unit=='fl oz')) %>% dplyr::group_by(cocktail_id) %>% dplyr::summarize(cocktail=dplyr::first(cocktail), rating=dplyr::first(rating), votes=dplyr::first(votes), url=dplyr::first(url), tot_ingr=sum(isfl)) %>% dplyr::ungroup() %>% mutate(votes=as.numeric(votes)) %>% dplyr::mutate(page_src=gsub('^http://(www.)?(.+).com/.+$','\\2',url)) } .gen_both <- function(raw_dat=NULL) { if (missing(raw_dat) || is.null(raw_dat)) { utils::data("cocktails", package="cocktailApp") raw_dat <- cocktails } recipe_df <- raw_dat %>% .add_id() cocktail_df <- recipe_df %>% .distill_info() list(recipe=recipe_df %>% dplyr::select(-cocktail,-rating,-votes,-url),cocktail=cocktail_df) } .filter_ingredients <- function(both,name_regex,must_have_ing,must_not_have_ing, ing_regex='',logical_sense=c('AND','OR'),extra_ids=NULL) { logical_sense <- match.arg(logical_sense) if (nzchar(name_regex)) { match_name <- both$cocktail %>% dplyr::distinct(cocktail,cocktail_id) %>% dplyr::filter(grepl(pattern=name_regex,x=cocktail,ignore.case=TRUE,perl=TRUE,fixed=FALSE)) %>% dplyr::distinct(cocktail_id) %>% dplyr::mutate(matches_name=nzchar(name_regex)) } else { match_name <- tibble::tribble(~cocktail_id,~matches_name) } if (!is.null(extra_ids)) { more_match <- both$cocktail %>% dplyr::filter(cocktail_id %in% extra_ids) %>% dplyr::select(cocktail_id) %>% dplyr::mutate(matches_name=TRUE) match_name <- match_name %>% rbind(more_match) } ok_by_ing <- both$recipe %>% dplyr::mutate(bad_ing=(short_ingredient %in% must_not_have_ing)) if (nzchar(ing_regex)) { ok_by_ing <- ok_by_ing %>% dplyr::mutate(match_re_ing=grepl(pattern=ing_regex,x=short_ingredient,ignore.case=TRUE,perl=TRUE,fixed=FALSE)) } else { ok_by_ing <- ok_by_ing %>% dplyr::mutate(match_re_ing=FALSE) } if ((length(must_have_ing) > 0) || nzchar(ing_regex)) { if ((logical_sense=='AND') && (length(must_have_ing) > 1)) { ok_by_ing <- ok_by_ing %>% dplyr::group_by(cocktail_id) %>% dplyr::summarize(ck_ok = (all(must_have_ing %in% short_ingredient) | any(match_re_ing)) & !any(bad_ing)) %>% dplyr::ungroup() } else { ok_by_ing <- ok_by_ing %>% dplyr::mutate(has_ing=(short_ingredient %in% must_have_ing)) %>% dplyr::group_by(cocktail_id) %>% dplyr::summarize(ck_ok=any(has_ing | match_re_ing) & !any(bad_ing)) %>% dplyr::ungroup() } } else { ok_by_ing <- tibble::tribble(~cocktail_id,~ck_ok) } new_recipe <- match_name %>% dplyr::left_join(both$recipe,by='cocktail_id') %>% dplyr::select(-matches_name) %>% rbind(ok_by_ing %>% dplyr::filter(ck_ok) %>% dplyr::select(-ck_ok) %>% dplyr::left_join(both$recipe,by='cocktail_id')) new_cocktail <- both$cocktail %>% dplyr::right_join(new_recipe %>% dplyr::distinct(cocktail_id),by='cocktail_id') list(recipe=new_recipe,cocktail=new_cocktail) } .filter_num_ingredients <- function(both,must_have_ing,min_rating,max_ingr,max_other_ingr) { tot_has <- both$recipe %>% dplyr::group_by(cocktail_id) %>% dplyr::summarize(tot_has_ingr=sum(short_ingredient %in% must_have_ing)) %>% dplyr::ungroup() new_cocktail <- both$cocktail %>% dplyr::filter(rating >= min_rating, tot_ingr <= max_ingr) %>% dplyr::left_join(tot_has,by='cocktail_id') %>% dplyr::filter(tot_ingr <= max_other_ingr + tot_has_ingr) %>% dplyr::select(-tot_has_ingr) new_recipe <- both$recipe %>% dplyr::right_join(new_cocktail %>% select(cocktail_id),by='cocktail_id') list(recipe=new_recipe,cocktail=new_cocktail) } .filter_tstat <- function(both,min_t=2,t_zero=2.5,miss_votes=20,t_digits=2) { new_cocktail <- both$cocktail %>% dplyr::mutate(tstat=signif((rating - t_zero) * sqrt(coalesce(votes,miss_votes)),t_digits)) %>% dplyr::filter(tstat >= min_t) new_recipe <- both$recipe %>% dplyr::right_join(new_cocktail %>% select(cocktail_id),by='cocktail_id') list(recipe=new_recipe,cocktail=new_cocktail) } .filter_src <- function(both,from_sources) { new_cocktail <- both$cocktail %>% dplyr::filter(page_src %in% from_sources) new_recipe <- both$recipe %>% dplyr::right_join(new_cocktail %>% select(cocktail_id),by='cocktail_id') list(recipe=new_recipe,cocktail=new_cocktail) } .add_description <- function(both) { descdat <- both$recipe %>% dplyr::filter(unit=='fl oz') %>% dplyr::arrange(dplyr::desc(amt)) %>% dplyr::group_by(cocktail_id) %>% dplyr::summarize(description=paste0(paste0(short_ingredient,collapse=', '),'.')) %>% dplyr::ungroup() new_cocktail <- both$cocktail %>% dplyr::left_join(descdat,by=c('cocktail_id')) list(recipe=both$recipe,cocktail=new_cocktail) } .merge_both <- function(both) { both$recipe %>% dplyr::left_join(both$cocktail,by='cocktail_id') %>% dplyr::select(cocktail,rating,amt,unit,ingredient,everything()) %>% dplyr::arrange(dplyr::desc(rating),cocktail,dplyr::desc(as.numeric(unit=='fl oz')),dplyr::desc(amt)) } .drinks_table <- function(both) { otdat <- both$cocktail %>% dplyr::mutate(cocktail=applylink(cocktail,url)) %>% dplyr::select(rating,tstat,cocktail,description) } .coingredients <- function(recipe_df) { sub_df <- recipe_df %>% dplyr::select(short_ingredient,cocktail_id,rating,proportion) coing <- sub_df %>% dplyr::filter(!is.na(proportion)) %>% dplyr::mutate(rating=coalesce(rating,1)) %>% dplyr::inner_join(sub_df %>% dplyr::rename(coingredient=short_ingredient,coamount=proportion),by=c('cocktail_id','rating')) %>% dplyr::mutate(cova=proportion * coamount) %>% dplyr::mutate(wts=rating) %>% dplyr::group_by(short_ingredient,coingredient) %>% dplyr::summarize(sum_cova=sum(cova*wts,na.rm=TRUE), sum_wts=sum(wts,na.rm=TRUE), ncocktails=n()) %>% dplyr::ungroup() %>% dplyr::arrange(dplyr::desc(ncocktails)) } .ingredient_rho <- function(recipe_df) { coing <- .coingredients(recipe_df) diagv <- coing %>% dplyr::filter(short_ingredient==coingredient) %>% dplyr::mutate(deno=sqrt(sum_cova)) rhov <- coing %>% dplyr::left_join(diagv %>% select(short_ingredient,deno),by='short_ingredient') %>% dplyr::left_join(diagv %>% select(coingredient,deno) %>% rename(deno2=deno),by='coingredient') %>% dplyr::mutate(rhoval=sum_cova / (deno * deno2)) %>% dplyr::filter(!is.na(rhoval)) %>% dplyr::select(short_ingredient,coingredient,ncocktails,rhoval) %>% dplyr::filter(ncocktails > 2) %>% dplyr::arrange(dplyr::desc(rhoval)) } .prepare_ternary <- function(both,two_ing) { stopifnot(length(two_ing) > 1) stopifnot(all(c('cocktail_id','cocktail','rating','page_src') %in% colnames(both$cocktail))) stopifnot(all(c('cocktail_id','unit','short_ingredient','proportion') %in% colnames(both$recipe))) bycols <- both$recipe %>% dplyr::filter(unit=='fl oz', short_ingredient %in% two_ing) %>% dplyr::group_by(cocktail_id,short_ingredient) %>% dplyr::summarize(tot_amt=sum(proportion,na.rm=TRUE)) %>% dplyr::ungroup() %>% dplyr::rename(proportion=tot_amt) %>% dplyr::group_by(cocktail_id) %>% dplyr::mutate(has_both=length(proportion) > 1, Other=1 - sum(proportion)) %>% dplyr::ungroup() %>% dplyr::filter(has_both) . <- NULL retv <- bycols %>% tidyr::spread(key=short_ingredient,value=proportion,fill=0) %>% setNames(gsub('\\s','_',names(.))) %>% dplyr::left_join(both$cocktail %>% select(cocktail_id,cocktail,rating,page_src),by='cocktail_id') } .make_bar_plot <- function(both_df) { ph <- both_df %>% dplyr::filter(unit=='fl oz') %>% dplyr::arrange(dplyr::desc(rating)) %>% mutate(pct_amt=100*proportion) %>% ggplot(aes(ingredient,pct_amt,fill=cocktail)) + geom_col(position='dodge') + coord_flip() + labs(y='amount (%)', x='ingredient', title='selected drinks') } .make_ggtern_plot <- function(tern_df,preing) { ing <- gsub('\\s','_',preing) ph <- tern_df %>% ggtern::ggtern(ggplot2::aes_string(x=ing[1],y=ing[2],z='Other', shape='page_src',label='cocktail',color='rating')) + ggplot2::geom_point(aes(size=rating),alpha=0.5) + ggtern::Llab(preing[1]) + ggtern::Tlab(preing[2]) + ggplot2::geom_text(hjust='inward',vjust='inward') + ggplot2::guides(shape=guide_legend(title='source')) ph } my_server <- function(input, output, session) { get_both <- reactive({ utils::data("cocktails", package="cocktailApp") both <- .gen_both(cocktails) }) get_ing_rho <- reactive({ both <- get_both() recipe_df <- both$recipe %>% left_join(both$cocktail,by='cocktail_id') rhov <- .ingredient_rho(recipe_df) }) suggested_ingr <- reactive({ retv <- get_ing_rho() %>% rename(ingredient=short_ingredient) %>% dplyr::filter(ingredient %in% input$must_have_ing,ingredient != coingredient,ncocktails > 5) %>% dplyr::arrange(dplyr::desc(rhoval)) }) filter_ingr <- reactive({ .filter_ingredients(both=get_both(),name_regex=input$name_regex,extra_ids=hobsons_choice$ids, must_have_ing=input$must_have_ing, must_not_have_ing=input$must_not_have_ing, ing_regex=input$ing_regex, logical_sense=input$logical_sense) }) filter_num_ingr <- reactive({ .filter_num_ingredients(both=filter_ingr(),must_have_ing=input$must_have_ing, min_rating=input$min_rating,max_ingr=input$max_ingr, max_other_ingr=input$max_other_ingr) }) filter_tstat <- reactive({ .filter_tstat(both=filter_num_ingr(),min_t=input$min_tstat,t_zero=input$t_zero) }) filter_src <- reactive({ .filter_src(both=filter_tstat(),from_sources=input$from_sources) }) final_both <- reactive({ .add_description(both=filter_src()) }) final_merged <- reactive({ .merge_both(both=final_both()) }) selectable <- reactive({ }) selected_drinks <- reactive({ both <- final_both() drinks <- both$cocktail selrows <- input$drinks_table_rows_selected otdat <- both$recipe %>% dplyr::inner_join(drinks[selrows,] %>% dplyr::select(cocktail_id,cocktail,rating),by='cocktail_id') otdat }) hobsons_choice <- reactiveValues(ids=NULL) observeEvent(input$hobsons,{ if (input$hobsons) { both <- .filter_num_ingredients(both=get_both(),must_have_ing=c(), min_rating=input$min_rating,max_ingr=input$max_ingr, max_other_ingr=input$max_other_ingr) both <- .filter_tstat(both=both,min_t=input$min_tstat,t_zero=input$t_zero) both <- .filter_src(both=both,from_sources=input$from_sources) eligible <- both$cocktail %>% distinct(cocktail_id) %>% sample_n(size=5,replace=FALSE) hobsons_choice$ids <- eligible$cocktail_id } else { hobsons_choice$ids <- NULL } }) output$drinks_table <- DT::renderDataTable({ otdat <- .drinks_table(both=final_both()) DT::datatable(otdat,caption='Matching cocktails. Click on a row to populate the ingredients table below.', escape=FALSE,rownames=FALSE, options=list(order=list(list(1,'desc'),list(0,'desc'),list(2,'asc')), paging=TRUE, pageLength=15)) }, server=TRUE) output$suggestions_table <- DT::renderDataTable({ selco <- suggested_ingr() DT::datatable(selco, caption='Coingredients.', escape=FALSE, rownames=FALSE, options=list(paging=TRUE, pageLength=20)) %>% DT::formatRound(columns=c('rhoval'),digits=2) }, server=TRUE) output$selected_ingredients_bar_plot <- renderPlot({ ph <- selected_drinks() %>% .make_bar_plot() ph }) output$ingredients_table <- renderTable({ retv <- selected_drinks() %>% dplyr::select(cocktail,amt,unit,ingredient) },striped=TRUE,width='100%') output$selected_ingredients_tern_plot <- renderPlot({ shiny::validate(shiny::need(length(input$must_have_ing) > 1,'Must select 2 or more must have ingredients.')) preing <- input$must_have_ing[1:2] tern_df <- .prepare_ternary(both=final_both(),two_ing=preing) shiny::validate(shiny::need(nrow(tern_df) > 0,paste('No cocktails found with both',preing[1],'and',preing[2]))) ph <- .make_ggtern_plot(tern_df,preing=preing) print(ph) NULL },height=900,width=1300) setBookmarkExclude(c('bookmark', 'drinks_table_cell_clicked', 'drinks_table_row_last_clicked')) observeEvent(input$bookmark,{ session$doBookmark() }) } cocktailApp <- function(page_title='Drink Schnauzer',enableBookmarking='url') { shinyApp(ui=function(request){ my_ui(page_title=page_title) }, server=my_server, enableBookmarking=enableBookmarking) }
test_that("Test Rosenbrock Banana optimization with objective and gradient in separate functions.", { x0 <- c( -1.2, 1 ) opts <- list( "algorithm" = "NLOPT_LD_LBFGS", "xtol_rel" = 1.0e-8, "print_level" = 0 ) eval_f <- function(x) { return( 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2 ) } eval_grad_f <- function(x) { return( c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]), 200 * (x[2] - x[1] * x[1])) ) } res <- nloptr( x0 = x0, eval_f = eval_f, eval_grad_f = eval_grad_f, opts = opts ) expect_equal(res$objective, 0.0) expect_equal(res$solution, c(1.0, 1.0)) } ) test_that("Test Rosenbrock Banana optimization with objective and gradient in the same function.", { x0 <- c( -1.2, 1 ) opts <- list( "algorithm" = "NLOPT_LD_LBFGS", "xtol_rel" = 1.0e-8, "print_level" = 0 ) eval_f_list <- function(x) { return( list( "objective" = 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2, "gradient" = c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]), 200 * (x[2] - x[1] * x[1])) ) ) } res <- nloptr( x0 = x0, eval_f = eval_f_list, opts = opts ) expect_equal(res$objective, 0.0) expect_equal(res$solution, c(1.0, 1.0)) } )
rnucDiag <- function(DNAbin, sppVector, n = 100){ lsv <- length(sppVector) psv <- table(sppVector)/lsv rss <- replicate(n, sample(1:length(unique(sppVector)), lsv, replace = TRUE, prob = psv), simplify = FALSE) rnd <- lapply(rss, function(xx) unlist(sapply(nucDiag(DNAbin, xx), length))) rndOrd <- sapply(rnd, function(xx) xx[order(names(xx))]) rssNum <- sapply(rss, table) NndNss <- tapply(unlist(rndOrd), unlist(rssNum), function(xx) xx) rndFreq <- lapply(NndNss, table) rmin <- sapply(rnd, min) rmean <- sapply(rnd, mean) rmedian <- sapply(rnd, median) rmax <- sapply(rnd, max) list(min = rmin, mean = rmean, median = rmedian, max = rmax, rndFreq = rndFreq) }
gni_parse <- function(names, ...) { names <- paste0(names, collapse = "|") cli <- crul::HttpClient$new(paste0(gni_base(), "parsers.json"), headers = tx_ual, opts = list(...)) tt <- cli$get(query = list(names = names)) tt$raise_for_status() out <- jsonlite::fromJSON(tt$parse("UTF-8"), FALSE) dt2df(lapply(out, gni_parser), idcol = FALSE) } gni_parser <- function(x) { positions_names <- vapply(x$scientificName$positions, function(y) paste("position_", y[[1]], sep = ""), "", USE.NAMES = FALSE) nums <- vapply(x$scientificName$positions, function(y) y[[2]], 1, USE.NAMES = FALSE) pv <- data.frame(as.list(setNames(nums, positions_names)), stringsAsFactors = FALSE) singles <- data.frame(x$scientificName[c("verbatim","canonical", "normalized","hybrid","parsed")], stringsAsFactors = FALSE) details_ <- x$scientificName$details[[1]] details_ <- details_[!names(details_) %in% 'status'] details <- dt2df(Map(function(x, y) data.frame(y, x, stringsAsFactors = FALSE), details_, names(details_)), idcol = FALSE)[,-3] details2 <- as.data.frame(t(data.frame(details[,2]))) names(details2) <- details[,1] row.names(details2) <- NULL data.frame(details2, singles, pv, stringsAsFactors = FALSE) }
filter_raw_data<-function(raw_data=NULL,filter_table=NULL,date_filter=FALSE){ .datatable.aware=TRUE if (is.null(raw_data)) { data_out<-NULL } else if (is.null(filter_table)){ data_out<-raw_data } else { ft<-time<-NULL if (date_filter){ data.table::setnames(raw_data,colnames(raw_data),tolower(colnames(raw_data))) if ("time_period" %in% colnames(raw_data)){data.table::setnames(raw_data,"time_period","time")} if ("obstime" %in% colnames(raw_data)){data.table::setnames(raw_data,"obstime","time")} raw_data$ft<-as.character(raw_data$time) raw_data[grepl("^\\d{4}$",time),ft:=paste0(time,"-01-01")] raw_data[grepl("[M]\\d\\d$",time),ft:=paste0(gsub('[M]',"-",time),"-01")] raw_data[grepl("[MD]",ft),ft:=gsub('[MD]',"-",ft)] raw_data[grepl("Q",time),ft:=paste0(substr(time,1,4),"-",lapply(substr(time,6,6),function(x){if (x<"4"){"0"}else{""}}),as.character((as.numeric(substr(time,6,6))-1)*3+1),"-01")] raw_data[grepl("S",time),ft:=paste0(substr(time,1,4),"-0",as.character((as.numeric(substr(time,6,6))-1)*6+1),"-01")] data_out<-data.table::rbindlist(lapply(1:nrow(filter_table),function (x){raw_data[(ft>=filter_table$sd[x] & ft<=filter_table$ed[x])]})) data_out<-data_out[,!'ft'][] }else{ filter_table<-unique(filter_table[,c("concept","code")]) data.table::setnames(raw_data,colnames(raw_data),toupper(colnames(raw_data))) concepts<-unique(filter_table$concept) data_out<-raw_data[eval(parse(text=paste(lapply(concepts,function(concept){ paste("(",paste0(filter_table$concept[filter_table$concept==concept],"==",'"',filter_table$code[filter_table$concept==concept],'"',collapse=" | "),")") }),collapse=" & ")))][] data.table::setnames(data_out,colnames(data_out),tolower(colnames(data_out))) } } data_out[] }
library(FLLat) data(simaCGH) result.pve <- FLLat.PVE(simaCGH,J.seq=1:(ncol(simaCGH)/2)) plot(result.pve) result.bic <- FLLat.BIC(simaCGH,J=5) result.bic$lam1 result.bic$lam2 plot(result.bic$opt.FLLat) plot(result.bic$opt.FLLat,type="weights") set.seed(1364) result.fdr <- FLLat.FDR(simaCGH,result.bic$opt.FLLat) result.fdr$thresh.control plot(result.fdr) tr.dat <- simaCGH[,1:15] tst.dat <- simaCGH[,16:20] result.tr <- FLLat(tr.dat,J=5,lam1=1,lam2=9) tst.pred <- predict(result.tr,newY=tst.dat) plot(tst.dat[,1],xlab="Probe",ylab="Y") lines(tst.pred$pred.Y[,1],col="red",lwd=3)
min_cut <- function(x, min.size = length(x)/10){ x.na <- x[is.na(x) == FALSE] p.x <- cumsum(prop.table(table(x.na))) t.x <- cumsum(table(x.na)) bm <- cbind(table(x.na),t.x) dif <- vector(length = nrow(bm)) for (i in 2:length(dif)) dif[i] <- bm[i,2] - bm[i-1,2] dif[1] <- bm[1, 2] bm <- cbind(bm, dif) group <- vector(length = nrow(bm)) g <- 1 collect <- 0 for (i in 1:nrow(bm)){ if (dif[i] >= min.size | collect >= min.size-1){ group[i] <- g g <- g + 1 collect <- 0 }else{ group[i] <- g collect <- collect + dif[i] } } x.group <- vector(length = length(x)) group.levels <- as.numeric(levels(as.factor(group))) values <- as.numeric(rownames(bm)) levs <- vector() for (i in 1:length(group.levels)){ g <- group.levels[i] val <- values[group == g] g <- paste(min(val), ":", max(val), sep = "") x.group[x %in% val] <- g levs <- c(levs, paste(min(val), ":", max(val), sep = "")) } x.group[is.na(x)] <- NA factor(x.group, labels = levs, ordered = TRUE) } cowboy_cut <- function(x, top.share = 0.10, bottom.share = 0.10, missing = "Missing"){ x[x %in% missing] <- NA x <- droplevels(x) x <- as.ordered(x) x <- as.numeric(x) x.top <- x x.bottom <- x x.top[is.na(x)] <- -Inf x.bottom[is.na(x)] <- Inf top <- quantile(x.top, probs = seq(0, 1, by = top.share), na.rm = TRUE, type = 3) %>% tail(2) %>% head(1) bottom <- quantile(x.bottom, probs = seq(0, 1, by = bottom.share), na.rm = TRUE, type = 3) %>% head(2) %>% tail(1) mid <- x[x != 0 & x < top] %>% quantile(probs = seq(0, 1, by = 0.33), type = 3, na.rm = TRUE) mid <- mid[-1] mid <- mid[-3] breaks <- c(-Inf, bottom, mid, top, Inf) o <- x %>% as.numeric() %>% cut(breaks = unique(breaks), include.lowest = TRUE) levels(o) <- paste0(1:nlevels(o), "/", nlevels(o)) o %>% fct_explicit_na(na_level = "Missing") } export <- function(object, file = "export.csv", dim = 1:5) { if (is.matrix(object) == TRUE|is.data.frame(object) == TRUE){ write.csv(object, file, fileEncoding = "UTF-8")} if ((class(object) == "tab.variable") == TRUE){ ll <- length(object) nam <- names(object) a <- object[[1]] coln <- ncol(a) line <- c(rep("", coln)) line2 <- c(rep("", coln)) a <- rbind(line, a, line2) for (i in 2:ll){ line <- c(rep("", coln)) line2 <- c(rep("", coln)) a <- rbind(a,line, object[[i]], line2) line2 <- c(rep("", coln)) } rownames(a)[rownames(a) == "line"] <- nam rownames(a)[rownames(a) == "line2"] <- "" out <- a write.csv(out, file, fileEncoding = "UTF-8") } if ((class(object) == "soc.mca") == TRUE){ coord.mod <- object$coord.mod[,dim] coord.sup <- object$coord.sup[,dim] coord.ind <- object$coord.ind[,dim] names.mod <- object$names.mod names.sup <- object$names.sup names.ind <- object$names.ind coord <- round(rbind(coord.mod, coord.sup, coord.ind), 2) names <- c(names.mod, names.sup, names.ind) rownames(coord) <- names ctr.mod <- object$ctr.mod[,dim] ctr.sup <- matrix(nrow = nrow(coord.sup), ncol = ncol(coord.sup)) ctr.ind <- object$ctr.ind[,dim] ctr <- round(1000*rbind(ctr.mod, ctr.sup, ctr.ind)) cor.mod <- round(100*object$cor.mod[,dim], 1) cor.sup <- matrix(nrow = nrow(coord.sup), ncol = ncol(coord.sup)) cor.ind <- matrix(nrow = nrow(coord.ind), ncol = ncol(coord.ind)) cor <- rbind(cor.mod, cor.sup, cor.ind) out <- cbind(coord, ctr, cor) colnames(out) <- c(paste("Coord:", dim), paste("Ctr:", dim), paste("Cor:", dim)) write.csv(out, file, fileEncoding = "UTF-8") } } invert <- function(x, dim = 1) { x$coord.mod[,dim] <- x$coord.mod[,dim] * -1 x$coord.all[, dim] <- x$coord.all[, dim] * -1 x$coord.ind[,dim] <- x$coord.ind[,dim] * -1 x$coord.sup[,dim] <- x$coord.sup[,dim] * -1 return(x) } to.MCA <- function(object, active, dim = 1:5) { rownames(active) <- object$names.ind rownames(object$coord.ind) <- object$names.ind var <- list(coord = object$coord.mod[,dim], cos2 = object$cor.mod[,dim], contrib = object$ctr.mod[,dim]) ind <- list(coord = object$coord.ind[,dim], cos2 = object$cor.ind[,dim], contrib = object$ctr.ind[,dim]) call <- list(marge.col = object$mass.mod, marge.row = 1/object$n.ind, row.w = rep(1, object$n.ind), X = active, ind.sup = NULL) eig <- matrix(0, nrow = length(dim), ncol = 3) rownames(eig) <- paste("dim ", dim, sep="") colnames(eig) <- c("eigenvalue", "percentage of variance", "cumulative percentage of variance") eig[,1] <- object$eigen[dim] eig[,2] <- eig[,1]/sum(object$eigen) *100 eig[,3] <- cumsum(eig[,2]) res <- list(eig=eig, var=var, ind=ind, call=call) class(res) <- c("MCA", "list") return(res) } barycenter <- function(object, mods = NULL, dim = 1){ new.coord <- sum(object$mass.mod[mods] * object$coord.mod[mods, dim]) / sum(object$mass.mod[mods]) new.coord } mca.eigen.check <- function(active, passive = "Missing"){ get.eigen <- function(x, y, passive = "Missing"){ d <- data.frame(x, y) r <- soc.mca(d, passive = passive) burt <- t(r$indicator.matrix.active) %*% r$indicator.matrix.active burt.s <- burt / diag(burt) diag(burt.s) <- 0 max(burt.s) o <- c("First eigen" = r$eigen[1], "Passive categories" = length(r$names.passive), "Max overlap (%)" = max(burt.s)) o } comb <- active %>% colnames() %>% combn(., 2, simplify = T) %>% t() %>% as_tibble() colnames(comb) <- c("x", "y") values <- purrr::map2_df(.x = comb$x, .y = comb$y, ~get.eigen(x = active[[.x]], y = active[[.y]], passive = passive)) o <- bind_cols(comb, values) o }
test_that("can pack multiple columns", { df <- tibble(a1 = 1, a2 = 2, b1 = 1, b2 = 2) out <- df %>% pack(a = c(a1, a2), b = c(b1, b2)) expect_named(out, c("a", "b")) expect_equal(out$a, df[c("a1", "a2")]) expect_equal(out$b, df[c("b1", "b2")]) }) test_that("packing no columns returns input", { df <- tibble(a1 = 1, a2 = 2, b1 = 1, b2 = 2) expect_equal(pack(df), df) }) test_that("can strip outer names from inner names", { df <- tibble(ax = 1, ay = 2) out <- pack(df, a = c(ax, ay), .names_sep = "") expect_named(out$a, c("x", "y")) }) test_that("all inputs must be named", { df <- tibble(a1 = 1, a2 = 2, b1 = 1, b2 = 2) expect_snapshot({ (expect_error(pack(df, a = c(a1, a2), c(b1, b2)))) (expect_error(pack(df, c(a1, a2), c(b1, b2)))) }) }) test_that("grouping is preserved", { df <- tibble(g1 = 1, g2 = 1, g3 = 1) out <- df %>% dplyr::group_by(g1, g2) %>% pack(g = c(g2, g3)) expect_equal(dplyr::group_vars(out), "g1") }) test_that("grouping is preserved", { df <- tibble(g = 1, x = tibble(y = 1)) out <- df %>% dplyr::group_by(g) %>% unpack(x) expect_equal(dplyr::group_vars(out), "g") }) test_that("non-df-cols are skipped ( df <- tibble(x = 1:2, y = tibble(a = 1:2, b = 1:2)) expect_identical(unpack(df, x), df) expect_identical(unpack(df, everything()), unpack(df, y)) }) test_that("empty columns that aren't data frames aren't unpacked ( df <- tibble(x = integer()) expect_identical(unpack(df, x), df) }) test_that("df-cols are directly unpacked", { df <- tibble(x = 1:3, y = tibble(a = 1:3, b = 3:1)) out <- df %>% unpack(y) expect_named(out, c("x", "a", "b")) expect_equal(out[c("a", "b")], df$y) }) test_that("can unpack 0-col dataframe", { df <- tibble(x = 1:3, y = tibble(.rows = 3)) out <- df %>% unpack(y) expect_named(out, c("x")) }) test_that("can unpack 0-row dataframe", { df <- tibble(x = integer(), y = tibble(a = integer())) out <- df %>% unpack(y) expect_named(out, c("x", "a")) }) test_that("can choose to add separtor", { df <- tibble(x = 1, y = tibble(a = 2), z = tibble(a = 3)) out <- df %>% unpack(c(y, z), names_sep = "_") expect_named(out, c("x", "y_a", "z_a")) }) test_that("can unpack 1-row but 0-col dataframe ( df <- tibble(x = tibble(.rows = 1)) expect_identical(unpack(df, x), tibble::new_tibble(list(), nrow = 1L)) })
dbGetInfo_MariaDBConnection <- function(dbObj, what = "", ...) { connection_info(dbObj@ptr) } setMethod("dbGetInfo", "MariaDBConnection", dbGetInfo_MariaDBConnection)
utils::globalVariables(c('ID','Distance','Model','id')) distances.plot <- function(tmatch, caliper=.25, label=FALSE) { tpsa <- attr(tmatch, 'triangle.psa') tmatch$id <- row.names(tmatch) tmp <- melt(tmatch[,c('id','D.m1','D.m2','D.m3')], id.vars=1) names(tmp) <- c('ID','Model','Distance') l <- (sd(tpsa$ps1, na.rm=TRUE) + sd(tpsa$ps2, na.rm=TRUE) + sd(tpsa$ps3, na.rm=TRUE)) stdev <- sapply(tpsa[,c('ps1','ps2','ps3')], sd, na.rm=TRUE) cat(paste("Standard deviations of propensity scores: ", paste(prettyNum(stdev, digits=2), collapse=' + '), " = ", prettyNum(l, digits=2), '\n', sep='' )) sddf <- data.frame(Model=c('1','2','3'), cumsum=caliper * 1:3) levels(tmp$Model) <- levels(sddf$Model) p <- ggplot(tmp, aes(x=ID, y=Distance)) + geom_bar(aes(fill=Model), stat='identity', width=1) + coord_flip() + geom_hline(data=sddf, aes(yintercept=cumsum, color=Model), linetype=2) + theme(axis.text.y=element_blank()) + xlab(NULL) + xlim(tmatch[order(tmatch$Dtotal),'id']) if(label & length(which(tmatch$Dtotal > 3 * (min(caliper)))) > 0) { p <- p + geom_text(data=tmatch[tmatch$Dtotal > 3 * (min(caliper)),], aes(x=id, y=0, label=id), size=3, hjust=1) } for(i in seq_along(caliper)) { cat(paste("Percentage of matches exceding a distance of ", prettyNum(caliper[i], digits=2), " (caliper = ", caliper[i], "): ", prettyNum(length(which(tmatch$Dtotal > 3 * caliper[i])) / length(tmatch$Dtotal) * 100, digits=2), '%\n', sep='')) } return(p) }
library(blastula) library(glue) seb_image <- add_image( "tests/manual_tests/young_adult_male.jpg", alt = "Seb himself", align = "center" ) company_logo <- add_image( "tests/manual_tests/msms_logo.png", alt = "msms logo", width = "50%", align = "center" ) email <- compose_email( body = md(glue(" {seb_image} Sebastian Génin has just joined Our Team! We are thrilled like \\ you would not believe at this outcome. Do you know Seb? If you don't, \\ well, you'll want to because he is quite an interesting person and \\ he can talk about virtually any topic. One hell of a conversationalist, \\ you might say. Sebastian will be joining the `2+2=5` team (now relocating in between the \\ *Accountaholics* and the *Product Pushers* on 9). He'll help in doing the \\ (nearly) impossible, which is what this fine team is generally known for. \\ If you're in the general vicinity, please stop over and say 'Yo, Seb!' &nbsp;&nbsp;&nbsp;&mdash;R.M.D. \\ ")), footer = md(glue(" {company_logo} Multi-Systems Merchant Services<br> 2703 Hoffman Avenue, 8th Fl.<br> New York, New York 10013<br> 917-882-8946<br> "))) email
rgammapois <- function(n, p, r){ choosefrom <- 0:10000 probs <- exp(lgamma(r+choosefrom)-lgamma(choosefrom+1)-lgamma(r)+choosefrom*log(p)+r*log(1-p)) mysample <- sample(x=choosefrom, size=n, replace=T, prob=probs) return(mysample) }
test_that("set_repaired_names()", { x <- set_names(1:3, letters[1:3]) expect_equal(set_repaired_names(x), x) expect_tibble_error(set_repaired_names(1, repair_hint = FALSE), error_column_names_cannot_be_empty(1, repair_hint = FALSE)) }) test_that("repaired_names()", { expect_equal(repaired_names(letters[1:3], repair_hint = FALSE), letters[1:3]) expect_tibble_error(repaired_names(c(""), repair_hint = FALSE), error_column_names_cannot_be_empty(1, repair_hint = FALSE)) expect_tibble_error(repaired_names(c("..1"), repair_hint = FALSE), error_column_names_cannot_be_dot_dot(1, repair_hint = FALSE)) expect_tibble_error(repaired_names(c("a", "a"), repair_hint = FALSE), error_column_names_must_be_unique("a", repair_hint = FALSE)) expect_equal(repaired_names(c("a", "a"), .name_repair = "minimal"), c("a", "a")) }) test_that("output test", { skip_if_not_installed("vctrs", "0.3.8.9001") expect_snapshot_with_error({ repaired_names(letters[1:3], repair_hint = FALSE) repaired_names("", repair_hint = FALSE) repaired_names("", repair_hint = TRUE) repaired_names(c("a", "a"), repair_hint = FALSE) repaired_names("..1", repair_hint = FALSE) repaired_names(c("a", "a"), repair_hint = FALSE, .name_repair = "universal") repaired_names(c("a", "a"), repair_hint = FALSE, .name_repair = "universal", quiet = TRUE) repaired_names(c("if"), repair_hint = FALSE, .name_repair = "universal") }) })
summary.sem <- function(object, ...) { ans <- NULL ans$call <- object$call ans$nclasses <- object$n.classes ans$formula <- object$formula if (!is.null(object$lambda)) { ans$trafo <- "Box-Cox" ans$lambda <- object$lambda } if (all(inherits(object, which = TRUE, c("sem", "lm")))) { ans$multipR <- round(object$r2, 4) ans$adjR <- round(object$adj.r2, 4) if (is.null(object$se)) { ans$coefficients <- cbind(object$coef) dimnames(ans$coefficients) <- list( names(object$coef), c("Estimate") ) } else if (!is.null(object$se)) { ans$coefficients <- cbind(object$coef, object$se, object$ci) dimnames(ans$coefficients) <- list( names(object$coef), c("Estimate", "Std. Error", "Lower 95%-level", "Upper 95%-level") ) } } else if (all(inherits(object, which = TRUE, c("sem", "lme")))) { ans$marginalR2 <- round(object$r2m, 4) ans$conditionalR2 <- round(object$r2c, 4) if (dim(object$VaCov)[1] == 1) { randomIntercept <- strsplit(as.character(object$formula[[3]][3]), "\\|")[[1]][2] randomIntercept <- strsplit(randomIntercept, ")") randomIntercept <- trimws(randomIntercept, "l") ans$random <- data.frame( Groups = c(randomIntercept, "Residual"), Name = c("(Intercept)", ""), Variance = c( as.numeric(object$VaCov), as.numeric(object$sigmae)^2 ), Std.Dev. = c( sqrt(as.numeric(object$VaCov)), object$sigmae ) ) rownames(ans$random) <- c() } else if (dim(object$VaCov)[1] == 2) { randomIntercept <- strsplit(as.character(object$formula[[3]][3]), "\\|")[[1]][2] randomIntercept <- strsplit(randomIntercept, ")") randomIntercept <- trimws(randomIntercept, "l") ans$random <- data.frame( Groups = c( randomIntercept, rownames(object$VaCov)[2], "Residual" ), Name = c("(Intercept)", "", ""), Variance = c( as.numeric(object$VaCov[1, 1]), as.numeric(object$VaCov[2, 2]), as.numeric(object$sigmae)^2 ), Std.Dev. = c( sqrt(as.numeric(as.numeric(object$VaCov[1, 1]))), sqrt(as.numeric(as.numeric(object$VaCov[2, 2]))), object$sigmae ) ) rownames(ans$random) <- c() } if (is.null(object$se)) { ans$coefficients <- cbind(object$coef) dimnames(ans$coefficients) <- list( names(object$coef), c("Estimate") ) } else if (!is.null(object$se)) { ans$coefficients <- cbind(object$coef, object$se, object$ci) dimnames(ans$coefficients) <- list( names(object$coef), c("Estimate", "Std. Error", "Lower 95%-level", "Upper 95%-level") ) } } class(ans) <- "summary.sem" ans } print.summary.sem <- function(x, ...) { cat("Call:\n") print(x$call) cat("\n") if (!is.null(x$random)) { cat("Random effects:\n") print(x$random) cat("\n") } cat("Fixed effects:\n") print(x$coefficients) cat("\n") if (!is.null(x$multipR)) { cat("Multiple R-squared: ", x$multipR, "Adjusted R-squared: ", x$adjR) } else if (!is.null(x$marginalR2)) { cat("Marginal R-squared: ", x$marginalR2, "Conditional R-squared: ", x$conditionalR2) } cat("\n") if (!is.null(x$trafo)) { cat("Lambda of the Box-Cox transformation: ", x$lambda) } cat("\n") cat(paste0( "Variable ", x$formula[2], " is divided into ", x$nclasses, " intervals.\n" )) }
write.output<-function(input,location,flip=FALSE){ outlist <- list() if(!is.logical(flip))stop('flip needs to be TRUE/FALSE') if(missing(location)){location<- FALSE} sample<-unique(input[,"ID"]) if(location != FALSE && is.character(location)){ pdf(file=paste(location,"/",sample,".pdf",sep=""),height=210/25.4,width=297/25.4,paper="A4r") } else if((location != FALSE && !is.character(location)) ){ stop("Please provide a character string containing a path to an output folder.") } years<-unique(input[,"YEAR"]) for(u in c(1:length(years)) ){ data_year<-input[which(input[,"YEAR"]==years[u]),] year<-years[u] if(flip==FALSE){ plot(data_year[,"XCAL"],data_year[,"YCAL"],ylab="Rel. Y-coordinates (micron)", ylim=c(0-max(data_year[,"YCAL"],na.rm=TRUE)*0.01,max(data_year[,"YCAL"],na.rm=TRUE)), main=paste(sample," - ",as.character(year)," - Rows: ",max(data_year[,"ROW"],na.rm=TRUE),sep=""),xlab="Rel. X-coordinates (micron)",pch=16,cex=0.2,col="white")} if(flip==TRUE){ plot(data_year[,"XCAL"],data_year[,"YCAL"],ylab="Rel. Y-coordinates (micron)", ylim=c(max(data_year[,"YCAL"],na.rm=TRUE),0-max(data_year[,"YCAL"],na.rm=TRUE)*0.01), main=paste(sample," - ",as.character(year)," - Rows: ",max(data_year[,"ROW"],na.rm=TRUE),sep=""),xlab="Rel. X-coordinates (micron)",pch=16,cex=0.2,col="white") } data_year[,"SQRLENGTH"] <-sqrt(data_year[,"CA"]) nrcells<-nrow(data_year) rows<-max(unique(data_year[,"ROW"])[which(is.na(unique(data_year[,"ROW"]))==FALSE)]) col_code<-rep(c(" for(i in c(1:nrcells)){ length<-data_year[i,"SQRLENGTH"]/2 x <-data_year[i,"XCAL"] y <-data_year[i,"YCAL"] x_cor<-c((x-length),(x+length),(x+length),(x-length)) y_cor<-c((y+length),(y+length),(y-length),(y-length)) if(is.na(data_year[i,"ROW"])==TRUE){ polygon(x_cor,y_cor) }else{ polygon(x_cor,y_cor,col=col_code[data_year[i,"ROW"]]) } if(is.na(data_year[i,"ROW"])==FALSE){ label_point<-data_year[i,"POSITION"] text(x,y,label=label_point,col='black',cex=0.5) }else{ next } } first_cells<-data_year[which(data_year[,"POSITION"]==1),] for(i in c(1:nrow(first_cells))){ x<-first_cells[i,"XCAL"] y<-first_cells[i,"YCAL"] length<-first_cells[i,"SQRLENGTH"]/1.2 label_point<-first_cells[i,"ROW"] text(x,y-length,label=label_point,col='black',cex=0.8,font=2) } a<-which(colnames(data_year)=="SQRLENGTH") data_year<-data_year[,-a] name<-paste(sample,"-",as.character(year),sep="") assign(name,data_year) } if(length(years)==1){ output_all_years<-get(paste(sample,"-",as.character(years[1]),sep="")) }else{ output_all_years<-get(paste(sample,"-",as.character(years[1]),sep="")) for(t in c(2:(length(years)))){ output_all_years<-rbind(output_all_years,get(paste(sample,"-",as.character(years[t]),sep=""))) } } if(location != FALSE){ location <- sub("\\/*$","", location) write.table(output_all_years,file=paste(location,"/",sample,"_output.txt",sep=""),row.names=FALSE,sep="\t") invisible(dev.off()) } else { return(output_all_years) } }
context("Bound Water Environments") load(file="vanddraabe_DataForTesting.rda") test_that("the correct normalized Bvalues are returned", { Bvalues <- seq(from = 10, to = 75, by = 5) nBvalues.answer <- c(-1.553797192, -1.31475147, -1.075705748, -0.8366600265, -0.5976143047, -0.3585685828, -0.1195228609, 0.1195228609, 0.3585685828, 0.5976143047, 0.8366600265, 1.075705748, 1.31475147, 1.553797192) expect_equal(NormalizedBvalue(Bvalues), nBvalues.answer) }) test_that("the correct mobility values are returned", { Bvalues <- seq(from=10, to=75, by=5) set.seed(13) occupancy <- sample(c(0.90, 0.95, 1.0), 14, replace = TRUE) mobility.answer <- c(0.2235294118, 0.3725490196, 0.4705882353, 0.6209150327, 0.7058823529, 0.8235294118, 0.9934640523, 1.0058823529, 1.2418300654, 1.2941176471, 1.3411764706, 1.4529411765, 1.5647058824, 1.862745098) expect_equal(Mobility(Bvalues, occupancy), mobility.answer) }) test_that("the correct calculated Bvalues are returned", { expect_equal(calcBvalue(rmsfValue=0.25), 4.9348022005446789962) expect_equal(calcBvalue(rmsfValue=0.50), 19.739208802178715985) expect_equal(calcBvalue(rmsfValue=0.75), 44.413219804902112742) expect_equal(calcBvalue(rmsfValue=1.00), 78.956835208714863938) expect_equal(calcBvalue(rmsfValue=1.25), 123.37005501361697668) }) test_that("the correct nearby hydration fraction values (sum, mean, sd) are returned", { names.res.nearby.atoms <- c("ARG CA", "PRO CB", "SER C", "PHE CB", "PHE CG", "PHE CZ", "CYS CA", "CYS O", "GLY C", "ALA C") cNHF.answer <- list(ahp.sum = 0.852, ahp.mu = 0.0852, ahp.sd = 0.1518550478) expect_equal(calcNearbyHydrationFraction(names.res.nearby.atoms), cNHF.answer) }) test_that("the correct number of hydrogen bonds are returned", { distances <- PDB.1hai.h2o.prot.dists[3, ] set.oi.idc <- prot.idc nearby.atoms.idc <- Nearby(distances, set.idc = prot.idc, radius = 3.6) names.atoms <- PDB.1hai.aoi.clean$elety[prot.idc] numHydroBonds.answer <- 4 expect_equal(calcNumHydrogenBonds(distances, nearby.atoms.idc, names.atoms, set.oi.idc), numHydroBonds.answer) }) test_that("the correct environment quality values are returned", { distances <- PDB.1hai.h2o.prot.dists[3, ] set.oi.idc <- prot.idc structure <- PDB.1hai.aoi.clean quality.answer <- list(o.sum = 9, o.mu = 1, o.sd = 0, b.exp.sum = 273.5600000000, b.exp.mu = 30.3955555556, b.exp.sd = 12.7242466487, mobility.sum = 0, mobility.mu = as.numeric(NA), mobility.sd = as.numeric(NA), nBvalue.sum = 0, nBvalue.mu = as.numeric(NA), nBvalue.sd = as.numeric(NA)) expect_equal(BoundWaterEnvironment.quality(distances, set.oi.idc, structure, radius = 3.6), quality.answer) })
getTargets <- function(data, effects) { f <- unpackData(data) effects <- effects[effects$include,] pData <- .Call(C_setupData, PACKAGE=pkgname, list(as.integer(f$observations)), list(f$nodeSets)) ans <- reg.finalizer(pData, clearData, onexit = FALSE) ans<- .Call(C_OneMode, PACKAGE=pkgname, pData, list(f$nets)) ans<- .Call(C_Behavior, PACKAGE=pkgname, pData, list(f$behavs)) ans<-.Call(C_ConstantCovariates, PACKAGE=pkgname, pData, list(f$cCovars)) ans<-.Call(C_ChangingCovariates,PACKAGE=pkgname, pData,list(f$vCovars)) ans<-.Call(C_DyadicCovariates,PACKAGE=pkgname, pData,list(f$dycCovars)) ans<-.Call(C_ChangingDyadicCovariates,PACKAGE=pkgname, pData, list(f$dyvCovars)) storage.mode(effects$parm) <- 'integer' storage.mode(effects$group) <- 'integer' storage.mode(effects$period) <- 'integer' effects$effectPtr <- NA myeffects <- split(effects, effects$name) ans<- .Call(C_effects, PACKAGE=pkgname, pData, myeffects) pModel <- ans[[1]][[1]] for (i in 1:length(ans[[2]])) { effectPtr <- ans[[2]][[i]] myeffects[[i]]$effectPtr <- effectPtr } ans <- .Call(C_getTargets, PACKAGE=pkgname, pData, pModel, myeffects, NULL, returnActorStatistics=FALSE, returnStaticChangeContributions=FALSE) ans } actorTargets <- function(data, effects, x, behaviorName, wave, imputedData = NULL, rate = FALSE) { depvarsNo <- length(data$depvars) behNo <- c(1:depvarsNo)[names(data$depvars) == behaviorName] beh <- data$depvars[[behNo]][,1,] n <- dim(data$depvars[[behNo]])[1] waves <- dim(data$depvars[[behNo]])[3] effects <- effects[effects$include,] effects$setting <- rep("", nrow(effects)) effects <- effects[effects$name==behaviorName,] effects <- effects[!effects$basicRate,] noEff <- dim(effects)[1] ans2 <- array(rep(NA, n*noEff), dim=c(n,noEff)) w <- wave vars <- data$depvars if (!is.null(imputedData)) { vars[[behNo]][,,w] <- imputedData beh[,w] <- imputedData } for (j in 1:n) { if (rate) { data$depvars[[behNo]][,1,] <- beh data$depvars[[behNo]][,1,c(1:waves)[-w]] <- NA data$depvars[[behNo]][j,1,(w+1):waves] <- rep(1,waves-w) data$depvars[[behNo]][j,1,1:w] <- rep(0,w) } else { for (k in 1:depvarsNo) { data$depvars[[k]][,,1] <- vars[[k]][,,waves] data$depvars[[k]][,,2:waves] <- vars[[k]][,,1:(waves-1)] } data$depvars[[behNo]][,1,c(1:waves)[-(w+1)]] <- NA data$depvars[[behNo]][j,1,c(1:waves)[-(w+1)]] <- rep(0,waves-1) } f <- unpackData(data,x) pData <- .Call(C_setupData, PACKAGE=pkgname, list(as.integer(f$observations)), list(f$nodeSets)) ans <- reg.finalizer(pData, clearData, onexit = FALSE) ans<- .Call(C_OneMode, PACKAGE=pkgname, pData, list(f$nets)) ans<- .Call(C_Behavior, PACKAGE=pkgname, pData, list(f$behavs)) ans<-.Call(C_ConstantCovariates, PACKAGE=pkgname, pData, list(f$cCovars)) ans<-.Call(C_ChangingCovariates,PACKAGE=pkgname, pData,list(f$vCovars)) ans<-.Call(C_DyadicCovariates,PACKAGE=pkgname, pData,list(f$dycCovars)) ans<-.Call(C_ChangingDyadicCovariates,PACKAGE=pkgname, pData, list(f$dyvCovars)) storage.mode(effects$parm) <- 'integer' storage.mode(effects$group) <- 'integer' storage.mode(effects$period) <- 'integer' effects$effectPtr <- NA myeffects <- split(effects, effects$name) ans<- .Call(C_effects, PACKAGE=pkgname, pData, myeffects) pModel <- ans[[1]][[1]] for (i in 1:length(ans[[2]])) { effectPtr <- ans[[2]][[i]] myeffects[[i]]$effectPtr <- effectPtr } ans <- .Call(C_getTargets, PACKAGE=pkgname, pData, pModel, myeffects, NULL, returnActorStatistics=FALSE, returnStaticChangeContributions=FALSE) ans2[j,] <- ans[,w] } list(effects=effects$effectName,effectType=effects$type, targets=ans2) }
mod <- logistic_reg(mixture = 1/3) %>% set_engine("glmnet", nlambda = 10)
library(neo4r) con <- neo4j_api$new( url = "http://localhost:7474", user = "neo4j", password = "neo4j" ) call_neo4j("CREATE CONSTRAINT ON (al:Band) ASSERT al.name IS UNIQUE;", con) call_neo4j("CREATE CONSTRAINT ON (al:City) ASSERT al.name IS UNIQUE;", con) call_neo4j("CREATE CONSTRAINT ON (al:record) ASSERT al.name IS UNIQUE;", con) call_neo4j("CREATE CONSTRAINT ON (al:artist) ASSERT al.name IS UNIQUE;", con) call_neo4j("MERGE (ancient:Band {name: 'Ancient', formed: 1992}) MERGE (acturus:Band {name: 'Arcturus', formed: 1991}) MERGE (burzum:Band {name: 'Burzum', formed: 1991}) MERGE (carpathianforest:Band {name: 'Carpathian Forest', formed: 1990}) MERGE (darkthrone:Band {name: 'Darkthrone', formed: 1986}) MERGE (emperor:Band {name: 'Emperor', formed: 1986}) MERGE (enslaved:Band {name: 'Enslaved', formed: 1991}) MERGE (gorgoroth:Band {name: 'Gorgoroth', formed: 1992}) MERGE (hades:Band {name: 'Hades', formed: 1992}) MERGE (immortal:Band {name: 'Immortal', formed: 1991}) MERGE (mayhem:Band {name: 'Mayhem', formed: 1984}) MERGE (satyricon:Band {name: 'Satyricon', formed: 1984}) MERGE (taake:Band {name: 'Taake', formed: 1993}) MERGE (bergen:City {name: 'Bergen'}) MERGE (oslo:City {name: 'Oslo'}) MERGE (sandnes:City {name: 'Sandnes'}) MERGE (rogaland:City {name: 'Rogaland'}) MERGE (deathcrush:record {name: 'Deathcrush', release: 1987}) MERGE (freezingmoon:record {name: 'Freezing Moon', release: 1987}) MERGE (carnage:record {name: 'Carnage', release: 1990}) MERGE (liveinleipzig:record {name: 'Live in Leipzig', release: 1990}) MERGE (demoi:record {name: 'Demo I', release: 1991}) MERGE (ablaze:record {name: 'A Blaze in the Northern Sky', release: 1991}) MERGE (immortal_rec:record {name: 'Immortal', release: 1991}) MERGE (demoii:record {name: 'Demo I', release: 1991}) MERGE (nema:record {name: 'Nema', release: 1991}) MERGE (burzum_rec:record {name: 'Burzum', release: 1992}) MERGE (detsom:record {name: 'Det som engang var', release: 1992}) MERGE (diabolical:record {name: 'Diabolical Fullmoon Mysticism', release: 1992}) MERGE (wrath:record {name: 'Wrath of the Tyrant', release: 1992}) MERGE (all_evil:record {name: 'All Evil', release: 1992}) MERGE (yggdrasill:record {name: 'Yggdrasill', release: 1992}) MERGE (funeral_moon:record {name: 'Under a Funeral Moon', release: 1992}) MERGE (aske:record {name: 'Aske', release: 1992}) MERGE (bloodlust:record {name: 'Bloodlust & Perversion', release: 1992}) MERGE (hvis:record {name: 'Hvis lyset tar oss', release: 1992}) MERGE (demys:record {name: 'De Mysteriis Dom Sathanas', release: 1992}) MERGE (hordanes:record {name: 'Hordanes Land', release: 1992}) MERGE (emperor_rec:record {name: 'Emperor', release: 1992}) MERGE (as_the_shadow:record {name: 'As the Shadows Rise', release: 1992}) MERGE (filosofem:record {name: 'Filosofem', release: 1993}) MERGE (theforest:record {name: 'The Forest Is My Throne', release: 1993}) MERGE (viking:record {name: 'Vikingligr Veldi', release: 1993}) MERGE (journey:record {name: 'Journey Through the Cold', release: 1993}) MERGE (moors:record {name: 'Moors of Svarttjern', release: 1993}) MERGE (asorcery:record {name: 'A Sorcery Written in Blood', release: 1993}) MERGE (inthenightside:record {name: 'In the Nightside Eclipse', release: 1993}) MERGE (darkmed:record {name: 'Dark Medieval Times', release: 1993}) MERGE (pureho:record {name: 'Pure Holocaust', release: 1993}) MERGE (trans:record {name: 'Transilvanian Hunger', release: 1993}) MERGE (euronymous:artist {name: 'Euronymous', born: 1968}) MERGE (vikernes:artist {name: 'Vikernes', born: 1973}) MERGE (fenriz:artist {name: 'Fenriz', born: 1971}) MERGE (gaahl:artist {name: 'Gaahl', born: 1975}) MERGE (euronymous)-[:PLAYED_IN]->(mayhem) MERGE (vikernes)-[:PLAYED_IN]->(burzum) MERGE (fenriz)-[:PLAYED_IN]->(Darkthrone) MERGE (gaahl)-[:PLAYED_IN]->(gorgoroth) MERGE (ancient)-[:IS_FROM]->(bergen) MERGE (acturus)-[:IS_FROM]->(oslo) MERGE (burzum)-[:IS_FROM]->(bergen) MERGE (carpathianforest)-[:IS_FROM]->(rogaland) MERGE (emperor)-[:IS_FROM]->(sandnes) MERGE (enslaved)-[:IS_FROM]->(rogaland) MERGE (gorgoroth)-[:IS_FROM]->(bergen) MERGE (hades)-[:IS_FROM]->(bergen) MERGE (immortal)-[:IS_FROM]->(bergen) MERGE (mayhem)-[:IS_FROM]->(oslo) MERGE (satyricon)-[:IS_FROM]->(oslo) MERGE (taake)-[:IS_FROM]->(bergen) MERGE (deathcrush)-[:WAS_RECORDED]->(mayhem) MERGE (freezingmoon)-[:WAS_RECORDED]->(mayhem) MERGE (carnage)-[:WAS_RECORDED]->(mayhem) MERGE (liveinleipzig)-[:WAS_RECORDED]->(mayhem) MERGE (demys)-[:WAS_RECORDED]->(mayhem) MERGE (demoi)-[:WAS_RECORDED]->(burzum) MERGE (demoii)-[:WAS_RECORDED]->(burzum) MERGE (burzum_rec)-[:WAS_RECORDED]->(burzum) MERGE (detsom)-[:WAS_RECORDED]->(burzum) MERGE (aske)-[:WAS_RECORDED]->(burzum) MERGE (hvis)-[:WAS_RECORDED]->(burzum) MERGE (filosofem)-[:WAS_RECORDED]->(burzum) MERGE (ablaze)-[:WAS_RECORDED]->(darkthrone) MERGE (funeral_moon)-[:WAS_RECORDED]->(darkthrone) MERGE (trans)-[:WAS_RECORDED]->(darkthrone) MERGE (immortal_rec)-[:WAS_RECORDED]->(immortal) MERGE (diabolical)-[:WAS_RECORDED]->(immortal) MERGE (pureho)-[:WAS_RECORDED]->(immortal) MERGE (nema)-[:WAS_RECORDED]->(enslaved) MERGE (yggdrasill)-[:WAS_RECORDED]->(enslaved) MERGE (hordanes)-[:WAS_RECORDED]->(enslaved) MERGE (viking)-[:WAS_RECORDED]->(enslaved) MERGE (wrath)-[:WAS_RECORDED]->(emperor) MERGE (all_evil)-[:WAS_RECORDED]->(satyricon) MERGE (theforest)-[:WAS_RECORDED]->(satyricon) MERGE (darkmed)-[:WAS_RECORDED]->(satyricon) MERGE (bloodlust)-[:WAS_RECORDED]->(carpathianforest) MERGE (journey)-[:WAS_RECORDED]->(carpathianforest) MERGE (moors)-[:WAS_RECORDED]->(carpathianforest) MERGE (emperor_rec)-[:WAS_RECORDED]->(emperor) MERGE (as_the_shadow)-[:WAS_RECORDED]->(emperor) MERGE (inthenightside)-[:WAS_RECORDED]->(emperor) MERGE (asorcery)-[:WAS_RECORDED]->(gorgoroth)", con)
observe({ updateSelectInput(session, inputId = "resp_bivar", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_bivar", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_woe", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_woe", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_woe2", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_woe2", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_segdist", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_segdist", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_2wayseg", choices = names(final_split$train)) updateSelectInput(session, inputId = "var1_2wayseg", choices = names(final_split$train)) updateSelectInput(session, inputId = "var2_2wayseg", choices = names(final_split$train)) }) bivar <- eventReactive(input$submit_bivar, { blorr::blr_bivariate_analysis(data = final_split$train, response = input$resp_bivar, input$var_bivar) }) woe_iv <- eventReactive(input$submit_woe, { blorr::blr_woe_iv(data = final_split$train, predictor = input$var_woe, response = input$resp_woe) }) woe_iv_2 <- eventReactive(input$submit_woe2, { blorr::blr_woe_iv_stats(data = final_split$train, response = input$resp_woe2, input$var_woe2) }) seg_dist <- eventReactive(input$submit_segdist, { blorr::blr_segment_dist(data = final_split$train, response = !! sym(as.character(input$resp_segdist)), predictor = !! sym(as.character(input$var_segdist))) }) twowayseg <- eventReactive(input$submit_2wayseg, { blorr::blr_segment_twoway(data = final_split$train, response = input$resp_2wayseg, variable_1 = input$var1_2wayseg, variable_2 = input$var2_2wayseg) }) output$bivar_out <- renderPrint({ bivar() }) output$woe_out <- renderPrint({ woe_iv() }) output$woe2_out <- renderPrint({ woe_iv_2() }) output$segdist_out <- renderPrint({ seg_dist() }) output$segdist_plot <- renderPlot({ plot(seg_dist()) }) output$twowayseg_out <- renderPrint({ twowayseg() })
bayesCox <- function(formula, data, grid = NULL, out = NULL, model = c("TimeIndep", "TimeVarying", "Dynamic"), base.prior = list(), coef.prior = list(), gibbs = list(), control = list(), ...) { Call <- match.call() model <- match.arg(model) base.prior <- do.call("bp_fun", base.prior) coef.prior <- do.call("cp_fun", coef.prior) if (model == "TimeIndep") { if (base.prior$type == "Gamma" && coef.prior$type == "Normal") id <- 11 if (base.prior$type == "GammaProcess" && coef.prior$type == "Normal") id <- 12 } else if (model == "TimeVarying") { if (base.prior$type == "Gamma" && coef.prior$type == "AR1") id <- 21 if (base.prior$type == "Gamma" && coef.prior$type == "HAR1") id <- 22 if (base.prior$type == "GammaProcess" && coef.prior$type == "AR1") id <- 23 if (base.prior$type == "GammaProcess" && coef.prior$type == "HAR1") id <- 24 } else if (model == "Dynamic") { if (base.prior$type == "Gamma" && coef.prior$type == "AR1") id <- 31 if (base.prior$type == "Gamma" && coef.prior$type == "HAR1") id <- 32 if (base.prior$type == "Const" && coef.prior$type == "AR1") id <- 33 if (base.prior$type == "Const" && coef.prior$type == "HAR1") id <- 34 if (base.prior$type == "GammaProcess" && coef.prior$type == "AR1") id <- 35 if (base.prior$type == "GammaProcess" && coef.prior$type == "HAR1") id <- 36 } else stop("Invalid 'model' specified.") gibbs <- do.call("gibbs_fun", gibbs) control <- do.call("control_bfun", control) mf <- model.frame(formula, data) mt <- attr(mf, "terms") mm <- model.matrix(formula, data) LRX <- cbind(mf[, 1L][, seq_len(2L)], mm[, - 1L]) eventIdx <- mf[, 1L][, 3L] tmpIdx <- eventIdx == 2 LRX[tmpIdx, 1L] <- 0 tmpIdx <- eventIdx == 0 LRX[tmpIdx, 2L] <- Inf tmpIdx <- eventIdx == 1 exactTimes <- LRX[tmpIdx, 2L] <- LRX[tmpIdx, 1L] cov.names <- colnames(mm)[- 1L] if (is.null(grid)) { charNum <- as.character(LRX[, seq_len(2)]) tmpList <- strsplit(charNum, "\\.") sigMax <- max(sapply(tmpList, function(a) { if (length(a) > 1) return(nchar(a[2L])) 0 })) roundPow <- 10 ^ min(sigMax, 2) left_ <- floor(LRX[, "time1"] * roundPow) / roundPow right_ <- ceiling(LRX[, "time2"] * roundPow) / roundPow finiteRight <- right_[! (is.infinite(right_) | is.na(right_))] grid <- unique(c(left_, finiteRight)) } grid <- grid[! (is.na(grid) | is.infinite(grid))] grid <- grid[! grid <= 0] if (length(exactTimes) > 0) { grid <- unique(c(grid, exactTimes)) } if (all(tmpIdx <- is.infinite(LRX[, "time2"]))) { stop("Subjects are all right censored.") } finiteRight <- max(LRX[! tmpIdx, "time2"]) if (max(grid) < finiteRight) { warning("The grid was expanded to cover all the finite endpoint ", "of censoring intervals.") grid <- unique(c(grid, finiteRight)) } grid <- sort(unique(grid)) toLeft <- stats::stepfun(grid, c(0, grid)) toRight <- stats::stepfun(grid, c(grid, Inf)) LRX[, "time1"] <- toLeft(LRX[, "time1"]) LRX[, "time2"] <- toRight(LRX[, "time2"]) LRX[is.infinite(LRX[, 2L]), 2L] <- max(grid[length(grid)], 999) LRX[is.na(LRX[, 2L]), 2L] <- max(grid[length(grid)], 999) if (control$intercept) { LRX <- cbind(LRX[, seq_len(2L)], 1, LRX[, - seq_len(2L)]) cov.names <- c("intercept", cov.names) } colnames(LRX) <- c("L", "R", cov.names) if (save_mcmc <- is.null(out)) { out <- sprintf("%s.txt", tempfile()) } K <- length(grid) nBeta <- length(cov.names) lambda <- rep(0, K) beta <- if (model == "TimeIndep") { rep(0, nBeta) } else { rep(0, nBeta * K) } nu <- rep(0, nBeta) jump <- rep(0, nBeta * K) res <- .C("bayesCox", as.double(LRX), as.integer(nrow(LRX)), as.integer(ncol(LRX) - 2), as.double(grid), as.integer(length(grid)), as.character(out), as.integer(id), as.double(base.prior$hyper[[1]]), as.double(base.prior$hyper[[2]]), as.double(coef.prior$hyper[[1]]), as.double(coef.prior$hyper[[2]]), as.integer(gibbs$iter), as.integer(gibbs$burn), as.integer(gibbs$thin), as.integer(gibbs$verbose), as.integer(gibbs$nReport), as.double(control$a0), as.double(control$eps0), lambda = as.double(lambda), beta = as.double(beta), nu = as.double(nu), jump = as.integer(jump), LPML = as.double(0), DHat = as.double(0), DBar = as.double(0), pD = as.double(0), DIC = as.double(0)) if (model != "TimeIndep") res$beta <- matrix(res$beta, K, nBeta) if (coef.prior$type != "HAR1") res$nu <- NULL if (model == "Dynamic") { res$jump <- matrix(res$jump, K, nBeta) } else { res$jump <- NULL } if (save_mcmc) { mcmc_list <- read_bayesCox(out, gibbs$burn, gibbs$thin) out <- NULL } else { mcmc_list <- NULL } structure(list( call = Call, formula = formula, grid = grid, out = out, model = model, LRX = LRX, base.prior = base.prior, coef.prior = coef.prior, gibbs = gibbs, control = control, xlevels = .getXlevels(mt, mf), N = nrow(LRX), K = K, nBeta = nBeta, cov.names = cov.names, mcmc = mcmc_list, est = list(lambda = res$lambda, beta = res$beta, nu = res$nu, jump = res$jump), measure = list(LPML = res$LPML, DHat = res$DHat, DBar = res$DBar, pD = res$pD, DIC = res$DIC) ), class = "bayesCox") } Gamma_fun <- function(shape = 0.1, rate = 0.1) { list(shape = shape, rate = rate) } Const_fun <- function(value = 1) { list(value = value, value = value) } GammaProcess_fun <- function(mean = 0.1, ctrl = 1) { list(mean = mean, ctrl = ctrl) } bp_fun <- function(type = c("Gamma", "Const", "GammaProcess"), ...) { type <- match.arg(type) hyper <- if (type == "Gamma") { Gamma_fun(...) } else if (type == "Const") { Const_fun(...) } else if (type == "GammaProcess") { GammaProcess_fun(...) } list(type = type, hyper = hyper) } Normal_fun <- function(mean = 0, sd = 1) { list(mean = mean, sd = sd) } AR1_fun <- function(sd = 1) { list(sd = sd, sd = sd) } HAR1_fun <- function(shape = 2, scale = 1) { list(shape = shape, scale = scale) } cp_fun <- function(type = c("Normal", "AR1", "HAR1"), ...) { type <- match.arg(type) hyper <- if (type == "Normal") { Normal_fun(...) } else if (type == "AR1") { AR1_fun(...) } else if (type == "HAR1") { HAR1_fun(...) } list(type = type, hyper = hyper) } gibbs_fun <- function(iter = 3000, burn = 500, thin = 1, verbose = TRUE, nReport = 100) { list(iter = as.integer(iter), burn = as.integer(burn), thin = as.integer(thin), verbose = verbose, nReport = as.integer(nReport)) } control_bfun <- function(intercept = FALSE, a0 = 100, eps0 = 1) { list(intercept = intercept, a0 = a0, eps0 = eps0) }
library(dplyr) library(ggplot2) N <- 50 I <- 120 d <- read.csv(file='input/data-lda.txt') d_cast <- d %>% group_by(PersonID) %>% summarise(n=n()) %>% ungroup() p <- ggplot(data=d_cast, aes(x=n)) + theme_bw(base_size=18) + geom_bar(color='grey5', fill='grey80') + scale_x_continuous(breaks=seq(10,40,10), limits=c(10,40)) + labs(x='count by PersonID', y='count') ggsave(file='output/fig11-6-left.png', plot=p, dpi=300, w=4, h=3) d_cast <- d %>% group_by(ItemID) %>% summarise(n=n()) %>% ungroup() p <- ggplot(data=d_cast, aes(x=n)) + theme_bw(base_size=18) + geom_bar(color='grey5', fill='grey80') + labs(x='count by ItemID', y='count') ggsave(file='output/fig11-6-right.png', plot=p, dpi=300, w=4, h=3)
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(anovir) sy_time <- c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23) sy_Suninf <- c(1,0.988,0.988,0.969,0.951,0.941,0.934,0.929,0.92,0.913,0.906,0.903,0.896,0.889,0.88,0.875,0.875,0.868,0.858,0.846,0.842,0.837,0.837,0.831) sy_Sobsinf <- c(1,0.979,0.966,0.942,0.915,0.902,0.887,0.875,0.869,0.859,0.841,0.81,0.788,0.747,0.732,0.696,0.68,0.652,0.616,0.6,0.584,0.574,0.561,0.545) sy_surv <- data.frame(sy_time, sy_Suninf, sy_Sobsinf) plot(sy_surv[, 1], sy_surv[, 2], type = 's', col = 'black', xlab = 'time (days)', ylab = 'Survival', xlim = c(0, 23), ylim = c(0, 1), main = 'Cumulative survival', axes = FALSE ) lines(sy_surv[, 3], type = 's', col = 'red') axis(side = 1, seq(0, 28, by = 7)) axis(side = 2, seq(0, 1.1, by = 0.2)) legend("bottomleft", c("Uninfected", "Infected"), lty = c(1, 1), col = c(1, 2)) sy_times <- c(1,3,4,5,6,7,8,9,10,11,12,13,14,15,17,18,19,20,21,23,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,7,21,22,23,7,14,21,22,23) sy_censor <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1) sy_inf <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1) sy_fq <- c(5,8,8,4,3,2,4,3,3,1,3,3,4,2,3,4,5,2,2,1,7,4,8,9,4,5,4,2,3,6,10,7,13,5,11,5,9,11,5,5,3,4,2,3,4,205,143,6,7,4,103,66) data_sy <- data.frame(sy_times, sy_inf, sy_censor, sy_fq) data_sy$fq <- data_sy$sy_fq head(data_sy) m01_prep_function <- function(a1, b1, a2, b2){ nll_basic( a1, b1, a2, b2, data = data_sy, time = sy_times, censor = sy_censor, infected_treatment = sy_inf, d1 = 'Weibull', d2 = 'Weibull') } m01 <- mle2(m01_prep_function, start = list(a1 = 3, b1 = 0.5, a2 = 3, b2 = 0.5) ) summary(m01) m02 <- mle2(m01_prep_function, start = list(a1 = 4.8, a2 = 3.6, b2 = 0.6), fixed = list(b1 = 1.0) ) summary(m02) AICc(m01, m02, nobs = 753)
knitr::opts_chunk$set(comment = " library(metan) inspect(data_ge) ge_details(data_ge, env = ENV, gen = GEN, resp = everything()) ge_plot(data_ge, GEN, ENV, GY) mge <- ge_means(data_ge, env = ENV, gen = GEN, resp = everything()) get_model_data(mge) %>% round_cols() get_model_data(mge, what = "env_means") %>% round_cols() get_model_data(mge, what = "gen_means") %>% round_cols() ammi_model <- performs_ammi(data_ge, ENV, GEN, REP, resp = c(GY, HM)) waas_index <- waas(data_ge, ENV, GEN, REP, GY, verbose = FALSE) a <- plot_scores(ammi_model) b <- plot_scores(ammi_model, type = 2, second = "PC3") c <- plot_scores(ammi_model, type = 2, polygon = TRUE, col.gen = "black", col.env = "gray70", col.segm.env = "gray70", axis.expand = 1.5) arrange_ggplot(a, b, c, tag_levels = "a", ncol = 1) predicted <- predict(ammi_model, naxis = c(4, 6)) predicted %>% subset(TRAIT == "GY") %>% make_mat(GEN, ENV, YpredAMMI) %>% round_cols() model2 <- gamem_met(data_ge, ENV, GEN, REP, everything()) plot(model2, which = c(1, 2, 7), ncol = 1) plot(model2, type = "re", nrow = 3) get_model_data(model2) %>% round_cols(digits = 3) library(ggplot2) d <- plot_blup(model2) e <- plot_blup(model2, prob = 0.1, col.shape = c("gray20", "gray80")) + coord_flip() arrange_ggplot(d, e, tag_levels = list(c("d", "e")), ncol = 1) get_model_data(model2, what = "blupge") %>% round_cols() model3 <- waasb(data_ge, ENV, GEN, REP, everything(), verbose = FALSE) get_model_data(model3, what = "WAASB") %>% round_cols() index <- blup_indexes(model3) get_model_data(index) %>% round_cols() gge_model <- gge(data_ge, ENV, GEN, GY) f <- plot(gge_model) g <- plot(gge_model, type = 2) arrange_ggplot(e, f, tag_levels = list(c("e", "f")), ncol = 1) stat_ge <- ge_stats(data_ge, ENV, GEN, REP, GY) get_model_data(stat_ge) %>% round_cols()
b_success_rate <- function(r, s, priors=NULL, warmup=1000, iter=2000, chains=4, seed=NULL, refresh=NULL, control=NULL, suppress_warnings=TRUE) { if (chains > 1) { options(mc.cores = parallel::detectCores()) } n <- length(r) m <- length(unique(s)) p_ids <- rep(0, 2) p_values <- rep(0, 4) df_pars <- data.frame(par=c("p", "tau"), index=c(1, 2)) if (!is.null(priors)) { for (p in priors) { par <- p[[1]] prior <- p[[2]] id <- 0 par_id <- df_pars[df_pars$par==par,] if (nrow(par_id) > 0) { id <- par_id$index } else { wrong_prior <- "Provided an unknown parameter for prior, use \"p\" or \"tau\"." warning(wrong_prior) return() } p_ids[id] <- get_prior_id(prior) if (p_ids[id] == 0) { wrong_prior <- "Provided an unknown prior family, use \"uniform\", \"normal\", \"gamma\" or \"beta\"." warning(wrong_prior) return() } if (length(prior@pars) != 2) { wrong_pars <- "Incorrect prior parameters, provide a vector of 2 numerical values." warning(wrong_pars) return() } p_values[2*id-1] <- prior@pars[1] p_values[2*id] <- prior@pars[2] } } stan_data <- list(n=n, m=m, r=r, s=s, p_ids = p_ids, p_values = p_values) if (is.null(seed)) { seed <- sample.int(.Machine$integer.max, 1) } if (is.null(refresh)) { refresh <- max(iter/10, 1) } if (suppress_warnings) { fit <- suppressWarnings(sampling(stanmodels$success_rate, data=stan_data, iter=iter, warmup=warmup, chains=chains, seed=seed, refresh=refresh, control=control)) } else { fit <- sampling(stanmodels$success_rate, data=stan_data, iter=iter, warmup=warmup, chains=chains, seed=seed, refresh=refresh, control=control) } extract_raw <- extract(fit, permuted=FALSE) i <- 1 p0 <- extract_raw[, 1, i] i <- i + 1 tau <- extract_raw[, 1, i] i <- i + 1 j <- i + m - 1 p <- extract_raw[, 1, i:j] i <- i + m lp__ <- extract_raw[, 1, i] extract <- list(p0=p0, tau=tau, p=p, lp__=lp__) out <- success_rate_class(extract=extract, data=stan_data, fit=fit) return(out) }
compRejectionFraction<-function(bkgLevel,respLevel,numCats,pretestP,anovaP, showProgress=FALSE, numTrialsPerCat=10,numCells=1000) { totPreselected<-0 totRejected<-0 totTrials<-numCats*numTrialsPerCat catLabels<-factor(rep(1:numCats,numTrialsPerCat)) for (i in 1:numCells) { if (showProgress) print(i) bkgCnts<-rpois(totTrials,bkgLevel) respCnts<-rpois(totTrials,respLevel) presel<-FALSE for (j in 1:numCats) { catSel<-catLabels==levels(catLabels)[j] pVal<-t.test(bkgCnts,respCnts[catSel],alternative='two.sided')$p.value if (pVal<pretestP) { presel<-TRUE break } } if (presel) { totPreselected<-totPreselected+1 mod<-glm(respCnts~catLabels) pVal<-anova(mod,test='F')$"Pr(>F)"[2] if (pVal<anovaP) totRejected<-totRejected+1 } } list( exclusionFrac=1-(totPreselected/numCells), rejectionFrac=totRejected/totPreselected ) }
convert_color = function(color, as_hex = FALSE) { if(inherits(color,"character")) { color = as.vector(grDevices::col2rgb(color))/255 } if(as_hex) { paste0(" } else { color } } rescale = function(vals, to=c(0,1)) { range_vals = range(vals[!is.infinite(vals)],na.rm=TRUE) vals = (vals-range_vals[1])/(range_vals[2]-range_vals[1]) (vals + to[1]) * (t[2]-t[1]) } get_file_type = function(file) { if(is.character(file)) { if(tools::file_ext(file) == "png") { imagetype = "png" } else { imagetype = "jpg" } } else if (length(dim(file)) == 3) { imagetype = "array" } else if (length(dim(file)) == 2) { imagetype = "matrix" } else { stop("`",file,"` not recognized class (png, jpeg, array, matrix).") } } fliplr = function(x) { if(length(dim(x)) == 2) { x[,ncol(x):1] } else { x[,ncol(x):1,] } } flipud = function(x) { if(length(dim(x)) == 2) { x[nrow(x):1,] } else { x[nrow(x):1,,] } }
test_that("cdb_id works correctly", { id1 <- cdb_id(Compadre, c("SpeciesAuthor", "MatrixPopulation")) expect_type(id1, "integer") expect_length(id1, nrow(Compadre@data)) id2 <- cdb_id(Compadre, "Family") expect_type(id2, "integer") expect_length(id2, nrow(Compadre@data)) expect_true(length(unique(id2)) == length(unique(Compadre@data$Family))) }) test_that("cdb_id warns and fails gracefully", { expect_error(cdb_id(Compadre@data)) expect_error(cdb_id(Compadre, c("SpeciesAuthor", "blah"))) })
asc2s <- function(k=12, x=rep(95, times=2), dir=2, r=(x[dir]-3)^(seq(k)/k)) { k <- length(r <- unique(round(r))) return(switch(dir, rbind(r=r+1, x1=2, x2=r+2, y1=2, y2=x[2]-1), rbind(r=r+1, x1=2, x2=x[1]-1, y1=2, y2=r+2))) } asc3s <- function(k=12, x=rep(95, times=3), dir=3, r=(x[dir]-3)^(seq(k)/k)) { k <- length(r <- unique(round(r))) return(switch(dir, rbind(r=r+1, x1=2, x2=r+2, y1=2, y2=x[2]-1, z1=2, z2=x[3]-1), rbind(r=r+1, x1=2, x2=x[1]-1, y1=2, y2=r+2, z1=2, z2=x[3]-1), rbind(r=r+1, x1=2, x2=x[1]-1, y1=2, y2=x[2]-1, z1=2, z2=r+2))) }
ArcList2Cmat <- function(nodes, arcs, directed = TRUE) { n <- length(nodes) Cmat <- matrix(nrow = n, ncol = n) Cmat[, ] <- Inf for (i in 1:nrow(Cmat)) { Cmat[i, i] <- NA } for (i in 1:nrow(arcs)) { Cmat[arcs[i, 1], arcs[i, 2]] <- arcs[i, 3] } if (!directed) { for (i in 1:nrow(arcs)) { Cmat[arcs[i, 2], arcs[i, 1]] <- arcs[i, 3] } } return(Cmat) }
do_oauth <- function(app = do_app, reauth = FALSE) { if (exists("auth_config", envir = cache) && !reauth) { return(cache$auth_config) } pat <- Sys.getenv("DO_PAT", "") if (!identical(pat, "")) { auth_config <- httr::add_headers(Authorization = paste0("Bearer ", pat)) } else if (!interactive()) { stop("In non-interactive environments, please set DO_PAT env to a DO", " access token (https://cloud.digitalocean.com/settings/api/tokens)", call. = FALSE) } else { endpt <- httr::oauth_endpoint( NULL, "authorize", "token", base_url = "https://cloud.digitalocean.com/v1/oauth") token <- httr::oauth2.0_token(endpt, app, scope = c("read", "write"), cache = !reauth) auth_config <- httr::config(token = token) } cache$auth_config <- auth_config auth_config } cache <- new.env(parent = emptyenv()) do_app <- httr::oauth_app( "Rstats", "6d5dbd8599989781ea6ca1fd7cd25a6a55a9f746afbeabb8834b8d5269751749", "b771ae783b65aae96bec459b1bdeb023810d318a6f73019a1fb0abf7dc01bc24" )
options(na.action=na.exclude) options(contrasts=c('contr.treatment', 'contr.poly')) library(survival) fit0 <- coxph(Surv(time, status) ~ ph.ecog + age, lung) fit1 <- coxph(Surv(time, status) ~ ph.ecog + pspline(age,3), lung) fit2 <- coxph(Surv(time, status) ~ ph.ecog + pspline(age,4), lung) fit3 <- coxph(Surv(time, status) ~ ph.ecog + pspline(age,8), lung) fit4 <- coxph(Surv(time, status) ~ ph.ecog + pspline(wt.loss,3), lung) fit5 <-coxph(Surv(time, status) ~ ph.ecog + pspline(age,3) + pspline(wt.loss,3), lung) fit1 fit2 fit3 fit4 fit5 rm(fit1, fit2, fit3, fit4, fit5)
test_that("empty input returns a list, but after the index size check", { expect_equal(pslide_index(list(integer(), integer()), integer(), ~.x), list()) expect_equal(pslide_index(list(integer(), 1), integer(), ~.x), list()) expect_equal(pslide_index(list(1, integer()), integer(), ~.x), list()) expect_error(pslide_index(list(integer(), integer()), 1, ~.x), class = "slider_error_index_incompatible_size") }) test_that("completely empty input returns a list", { expect_equal(pslide_index(list(), integer(), ~.x), list()) }) test_that("pslide_index() forces arguments in the same way as base R / pmap()", { f_slide <- pslide_index(list(1:2, 1:2, 1:2), 1:2, function(i, j, k) function(x) x + i + j + k) f_base <- mapply(function(i, j, k) function(x) x + i + j + k, 1:2, 1:2, 1:2) expect_equal(f_slide[[1]](0), f_base[[1]](0)) expect_equal(f_slide[[2]](0), f_base[[2]](0)) })
ghelp <- function(item = c("GENERAL", "SELECT", "SPECIES", "KEYWORD"), file = c("HELP", "HELP_WIN"), socket = autosocket(), catresult = TRUE){ item <- item[1] file <- file[1] if(!(file %in% c("HELP", "HELP_WIN"))) stop("Wrong file agument") request <- paste("ghelp&file=", file, "&item=", item, sep = "") writeLines(request, socket, sep = "\n") answerFromServer <- readLines(socket) if(length(answerFromServer) == 0){ warning("Empty answer from server") return(NA) } answerFromServer[1] <- unlist(strsplit(answerFromServer[1], split = "&"))[2] if(catresult) cat(answerFromServer, sep = "\n") invisible(answerFromServer) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) knitr::include_graphics("figures/workflow.png") library(bulkAnalyseR) counts.in <- system.file("extdata", "expression_matrix.csv", package = "bulkAnalyseR") exp <- as.matrix(read.csv(counts.in, row.names = 1)) head(exp) meta <- data.frame( srr = colnames(exp), timepoint = rep(c("0h", "12h", "36h"), each = 2) ) exp.proc <- preprocessExpressionMatrix(exp, output.plot = TRUE) knitr::include_graphics("figures/ScreenShot.png") knitr::include_graphics("figures/JSI.png") knitr::include_graphics("figures/PCA.png") knitr::include_graphics("figures/MA_QC.png") knitr::include_graphics("figures/DE.png") knitr::include_graphics("figures/VolcanoPlot.png") knitr::include_graphics("figures/MAPlot.png") knitr::include_graphics("figures/PCA_DE.png") knitr::include_graphics("figures/ExpressionHeatmap.png") knitr::include_graphics("figures/Enrichment.png") knitr::include_graphics("figures/ExpressionPatterns.png") knitr::include_graphics("figures/ExpressionPatternsLinePlot.png") knitr::include_graphics("figures/ExpressionPatternsHeatmap.png") knitr::include_graphics("figures/CrossPlot.png") knitr::include_graphics("figures/GRN.png")
if ("package:dendextendRcpp" %in% search()) { detach("package:dendextendRcpp") return_dendextendRcpp <- TRUE } else { return_dendextendRcpp <- FALSE } detach("package:dendextend") suppressWarnings(require(ape, quietly = TRUE)) suppressPackageStartupMessages(library(dendextend)) if (return_dendextendRcpp) suppressPackageStartupMessages(library(dendextendRcpp)) rm(return_dendextendRcpp) context("Rotate a tree around its hinges") test_that("Rotate a dendrogram", { hc <- hclust(dist(USArrests[1:3, ]), "ave") dend <- as.dendrogram(hc) expect_equal(rev(labels(dend)), labels(rotate(dend, 3:1))) expect_equal(rev(labels(dend)), labels(rotate(dend, rev(labels(dend))))) }) test_that("Rotate a dendrogram (but not exactly to what we asked for)", { hc <- hclust(dist(USArrests[1:3, ]), "ave") dend <- as.dendrogram(hc) new_order <- c(3, 1, 2) expect_false(all(labels(dend)[new_order] == labels(rotate(dend, new_order)))) expect_false(all(labels(dend)[new_order] == labels(rotate(dend, labels(dend)[new_order])))) }) test_that("Rotate a dendrogram - works with either numeric or character", { hc <- hclust(dist(USArrests[1:3, ]), "ave") dend <- as.dendrogram(hc) new_order <- c(2, 3, 1) expect_equivalent(rotate(dend, new_order), rotate(dend, labels(dend)[new_order])) expect_equivalent( labels(rotate(dend, new_order)), labels(rotate(dend, labels(dend)[new_order])) ) }) test_that("Rotate hclust", { hc <- hclust(dist(USArrests[1:3, ]), "ave") expect_equal(rev(labels(hc)), labels(rotate(hc, 3:1))) expect_equal(rev(labels(hc)), labels(rotate(hc, rev(labels(hc))))) }) test_that("Rotate a hclust (but not exactly to what we asked for)", { hc <- hclust(dist(USArrests[1:3, ]), "ave") new_order <- c(3, 1, 2) expect_false(all(labels(hc)[new_order] == labels(rotate(hc, new_order)))) expect_false(all(labels(hc)[new_order] == labels(rotate(hc, labels(hc)[new_order])))) })
npqcmstest <- function(formula, data = NULL, subset, xdat, ydat, model = stop(paste(sQuote("model")," has not been provided")), tau = 0.5, distribution = c("bootstrap", "asymptotic"), bwydat = c("y","varepsilon"), boot.method=c("iid","wild","wild-rademacher"), boot.num = 399, pivot = TRUE, density.weighted = TRUE, random.seed = 42, ...) { pcall = paste(deparse(model$call),collapse="") if(length(grep("model = TRUE", pcall)) == 0) stop(paste(sQuote("model")," is missing components ", sQuote("model"), ".\nTo fix this please invoke ", sQuote("rq"), " with ", sQuote("model=TRUE"), ".\nSee help for further info.", sep="")) if(tau <=0 | tau >=1) stop("tau must lie in (0,1)") if(boot.num < 9) stop("number of bootstrap replications must be >= 9") miss.xy = c(missing(xdat),missing(ydat)) miss.f = missing(formula) if (any(miss.xy) && !all(miss.xy)) stop("one of, but not both, xdat and ydat was specified") else if(all(miss.xy) & miss.f) stop("xdat, and ydat, are missing, and no formula is specified.") else if(all(miss.xy) & !miss.f){ mf <- eval(parse(text=paste("model.frame(formula = formula, data = data,", ifelse(missing(subset),"","subset = subset,"), "na.action = na.omit)"))) ydat <- model.response(mf) xdat <- mf[, attr(attr(mf, "terms"),"term.labels"), drop = FALSE] na.index <- unclass(attr(xdat,"na.action")) } else if(!miss.f){ stop(paste("A formula was specified along with xdat and ydat.\n", "Please see the documentation on proper interface usage.")) } else { xdat = toFrame(xdat) goodrows = 1:dim(xdat)[1] rows.omit = attr(na.omit(data.frame(xdat,ydat)), "na.action") goodrows[rows.omit] = 0 if (all(goodrows==0)) stop("Data has no rows without NAs") xdat = xdat[goodrows,,drop = FALSE] ydat = ydat[goodrows] na.index = which(goodrows==0) } if(exists(".Random.seed", .GlobalEnv)) { save.seed <- get(".Random.seed", .GlobalEnv) exists.seed = TRUE } else { exists.seed = FALSE } set.seed(random.seed) distribution = match.arg(distribution) boot.method = match.arg(boot.method) bwydat = match.arg(bwydat) model.resid <- residuals(model, type = "response") n = length(model.resid) console <- newLineConsole() console <- printPush("Bandwidth selection", console) if(bwydat == "y") { bw <- npregbw(xdat=xdat, ydat=model$y, ...) } else if(bwydat == "varepsilon"){ varepsilon <- ifelse(model.resid<=0,1-tau,-tau) bw <- npregbw(xdat=xdat, ydat=varepsilon, ...) } console <- printPop(console) fhat <- 1 prodh <- if (bw$ncon == 0) 1.0 else prod(bw$bw[bw$icon]) if (!density.weighted) fhat <- npksum(txdat = xdat, bws = bw$bw, leave.one.out = TRUE, bandwidth.divide = FALSE,...)$ksum/(n*prodh) if(min(fhat) == 0) stop(paste(sep="","\nAttempt to divide by zero density.", "\nYou can try re-running the test with `density.weighted=TRUE'\n")) In <- function(xdat, model.resid, bw) { n <- length(model.resid) varepsilon <- ifelse(model.resid<=0,1-tau,-tau) return( sum(varepsilon*npksum(txdat=xdat, tydat=varepsilon, bws=bw$bw, leave.one.out=TRUE, bandwidth.divide=TRUE,...)$ksum/fhat)/n^2 ) } Omega.hat <- function(xdat, model.resid, bw) { n <- length(model.resid) varepsilon <- ifelse(model.resid<=0,1-tau,-tau) return( 2*prod(bw$bw[bw$icon])* sum(varepsilon^2* npksum(txdat=xdat, tydat=varepsilon^2, bws=bw$bw, leave.one.out=TRUE, kernel.pow=2, bandwidth.divide=TRUE,...)$ksum/fhat^2)/n^2 ) } Jn <- function(xdat, model.resid, bw) { n <- length(model.resid) n*sqrt(prodh)*In(xdat, model.resid, bw)/sqrt(Omega.hat(xdat, model.resid, bw)) } yhat <- fitted(model) boot.wild <- function(model.resid) { a <- -0.6180339887499 P.a <-0.72360679774998 b <- 1.6180339887499 y.star <- yhat + (model.resid-mean(model.resid))* ifelse(rbinom(length(model.resid),1,P.a)==1,a,b)+ mean(model.resid) suppressWarnings(resid <- residuals(rq(y.star~ model$x - 1, tau=tau), type = "response")) return(if (pivot) Jn(xdat, resid, bw) else In(xdat, resid, bw)) } boot.wild.rademacher <- function(model.resid) { a <- -1 P.a <- 0.5 b <- 1 y.star <- yhat + (model.resid-mean(model.resid))* ifelse(rbinom(length(model.resid),1,P.a)==1,a,b)+ mean(model.resid) suppressWarnings(resid <- residuals(rq(y.star~ model$x - 1, tau=tau), type = "response")) return(if (pivot) Jn(xdat, resid, bw) else In(xdat, resid, bw)) } boot.iid <- function(model.resid) { y.star <- yhat + sample(model.resid, replace=TRUE) suppressWarnings(resid <- residuals(rq(y.star~ model$x - 1, tau=tau), type = "response")) return(if (pivot) Jn(xdat, resid, bw) else In(xdat, resid, bw)) } if(distribution == "bootstrap"){ Sn.bootstrap <- numeric(boot.num) for(ii in 1:boot.num) { console <- printPush(paste(sep="", "Bootstrap replication ", ii, "/", boot.num, "..."), console) if(boot.method == "iid"){ Sn.bootstrap[ii] <- boot.iid(model.resid) } else if(boot.method == "wild"){ Sn.bootstrap[ii] <- boot.wild(model.resid) } else if(boot.method == "wild-rademacher"){ Sn.bootstrap[ii] <- boot.wild.rademacher(model.resid) } console <- printPop(console) } Sn.bootstrap <- sort(Sn.bootstrap) cat("\n") } tIn = In(xdat, model.resid, bw) to.h = Omega.hat(xdat, model.resid, bw) s.d = if (pivot) 1.0 else sqrt(to.h/prodh)/n if(distribution == "asymptotic") { tJn = list( Jn = n*sqrt(prodh)*tIn/sqrt(to.h), In = tIn, Omega.hat = to.h, q.90=qnorm(p = .90, sd = s.d), q.95=qnorm(p = .95, sd = s.d), q.99=qnorm(p = .99, sd = s.d), bw = bw, Jn.bootstrap = NA, In.bootstrap = NA, pivot = pivot) Sn = if (pivot) tJn$Jn else tIn tJn$P <- (1-pnorm(Sn, sd = s.d)) } else { tJn = list( Jn = n*sqrt(prodh)*tIn/sqrt(to.h), In = tIn, Omega.hat = to.h, q.90=Sn.bootstrap[ceiling(0.90*boot.num)], q.95=Sn.bootstrap[ceiling(0.95*boot.num)], q.99=Sn.bootstrap[ceiling(0.99*boot.num)], bw=bw, Jn.bootstrap = if(pivot) Sn.bootstrap else NA, In.bootstrap = if(pivot) NA else Sn.bootstrap, pivot = pivot ) Sn = if (pivot) tJn$Jn else tIn tJn$P <- mean(ifelse(Sn.bootstrap > Sn, 1, 0)) } if(exists.seed) assign(".Random.seed", save.seed, .GlobalEnv) cmstest(Jn = tJn$Jn, In = tJn$In, Omega.hat = tJn$Omega.hat, sd = s.d, q.90 = tJn$q.90, q.95 = tJn$q.95, q.99 = tJn$q.99, P = tJn$P, bws = bw, distribution = distribution, Jn.bootstrap = tJn$Jn.bootstrap, In.bootstrap = tJn$In.bootstrap, pivot = pivot, model = model, boot.method = boot.method, boot.num = boot.num, na.index = na.index) }
suppressPackageStartupMessages(library("argparse")) parser = ArgumentParser() parser$add_argument("--infercnv_obj", help="infercnv_obj file", required=TRUE, nargs=1) parser$add_argument("--scale", help="scale", action='store_true', default=FALSE) parser$add_argument("--subtract", help="subtract", action='store_true', default=FALSE) parser$add_argument("--smooth", help="smooth", action='store_true', default=TRUE) parser$add_argument("--show_tumor", help="show tumor instead of normal", action='store_true', default=FALSE) parser$add_argument("--output", help="name of output png file", required=TRUE) args = parser$parse_args() library(infercnv) library(tidyverse) library(futile.logger) infercnv_obj_file = args$infercnv_obj infercnv_obj = readRDS(infercnv_obj_file) if (! infercnv:::has_reference_cells(infercnv_obj)) { stop("Error, cannot tune parameters without reference 'normal' cells defined") } if (args$scale) { infercnv_obj <- infercnv:::scale_infercnv_expr(infercnv_obj) } if (args$subtract) { infercnv_obj <- subtract_ref_expr_from_obs(infercnv_obj, inv_log=FALSE) } if (args$smooth) { infercnv_obj <- smooth_by_chromosome(infercnv_obj, window_length=101, smooth_ends=TRUE) } if (args$show_tumor) { expr_vals <- [email protected][, unlist(infercnv_obj@observation_grouped_cell_indices)] } else { expr_vals <- [email protected][, unlist(infercnv_obj@reference_grouped_cell_indices)] } mu = mean(expr_vals) sigma = sd(expr_vals) data.want = data.frame(vals=as.numeric(expr_vals)) mean_delta = infercnv:::determine_mean_delta_via_Z(sigma, p=0.05) KS_delta = infercnv:::get_HoneyBADGER_setGexpDev(gexp.sd=sigma, alpha=0.05) png(args$output) message("plotting ncells distribution") message("mean delta: ", mean_delta) message("KS_delta: ", KS_delta) p = data.want %>% ggplot(aes(vals)) + geom_density(alpha=0.3) p = p + stat_function(fun=dnorm, color='black', args=list('mean'=mu,'sd'=sigma)) p = p + stat_function(fun=dnorm, color='blue', args=list('mean'=mu-mean_delta,'sd'=sigma)) + stat_function(fun=dnorm, color='blue', args=list('mean'=mu+mean_delta,'sd'=sigma)) p = p + stat_function(fun=dnorm, color='magenta', args=list('mean'=mu-KS_delta,'sd'=sigma)) + stat_function(fun=dnorm, color='magenta', args=list('mean'=mu+KS_delta,'sd'=sigma)) plot(p)
print.drop.test <- function (x, digits = max(5, .Options$digits - 2), ...) { cat("\nDrop in Dispersion Test\n") y <- c(x$F, x$p.value) names(y) <- c("F-Statistic", "p-value") print(format(y, digits = digits), quote = FALSE) }
adjustCounts = function(sc,clusters=NULL,method=c('subtraction','soupOnly','multinomial'),roundToInt=FALSE,verbose=1,tol=1e-3,pCut=0.01,...){ method = match.arg(method) if(!is(sc,'SoupChannel')) stop("sc must be an object of type SoupChannel") if(!'rho' %in% colnames(sc$metaData)) stop("Contamination fractions must have already been calculated/set.") if(is.null(clusters)){ if('clusters' %in% colnames(sc$metaData)){ clusters = setNames(as.character(sc$metaData$clusters),rownames(sc$metaData)) }else{ warning("Clustering data not found. Adjusting counts at cell level. You will almost certainly get better results if you cluster data first.") clusters=FALSE } } if(clusters[1]!=FALSE){ if(!all(colnames(sc$toc) %in% names(clusters))) stop("Invalid cluster specification. clusters must be a named vector with all column names in the table of counts appearing.") s = split(colnames(sc$toc),clusters[colnames(sc$toc)]) tmp = sc tmp$toc = do.call(cbind,lapply(s,function(e) rowSums(sc$toc[,e,drop=FALSE]))) tmp$toc = Matrix(tmp$toc,sparse=TRUE) tmp$metaData = data.frame(nUMIs = sapply(s,function(e) sum(sc$metaData[e,'nUMIs'])), rho = sapply(s,function(e) sum(sc$metaData[e,'rho']*sc$metaData[e,'nUMIs'])/sum(sc$metaData[e,'nUMIs']))) out = adjustCounts(tmp,clusters=FALSE,method=method,roundToInt=FALSE,verbose=verbose,tol=tol,pCut=pCut) out = tmp$toc - out out = expandClusters(out,sc$toc,clusters,sc$metaData$nUMIs*sc$metaData$rho,verbose=verbose,...) out = sc$toc - out }else{ if(method=='multinomial'){ if(verbose>1) message("Initialising with subtraction method.") fitInit = sc$toc - adjustCounts(sc,clusters=FALSE,method='subtraction',roundToInt=TRUE) ps = sc$soupProfile$est out = list() if(verbose>0){ message(sprintf("Fitting multinomial distribution to %d cells/clusters.",ncol(sc$toc))) pb=initProgBar(1,ncol(sc$toc)) } for(i in seq(ncol(sc$toc))){ if(verbose>0) setTxtProgressBar(pb,i) tgtN = round(sc$metaData$rho[i]*sc$metaData$nUMIs[i]) lims = sc$toc[,i] fit = fitInit[,i] while(TRUE){ increasable = fit<lims decreasable = fit>0 delInc = log(ps[increasable]) - log(fit[increasable]+1) delDec = -log(ps[decreasable]) +log(fit[decreasable]) wInc = wIncAll = which(increasable)[which(delInc==max(delInc))] wDec = wDecAll = which(decreasable)[which(delDec==max(delDec))] nInc = length(wIncAll) nDec = length(wDecAll) if(nInc>1) wInc = sample(wIncAll,1) if(nDec>1) wDec = sample(wDecAll,1) curN = sum(fit) if(curN<tgtN){ if(verbose>2) message(sprintf(" fit[wInc] = fit[wInc]+1 }else if(curN>tgtN){ if(verbose>2) message(sprintf(" fit[wDec] = fit[wDec]-1 }else{ delTot = max(delInc)+max(delDec) if(verbose>2) message(sprintf(" if(delTot==0){ fit[wDecAll] = fit[wDecAll]-1 zeroBucket = unique(c(wIncAll,wDecAll)) fit[zeroBucket] = fit[zeroBucket] + length(wDecAll)/length(zeroBucket) if(verbose>2) message(sprintf("Ambiguous final configuration. Shared %d reads between %d equally likely options",length(wDecAll),length(zeroBucket))) break }else if(delTot<0){ if(verbose>2) message("Unique final configuration.") break }else{ fit[wInc] = fit[wInc]+1 fit[wDec] = fit[wDec]-1 } } } out[[i]]=fit } if(verbose>0) close(pb) out = do.call(cbind,out) out = as(out,'dgTMatrix') rownames(out) = rownames(sc$toc) colnames(out) = colnames(sc$toc) out = sc$toc - out }else if(method=='soupOnly'){ if(verbose>0) message("Identifying and removing genes likely to be pure contamination in each cell.") out = as(sc$toc,'dgTMatrix') if(verbose>1) message("Calculating probability of each gene being soup") p = ppois(out@x-1,sc$metaData$nUMIs[out@j+1]*sc$soupProfile$est[out@i+1]*sc$metaData$rho[out@j+1],lower.tail=FALSE) o = order(-(out@j+1),p,decreasing=TRUE) if(verbose>1) message("Calculating probability of the next count being soup") s = split(o,out@j[o]+1) rTot = unlist(lapply(s,function(e) cumsum(out@x[e])),use.names=FALSE) pSoup = ppois(rTot-out@x[o]-1,sc$metaData$nUMIs[out@j[o]+1]*sc$metaData$rho[out@j[o]+1],lower.tail=FALSE) if(verbose>1) message("Filtering table of counts") pp = p[o]*pSoup q = pchisq(-2*log(pp),4,lower.tail=FALSE) w = which(q<pCut) dropped = data.frame(cell=colnames(out)[out@j[o[-w]]+1], gene=rownames(out)[out@i[o[-w]]+1], cnt = out@x[o[-w]]) if(verbose>2){ message(sprintf("Most removed genes are:")) x = sort(table(dropped$gene)/ncol(out),decreasing=TRUE) print(x[seq_len(min(length(x),100))]) } out = sparseMatrix(i=out@i[o[w]]+1, j=out@j[o[w]]+1, x=out@x[o[w]], dims=dim(out), dimnames=dimnames(out), giveCsparse=FALSE) }else if(method=='subtraction'){ out = as(sc$toc,'dgTMatrix') expSoupCnts = sc$metaData$nUMIs * sc$metaData$rho soupFrac = sc$soupProfile$est out = out - do.call(cbind,lapply(seq(ncol(out)),function(e) alloc(expSoupCnts[e],out[,e],soupFrac))) out = as(out,'dgTMatrix') w = which(out@x>0) out = sparseMatrix(i=out@i[w]+1, j=out@j[w]+1, x=out@x[w], dims=dim(out), dimnames=dimnames(out), giveCsparse=FALSE) }else{ stop("Impossible!") } } if(roundToInt){ if(verbose>1) message("Rounding to integers.") out@x = floor(out@x)+rbinom(length(out@x),1,out@x-floor(out@x)) } return(out) }
train <- read.csv("train.csv", header = TRUE) test <- read.csv("test.csv", header = TRUE) test.survived <- data.frame(survived = rep("None", nrow(test)), test[,]) data.combined <- rbind(train, test.survived) str(data.combined) data.combined$survived <- as.factor(data.combined$survived) data.combined$pclass <- as.factor(data.combined$pclass) table(data.combined$survived) table(data.combined$pclass) library(ggplot2) train$pclass <- as.factor(train$pclass) ggplot(train, aes(x = pclass, fill = factor(survived))) + geom_bar() + xlab("Pclass") + ylab("Total Count") + labs(fill = "Survived") head(as.character(train$name)) length(unique(as.character(data.combined$name))) dup.names <- as.character(data.combined[which(duplicated(as.character(data.combined$name))), "name"]) data.combined[which(data.combined$name %in% dup.names),] library(stringr) misses <- data.combined[which(str_detect(data.combined$name, "Miss.")),] misses[1:5,] mrses <- data.combined[which(str_detect(data.combined$name, "Mrs.")), ] mrses[1:5,] males <- data.combined[which(data.combined$sex == "male"), ] males[1:5,] extractTitle <- function(name) { name <- as.character(name) if (length(grep("Miss.", name)) > 0) { return ("Miss.") } else if (length(grep("Master.", name)) > 0) { return ("Master.") } else if (length(grep("Mrs.", name)) > 0) { return ("Mrs.") } else if (length(grep("Mr.", name)) > 0) { return ("Mr.") } else { return ("Other") } } titles <- NULL for (i in 1:nrow(data.combined)) { titles <- c(titles, extractTitle(data.combined[i,"name"])) } data.combined$title <- as.factor(titles) ggplot(data.combined[1:891,], aes(x = title, fill = survived)) + geom_bar() + facet_wrap(~pclass) + ggtitle("Pclass") + xlab("Title") + ylab("Total Count") + labs(fill = "Survived")
riverbuilder = function(filename, directory, overwrite){ if(!file.exists(filename)) stop("File specified was not found.") if(directory == '' || typeof(directory) != "character" || !dir.exists(directory)) { print("Empty or invalid argument for the directory parameter. Writing to a temporary location.") directory = tempdir() } file_outputs = c( "CenterlineCurvature.png", "ValleySection.png", "GCS.png", "LongitudinalProfile.png", "Planform.png", "BoundaryPoints.csv", "Data.csv", "CartesianCoordinates.csv", "CenterlineCurvature.csv", "ValleySection.csv", "GCS.csv", "LongitudinalProfile.csv", "Planform.csv" ) graph_names = c( "Centerline Curvature", "Cross Section", "Geometric Covariance Structures", "Longitudinal Profile", "Planform" ) river_properties = c( "Meandering Centerline Function", "Centerline Curvature Function", "Bankfull Width Function", "Thalweg Elevation Function", "Left Floodplain Function", "Right Floodplain Function", "Cross-Sectional Shape" ) function_types = c( "SIN_SQ", "SIN", "COS", "LINE", "PERL" ) crossSectionalShapes = c( "SU", "AU", "TZ" ) for(i in seq(from=1, to=length(file_outputs), by=1)) { coordinate_file = paste(directory, "/", file_outputs[i], sep="") if(file.exists(coordinate_file)) { if(overwrite) file.remove(coordinate_file) else stop(paste("One or more output files already exist(s) in '", directory, "'. Program exit.", sep="")) } } random = function() { Zr <<- (Ar * Zr + Cr) %% Mr return(Zr / Mr - 0.5) } evaluateNumerical = function(input) { if(grepl("PI", input)) { if(input == "PI") return(pi) else { if(typeof(input) != "character") input = as.character(input) length = length(strsplit(input, "")[[1]]) a = b = "" j = 1 if(substring(input, 1, 2) == "PI") { a = "1" j = j + 3 } else { while(substring(input, j, j) != "*") { a = paste(a, substring(input, j, j), sep="") j = j + 1 } j = j + 4 } if(j > length) b = "1" else b = paste(b, substring(input, j, length), sep="") return(as.double(a) * pi / as.double(b)) } } else return(as.double(input)) } storeFunction = function(variable, input) { if(grepl(river_properties[1], variable)) Mc_functions <<- rbind(Mc_functions, input) else if(grepl(river_properties[2], variable)) { if(XS_shape == crossSectionalShapes[2] && nrow(Cs_functions) == 1) { if(input[1] != function_types[2]) stop("Please provide a sine function for the AU cross-sectional shape. Program exit.") else input[1] = "NA" } Cs_functions <<- rbind(Cs_functions, input) } else if(grepl(river_properties[3], variable)) Wbf_functions <<- rbind(Wbf_functions, input) else if(grepl(river_properties[4], variable)) Zt_functions <<- rbind(Zt_functions, input) else if(grepl(river_properties[5], variable)) LeftFP_functions <<- rbind(LeftFP_functions, input) else if(grepl(river_properties[6], variable)) RightFP_functions <<- rbind(RightFP_functions, input) } evaluateFunctions = function(functions, ivs, key) { output = 0 for(i in seq(from=2, to=nrow(functions), by=1)) output = output + computeFunction(functions[i,], ivs, key) return(output) } computeFunction = function(fun, iv, key) { output = 0 if(grepl(function_types[1], fun[1])) output = evaluateNumerical(fun[2])*(sin(evaluateNumerical(fun[3])*iv[1] + evaluateNumerical(fun[4])))**2 else if(grepl(function_types[2], fun[1])) output = evaluateNumerical(fun[2])*sin(evaluateNumerical(fun[3])*iv[1] + evaluateNumerical(fun[4])) else if(grepl(function_types[3], fun[1])) output = evaluateNumerical(fun[2])*cos(evaluateNumerical(fun[3])*iv[1] + evaluateNumerical(fun[4])) else if(grepl(function_types[4], fun[1])) output = evaluateNumerical(fun[2])*iv[2] + evaluateNumerical(fun[3]) else if(grepl(function_types[5], fun[1])) { ra = ga rb = gb if(!is.null(perlins[[key]])) { ra = perlins[[key]][1] rb = perlins[[key]][2] } if(iv[3] %% evaluateNumerical(fun[3]) < 1) { ra = rb rb = random() output = 2*ra*evaluateNumerical(fun[2]) } else { output = interpolate(ra, rb, (iv[3] %% evaluateNumerical(fun[3]))/evaluateNumerical(fun[3]))*evaluateNumerical(fun[2])*2 } perlins[[key]] <<- rbind(c(ra, rb)) } return(output) } isFunction = function(input) { for(i in seq(from=1, to=length(function_types), by=1)) if(grepl(function_types[i], input)) return(TRUE) return(FALSE) } isMatched = function(f1, f2) { for(i in seq(from=1, to=length(function_types), by=1)) if(grepl(function_types[i], f1) && grepl(function_types[i], f2)) return(TRUE) return(FALSE) } isDefined = function(input) { return(!is.null(userDefinedFunctions[[input]])) } standardize = function(x, m, sd) { if(sd == 0) return(0) else return( (x-m)/sd ) } interpolate = function(pa, pb, px) { ft = px * pi f = (1 - cos(ft)) * 0.5 return(pa * (1 - f) + pb * f) } crossSection = function(type, i, j) { output = 0 if(type == crossSectionalShapes[1]) output = topsofBank[i] - bankfullDepths[i]*sqrt((1-(n_xs[i,j]/n_xs[i,1])**2)) else if(type == crossSectionalShapes[2]) { if(bankfullWidths[i] != 0) { if(centerlineCurvatures[i] > 0) output = topsofBank[i]-((4*bankfullDepths[i]*(((bankfullWidths[i]/2)-n_xs[i,j])/bankfullWidths[i])^k_s[i]) * (1-(((bankfullWidths[i]/2)-n_xs[i,j])/bankfullWidths[i])^k_s[i])) else output = topsofBank[i]-((4*bankfullDepths[i]*((1-((bankfullWidths[i]/2-n_xs[i,j])/bankfullWidths[i]))^k_s[i])) * (1-((1-(bankfullWidths[i]/2-n_xs[i,j])/bankfullWidths[i])^k_s[i]))) } } else if(type == crossSectionalShapes[3]) { if(base < 0 || base > ChannelXSPoints) stop("Invalid trapezoidal base length. Program exit.") inc = 0 if(base %% 2 == 0) { partition = base/2 inc = 1 } else partition = ceiling(base/2) if(j == 1 || j == ChannelXSPoints) output = topsofBank[i] else if((j >= 2 && j <= floor(ChannelXSPoints/2)-partition) || j > floor(ChannelXSPoints/2)+partition+inc) { deltaX = n_xs[i,j]-n_xs[i,j-1] deltaY = -bankfullDepths[i]/((ChannelXSPoints/2) - (base/2)) if(j > floor(ChannelXSPoints/2)+partition+inc) deltaY = -deltaY xs_slope = deltaY/deltaX output = topsofBank[i] - (ChannelXSPoints/(ChannelXSPoints-base))*bankfullDepths[i] + xs_slope*(n_xs[i,j]) } else if(j >= floor(ChannelXSPoints/2)-partition+1 && j <= floor(ChannelXSPoints/2)+partition+inc) output = topsofBank[i] - bankfullDepths[i] } else stop("Invalid input for cross-sectional shape. Program exit.") return(output) } parameters = c() userDefinedFunctions = c() userDefinedDepth = TRUE Mc_functions = data.frame(matrix(ncol=6)) Cs_functions = data.frame(matrix(ncol=6)) Wbf_functions = data.frame(matrix(ncol=6)) Zt_functions = data.frame(matrix(ncol=6)) LeftFP_functions = data.frame(matrix(ncol=6)) RightFP_functions = data.frame(matrix(ncol=6)) XS_shape = "" base = 0 perlins = c() fergusons = c() k1 = c() print(paste("Generating SRV files in", directory, "...")) inputs = read.table(filename, sep="=", header=FALSE, colClasses = c("character")) for(i in seq(from=1, to=length(inputs$V2), by=1)) { col1 = (inputs$V1)[i] col2 = (inputs$V2)[i] input = col2 input = strsplit(input, split="[(), ]")[[1]] input = input[nchar(input)>0] if(isFunction(col1)) { if(isMatched(col1, col2) && !isDefined(col1) && grepl("[0-9]", col1)) userDefinedFunctions[[col1]] = input else stop("A user-defined function has an invalid name, values, or was defined more than once. Program exit.") } else if(!isFunction(col1) && isFunction(col2)) { if(grepl("(,)", col2)) storeFunction(col1, input) else { if(isDefined(col2)) { input = userDefinedFunctions[[col2]] storeFunction(col1, input) } else stop("Attempted to assign with an undefined function. Program exit.") } } else if(grepl("(,)", col2)) stop("Attempted to assign with values but no specific function. Program exit.") else if(grepl(river_properties[7], col1)) { if(grepl(crossSectionalShapes[3], col2)) { if(length(input) != 2 || grepl("[A-z]", input[2]) || grepl("[[:punct:]]", input[2])) stop("Invalid input for trapezoidal cross section. Program exit.") XS_shape = input[1] base = as.double(input[2]) } else XS_shape = col2 } else { if(grepl("Hbf", col1)) { input = strsplit(col1, ",")[[1]][2] if(grepl("B", input)) userDefinedDepth = FALSE } parameters = c(parameters, evaluateNumerical(col2)) } } datum = parameters[1] length = parameters[2] XResolution = length/parameters[3] ChannelXSPoints = parameters[4] valleySlope = parameters[5] criticalShieldsStress = parameters[6] bankfullWidth = parameters[7] bankfullWidthMin = parameters[8] bankfullDepth = parameters[9] medianSedimentSize = parameters[10] FPWidth = parameters[11] outerFPEdgeHeight = parameters[12] terraceWidth = parameters[13] outerTerraceEdgeHeight = parameters[14] boundaryWidth = parameters[15] increments = c() xrads = c() xms = c() channelMeanders = c() scms = c(0) dscms = c() scms_r = c() dxcmds = c() dycmds = c() thalwegs = c() thalwegsNoSlope = c() topsofBank = c() bankfullDepths = c() wbf_pfs = c() bankfullWidths = c() bankfullWidths_L = c() bankfullWidths_R = c() centerlineCurvature_pfs = c() firstDerivatives = rep(0, XResolution) secondDerivatives = rep(0, XResolution) centerlineCurvatures = c() yRightWaves = c() yLeftWaves = c() yRightToe = c() zRightToe = c() yRightTop = c() zRightTop = c() yLeftToe = c() zLeftToe = c() yLeftTop = c() zLeftTop = c() b_s = c() k_s = c() h_n = matrix(nrow=XResolution, ncol=ChannelXSPoints) n_xs = matrix(nrow=XResolution, ncol=ChannelXSPoints) bankPoints = matrix(nrow=XResolution, ncol=ChannelXSPoints) xShifts = matrix(nrow=XResolution, ncol=ChannelXSPoints) Wbf_stds = c() Zt_stds = c() CV_WZ = c() CV_ZC = c() disturbedDx = c(0) disturbedDy = c(0) disturbedThetas = c() disturbedX = c(0) disturbedY = c(0) fergusonY = c(0, 0.25) dxi = length/XResolution dxr = (dxi/length)*2*pi confinementRatio = bankfullWidth/(FPWidth+terraceWidth+bankfullWidth) ks = 6.1*medianSedimentSize n = 0.034*(ks^(1/6)) positiveGCS = 0 negativeGCS = 0 posPercentGCS = 0 negPercentGCS = 0 ki = -1 incr = 1/floor(ChannelXSPoints/2) Mr = 4294967296 Ar = 1664525 Cr = 1 Zr = floor(runif(1)*Mr) ga = random() gb = random() while(ki < 1+incr) { k1 = c(k1, round(ki, digits=5)) ki = ki + incr } if(ChannelXSPoints %% 2 == 0) k1 = k1[abs(k1) > 0] if(bankfullWidthMin > bankfullWidth) stop("Minimum bankfull width is greater than base bankfull width. Program exit.") print("Computing river properties...") for(i in seq(from=1, to=XResolution, by=1)) { increments = c(increments, i-1) xrads = c(xrads, (i-1)*dxr) xms = c(xms, (increments[i]/XResolution)*length) channelMeanders = c(channelMeanders, evaluateFunctions(Mc_functions, c(xrads[i], xms[i], increments[i]), "M")) if(i >= 2) { if(i == 2) dscms = c(dscms, sqrt((channelMeanders[i]-channelMeanders[i-1])**2 + (xms[i]-xms[i-1])**2)) dscms = c(dscms, sqrt((channelMeanders[i]-channelMeanders[i-1])**2 + (xms[i]-xms[i-1])**2)) scms = c(scms, scms[i-1] + dscms[i]) } scms_r = c(scms_r, 2*pi*scms[i]/length) yRightWaves = c(yRightWaves, evaluateFunctions(RightFP_functions, c(xrads[i], xms[i], increments[i]), "R")) yLeftWaves = c(yLeftWaves, evaluateFunctions(LeftFP_functions, c(xrads[i], xms[i], increments[i]), "L")) wbf_pfs = c(wbf_pfs, evaluateFunctions(Wbf_functions, c(scms_r[i], xms[i], increments[i]), "W")) if(wbf_pfs[i]*bankfullWidth+bankfullWidth >= bankfullWidthMin) bankfullWidths = c(bankfullWidths, wbf_pfs[i]*bankfullWidth + bankfullWidth) else bankfullWidths = c(bankfullWidths, bankfullWidthMin) bankfullWidths_L = c(bankfullWidths_L, -bankfullWidths[i]/2) bankfullWidths_R = c(bankfullWidths_R, bankfullWidths[i]/2) centerlineCurvature_pfs = c(centerlineCurvature_pfs, evaluateFunctions(Cs_functions, c(scms_r[i], xms[i], increments[i]), "E")) if(XS_shape == crossSectionalShapes[2]) { firstDerivatives[i] = as.double(Cs_functions[2,2])*cos(as.double(Cs_functions[2,3])*scms_r[i] + as.double(Cs_functions[2,4])) secondDerivatives[i] = as.double(Cs_functions[2,2])*(-sin(as.double(Cs_functions[2,3])*scms_r[i] + as.double(Cs_functions[2,4]))) } if(i == 1) { centerlineCurvatures = c(centerlineCurvatures, centerlineCurvature_pfs[i]) } else { if(length(dxcmds) == 0) dxcmds = c(dxcmds, (xms[i]-xms[i-1])/dscms[i-1]) if(length(dycmds) == 0) dycmds = c(dycmds, (channelMeanders[i]-channelMeanders[i-1])/dscms[i-1]) dxcmds = c(dxcmds, (xms[i]-xms[i-1])/dscms[i]) dycmds = c(dycmds, (channelMeanders[i]-channelMeanders[i-1])/dscms[i]) centerlineCurvatures = c(centerlineCurvatures, centerlineCurvature_pfs[i]+secondDerivatives[i]/((1 + (firstDerivatives[i])**2)**(3/2))) } } maxCenterlineCurvature = abs(centerlineCurvatures)[which.max(abs(centerlineCurvatures))]*1.2 disturbedAmp = 110*pi/180 disturbedMeander = scms[length(scms)] ds = 1 for(i in seq(from=1, to=XResolution, by=1)) { if(centerlineCurvatures[i] < 0) b_s = c(b_s, (0.5*(1-((abs(centerlineCurvatures[i]))/maxCenterlineCurvature)))) else if(centerlineCurvatures[i] > 0) b_s = c(b_s, (0.5*(1+((centerlineCurvatures[i])/maxCenterlineCurvature)))) else if(centerlineCurvatures[i] == 0) b_s = c(b_s, 0.5) if(centerlineCurvatures[i] < 0) k_s = c(k_s, (-log(2)/log(b_s[i]))) else k_s = c(k_s, (-log(2)/log(1-b_s[i]))) disturbedThetas = c(disturbedThetas, disturbedAmp*sin(2*pi*scms[i]/disturbedMeander)) if(i != 1) { disturbedDx = c(disturbedDx, ds*cos(disturbedThetas[i])) disturbedDy = c(disturbedDy, ds*sin(disturbedThetas[i])) disturbedX = c(disturbedX, disturbedX[i-1]+disturbedDx[i]) disturbedY = c(disturbedY, disturbedY[i-1]+disturbedDy[i]) } } sinuosity = scms[length(scms)]/xms[length(xms)] channelSlope = ((XResolution*sum(scms*centerlineCurvatures)-sum(scms)*sum(centerlineCurvatures))/ (XResolution*sum(scms**2)-(sum(scms))**2)) + (valleySlope/sinuosity) channelIntercept = ((sum(centerlineCurvatures)*sum((scms**2))-sum(scms)*sum(scms*centerlineCurvatures))/ (XResolution*sum(scms**2)-(sum(scms))**2)) disturbedY = (disturbedY - disturbedY[which.max(disturbedY)]/2) if(!userDefinedDepth) bankfullDepth = (165*medianSedimentSize*criticalShieldsStress)/channelSlope widthToDepthRatio = bankfullWidth/bankfullDepth Wbf_a1 = as.double(Wbf_functions[2,2]) Zt_a1 = as.double(Zt_functions[2,2]) Zt_f1 = as.double(Zt_functions[2,3]) wr = bankfullWidth*Wbf_a1+bankfullWidth wp = -bankfullWidth*Wbf_a1+bankfullWidth hres = 2*bankfullDepth*Zt_a1-(pi*bankfullWidth*valleySlope/Zt_f1) hr = hres/((wr/wp)-1) for(i in seq(from=1, to=XResolution, by=1)) { thalwegs = c(thalwegs, (bankfullDepth*(evaluateFunctions(Zt_functions, c(scms_r[i], xms[i], increments[i]), "T") + bankfullDepth)) + scms[i]*channelSlope + datum) if(i == 1) thalwegsNoSlope = c(thalwegsNoSlope, thalwegs[i]) else thalwegsNoSlope = c(thalwegsNoSlope, thalwegs[i]-(scms[i]-scms[1])*channelSlope) } for(i in seq(from=1, to=XResolution, by=1)) { if(i == 1) topsofBank = c(topsofBank, thalwegsNoSlope[which.max(thalwegsNoSlope)] + bankfullDepth) else topsofBank = c(topsofBank, topsofBank[i-1]+(scms[i]-scms[i-1])*valleySlope) bankfullDepths = c(bankfullDepths, topsofBank[i] - thalwegs[i]) for(j in seq(from=1, to=ChannelXSPoints, by=1)) { n_xs[i,j] = k1[j]*bankfullWidths[i]/2 bankPoints[i,j] = channelMeanders[i] + n_xs[i,j]*dxcmds[i] xShifts[i,j] = xms[i] - n_xs[i,j]*dycmds[i] h_n[i,j] = crossSection(XS_shape, i, j) } } maxLength = which(bankPoints == max(bankPoints), arr.ind = TRUE) minLength = which(bankPoints == min(bankPoints), arr.ind = TRUE) maxRow = maxLength[1,1] maxCol = maxLength[1,2] minRow = minLength[1,1] minCol = minLength[1,2] maxRightBank = bankPoints[maxRow, maxCol] minLeftBank = bankPoints[minRow, minCol] maxRightToe = yRightWaves[which.max(yRightWaves)] minLeftToe = yLeftWaves[which.min(yLeftWaves)] minRightToe = yRightWaves[which.min(yRightWaves)] maxLeftToe = yLeftWaves[which.max(yLeftWaves)] for(i in seq(from=1, to=XResolution, by=1)) { yRightToe = c(yRightToe, yRightWaves[i] + FPWidth/2 + maxRightBank - minRightToe) yLeftToe = c(yLeftToe, -yLeftWaves[i] - FPWidth/2 + minLeftBank + minLeftToe) zRightToe = c(zRightToe, topsofBank[i] + outerFPEdgeHeight) zLeftToe = c(zLeftToe, zRightToe[i]) yRightTop = c(yRightTop, yRightToe[i] + terraceWidth/2) yLeftTop = c(yLeftTop, yLeftToe[i] - terraceWidth/2) zRightTop = c(zRightTop, zRightToe[i] + outerTerraceEdgeHeight) zLeftTop = c(zLeftTop, zRightTop[i]) standardizedDepth = standardize(bankfullDepths[i], mean(bankfullDepths), sd(bankfullDepths)) standardizedWidth = standardize(bankfullWidths[i], mean(bankfullWidths), sd(bankfullWidths)) Wbf_stds = c(Wbf_stds, standardizedWidth) Zt_stds = c(Zt_stds, standardize(thalwegsNoSlope[i], mean(thalwegsNoSlope), sd(thalwegsNoSlope))) CV_WZ = c(CV_WZ, Wbf_stds[i]*Zt_stds[i]) CV_ZC = c(CV_ZC, Zt_stds[i]*standardize(centerlineCurvatures[i], mean(centerlineCurvatures), sd(centerlineCurvatures))) currentGCS = standardizedDepth*standardizedWidth if(currentGCS > 0) positiveGCS = positiveGCS + 1 else if(currentGCS < 0) negativeGCS = negativeGCS + 1 } if(positiveGCS != 0 || negativeGCS != 0) { negPercentGCS = 100*negativeGCS/(negativeGCS+positiveGCS) posPercentGCS = 100*positiveGCS/(negativeGCS+positiveGCS) } print("Computations complete.") Graph_yRightTop = c(round(yRightToe[XResolution/2], digits=3), round(yRightTop[XResolution/2], digits=3)) Graph_zRightTop = c(round(zRightToe[XResolution/2], digits=3), round(zRightTop[XResolution/2], digits=3)) Graph_yLeftTop = c(round(yLeftToe[XResolution/2], digits=3), round(yLeftTop[XResolution/2], digits=3)) Graph_zLeftTop = c(round(zLeftToe[XResolution/2], digits=3), round(zLeftTop[XResolution/2], digits=3)) Graph_yRightToe = c(round(n_xs[XResolution/2, ChannelXSPoints], digits=3), round(yRightToe[XResolution/2], digits=3)) Graph_zRightToe = c(round(h_n[XResolution/2, ChannelXSPoints], digits=3), round(zRightToe[XResolution/2], digits=3)) Graph_yLeftToe = c(round(n_xs[XResolution/2, 1], digits=3), round(yLeftToe[XResolution/2], digits=3)) Graph_zLeftToe = c(round(h_n[XResolution/2, 1], digits=3), round(zLeftToe[XResolution/2], digits=3)) Graph_yRightBoundary = c(round(yRightTop[XResolution/2], digits=3), round(yRightTop[XResolution/2]+boundaryWidth, digits=3)) Graph_zRightBoundary = c(round(zRightTop[XResolution/2], digits=3), round(zRightTop[XResolution/2], digits=3)) Graph_yLeftBoundary = c(round(yLeftTop[XResolution/2], digits=3), round(yLeftTop[XResolution/2]-boundaryWidth, digits=3)) Graph_zLeftBoundary = c(round(zLeftTop[XResolution/2], digits=3), round(zLeftTop[XResolution/2], digits=3)) png(filename=file.path(directory, file_outputs[1]), 10, 7.5, "in", res=100) plot(main = "Centerline Curvature", round(scms, digits=3), round(centerlineCurvatures, digits=3), ylim = range(centerlineCurvatures[which.min(centerlineCurvatures)]-0.05,centerlineCurvatures[which.max(centerlineCurvatures)]+0.05), col = "darkblue", xlab = "S (meters)", ylab = "Elevation (meters)", cex = 0.75) lines(round(scms, digits=3), round(centerlineCurvatures, digits=3), col = "darkblue") dev.off() print(paste(file_outputs[1], "generated.")) png(filename=file.path(directory, file_outputs[2]), 10, 7.5, "in", res=100) plot(main = "Valley Section", round(n_xs[XResolution/2,], digits=3), round(h_n[XResolution/2,], digits=3), xlim = range(yLeftTop[which.min(yLeftTop)]-boundaryWidth, yRightTop[which.max(yRightTop)]+boundaryWidth), ylim = range(h_n[XResolution/2,which.min(h_n[XResolution/2,])], zRightTop[which.max(zRightTop)]), col = "darkblue", xlab = "Y (meters)", ylab = "Elevation (meters)", cex = 0.75) lines(round(n_xs[XResolution/2,], digits=3), round(h_n[XResolution/2,], digits=3), col = "darkblue", lwd = 4) points(yRightToe[XResolution/2], zRightToe[XResolution/2], col = "chocolate4") lines(Graph_yRightToe, Graph_zRightToe, col = "chocolate4", lwd = 4) points(yLeftToe[XResolution/2], zLeftToe[XResolution/2], col = "chocolate4") lines(Graph_yLeftToe, Graph_zLeftToe, col = "chocolate4", lwd = 4) points(yRightTop[XResolution/2], zRightTop[XResolution/2], col = "black") lines(Graph_yRightTop, Graph_zRightTop, col = "black", lwd = 4) points(yLeftTop[XResolution/2], zLeftTop[XResolution/2], col = "black") lines(Graph_yLeftTop, Graph_zLeftTop, col = "black", lwd = 4) points(yRightTop[XResolution/2]+boundaryWidth, zRightTop[XResolution/2], col = "darkorchid4") lines(Graph_yRightBoundary, Graph_zRightBoundary, col = "darkorchid4", lwd = 4) points(yLeftTop[XResolution/2]-boundaryWidth, zLeftTop[XResolution/2], col = "darkorchid4") lines(Graph_yLeftBoundary, Graph_zLeftBoundary, col = "darkorchid4", lwd = 4) par(xpd = TRUE) legend("topright", inset = c(0, -0.13), c("Boundaries", "Terrace", "Floodplain", "Channel"), lty = c(1,1,1,1), lwd = c(4,4,4,4), col = c("darkorchid4", "black", "chocolate4", "darkblue"), cex = 0.75) dev.off() print(paste(file_outputs[2], "generated.")) png(filename=file.path(directory, file_outputs[3]), 10, 7.5, "in", res=100) plot(main = "Geometric Covariance Structures", round(xms, digits=3), round(CV_WZ, digits=3), ylim = range(min(CV_WZ[which.min(CV_WZ)]-0.5, CV_ZC[which.min(CV_ZC)]-0.5),max(CV_WZ[which.max(CV_WZ)]+0.5, CV_ZC[which.max(CV_ZC)]+0.5)), col = "forestgreen", xlab = "X (meters)", ylab = "Geometric Covariance", cex = 0.75) lines(round(xms, digits=3), round(CV_WZ, digits=3), col = "forestgreen") par(new = TRUE) plot(round(xms, digits=3), round(CV_ZC, digits=3), ylim = range(min(CV_WZ[which.min(CV_WZ)]-0.5, CV_ZC[which.min(CV_ZC)]-0.5),max(CV_WZ[which.max(CV_WZ)]+0.5, CV_ZC[which.max(CV_ZC)]+0.5)), col = "darkred", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(CV_ZC, digits=3), col = "darkred") par(xpd = TRUE) legend("topright", inset = c(0, -0.11), c("C(Wbf*Zt)", "C(Zt*Cs)"), lty = c(1,1), lwd = c(4,4), col = c("forestgreen", "darkred"), cex = 1) dev.off() print(paste(file_outputs[3], "generated.")) png(filename=file.path(directory, file_outputs[4]), 10, 7.5, units = "in", res=100) plot(main = "Longitudinal Profile", round(xms, digits=3), round(zRightTop, digits=3), ylim = range(thalwegs[which.min(thalwegs)]-5,zRightTop[which.max(zRightTop)]+5), col = "black", xlab = "X (meters)", ylab = "Elevation (meters)", cex = 0.75) lines(round(xms, digits=3), round(zRightTop, digits=3), col = "black") par(new = TRUE) plot(round(xms, digits=3), round(zRightToe, digits=3), ylim = range(thalwegs[which.min(thalwegs)]-5,zRightTop[which.max(zRightTop)]+5), col = "chocolate4", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(zRightToe, digits=3), col = "chocolate4") par(new = TRUE) plot(round(xms, digits=3), round(topsofBank, digits=3), ylim = range(thalwegs[which.min(thalwegs)]-5,zRightTop[which.max(zRightTop)]+5), col = "chartreuse4", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(topsofBank, digits=3), col = "chartreuse4") par(new = TRUE) plot(round(xms, digits=3), round(thalwegs, digits=3), ylim = range(thalwegs[which.min(thalwegs)]-5,zRightTop[which.max(zRightTop)]+5), col = "dimgray", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(thalwegs, digits=3), col = "dimgray") par(xpd = TRUE) legend("topright", inset = c(0, -0.13), c("Valley Top", "Valley Floor", "Bank Top", "Thalweg Elevation"), lty = c(1,1,1,1), lwd = c(4,4,4,4), col = c("black", "chocolate4", "chartreuse4", "dimgray"), cex = 0.75) dev.off() print(paste(file_outputs[4], "generated.")) png(filename=file.path(directory, file_outputs[5]), 10, 7.5, units = "in", res=100) plot(main = "Planform", round(xms, digits=3), round(channelMeanders, digits=3), ylim = range((yLeftTop[which.min(yLeftTop)]-5),(yRightTop[which.max(yRightTop)]+5)), col = "darkblue", xlab = "X (meters)", ylab = "Y (meters)", cex = 0.75) lines(round(xms, digits=3), round(channelMeanders, digits=3), col = "darkblue") par(new = TRUE) plot(round(xms, digits=3), round(bankPoints[,ChannelXSPoints], digits=3), ylim = range((yLeftTop[which.min(yLeftTop)]-5),(yRightTop[which.max(yRightTop)]+5)), col = "chartreuse4", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(bankPoints[,ChannelXSPoints], digits=3), col = "chartreuse4") par(new = TRUE) plot(round(xms, digits=3), round(bankPoints[,1], digits=3), ylim = range((yLeftTop[which.min(yLeftTop)]-5),(yRightTop[which.max(yRightTop)]+5)), col = "chartreuse4", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(bankPoints[,1], digits=3), col = "chartreuse4") par(new = TRUE) plot(round(xms, digits=3), round(yRightToe, digits=3), ylim = range((yLeftTop[which.min(yLeftTop)]-5),(yRightTop[which.max(yRightTop)]+5)), col = "chocolate4", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(yRightToe, digits=3), col = "chocolate4") par(new = TRUE) plot(round(xms, digits=3), round(yLeftToe, digits=3), ylim = range((yLeftTop[which.min(yLeftTop)]-5),(yRightTop[which.max(yRightTop)]+5)), col = "chocolate4", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(yLeftToe, digits=3), col = "chocolate4") par(new = TRUE) plot(round(xms, digits=3), round(yRightTop, digits=3), ylim = range((yLeftTop[which.min(yLeftTop)]-5),(yRightTop[which.max(yRightTop)]+5)), col = "black", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(yRightTop, digits=3), col = "black") par(new = TRUE) plot(round(xms, digits=3), round(yLeftTop, digits=3), ylim = range((yLeftTop[which.min(yLeftTop)]-5),(yRightTop[which.max(yRightTop)]+5)), col = "black", axes = FALSE, xlab = "", ylab = "", cex = 0.75) lines(round(xms, digits=3), round(yLeftTop, digits=3), col = "black") par(xpd = TRUE) legend("topright", inset = c(0, -0.13), c("Channel Meander", "Channel Banks", "Valley Floors", "Valley Tops"), lty = c(1,1,1,1), lwd = c(4,4,4,4), col = c("darkblue", "chartreuse4", "chocolate4", "black"), cex = 0.75) dev.off() print(paste(file_outputs[5], "generated.")) values = data.frame(matrix(nrow=17, ncol=1), stringsAsFactors=FALSE) values[1,1] = XResolution*(ChannelXSPoints+2) values[2,1] = XResolution*ChannelXSPoints values[3,1] = XResolution*(ChannelXSPoints+5) values[4,1] = XResolution*(ChannelXSPoints-1) values[5,1] = 0 values[6,1] = XResolution*(ChannelXSPoints+4) values[7,1] = XResolution*(ChannelXSPoints+1) values[8,1] = XResolution*(ChannelXSPoints+3) values[9,1] = XResolution*(ChannelXSPoints+4)-1 values[10,1] = XResolution*(ChannelXSPoints+2)-1 values[11,1] = XResolution*(ChannelXSPoints+5)-1 values[12,1] = XResolution-1 values[13,1] = XResolution*ChannelXSPoints-1 values[14,1] = XResolution*(ChannelXSPoints+6)-1 values[15,1] = XResolution*(ChannelXSPoints+1)-1 values[16,1] = XResolution*(ChannelXSPoints+3)-1 values[17,1] = XResolution*(ChannelXSPoints+2) write.table(values, file = file.path(directory, file_outputs[6]), append = FALSE, row.names = FALSE, col.names = FALSE, quote = FALSE) print(paste(file_outputs[6], "generated.")) values = data.frame(matrix(nrow=14, ncol=1), stringsAsFactors=FALSE) rownames(values) = c("Coefficient of Variation (Wbf):", "Standard Deviation (Wbf):", "Average (Wbf):", "Coefficient of Variation (Hbf):", "Standard Deviation (Hbf):", "Average (Hbf):", "wr:", "wp:", "hres:", "hr:", "GCS (-):", "GCS (+):", "Sinuosity:", "Channel Slope:") values[1,1] = c(round(sd(bankfullWidths)/mean(bankfullWidths), digits=3)) values[2,1] = c(round(sd(bankfullWidths), digits=3)) values[3,1] = c(round(mean(bankfullWidths), digits=3)) values[4,1] = c(round(sd(bankfullDepths)/mean(bankfullDepths), digits=3)) values[5,1] = c(round(sd(bankfullDepths), digits=3)) values[6,1] = c(round(mean(bankfullDepths), digits=3)) values[7,1] = c(round(wr, digits=3)) values[8,1] = c(round(wp, digits=3)) values[9,1] = c(round(hres, digits=3)) values[10,1] = c(round(hr, digits=3)) values[11,1] = c(paste(as.character(round(negPercentGCS, digits=3)), "%", sep="")) values[12,1] = c(paste(as.character(round(posPercentGCS, digits=3)), "%", sep="")) values[13,1] = c(round(sinuosity, digits=3)) values[14,1] = c(round(channelSlope, digits=5)) write.table(values, file = file.path(directory, file_outputs[7]), append = FALSE, col.names = FALSE, sep = "\t", quote = FALSE) print(paste(file_outputs[7], "generated.")) header1 = data.frame("X,Y,Z") header2 = data.frame("X,Y") header3 = data.frame("X,Z") header4 = data.frame("Y,Z") firstSet = data.frame(rbind(c(format(round(xShifts[1,1], 6), nsmall=6), format(round(bankPoints[1,1], 6), nsmall=6), format(round(h_n[1,1], 6), nsmall=6)))) points = data.frame() for(j in seq(from=1, to=ChannelXSPoints, by=1)) for(i in seq(from=1, to=XResolution, by=1)) if(i != 1 || j != 1) points = rbind(points, c(round(xShifts[i,j], digits=3), round(bankPoints[i,j], digits=3), round(h_n[i,j], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yRightTop[i], digits=3), round(zRightTop[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yLeftTop[i], digits=3), round(zLeftTop[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(boundaryWidth + yRightTop[which.max(yRightTop)], digits=3), round(zRightTop[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(-boundaryWidth - yRightTop[which.max(yRightTop)], digits=3), round(zRightTop[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yLeftToe[i], digits=3), round(zLeftToe[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yRightToe[i], digits=3), round(zRightToe[i], digits=3))) write.table(header1, file=file.path(directory, file_outputs[8]), row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) write.table(firstSet, file=file.path(directory, file_outputs[8]), row.names=FALSE, col.names=FALSE, quote=FALSE, sep=",", append=TRUE) write.table(points, file=file.path(directory, file_outputs[8]), row.names=FALSE, col.names=FALSE, sep= ",", append=TRUE) print(paste(file_outputs[8], "generated.")) points = data.frame() for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(scms[i], digits=3), round(centerlineCurvatures[i], digits=3))) write.table(header2, file=file.path(directory, file_outputs[9]), row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) write.table(points, file=file.path(directory, file_outputs[9]), row.names=FALSE, col.names=FALSE, sep= ",", append=TRUE) print(paste(file_outputs[9], "generated.")) points = data.frame() for(i in seq(from=1, to=ChannelXSPoints, by=1)) points = rbind(points, c(round(n_xs[XResolution/2,i], digits=3), round(h_n[XResolution/2,i], digits=3))) points = rbind(points, c(round(yRightTop[XResolution/2]+boundaryWidth, digits=3), round(zRightTop[XResolution/2], digits=3))) points = rbind(points, c(round(yLeftTop[XResolution/2]-boundaryWidth, digits=3), round(zLeftTop[XResolution/2], digits=3))) points = rbind(points, c(round(yRightTop[XResolution/2], digits=3), round(zRightTop[XResolution/2], digits=3))) points = rbind(points, c(round(yRightToe[XResolution/2], digits=3), round(zRightToe[XResolution/2], digits=3))) points = rbind(points, c(round(yLeftTop[XResolution/2], digits=3), round(zLeftTop[XResolution/2], digits=3))) points = rbind(points, c(round(yLeftToe[XResolution/2], digits=3), round(zLeftToe[XResolution/2], digits=3))) write.table(header4, file=file.path(directory, file_outputs[10]), row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) write.table(points, file=file.path(directory, file_outputs[10]), row.names=FALSE, col.names=FALSE, sep= ",", append=TRUE) print(paste(file_outputs[10], "generated.")) points = data.frame() for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(CV_WZ[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(CV_ZC[i], digits=3))) write.table(header2, file=file.path(directory, file_outputs[11]), row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) write.table(points, file=file.path(directory, file_outputs[11]), row.names=FALSE, col.names=FALSE, sep= ",", append=TRUE) print(paste(file_outputs[11], "generated.")) points = data.frame() for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(zRightTop[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(zRightToe[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(thalwegs[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(topsofBank[i], digits=3))) write.table(header3, file=file.path(directory, file_outputs[12]), row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) write.table(points, file=file.path(directory, file_outputs[12]), row.names=FALSE, col.names=FALSE, sep= ",", append=TRUE) print(paste(file_outputs[12], "generated.")) points = data.frame() for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(channelMeanders[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(bankPoints[i,ChannelXSPoints], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(bankPoints[i,1], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yRightTop[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yLeftTop[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yRightToe[i], digits=3))) for(i in seq(from=1, to=XResolution, by=1)) points = rbind(points, c(round(xms[i], digits=3), round(yLeftToe[i], digits=3))) write.table(header2, file=file.path(directory, file_outputs[13]), row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) write.table(points, file=file.path(directory, file_outputs[13]), row.names=FALSE, col.names=FALSE, sep= ",", append=TRUE) print(paste(file_outputs[13], "generated.")) print("Done.") }
expected <- eval(parse(text="structure(list(sec = 59.7693939208984, min = 47L, hour = 18L, mday = 17L, mon = 2L, year = 114L, wday = 1L, yday = 75L, isdst = 0L), .Names = c(\"sec\", \"min\", \"hour\", \"mday\", \"mon\", \"year\", \"wday\", \"yday\", \"isdst\"), class = c(\"POSIXlt\", \"POSIXt\"), tzone = \"GMT\")")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(sec = 59.7693939208984, min = 47L, hour = 18L, mday = 17L, mon = 2L, year = 114L, wday = 1L, yday = 75L, isdst = 0L), .Names = c(\"sec\", \"min\", \"hour\", \"mday\", \"mon\", \"year\", \"wday\", \"yday\", \"isdst\"), class = c(\"POSIXlt\", \"POSIXt\"), tzone = \"GMT\"))")); do.call(`invisible`, argv); }, o=expected);
simqOTOR <- function(temps, n0, Nn, Ah, An, ff, ae, hr, outfile=NULL, plot=TRUE) { UseMethod("simqOTOR") } simqOTOR.default <- function(temps, n0, Nn, Ah, An, ff, ae, hr, outfile=NULL, plot=TRUE) { stopifnot(is.numeric(temps), all(temps>0), length(n0)==1L, n0>0, length(Nn)==1L, is.numeric(Nn), Nn>0, Nn>=n0, length(Ah)==1L, is.numeric(Ah), Ah>0, length(An)==1L, is.numeric(An), An>0, length(ff)==1L, is.numeric(ff), ff>0, length(ae)==1L, is.numeric(ae), ae>0, length(hr)==1L, is.numeric(hr), hr>0, is.null(outfile) || is.character(outfile), length(plot)==1L, is.logical(plot)) if (!is.null(outfile)) { if (length(outfile)!=1L) stop("Error: outfile should be an one-element vector!") } nt <- length(temps) vecy <- double(nt) info <- -100 res <- .Fortran("qeOTOR", as.integer(nt), as.double(temps), as.double(n0), as.double(Nn), as.double(Ah), as.double(An), as.double(ff), as.double(ae), as.double(hr), vecy=as.double(vecy), info=as.integer(info), PACKAGE="tgcd") if(res$info!=2L) { stop("Error: fail in solving ordinary equation!") } kbz = 8.617385e-05 tout <- temps yout <- ff*(res$vecy)^2L*exp(-ae/kbz/temps)*Ah/ (Ah*res$vecy+An*(Nn-res$vecy))/hr calShape <- function(x, y) { ny <- length(y) maxloc <- which.max(y) hmaxval <- max(y)/2.0 Tm <- x[maxloc] T1 <- approx(x=y[1L:maxloc], y=x[1L:maxloc], xout=hmaxval)$y T2 <- approx(x=y[maxloc:ny], y=x[maxloc:ny], xout=hmaxval)$y d1 <- Tm-T1 d2 <- T2-Tm thw <- T2-T1 sf <- d2/thw return( c("T1"=T1, "T2"=T2, "Tm"=Tm, "d1"=d1, "d2"=d2, "thw"=thw, "sf"=sf) ) } sp <- try(calShape(tout, yout), silent=TRUE) if (plot==TRUE) { opar <- par("mfrow", "mar") on.exit(par(opar)) layout(cbind(c(rep(1,13), 2, rep(3,6)), c(rep(1,13), 2, rep(3,6)))) par(mar=c(0,5.1,3.1,1.1)) plot(tout, yout, type="l", lwd=5, col="skyblue3", ylab="TL Intensity (counts)", las=0, lab=c(7,7,9), xaxt="n", xaxs="r", yaxs="r", cex.lab=2.0, cex.axis=1.5) box(lwd=2L) XaxisCentral <- median(axTicks(side=1L)) if (class(sp)=="try-error") { legend(ifelse(tout[which.max(yout)] > XaxisCentral, "topleft", "topright"), legend=c(paste("n0: ", format(n0,digits=3,scientific=TRUE)," (1/cm^3)",sep=""), paste("ae: ",round(ae,2L)," (eV)",sep=""), paste("ff: ",format(ff,digits=3,scientific=TRUE)," (1/s)",sep=""), paste("hr: ",round(hr,2L)," (K/s)",sep=""), paste("Ah: ",format(Ah,digits=3,scientific=TRUE)," (cm^3/s)",sep=""), paste("An: ",format(An,digits=3,scientific=TRUE)," (cm^3/s)",sep="")), yjust=2, ncol=1, cex=2.0, bty="n", pt.bg="white") } else { legend(ifelse(tout[which.max(yout)] > XaxisCentral, "topleft", "topright"), legend=c(paste("n0: ", format(n0,digits=3,scientific=TRUE)," (1/cm^3)",sep=""), paste("ae: ",round(ae,2L)," (eV)",sep=""), paste("ff: ",format(ff,digits=3,scientific=TRUE)," (1/s)",sep=""), paste("hr: ",round(hr,2L)," (K/s)",sep=""), paste("Ah: ",format(Ah,digits=3,scientific=TRUE)," (cm^3/s)",sep=""), paste("An: ",format(An,digits=3,scientific=TRUE)," (cm^3/s)",sep=""), paste("sf: ",round(sp["sf"],2L),sep="")), yjust=2, ncol=1, cex=2.0, bty="n", pt.bg="white") } par(mar=c(0,5.1,0,1.1)) plot(c(0,0), type="n", xaxt="n", yaxt="n", xlab="n", ylab="") par(mar=c(5.1, 5.1, 0, 1.1)) plot(tout, res$vecy, type="l", xlab = "Temperature(K)", ylab="Concentration", las=0, lab=c(7,7,9), xaxs="r", yaxs="i", ylim=c(-0.1*n0, 1.1*n0), col="grey", lwd=5, cex.lab=2.0, cex.axis=1.5) box(lwd=2L) } if (class(sp)=="try-error") sp <- NULL if (!is.null(outfile)) { PeakSig <- cbind(tout, yout, res$vecy) colnames(PeakSig) <- c("temps","tl", "n") write.csv(PeakSig, file=paste(outfile, ".csv", sep="")) } return(invisible(list("temps"=tout, "tl"=yout, "n"=res$vecy, "sp"=sp))) }
epi.ssstrataestb <- function (strata.n, strata.Py, epsilon, error = "relative", nfractional = FALSE, conf.level = 0.95) { N. <- 1 - ((1 - conf.level) / 2) z <- qnorm(N., mean = 0, sd = 1) epsilon.r <- ifelse(error == "relative", epsilon, epsilon / strata.Py) N <- sum(strata.n) mean <- sum(strata.n * strata.Py) / N strata.var = (strata.Py * (1 - strata.Py)) phi <- (strata.n * sqrt(strata.var)) / sum(strata.n * sqrt(strata.var)) sigma.bx <- sum((strata.n^2 * strata.var) / ((phi) * (mean^2))) sigma.bxd <- sum((strata.n * strata.var) / mean^2) if(nfractional == TRUE){ total.sample <- ((z^2/N^2) * sigma.bx) / ((epsilon.r^2) + ((z^2/N^2) * sigma.bxd)) strata.sample <- strata.n * (total.sample / N) } if(nfractional == FALSE){ total.sample <- ceiling(((z^2/N^2) * sigma.bx) / ((epsilon.r^2) + ((z^2/N^2) * sigma.bxd))) strata.sample <- ceiling(strata.n * (total.sample / N)) } result.01 <- c(strata.sample) result.02 <- c(total.sample) result.03 <- cbind(mean = mean, sigma.bx = sigma.bx, sigma.bxd = sigma.bxd, phi = phi) rval <- list(strata.sample = result.01, total.sample = result.02, stats = result.03) return(rval) }
npudist <- function(bws, ...){ args <- list(...) if (!missing(bws)){ if (is.recursive(bws)){ if (!is.null(bws$formula) && is.null(args$tdat)) UseMethod("npudist",bws$formula) else if (!is.null(bws$call) && is.null(args$tdat)) UseMethod("npudist",bws$call) else if (!is.call(bws)) UseMethod("npudist",bws) else UseMethod("npudist",NULL) } else { UseMethod("npudist", NULL) } } else { UseMethod("npudist", NULL) } } npudist.formula <- function(bws, data = NULL, newdata = NULL, ...){ tt <- terms(bws) m <- match(c("formula", "data", "subset", "na.action"), names(bws$call), nomatch = 0) tmf <- bws$call[c(1,m)] tmf[[1]] <- as.name("model.frame") tmf[["formula"]] <- tt umf <- tmf <- eval(tmf, envir = environment(tt)) tdat <- tmf[, attr(attr(tmf, "terms"),"term.labels"), drop = FALSE] if ((has.eval <- !is.null(newdata))) { umf <- emf <- model.frame(tt, data = newdata) edat <- emf[, attr(attr(emf, "terms"),"term.labels"), drop = FALSE] } ev <- eval(parse(text=paste("npudist(tdat = tdat,", ifelse(has.eval,"edat = edat,",""), "bws = bws, ...)"))) ev$omit <- attr(umf,"na.action") ev$rows.omit <- as.vector(ev$omit) ev$nobs.omit <- length(ev$rows.omit) ev$dist <- napredict(ev$omit, ev$dist) ev$derr <- napredict(ev$omit, ev$derr) return(ev) } npudist.call <- function(bws, ...) { npudist(tdat = eval(bws$call[["dat"]], environment(bws$call)), bws = bws, ...) } npudist.dbandwidth <- function(bws, tdat = stop("invoked without training data 'tdat'"), edat, ...){ no.e = missing(edat) tdat = toFrame(tdat) if (!no.e) edat = toFrame(edat) if (!(no.e || tdat %~% edat )) stop("tdat and edat are not similar data frames!") if (length(bws$bw) != length(tdat)) stop("length of bandwidth vector does not match number of columns of 'tdat'") ccon = unlist(lapply(as.data.frame(tdat[,bws$icon]),class)) if ((any(bws$icon) && !all((ccon == class(integer(0))) | (ccon == class(numeric(0))))) || (any(bws$iord) && !all(unlist(lapply(as.data.frame(tdat[,bws$iord]),class)) == class(ordered(0)))) || (any(bws$iuno) && !all(unlist(lapply(as.data.frame(tdat[,bws$iuno]),class)) == class(factor(0))))) stop("supplied bandwidths do not match 'tdat' in type") tdat = na.omit(tdat) rows.omit <- unclass(na.action(tdat)) if (!no.e){ edat = na.omit(edat) rows.omit <- unclass(na.action(edat)) } tnrow = nrow(tdat) enrow = ifelse(no.e,tnrow,nrow(edat)) tdat <- adjustLevels(tdat, bws$xdati) if (!no.e) edat <- adjustLevels(edat, bws$xdati, allowNewCells = TRUE) if(no.e) teval <- tdat else teval <- edat tdat = toMatrix(tdat) tuno = tdat[, bws$iuno, drop = FALSE] tcon = tdat[, bws$icon, drop = FALSE] tord = tdat[, bws$iord, drop = FALSE] if (!no.e){ edat = toMatrix(edat) euno = edat[, bws$iuno, drop = FALSE] econ = edat[, bws$icon, drop = FALSE] eord = edat[, bws$iord, drop = FALSE] } else { euno = data.frame() eord = data.frame() econ = data.frame() } myopti = list( num_obs_train = tnrow, num_obs_eval = enrow, num_uno = bws$nuno, num_ord = bws$nord, num_con = bws$ncon, int_LARGE_SF = ifelse(bws$scaling, SF_NORMAL, SF_ARB), BANDWIDTH_den_extern = switch(bws$type, fixed = BW_FIXED, generalized_nn = BW_GEN_NN, adaptive_nn = BW_ADAP_NN), int_MINIMIZE_IO=ifelse(options('np.messages'), IO_MIN_FALSE, IO_MIN_TRUE), ckerneval = switch(bws$ckertype, gaussian = CKER_GAUSS + bws$ckerorder/2 - 1, epanechnikov = CKER_EPAN + bws$ckerorder/2 - 1, uniform = CKER_UNI, "truncated gaussian" = CKER_TGAUSS), ukerneval = switch(bws$ukertype, aitchisonaitken = UKER_AIT, liracine = UKER_LR), okerneval = switch(bws$okertype, wangvanryzin = OKER_WANG, liracine = OKER_NLR), no.e = no.e, mcv.numRow = attr(bws$xmcv, "num.row"), densOrDist = NP_DO_DIST, old.dist = FALSE, int_do_tree = ifelse(options('np.tree'), DO_TREE_YES, DO_TREE_NO)) myout= .C("np_density", as.double(tuno), as.double(tord), as.double(tcon), as.double(euno), as.double(eord), as.double(econ), as.double(c(bws$bw[bws$icon],bws$bw[bws$iuno],bws$bw[bws$iord])), as.double(bws$xmcv), as.double(attr(bws$xmcv, "pad.num")), as.double(bws$nconfac), as.double(bws$ncatfac), as.double(bws$sdev), as.integer(myopti), dist = double(enrow), derr = double(enrow), log_likelihood = double(1), PACKAGE="np" )[c("dist","derr", "log_likelihood")] ev <- npdistribution(bws=bws, eval=teval, dist = myout$dist, derr = myout$derr, ntrain = tnrow, trainiseval = no.e, rows.omit = rows.omit) return(ev) } npudist.default <- function(bws, tdat, ...){ sc <- sys.call() sc.names <- names(sc) bws.named <- any(sc.names == "bws") tdat.named <- any(sc.names == "tdat") no.bws <- missing(bws) no.tdat <- missing(tdat) if(tdat.named) tdat <- toFrame(tdat) sc.bw <- sc sc.bw[[1]] <- quote(npudistbw) if(bws.named){ sc.bw$bandwidth.compute <- FALSE } ostxy <- c('tdat') nstxy <- c('dat') m.txy <- match(ostxy, names(sc.bw), nomatch = 0) if(any(m.txy > 0)) { names(sc.bw)[m.txy] <- nstxy[m.txy > 0] } tbw <- eval.parent(sc.bw) eval(parse(text=paste("npudist(bws = tbw", ifelse(no.tdat, "", ifelse(tdat.named, ",tdat = tdat",",tdat")), ",...)"))) }
`weighted.median` <- function(y, w) { ox <- order(y) y <- y[ox] w <-w[ox] k <- 1 low <- cumsum(c(0,w)) up <- sum(w)-low df <- low-up repeat { if (df[k] < 0) k<-k+1 else if (df[k] == 0) return((w[k]*y[k]+w[k-1]*y[k-1])/(w[k]+w[k-1])) else return(y[k-1]) } }
mat_pw_gst <- function(x, pop_names = NULL){ if (inherits(x, "genind")){ tmp <- tempfile(fileext = ".txt") genind_to_genepop(x, output = tmp) mat_gst <- diveRsity::diffCalc(infile = tmp, outfile = NULL, fst = TRUE, pairwise = TRUE) mat_gst <- mat_gst$pairwise$Gst pop_names <- x@pop[order(as.character(x@pop))] pop_names <- as.character(pop_names[-which(duplicated(pop_names))]) row.names(mat_gst) <- colnames(mat_gst) <- pop_names } else if (inherits(x, "character")){ mat_gst <- diveRsity::diffCalc(infile = x, outfile = NULL, fst = TRUE, pairwise = TRUE) mat_gst <- mat_gst$pairwise$Gst if (is.vector(pop_names)){ if(length(pop_names) != nrow(mat_gst)){ stop(paste("'pop_names' must have ", length(row.names(mat_gst)), " elements, it has ", length(pop_names),sep="")) } if(any(duplicated(pop_names))){ stop("At least one population appears twice in 'pop_names'.") } } row.names(mat_gst) <- colnames(mat_gst) <- pop_names } else { stop("Input value x must be either a 'genind' object or a character string.") } makeSymm <- function(m) { m[upper.tri(m)] <- t(m)[upper.tri(m)] return(m) } if(all(row.names(mat_gst) == colnames(mat_gst))){ mat_gst <- makeSymm(mat_gst) } else { stop("An error occured while making the matrix symmetric.") } diag(mat_gst) <- rep(0, length(diag(mat_gst))) mat_gst[mat_gst < 0] <- 0 return(mat_gst) }
targets::tar_test("tar_jags_rep_dic()", { skip_if_not_installed("rjags") skip_if_not_installed("R2jags") skip_on_cran() skip_if_not_installed("dplyr") tar_jags_example_file(path = "a.jags") tar_jags_example_file(path = "b.jags") targets::tar_script({ list( tar_jags_rep_dic( model, jags_files = c(x = "a.jags", y = "b.jags"), data = tar_jags_example_data(), parameters.to.save = "beta", stdout = R.utils::nullfile(), stderr = R.utils::nullfile(), refresh = 0, n.iter = 2e3, n.burnin = 1e3, n.thin = 1, n.chains = 4, batches = 2, reps = 2, combine = TRUE ) ) }) out <- targets::tar_manifest(callr_function = NULL) expect_equal(nrow(out), 9L) out <- targets::tar_network(callr_function = NULL, targets_only = TRUE)$edges out <- dplyr::arrange(out, from, to) rownames(out) <- NULL exp <- tibble::tribble( ~from, ~to, "model_data", "model_x", "model_file_x", "model_lines_x", "model_lines_x", "model_x", "model_batch", "model_data", "model_data", "model_y", "model_lines_y", "model_y", "model_file_y", "model_lines_y", "model_x", "model", "model_y", "model" ) exp <- dplyr::arrange(exp, from, to) rownames(exp) <- NULL expect_equal(out, exp) capture.output(suppressWarnings(targets::tar_make(callr_function = NULL))) meta <- tar_meta(starts_with("model_data_")) expect_equal(nrow(meta), 2L) expect_equal(targets::tar_read(model_file_x), "a.jags") expect_equal(targets::tar_read(model_file_y), "b.jags") out <- targets::tar_read(model_data) expect_equal(length(out), 2L) out <- out[[2]] expect_equal(length(out), 2L) out <- out[[2]] expect_true(is.list(out)) expect_equal(length(out), 4L) expect_equal(out$n, 10L) expect_equal(length(out$x), 10L) expect_equal(length(out$y), 10L) expect_true(is.numeric(out$x)) expect_true(is.numeric(out$y)) out1 <- targets::tar_read(model_x) out2 <- targets::tar_read(model_y) out <- targets::tar_read(model) expect_true("dic" %in% colnames(out)) expect_equal(sort(unique(out$.file)), sort(unique(c("a.jags", "b.jags")))) expect_equal(sort(unique(out$.name)), sort(unique(c("x", "y")))) expect_equal(dplyr::bind_rows(out1, out2), out) expect_true(tibble::is_tibble(out1)) expect_true(tibble::is_tibble(out2)) expect_equal(length(unique(table(out1$.rep))), 1L) expect_equal(length(unique(table(out2$.rep))), 1L) expect_equal(length(table(out1$.rep)), 4L) expect_equal(length(table(out2$.rep)), 4L) expect_equal(nrow(out1), 4L) expect_equal(nrow(out2), 4L) expect_equal(targets::tar_outdated(callr_function = NULL), character(0)) write("", file = "b.jags", append = TRUE) out <- targets::tar_outdated(callr_function = NULL) exp <- c("model_file_y", "model_lines_y", "model_y", "model") expect_equal(sort(out), sort(exp)) targets::tar_script({ list( tar_jags_rep_dic( model, jags_files = c(x = "a.jags", y = "b.jags"), data = c(tar_jags_example_data()), parameters.to.save = "beta", stdout = R.utils::nullfile(), stderr = R.utils::nullfile(), refresh = 0, n.iter = 2e3, n.burnin = 1e3, n.thin = 1, n.chains = 4, batches = 2, reps = 2, combine = TRUE ) ) }) out <- targets::tar_outdated(callr_function = NULL) exp <- c( "model_file_y", "model_lines_y", "model_y", "model", "model_x", "model_data" ) expect_equal(sort(out), sort(exp)) }) targets::tar_test("tar_jags_rep_dic() errors correctly if no JAGS file", { skip_if_not_installed("rjags") skip_if_not_installed("R2jags") expect_error( tar_jags_rep_dic( model, jags_files = c(x = "a.jags", y = "b.jags"), data = c(tar_jags_example_data()), parameters.to.save = "beta", stdout = R.utils::nullfile(), stderr = R.utils::nullfile(), refresh = 0, n.iter = 2e3, n.burnin = 1e3, n.thin = 1, n.chains = 4, batches = 2, reps = 2, combine = TRUE ), class = "tar_condition_validate" ) })
SamplerUnif = R6Class("SamplerUnif", inherit = SamplerHierarchical, public = list( initialize = function(param_set) { assert_param_set(param_set, must_bounded = TRUE, no_deps = FALSE, no_untyped = TRUE) samplers = lapply(param_set$params, Sampler1DUnif$new) super$initialize(param_set, samplers) } ) )
CorrHetSNSol <- function(Nres,SNres,CvCase,Conf,Xscld,Xmean,Xsd,XsdOutPrd,grouping,Mxt,lglikdif,limlnk2,OptCntrl,getvcov=TRUE,bordertol=1e-2,maxsk=0.99527) { GetvcovHetD <- function(Res) { HoMxtparnam <- paste("mu_",Xnames,"_",grplvls[1],sep="") for (g in 2:k) HoMxtparnam <- c(HoMxtparnam,paste("mu_",Xnames,"_",grplvls[g],sep="")) for (i in 1:p) HoMxtparnam <- c(HoMxtparnam,paste("Sigma_",Xnames[i],"_",Xnames[i:p],sep="")) HoMxtparnam <- c(HoMxtparnam,paste("gamma1_",Xnames,sep="")) npar <- SKnpar(Conf,p,p/2,Ngrps=k) grpModMat <- model.matrix(~ grouping) Gmat <- model.matrix(~ grplvls) InFData <- try( sn.infoMv( dp=list(beta=as.matrix(rbind(Res$ksi[1,],Res$beta2k)),Omega=Res$Omega,alpha=Res$alpha), y=Xscld, x=grpModMat ) ) if ( is.null(InFData) || class(InFData)[1] == "try-error" || is.null(InFData$asyvar.cp) ) { return( list(mleCPvcov=NULL,muEse=NULL,SigmaEse=NULL,gamma1Ese=NULL,status="Invalid") ) } if (Conf==1) { betavcov <- InFData$asyvar.cp nSpar <- p*(p+1)/2 } else { nparC1 <- (k+1)*p + p*(p+1)/2 parind <- c(1:(k*p),(k*p)+SigCind(Conf,p/2),(nparC1-p+1):nparC1) nSpar <- length(parind) - (k+1)*p betavcov <- Safepdsolve(InFData$info.cp[parind,parind],maxlnk2=limlnk2,scale=TRUE) } if ( !is.null(betavcov) ) { mleCPvcov <- matrix(nrow=npar,ncol=npar) muind <- 1:(p*k) nmugind <- NULL for (g in 1:k) nmugind <- c(nmugind,(0:(p-1))*k+g) Sind <- p*k + 1:nSpar gamma1ind <- p*k + nSpar + 1:p Sgamma1ind <- c(Sind,gamma1ind) M <- kronecker(diag(p),Gmat) mleCPvcov[muind,muind] <- (M %*% betavcov[muind,muind] %*% t(M))[nmugind,nmugind] mleCPvcov[muind,Sgamma1ind] <- (M %*% betavcov[muind,Sgamma1ind])[nmugind,] mleCPvcov[Sgamma1ind,muind] <- t(mleCPvcov[muind,Sgamma1ind]) mleCPvcov[Sgamma1ind,Sgamma1ind] <- betavcov[Sgamma1ind,Sgamma1ind] if (Conf==1) { rownames(mleCPvcov) <- colnames(mleCPvcov) <- HoMxtparnam } else { rownames(mleCPvcov) <- colnames(mleCPvcov) <- HoMxtparnam[parind] } } else { mleCPvcov <- NULL } if (is.null(mleCPvcov)) return( list(mleCPvcov=NULL,muEse=NULL,SigmaEse=NULL,gamma1Ese=NULL) ) mleCPvcov <- mleCPvcov * SNVCovscaling(Conf,p,Xsd,k=k) CPStderr <- sqrt(diag(mleCPvcov)) muEse <- matrix(CPStderr[1:(k*p)],nrow=k,ncol=p,byrow=TRUE) gammaind <- (npar-p+1):npar gamma1Ese <- CPStderr[gammaind] SigmaEse <- matrix(nrow=p,ncol=p) cnt <- k*p for (j1 in 1:p) for (j2 in j1:p) { if (FreePar(q,j1,j2,Conf)) { cnt <- cnt+1 SigmaEse[j1,j2] <- SigmaEse[j2,j1] <- CPStderr[cnt] } } names(gamma1Ese) <- rownames(SigmaEse) <- colnames(SigmaEse) <- Xnames rownames(muEse) <- grplvls colnames(muEse) <- Xnames list(mleCPvcov=mleCPvcov,muEse=muEse,SigmaEse=SigmaEse,gamma1Ese=gamma1Ese,status="Regular") } GetvcovSingD <- function(Res) { SngDparnam <- paste("mu_",Xnames,sep="") for (i in 1:p) SngDparnam <- c(SngDparnam,paste("Sigma_",Xnames[i],"_",Xnames[i:p],sep="")) SngDparnam <- c(SngDparnam,paste("gamma1_",Xnames,sep="")) npar <- SKnpar(Conf,p,p/2) InFData <- try( sn.infoMv( dp=list(xi=Res$ksi,Omega=Res$Omega,alpha=Res$alpha), y=Xscld, x=matrix(1,nrow=n,ncol=1) ) ) if ( is.null(InFData) || class(InFData)[1] == "try-error" || is.null(InFData$asyvar.cp) ) { return( list(mleCPvcov=NULL,muEse=NULL,SigmaEse=NULL,gamma1Ese=NULL,status="Invalid") ) } if (Conf==1) { mleCPvcov <- InFData$asyvar.cp rownames(mleCPvcov) <- colnames(mleCPvcov) <- SngDparnam } else { nparC1 <- 2*p + p*(p+1)/2 parind <- c(1:p,p+SigCind(Conf,p/2),(nparC1-p+1):nparC1) mleCPvcov <- Safepdsolve(InFData$info.cp[parind,parind],maxlnk2=limlnk2,scale=TRUE) if ( !is.null(mleCPvcov) ) { rownames(mleCPvcov) <- colnames(mleCPvcov) <- SngDparnam[parind] } } if (is.null(mleCPvcov)) return( list(mleCPvcov=NULL,muEse=NULL,SigmaEse=NULL,gamma1Ese=NULL) ) mleCPvcov <- mleCPvcov * SNVCovscaling(Conf,p,Xsd,k=k) CPStderr <- sqrt(diag(mleCPvcov)) muEse <- CPStderr[1:p] gammaind <- (npar-p+1):npar gamma1Ese <- CPStderr[gammaind] SigmaEse <- matrix(nrow=p,ncol=p) cnt <- k*p for (j1 in 1:p) for (j2 in j1:p) { if (FreePar(q,j1,j2,Conf)) { cnt <- cnt+1 SigmaEse[j1,j2] <- SigmaEse[j2,j1] <- CPStderr[cnt] } } names(gamma1Ese) <- rownames(SigmaEse) <- colnames(SigmaEse) <- names(muEse) <- Xnames list(mleCPvcov=mleCPvcov,muEse=muEse,SigmaEse=SigmaEse,gamma1Ese=gamma1Ese,status="Regular") } p <- ncol(Xscld) q <- p/2 n <- nrow(Xscld) grplvls <- levels(grouping) k <- length(grplvls) n1scvct <- rep(1,n) Xnames <- names(Xmean) zmu <- scale(Nres@mleNmuE,center=Xmean,scale=Xsd) displcmnt <- -Xmean sclfactor <- 1./Xsd NewSNres <- list() if (Mxt=="Hom" || Mxt=="Loc") { zmug1 <- zmu[1,] if (k>2) { beta2k <- scale(zmu[-1,],center=zmug1,scale=FALSE) } else { beta2k <- zmu[-1,] - zmug1 } zSigma <- Nres@CovConfCases[[CvCase]]$mleSigE/XsdOutPrd if (Conf==1) { DP <- cnvCPtoDP(p,zmu[1,],zSigma,rep(0.,p),limlnk2=limlnk2) newpar <- c(DP$ksi,beta2k,DP$alpha/DP$omega) SNStdDtRes <- SNCnf1MaxLik(Xscld,initpar=newpar,grouping=grouping,limlnk2=limlnk2,OptCntrl=OptCntrl) } else { SigmaSrpar <- GetCovPar(zSigma,Conf,test=FALSE) newpar <- c(zmug1,beta2k,SigmaSrpar,rep(0.,p)) SNStdDtRes <- SNCMaxLik(Xscld,Config=Conf,initpar=newpar,grouping=grouping,limlnk2=limlnk2,OptCntrl=OptCntrl) } NewSNres$muE <- scale( scale(SNStdDtRes$mu,center=FALSE,scale=sclfactor),center=displcmnt,scale=FALSE ) NewSNres$ksiE <- scale( scale(SNStdDtRes$ksi,center=FALSE,scale=sclfactor),center=displcmnt,scale=FALSE ) attr(NewSNres$muE,"scaled:center") <- attr(NewSNres$ksiE,"scaled:center") <- attr(NewSNres$muE,"scaled:scale") <- attr(NewSNres$ksiE,"scaled:scale") <- NULL NewSNres$SigmaE <- XsdOutPrd*SNStdDtRes$Sigma NewSNres$gamma1E <- SNStdDtRes$gamma1 NewSNres$OmegaE <- XsdOutPrd*SNStdDtRes$Omega NewSNres$alphaE <- SNStdDtRes$alpha NewSNres$logLik <- SNStdDtRes$lnLik + lglikdif colnames(NewSNres$muE) <- colnames(NewSNres$ksiE) <- Xnames rownames(NewSNres$muE) <- rownames(NewSNres$ksiE) <- grplvls if ( !is.null(NewSNres$gamma1E) && !is.null(NewSNres$alphaE) && !is.null(NewSNres$SigmaE) && !is.null(NewSNres$OmegaE) ) { names(NewSNres$gamma1E) <- names(NewSNres$alphaE) <- dimnames(NewSNres$SigmaE)[[1]] <- dimnames(NewSNres$SigmaE)[[2]] <- dimnames(NewSNres$OmegaE)[[1]] <- dimnames(NewSNres$OmegaE)[[2]] <- Xnames } } else if (Mxt=="Het" || Mxt=="Gen") { NewSNres$muE <- matrix(nrow=k,ncol=p) NewSNres$gamma1E <- matrix(nrow=k,ncol=p) NewSNres$ksiE <- matrix(nrow=k,ncol=p) NewSNres$alphaE <- matrix(nrow=k,ncol=p) nparbyg <- SKnpar(Conf,p,q) anams <- list(Xnames,Xnames,grplvls) mnams <- list(grplvls,Xnames) NewSNres$SigmaE <- array(dim=c(p,p,k),dimnames=anams) NewSNres$OmegaE <- array(dim=c(p,p,k),dimnames=anams) NewSNres$logLik <- 0. if (getvcov) { NewSNres$status <- "Regular" NewSNres$mleCPvcov <- array(dim=c(nparbyg,nparbyg,k),dimnames=list(NULL,NULL,grplvls)) NewSNres$muEse <- matrix(nrow=k,ncol=p,dimnames=mnams) NewSNres$SigmaEse <- array(dim=c(p,p,k),dimnames=anams) NewSNres$gamma1Ese <- matrix(nrow=k,ncol=p,dimnames=mnams) } else { NewSNres$status <- "OnHold" NewSNres$mleCPvcov <- NewSNres$muEse <- NewSNres$SigmaEse <- NewSNres$gamma1Ese <- NULL } for (g in 1:k) { Xscldg <- Xscld[grouping==grplvls[g],] zSigma <- Nres@CovConfCases[[CvCase]]$mleSigE[,,g]/XsdOutPrd if (Conf==1) { DP <- cnvCPtoDP(p,zmu[g,],zSigma,rep(0.,p),limlnk2=limlnk2) newpar <- c(DP$ksi,DP$alpha/DP$omega) SNStdDtRes <- SNCnf1MaxLik(Xscldg,initpar=newpar,grouping=NULL,limlnk2=limlnk2,OptCntrl=OptCntrl) } else { SigmaSrpar <- GetCovPar(zSigma,Conf,test=FALSE) newpar <- c(zmu[g,],SigmaSrpar,rep(0.,p)) SNStdDtRes <- SNCMaxLik(Xscldg,Config=Conf,initpar=newpar,grouping=NULL,limlnk2=limlnk2,OptCntrl=OptCntrl) } NewSNres$muE[g,] <- SNStdDtRes$mu/sclfactor-displcmnt NewSNres$ksiE[g,] <- SNStdDtRes$ksi/sclfactor-displcmnt NewSNres$SigmaE[,,g] <- XsdOutPrd*SNStdDtRes$Sigma NewSNres$gamma1E[g,] <- SNStdDtRes$gamma1 NewSNres$OmegaE[,,g] <- XsdOutPrd*SNStdDtRes$Omega if (!is.null(SNStdDtRes$alpha)) NewSNres$alphaE[g,] <- SNStdDtRes$alpha NewSNres$logLik <- NewSNres$logLik + SNStdDtRes$lnLik if (getvcov) { if ( (!is.null(SNStdDtRes$c2) && SNStdDtRes$c2 > bordertol) || (maxsk-max(abs(SNStdDtRes$gamma1)) < bordertol) ) { vcovl <- GetvcovSingD(SNStdDtRes) if (!is.null(vcovl$muEse)) NewSNres$muEse[g,] <- vcovl$muEse if (!is.null(vcovl$gamma1Ese))NewSNres$gamma1Ese[g,] <- vcovl$gamma1Ese if (!is.null(vcovl$SigmaEse)) NewSNres$SigmaEse[,,g] <- vcovl$SigmaEse if (!is.null(vcovl$mleCPvcov)) { NewSNres$mleCPvcov[,,g] <- vcovl$mleCPvcov if (g==1) dimnames(NewSNres$mleCPvcov)[[1]] <- dimnames(NewSNres$mleCPvcov)[[2]] <- rownames(NewSNres$mleCPvcov) } } else { NewSNres$status <- "Onborder" } } } NewSNres$logLik <- NewSNres$logLik + lglikdif colnames(NewSNres$muE) <- colnames(NewSNres$ksiE) <- Xnames rownames(NewSNres$muE) <- rownames(NewSNres$ksiE) <- grplvls if ( !is.null(NewSNres$gamma1E) && !is.null(NewSNres$alphaE) && !is.null(NewSNres$SigmaE) && !is.null(NewSNres$OmegaE) ) { names(NewSNres$gamma1E) <- names(NewSNres$alphaE) <- dimnames(NewSNres$SigmaE)[[1]] <- dimnames(NewSNres$SigmaE)[[2]] <- dimnames(NewSNres$OmegaE)[[1]] <- dimnames(NewSNres$OmegaE)[[2]] <- Xnames dimnames(NewSNres$SigmaE)[[3]] <- dimnames(NewSNres$OmegaE)[[3]] <- grplvls } } NewSNres }
buildDepots = function(n.depots, cluster.centers, distances) { n.cluster = nrow(cluster.centers) depot.1.idx = sample(seq(n.cluster), 1L) depot.coordinates = cluster.centers[depot.1.idx, , drop = FALSE] if (n.depots == 2L) { depot.2.idx = distances$max.distance.idx[depot.1.idx] depot.coordinates = rbind(depot.coordinates, cluster.centers[depot.2.idx, , drop = FALSE]) } return(depot.coordinates) }
hypotestBAF1x<-function(x,n,th0,a1,b1) { if (missing(x)) stop("'x' is missing") if (missing(n)) stop("'n' is missing") if (missing(th0)) stop("'th0' is missing") if (missing(a1)) stop("'a1' is missing") if (missing(b1)) stop("'b1' is missing") if ((class(x) != "integer") & (class(x) != "numeric") || length(x) >1|| x>n || x<0 ) stop("'x' has to be between 0 and n") if ((class(n) != "integer") & (class(n) != "numeric") || length(n) >1|| n<0 ) stop("'n' has to be greater or equal to 0") if ((class(th0) != "integer") & (class(th0) != "numeric") || length(th0) >1|| th0>1 || th0<=0 ) stop("'th0' has to be between 0 and 1") if ((class(a1) != "integer") & (class(a1) != "numeric") || length(a1) >1|| a1<=0 ) stop("'a1' has to be greater than 0") if ((class(b1) != "integer") & (class(b1) != "numeric") || length(b1) >1|| b1<=0 ) stop("'b1' has to be greater than 0") BaFa01=(beta(a1,b1)/beta(x+a1,n-x+b1))*(th0^x)*((1-th0)^(n-x)) rdf=data.frame(x,BaFa01) ndf1=subset(rdf,(BaFa01<3 & BaFa01 >= 1)) ndf2=subset(rdf,(BaFa01<20 & BaFa01 >= 3)) ndf3=subset(rdf,(BaFa01<150 & BaFa01 >= 20)) ndf4=subset(rdf,(BaFa01>=150)) ndf5=subset(rdf,(BaFa01<1 & BaFa01 >= 1/3)) ndf6=subset(rdf,(BaFa01<1/3 & BaFa01 >= 1/20)) ndf7=subset(rdf,(BaFa01<1/20 & BaFa01 >= 1/150)) ndf8=subset(rdf,(BaFa01<1/150)) if(length(ndf1$x)>0){ ndf1$Interpretation="Evidence against H1 is not worth more than a bare mention"} if(length(ndf2$x)>0){ ndf2$Interpretation="Evidence against H1 is positive"} if(length(ndf3$x)>0){ ndf3$Interpretation="Evidence against H1 is strong"} if(length(ndf4$x)>0){ ndf4$Interpretation="Evidence against H1 is very strong"} if(length(ndf5$x)>0){ ndf5$Interpretation="Evidence against H0 is not worth more than a bare mention"} if(length(ndf6$x)>0){ ndf6$Interpretation="Evidence against H0 is positive"} if(length(ndf7$x)>0){ ndf7$Interpretation="Evidence against H0 is strong"} if(length(ndf8$x)>0){ ndf8$Interpretation="Evidence against H0 is very strong"} cbdf=rbind(ndf1,ndf2,ndf3,ndf4,ndf5,ndf6,ndf7,ndf8) ndf=cbdf[order(cbdf$x),] row.names(ndf)<-NULL return(ndf) } hypotestBAF2x<-function(x,n,th0,a1,b1) { if (missing(x)) stop("'x' is missing") if (missing(n)) stop("'n' is missing") if (missing(th0)) stop("'th0' is missing") if (missing(a1)) stop("'a1' is missing") if (missing(b1)) stop("'b1' is missing") if ((class(x) != "integer") & (class(x) != "numeric") || length(x) >1|| x>n || x<0 ) stop("'x' has to be between 0 and n") if ((class(n) != "integer") & (class(n) != "numeric") || length(n) >1|| n<0 ) stop("'n' has to be greater or equal to 0") if ((class(th0) != "integer") & (class(th0) != "numeric") || length(th0) >1|| th0>1 || th0<=0 ) stop("'th0' has to be between 0 and 1") if ((class(a1) != "integer") & (class(a1) != "numeric") || length(a1) >1|| a1<=0 ) stop("'a1' has to be greater than 0") if ((class(b1) != "integer") & (class(b1) != "numeric") || length(b1) >1|| b1<=0 ) stop("'b1' has to be greater than 0") bet1=function(p) dbeta(p,shape1=a1,shape2=b1) bet2=function(p) dbeta(p,shape1=x+a1,shape2=n-x+b1) t1=integrate(bet1,th0,1)$value t2=integrate(bet2,th0,1)$value BaFa01=(t1/t2)*(th0^x)*((1-th0)^(n-x)) rdf=data.frame(x,BaFa01) ndf1=subset(rdf,(BaFa01<3 & BaFa01 >= 1)) ndf2=subset(rdf,(BaFa01<20 & BaFa01 >= 3)) ndf3=subset(rdf,(BaFa01<150 & BaFa01 >= 20)) ndf4=subset(rdf,(BaFa01>=150)) ndf5=subset(rdf,(BaFa01<1 & BaFa01 >= 1/3)) ndf6=subset(rdf,(BaFa01<1/3 & BaFa01 >= 1/20)) ndf7=subset(rdf,(BaFa01<1/20 & BaFa01 >= 1/150)) ndf8=subset(rdf,(BaFa01<1/150)) if(length(ndf1$x)>0){ ndf1$Interpretation="Evidence against H1 is not worth more than a bare mention"} if(length(ndf2$x)>0){ ndf2$Interpretation="Evidence against H1 is positive"} if(length(ndf3$x)>0){ ndf3$Interpretation="Evidence against H1 is strong"} if(length(ndf4$x)>0){ ndf4$Interpretation="Evidence against H1 is very strong"} if(length(ndf5$x)>0){ ndf5$Interpretation="Evidence against H0 is not worth more than a bare mention"} if(length(ndf6$x)>0){ ndf6$Interpretation="Evidence against H0 is positive"} if(length(ndf7$x)>0){ ndf7$Interpretation="Evidence against H0 is strong"} if(length(ndf8$x)>0){ ndf8$Interpretation="Evidence against H0 is very strong"} cbdf=rbind(ndf1,ndf2,ndf3,ndf4,ndf5,ndf6,ndf7,ndf8) ndf=cbdf[order(cbdf$x),] row.names(ndf)<-NULL return(ndf) } hypotestBAF3x<-function(x,n,th0,a1,b1) { if (missing(x)) stop("'x' is missing") if (missing(n)) stop("'n' is missing") if (missing(th0)) stop("'th0' is missing") if (missing(a1)) stop("'a1' is missing") if (missing(b1)) stop("'b1' is missing") if ((class(x) != "integer") & (class(x) != "numeric") || length(x) >1|| x>n || x<0 ) stop("'x' has to be between 0 and n") if ((class(n) != "integer") & (class(n) != "numeric") || length(n) >1|| n<0 ) stop("'n' has to be greater or equal to 0") if ((class(th0) != "integer") & (class(th0) != "numeric") || length(th0) >1|| th0>1 || th0<=0 ) stop("'th0' has to be between 0 and 1") if ((class(a1) != "integer") & (class(a1) != "numeric") || length(a1) >1|| a1<=0 ) stop("'a1' has to be greater than 0") if ((class(b1) != "integer") & (class(b1) != "numeric") || length(b1) >1|| b1<=0 ) stop("'b1' has to be greater than 0") bet1=function(p) dbeta(p,shape1=a1,shape2=b1) bet2=function(p) dbeta(p,shape1=x+a1,shape2=n-x+b1) t1=integrate(bet1,0,th0)$value t2=integrate(bet2,0,th0)$value BaFa01=(t1/t2)*(th0^x)*((1-th0)^(n-x)) rdf=data.frame(x,BaFa01) ndf1=subset(rdf,(BaFa01<3 & BaFa01 >= 1)) ndf2=subset(rdf,(BaFa01<20 & BaFa01 >= 3)) ndf3=subset(rdf,(BaFa01<150 & BaFa01 >= 20)) ndf4=subset(rdf,(BaFa01>=150)) ndf5=subset(rdf,(BaFa01<1 & BaFa01 >= 1/3)) ndf6=subset(rdf,(BaFa01<1/3 & BaFa01 >= 1/20)) ndf7=subset(rdf,(BaFa01<1/20 & BaFa01 >= 1/150)) ndf8=subset(rdf,(BaFa01<1/150)) if(length(ndf1$x)>0){ ndf1$Interpretation="Evidence against H1 is not worth more than a bare mention"} if(length(ndf2$x)>0){ ndf2$Interpretation="Evidence against H1 is positive"} if(length(ndf3$x)>0){ ndf3$Interpretation="Evidence against H1 is strong"} if(length(ndf4$x)>0){ ndf4$Interpretation="Evidence against H1 is very strong"} if(length(ndf5$x)>0){ ndf5$Interpretation="Evidence against H0 is not worth more than a bare mention"} if(length(ndf6$x)>0){ ndf6$Interpretation="Evidence against H0 is positive"} if(length(ndf7$x)>0){ ndf7$Interpretation="Evidence against H0 is strong"} if(length(ndf8$x)>0){ ndf8$Interpretation="Evidence against H0 is very strong"} cbdf=rbind(ndf1,ndf2,ndf3,ndf4,ndf5,ndf6,ndf7,ndf8) ndf=cbdf[order(cbdf$x),] row.names(ndf)<-NULL return(ndf) } hypotestBAF4x<-function(x,n,th0,a0,b0,a1,b1) { if (missing(x)) stop("'x' is missing") if (missing(n)) stop("'n' is missing") if (missing(th0)) stop("'th0' is missing") if (missing(a0)) stop("'a0' is missing") if (missing(b0)) stop("'b0' is missing") if (missing(a1)) stop("'a1' is missing") if (missing(b1)) stop("'b1' is missing") if ((class(x) != "integer") & (class(x) != "numeric") || length(x) >1|| x>n || x<0) stop("'x' has to be between 0 and n") if ((class(n) != "integer") & (class(n) != "numeric") || length(n) >1|| n<0 ) stop("'n' has to be greater or equal to 0") if ((class(th0) != "integer") & (class(th0) != "numeric") || length(th0) >1|| th0>1 || th0<=0 ) stop("'th0' has to be between 0 and 1") if ((class(a0) != "integer") & (class(a0) != "numeric") || length(a0) >1|| a0<=0 ) stop("'a0' has to be greater than 0") if ((class(b0) != "integer") & (class(b0) != "numeric") || length(b0) >1|| b0<=0 ) stop("'b0' has to be greater than 0") if ((class(a1) != "integer") & (class(a1) != "numeric") || length(a1) >1|| a1<=0 ) stop("'a1' has to be greater than 0") if ((class(b1) != "integer") & (class(b1) != "numeric") || length(b1) >1|| b1<=0 ) stop("'b1' has to be greater than 0") bet0=function(p) dbeta(p,shape1=a0,shape2=b0) bet01=function(p) dbeta(p,shape1=x+a0,shape2=n-x+b0) bet1=function(p) dbeta(p,shape1=a1,shape2=b1) bet11=function(p) dbeta(p,shape1=x+a1,shape2=n-x+b1) t0=integrate(bet0,0,th0)$value t1=integrate(bet1,th0,1)$value t01=integrate(bet01,0,th0)$value t11=integrate(bet11,th0,1)$value BaFa01=t01*t1/(t0*t11) rdf=data.frame(x,BaFa01) ndf1=subset(rdf,(BaFa01<3 & BaFa01 >= 1)) ndf2=subset(rdf,(BaFa01<20 & BaFa01 >= 3)) ndf3=subset(rdf,(BaFa01<150 & BaFa01 >= 20)) ndf4=subset(rdf,(BaFa01>=150)) ndf5=subset(rdf,(BaFa01<1 & BaFa01 >= 1/3)) ndf6=subset(rdf,(BaFa01<1/3 & BaFa01 >= 1/20)) ndf7=subset(rdf,(BaFa01<1/20 & BaFa01 >= 1/150)) ndf8=subset(rdf,(BaFa01<1/150)) if(length(ndf1$x)>0){ ndf1$Interpretation="Evidence against H1 is not worth more than a bare mention"} if(length(ndf2$x)>0){ ndf2$Interpretation="Evidence against H1 is positive"} if(length(ndf3$x)>0){ ndf3$Interpretation="Evidence against H1 is strong"} if(length(ndf4$x)>0){ ndf4$Interpretation="Evidence against H1 is very strong"} if(length(ndf5$x)>0){ ndf5$Interpretation="Evidence against H0 is not worth more than a bare mention"} if(length(ndf6$x)>0){ ndf6$Interpretation="Evidence against H0 is positive"} if(length(ndf7$x)>0){ ndf7$Interpretation="Evidence against H0 is strong"} if(length(ndf8$x)>0){ ndf8$Interpretation="Evidence against H0 is very strong"} cbdf=rbind(ndf1,ndf2,ndf3,ndf4,ndf5,ndf6,ndf7,ndf8) ndf=cbdf[order(cbdf$x),] row.names(ndf)<-NULL return(ndf) } hypotestBAF5x<-function(x,n,th0,a0,b0,a1,b1) { if (missing(x)) stop("'x' is missing") if (missing(th0)) stop("'th0' is missing") if (missing(a0)) stop("'a0' is missing") if (missing(b0)) stop("'b0' is missing") if (missing(a1)) stop("'a1' is missing") if (missing(b1)) stop("'b1' is missing") if ((class(x) != "integer") & (class(x) != "numeric") || length(x) >1||x>n || x<0) stop("'x' has to be between 0 and n") if ((class(n) != "integer") & (class(n) != "numeric") || length(n) >1|| n<0 ) stop("'n' has to be greater or equal to 0") if ((class(th0) != "integer") & (class(th0) != "numeric") || length(th0) >1|| th0>1 || th0<=0 ) stop("'th0' has to be between 0 and 1") if ((class(a0) != "integer") & (class(a0) != "numeric") || length(a0) >1|| a0<=0 ) stop("'a0' has to be greater than 0") if ((class(b0) != "integer") & (class(b0) != "numeric") || length(b0) >1|| b0<=0 ) stop("'b0' has to be greater than 0") if ((class(a1) != "integer") & (class(a1) != "numeric") || length(a1) >1|| a1<=0 ) stop("'a1' has to be greater than 0") if ((class(b1) != "integer") & (class(b1) != "numeric") || length(b1) >1|| b1<=0 ) stop("'b1' has to be greater than 0") bet0=function(p) dbeta(p,shape1=a0,shape2=b0) bet01=function(p) dbeta(p,shape1=x+a0,shape2=n-x+b0) bet1=function(p) dbeta(p,shape1=a1,shape2=b1) bet11=function(p) dbeta(p,shape1=x+a1,shape2=n-x+b1) t0=integrate(bet0,th0,1)$value t1=integrate(bet1,0,th0)$value t01=integrate(bet01,th0,1)$value t11=integrate(bet11,0,th0)$value BaFa01=t01*t1/(t0*t11) rdf=data.frame(x,BaFa01) ndf1=subset(rdf,(BaFa01<3 & BaFa01 >= 1)) ndf2=subset(rdf,(BaFa01<20 & BaFa01 >= 3)) ndf3=subset(rdf,(BaFa01<150 & BaFa01 >= 20)) ndf4=subset(rdf,(BaFa01>=150)) ndf5=subset(rdf,(BaFa01<1 & BaFa01 >= 1/3)) ndf6=subset(rdf,(BaFa01<1/3 & BaFa01 >= 1/20)) ndf7=subset(rdf,(BaFa01<1/20 & BaFa01 >= 1/150)) ndf8=subset(rdf,(BaFa01<1/150)) if(length(ndf1$x)>0){ ndf1$Interpretation="Evidence against H1 is not worth more than a bare mention"} if(length(ndf2$x)>0){ ndf2$Interpretation="Evidence against H1 is positive"} if(length(ndf3$x)>0){ ndf3$Interpretation="Evidence against H1 is strong"} if(length(ndf4$x)>0){ ndf4$Interpretation="Evidence against H1 is very strong"} if(length(ndf5$x)>0){ ndf5$Interpretation="Evidence against H0 is not worth more than a bare mention"} if(length(ndf6$x)>0){ ndf6$Interpretation="Evidence against H0 is positive"} if(length(ndf7$x)>0){ ndf7$Interpretation="Evidence against H0 is strong"} if(length(ndf8$x)>0){ ndf8$Interpretation="Evidence against H0 is very strong"} cbdf=rbind(ndf1,ndf2,ndf3,ndf4,ndf5,ndf6,ndf7,ndf8) ndf=cbdf[order(cbdf$x),] row.names(ndf)<-NULL return(ndf) } hypotestBAF6x<-function(x,n,th1,a1,b1,th2,a2,b2) { if (missing(x)) stop("'x' is missing") if (missing(n)) stop("'n' is missing") if (missing(th1)) stop("'th1' is missing") if (missing(a1)) stop("'a1' is missing") if (missing(b1)) stop("'b1' is missing") if (missing(th2)) stop("'th2' is missing") if (missing(a2)) stop("'a2' is missing") if (missing(b2)) stop("'b2' is missing") if ((class(x) != "integer") & (class(x) != "numeric") || length(x) >1||x>n || x<0) stop("'x' has to be between 0 and n") if ((class(n) != "integer") & (class(n) != "numeric") || length(n) >1|| n<0 ) stop("'n' has to be greater or equal to 0") if ((class(th1) != "integer") & (class(th1) != "numeric") || length(th1) >1|| th1<0 ) stop("'th1' has to be greater than 0") if ((class(a1) != "integer") & (class(a1) != "numeric") || length(a1) >1|| a1<=0 ) stop("'a1' has to be greater than 0") if ((class(b1) != "integer") & (class(b1) != "numeric") || length(b1) >1|| b1<=0 ) stop("'b1' has to be greater than 0") if ((class(th2) != "integer") & (class(th2) != "numeric") || length(th2) >1|| th2<0 ) stop("'th2' has to be greater than 0") if ((class(a2) != "integer") & (class(a2) != "numeric") || length(a2) >1|| a2<=0 ) stop("'a2' has to be greater than 0") if ((class(b2) != "integer") & (class(b2) != "numeric") || length(b2) >1|| b2<=0 ) stop("'b2' has to be greater than 0") bet1=function(p) dbeta(p,shape1=x+a1,shape2=n-x+b1) bet2=function(p) dbeta(p,shape1=x+a2,shape2=n-x+b2) t1=integrate(bet1,0,th1)$value t2=integrate(bet2,th2,1)$value BaFa01=t1/t2 rdf=data.frame(x,BaFa01) ndf1=subset(rdf,(BaFa01<3 & BaFa01 >= 1)) ndf2=subset(rdf,(BaFa01<20 & BaFa01 >= 3)) ndf3=subset(rdf,(BaFa01<150 & BaFa01 >= 20)) ndf4=subset(rdf,(BaFa01>=150)) ndf5=subset(rdf,(BaFa01<1 & BaFa01 >= 1/3)) ndf6=subset(rdf,(BaFa01<1/3 & BaFa01 >= 1/20)) ndf7=subset(rdf,(BaFa01<1/20 & BaFa01 >= 1/150)) ndf8=subset(rdf,(BaFa01<1/150)) if(length(ndf1$x)>0){ ndf1$Interpretation="Evidence against H1 is not worth more than a bare mention"} if(length(ndf2$x)>0){ ndf2$Interpretation="Evidence against H1 is positive"} if(length(ndf3$x)>0){ ndf3$Interpretation="Evidence against H1 is strong"} if(length(ndf4$x)>0){ ndf4$Interpretation="Evidence against H1 is very strong"} if(length(ndf5$x)>0){ ndf5$Interpretation="Evidence against H0 is not worth more than a bare mention"} if(length(ndf6$x)>0){ ndf6$Interpretation="Evidence against H0 is positive"} if(length(ndf7$x)>0){ ndf7$Interpretation="Evidence against H0 is strong"} if(length(ndf8$x)>0){ ndf8$Interpretation="Evidence against H0 is very strong"} cbdf=rbind(ndf1,ndf2,ndf3,ndf4,ndf5,ndf6,ndf7,ndf8) ndf=cbdf[order(cbdf$x),] row.names(ndf)<-NULL return(ndf) }
jagsBayesianModel <- function (model = NULL, ... ) { arguments <- list(...) if (is.null(model)) return(jagsTwoBaselinesFull(...)) else if (model == "oneBaseline") return(jagsOneBaseline(...)) else if (model == "twoBaselines") return(jagsTwoBaselines(...)) else if (model == "twoBaselinesFull") return(jagsTwoBaselinesFull(...)) }
load_package <- function (package1, ...) { packages <- c(package1, ...) assert_that(qtest(packages, "S"), msg = "One of the provided package(s) is(are) not a string. Please make sure that each packages is a string.") for (package in packages) { try(do.call(library, list(package))) } }
SpatialLinesDataFrame = function(sl, data, match.ID = TRUE) { if (is.character(match.ID)) { row.names(data) = data[, match.ID[1]] match.ID = TRUE } if (match.ID) { Sl_IDs <- sapply(slot(sl, "lines"), function(x) slot(x, "ID")) data_IDs <- row.names(data) mtch <- match(Sl_IDs, data_IDs) if (any(is.na(mtch))) stop("row.names of data and Lines IDs do not match") if (length(unique(mtch)) != length(Sl_IDs)) stop("row.names of data and Lines IDs do not match") data <- data[mtch, , drop=FALSE] } if (nrow(data) != length(sl@lines)) stop("length of data.frame does not match number of Lines elements") new("SpatialLinesDataFrame", sl, data = data) } names.SpatialLinesDataFrame = function(x) names(x@data) "names<-.SpatialLinesDataFrame" = function(x,value) { checkNames(value); names(x@data)<-value; x } as.data.frame.SpatialLinesDataFrame = function(x, row.names, optional, ...) x@data setMethod("addAttrToGeom", signature(x = "SpatialLines", y = "data.frame"), function(x, y, match.ID, ...) SpatialLinesDataFrame(x, y, match.ID = match.ID, ...) ) setAs("SpatialLinesDataFrame", "SpatialMultiPointsDataFrame", function(from) SpatialMultiPointsDataFrame(as(geometry(from), "SpatialMultiPoints"), from@data) ) setAs("SpatialLinesDataFrame", "data.frame", function(from) as.data.frame.SpatialLinesDataFrame(from)) row.names.SpatialLinesDataFrame <- function(x) { sapply(slot(x, "lines"), slot, "ID") } "row.names<-.SpatialLinesDataFrame" <- function(x, value) { spChFIDs(x, value) } setMethod("[", c("SpatialLinesDataFrame", "ANY", "ANY"), function(x, i, j, ... , drop = TRUE) { missing.i = missing(i) missing.j = missing(j) nargs = nargs() if (missing.i && missing.j) { i = TRUE j = TRUE } else if (missing.j && !missing.i) { if (nargs == 2) { j = i i = TRUE } else { j = TRUE } } else if (missing.i && !missing.j) i = TRUE if (is.matrix(i)) stop("matrix argument not supported in SpatialLinesDataFrame selection") if (is(i, "Spatial")) i = !is.na(over(x, geometry(i))) if (is.logical(i)) { if (length(i) == 1 && i) i = 1:length(x@lines) else i <- which(i) } else if (is.character(i)) { i <- match(i, row.names(x)) } if (any(is.na(i))) stop("NAs not permitted in row index") x@lines = x@lines[i] x@data = x@data[i, j, ..., drop = FALSE] if (length(x@lines) > 0) x@bbox = .bboxSls(x@lines) x }) lines.SpatialLinesDataFrame = function(x, y = NULL, ...) lines(as(x, "SpatialLines"), ...) setAs("SpatialLinesDataFrame", "SpatialPointsDataFrame", function(from) { spp = as(as(from, "SpatialLines"), "SpatialPointsDataFrame") dfl = from@data[spp$Lines.NR, , drop = FALSE] spp@data = cbind(dfl, spp@data) spp } ) dim.SpatialLinesDataFrame = function(x) dim(x@data) setMethod("split", "SpatialLinesDataFrame", split.data.frame) print.SpatialLinesDataFrame = function(x, ..., digits = getOption("digits"), asWKT = .asWKT) print(data.frame(asWKTSpatialLines(x, digits), x@data),..., digits = digits) setMethod("geometry", "SpatialLinesDataFrame", function(obj) as(obj, "SpatialLines")) length.SpatialLinesDataFrame = function(x) { length(x@lines) }
Cal_grpWTs <- function(P, Q, G, R, gmax, PQ.grps) { PP=P QQ=Q GG=G RR=R ggmax=gmax PQgrps=as.vector(t(PQ.grps)) grpWTs=rep(0, GG*RR) Gcounts=rep(0,GG) Rcounts=rep(0,RR) junk=.C("Cal_grpWTs", as.integer(PP), as.integer(QQ), as.integer(GG), as.integer(RR), as.integer(ggmax), as.integer(PQgrps), grpWTs=as.double(grpWTs), as.integer(Gcounts), as.integer(Rcounts) ) grpWTs.result=matrix(junk$grpWTs, nrow=GG, byrow=T) return(list(grpWTs=grpWTs.result)) }
mtcars women library('knitr') knitr::kable(head(mtcars))
is.variable <- function(x) inherits(x, "CrunchVariable") is.Numeric <- function(x) inherits(x, "NumericVariable") is.Categorical <- function(x) inherits(x, "CategoricalVariable") is.Text <- function(x) inherits(x, "TextVariable") is.Datetime <- function(x) inherits(x, "DatetimeVariable") is.Multiple <- function(x) inherits(x, "MultipleResponseVariable") is.MR <- is.Multiple is.MultipleResponse <- is.Multiple is.CA <- function(x) { return(identical(class(x), class(CategoricalArrayVariable()))) } is.CategoricalArray <- is.CA is.NumericArray <- function(x) inherits(x, "NumericArrayVariable") is.Array <- function(x) inherits(x, "ArrayVariable") has.categories <- function(x) { if (!is.character(x)) { x <- type(x) } return(x %in% c("categorical_array", "multiple_response", "categorical")) } is.subvariable <- function(x) { grepl("subvariables", self(x)) } CASTABLE_TYPES <- c("numeric", "text", "categorical") NULL setMethod("type", "CrunchVariable", function(x) type(tuple(x))) setMethod("type", "VariableEntity", function(x) x@body$type) setMethod("types", "list", function(x) { vapply(x, type, character(1), USE.NAMES = FALSE) }) castVariable <- function(x, value) { if (!(type(x) %in% CASTABLE_TYPES)) { halt("Cannot change the type of a ", class(x), " by type<-") } if (!(value %in% CASTABLE_TYPES)) { halt( dQuote(value), " is not a Crunch variable type that can be assigned.", " Valid types are ", serialPaste(dQuote(CASTABLE_TYPES)) ) } if (type(x) != value) { crPOST(shojiURL(x, "views", "cast"), body = toJSON(list(cast_as = value))) x <- refresh(x) } invisible(x) } setMethod("type<-", "CrunchVariable", castVariable)
plot.Predict.Treat.T0T1.ContCont <- function(x, Xlab, Main, alpha=0.05, Cex.Legend=1, ...){ Object <- x if (missing(Xlab)) {Xlab <- expression(paste(Delta, "T"[j], "|S"[j]))} if (missing(Main)) {Main=" "} min_T0T1 <- min(Object$T0T1) max_T0T1 <- max(Object$T0T1) crit_val <- qnorm(c(alpha/2), mean=0, sd=1, lower.tail=FALSE) if (class(Object)=="Predict.Treat.T0T1.ContCont") { user_req_SD_Delta.T_givenS <- sqrt(Object$Var_Delta.T_S) Pred_T <- Object$Pred_T x <- ((seq(-4,4,length=1000)*user_req_SD_Delta.T_givenS))*1 + Pred_T hx <- dnorm(x, Pred_T, user_req_SD_Delta.T_givenS) plot(x=x, y=(hx*crit_val), type="l", xlab=Xlab, ylab="", main=Main, lwd=2, col=2, ...) abline(v = Pred_T, lty=2) SD_hier <- user_req_SD_Delta.T_givenS col_hier <- 2 x1 <- Pred_T - (SD_hier * crit_val) x2 <- Pred_T + (SD_hier * crit_val) sam <- cbind(x, hx) y1 <- sam[,2][which.min(abs(sam[,1]-x1))] y2 <- sam[,2][which.min(abs(sam[,1]-x2))] segments(x0 = x1, y0 = 0, x1 = x1, y1 = y1, col=col_hier, lwd=2, lty=2) segments(x0 = x2, y0 = 0, x1 = x2, y1 = y2, col=col_hier, lwd=2, lty=2) legend("topright", inset=.05, legend=c(bquote(paste(rho[T0T1], "="~.(Object$T0T1))), expression()), lwd=2, col=c(2), cex=Cex.Legend) } }
pampe <- function(time.pretr, time.tr, treated, controls = "All", data, nbest=1, nvmax=length(controls), select="AICc", placebos=FALSE){ intercept=TRUE if (length(treated) != 1){ stop("You can only have one treated unit.") } if (length(c(time.pretr, time.tr)) > nrow(data)){ stop("Treatment period has exceeded the data.") } if (length(which(is.na(data)))>0){ stop("There are missing values in the data. Pampe does not allow for unbalanced data at this point.") } if (class(treated) == "numeric"){ treated <- colnames(data)[treated] } if(is.null(rownames(data))){ rownames(data) <- 1:nrow(data) } if(is.null(colnames(data))){ colnames(data) <- 1:ncol(data) } if(controls[1]!="All"){ controls <- which(colnames(data) %in% controls) } if (controls[1]=="All"){ controls <- -which(colnames(data)==treated) if (nvmax==length(controls)){ if (ncol(data[,controls])+3>=length(time.pretr)){ nvmax <- length(time.pretr)-4 } if (ncol(data[,controls])+3<length(time.pretr)){ nvmax <- ncol(data[,controls]) } } } if (length(controls)!=1){ if (class(controls)=="character"){ controls <- which(colnames(data) %in% controls) } } if (class(time.pretr)=="character"){ } if (class(time.tr)=="character"){ } if (nvmax+3>=length(time.pretr)){ stop("You have selected too many controls. Please change the 'nvmax' setting.") } treated.original <- treated possible.ctrls.all <- colnames(data)[controls] select.models <- invisible(regsubsets(x=data[time.pretr, controls], y=data[time.pretr, c(treated)], names=colnames(data[,controls]), intercept=intercept, nbest=nbest, nvmax=nvmax, matrix.logical=TRUE, really.big=TRUE)) select.criteria <- invisible(regsubsets2aic(x=data[time.pretr, controls], y=data[time.pretr, c(treated)], z=select.models)) controls <- unlist(strsplit(select.criteria[which.min(select.criteria[,select]),'model'], split=" + ", fixed=TRUE)) fmla <- paste(paste("`", treated, "`", sep=""), " ~ ", paste(paste("`", controls, "`", sep=""), collapse= "+")) ols <- invisible(lm(fmla, data=data[time.pretr,])) results <- (cbind(matrix(data=1,ncol=1,nrow=nrow(data)), as.matrix(subset(data, select=controls))) %*% as.matrix(ols$coefficients))[c(time.pretr, time.tr),] tr.effect <- matrix(NA, nrow=length(c(time.pretr, time.tr)), ncol=1) tr.effect[,1] <- as.matrix(data[,treated])[c(time.pretr, time.tr),]-results results <- cbind(as.matrix(data[,treated])[c(time.pretr, time.tr),], results) colnames(results) <- c("Actual", "Counterfactual") mspe <- matrix(NA, ncol=1, nrow=1) mspe[1,1] <- sum((tr.effect[(time.pretr-min(time.pretr)+1),1])^2) controls.estim <- controls tr.effect1 <- tr.effect mspe1 <- mspe if (("All" %in% placebos)==TRUE | ("Both" %in% placebos)==TRUE){ placebos <- c("controls", "time")} if (("controls" %in% placebos)==TRUE) { tr.effect <- cbind(tr.effect1, matrix(NA, nrow=length(c(time.pretr, time.tr)), ncol=(length(possible.ctrls.all)))) colnames(tr.effect) <- c(treated, possible.ctrls.all) rownames(tr.effect) <- rownames(data)[c(time.pretr, time.tr)] mspe <- cbind(mspe1, matrix(NA, ncol=(length(possible.ctrls.all)), nrow=1)) colnames(mspe) <- c(treated, possible.ctrls.all) rownames(mspe) <- 'mspe' placebo.r2 <- vector() for(i in 1:(length(possible.ctrls.all))) { treated <- possible.ctrls.all[i] possible.ctrls <- possible.ctrls.all[-i] select.models <- regsubsets(x=data[time.pretr, possible.ctrls], y=data[time.pretr, treated], names=colnames(data[,possible.ctrls]), intercept=intercept, nbest=nbest, nvmax=nvmax, matrix.logical=TRUE, really.big=TRUE) select.criteria <- regsubsets2aic(x=data[time.pretr, possible.ctrls], y=data[time.pretr, treated], z=select.models) controls <- unlist(strsplit(select.criteria[which.min(select.criteria[,select]),'model'], split=" + ", fixed=TRUE)) fmla <- paste(paste("`", treated, "`", sep=""), " ~ ", paste(paste("`", controls, "`", sep=""), collapse= "+")) temp.placebo <- lm(fmla, data=data[time.pretr,]) placebo.r2[i] <- summary(temp.placebo)$r.squared tr.effect[,(i+1)] <- as.matrix(data[,treated])[c(time.pretr, time.tr),]-(cbind(matrix(data=1,ncol=1,nrow=nrow(data)), as.matrix(subset(data, select=controls))) %*% as.matrix(temp.placebo$coefficients))[c(time.pretr, time.tr),] } for(i in 1:length(possible.ctrls.all)) { mspe[1,(i+1)] <- sum(tr.effect[(time.pretr-min(time.pretr)+1),i+1]^2) } tr.effect.ctrl <- tr.effect mspe.ctrl <- mspe } if (("time" %in% placebos)==TRUE) { time.pretr.original <- time.pretr time.tr.original <- time.tr nvmax.user <- nvmax placebo.r2 <- vector() time.reassign <- ceiling(mean(time.pretr)):(max(time.pretr)-1) possible.ctrls <- possible.ctrls.all treated <- treated.original tr.effect <- cbind(tr.effect1, matrix(NA, nrow=length(c(time.pretr, time.tr)), ncol=(length(time.reassign)))) colnames(tr.effect) <- c(rownames(data)[time.tr[1]], rownames(data)[time.reassign+1]) rownames(tr.effect) <- rownames(data)[c(time.pretr, time.tr)] mspe <- cbind(mspe1, matrix(NA, ncol=(length(time.reassign)), nrow=1)) colnames(mspe) <- c(rownames(data)[time.tr[1]], rownames(data)[time.reassign+1]) rownames(mspe) <- 'mspe' for(i in 1:length(time.reassign)) { time.pretr <- time.pretr[1]:time.reassign[i] time.tr <- (time.reassign[i]+1):time.tr[length(time.tr)] if (length(possible.ctrls)+3>=length(time.pretr)){ nvmax = length(time.pretr) - 3 } select.models <- regsubsets(x=data[time.pretr, possible.ctrls], y=data[time.pretr, treated], names=colnames(data[,possible.ctrls]), intercept=intercept, nbest=nbest, nvmax=nvmax, matrix.logical=TRUE, really.big=TRUE) select.criteria <- regsubsets2aic(x=data[time.pretr, possible.ctrls], y=data[time.pretr, treated], z=select.models) controls <- unlist(strsplit(select.criteria[which.min(select.criteria[,select]),'model'], split=" + ", fixed=TRUE)) fmla <- paste(paste("`", treated, "`", sep=""), " ~ ", paste(paste("`", controls, "`", sep=""), collapse= "+")) temp.placebo <- lm(fmla, data=data[time.pretr,]) placebo.r2[i] <- summary(temp.placebo)$r.squared tr.effect[,(i+1)] <- as.matrix(data[,treated])[c(time.pretr, time.tr),]-(cbind(matrix(data=1,ncol=1,nrow=nrow(data)), as.matrix(subset(data, select=controls))) %*% as.matrix(temp.placebo$coefficients))[c(time.pretr, time.tr),] nvmax = nvmax.user time.tr <- time.tr.original time.pretr <- time.pretr.original } for(i in 1:length(time.reassign)) { mspe[1,(i+1)] <- sum(tr.effect[(time.pretr-min(time.pretr)+1),i+1]^2) } tr.effect.time <- tr.effect mspe.time <- mspe } if (FALSE %in% placebos){ result <- list(controls=controls, model=ols, counterfactual=results, data=data) class(result) <- "pampe" return(result) } if (("controls" %in% placebos)==TRUE&length(placebos)==1) { result <-list(controls=controls.estim, model=ols, counterfactual=results,placebo.ctrl=list(mspe=mspe.ctrl, tr.effect=tr.effect.ctrl), data=data) class(result) <- "pampe" return(result) } if (("time" %in% placebos)==TRUE&length(placebos)==1) { result <- list(controls=controls.estim, model=ols, counterfactual=results,placebo.time=list(mspe=mspe.time, tr.effect=tr.effect.time), data=data) class(result) <- "pampe" return(result) } if (length(placebos)==2) { result <- list(controls=controls.estim, model=ols, counterfactual=results,placebo.ctrl=list(mspe=mspe.ctrl, tr.effect=tr.effect.ctrl), placebo.time=list(mspe=mspe.time, tr.effect=tr.effect.time), data=data) class(result) <- "pampe" return(result)} }
test_that("orphanMetabolites function: output class is wrong", { expect_true(is.vector( orphanMetabolites(reactionList = "2 A[c] + 3 B[c] => 5 D[c]", actingAs = "product") )) expect_true(is.vector( orphanMetabolites(reactionList = "2 5-A[c] + 3 B[c] <=> 5 3D[c]", actingAs = "product") )) expect_true(is.vector( orphanMetabolites(reactionList = "2 A[c] + 3 B[c] => 5 D[c]", actingAs = "reactant") )) expect_true(is.vector( orphanMetabolites(reactionList = "2 5-A[c] + 3 B[c] <=> 5 3D[c]", actingAs = "reactant") )) }) test_that("orphanProducts function: output value is wrong", { expect_equal( orphanMetabolites(reactionList = "2 A[c] + 3 B[c] => 5 D[c]", actingAs = "product"), c("D[c]") ) expect_equivalent( orphanMetabolites("2 5-A[c] + 3 B[c] <=> 5 3D[c]", actingAs = "product"), c("3D[c]", "5-A[c]", "B[c]") ) expect_equal( orphanMetabolites(reactionList = "2 A[c] + 3 B[c] => 5 D[c]", actingAs = "reactant"), c("A[c]", "B[c]") ) expect_equivalent( orphanMetabolites(reactionList = "2 5-A[c] + 3 B[c] <=> 5 3D[c]", actingAs = "reactant"), c("3D[c]", "5-A[c]", "B[c]") ) })
set.seed(123) theta <- c(0, 5, 3.5) N <- 100 T <- 1 x <- 10 Z <- rnorm(N) Dt <- 1/N A <- theta[3]*sqrt(Dt)*Z P <- (1-theta[2]*Dt)^(0:(N-1)) X0 <- x X <- sapply(2:(N+1), function(x) X0*(1-theta[2]*Dt)^(x-1) + A[1:(x-1)] %*% P[(x-1):1]) Y <- ts(c(X0,X),start=0, deltat=1/N) plot(Y)
render_plot <- function(Object, Class, Stock=NULL, RMD=NULL, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars=NULL, open=TRUE, dev=FALSE, parallel=TRUE) { SampCpars <- list() if (!requireNamespace("knitr", quietly = TRUE)) { stop("Package \"knitr\" needed for this function to work. Please install it.", call. = FALSE) } if (!requireNamespace("rmarkdown", quietly = TRUE)) { stop("Package \"rmarkdown\" needed for this function to work. Please install it.", call. = FALSE) } if (is.null(plotPars)) plotPars <- list(breaks=10, col="darkgray", axes=FALSE, cex.main=1, lwd=2) if (class(Object) == "OM") { nsim <- Object@nsim nyears <- Object@nyears proyears <- Object@proyears SampCpars <- if(length(Object@cpars)>0) SampCpars <- SampleCpars(Object@cpars, nsim, silent=TRUE) set.seed(Object@seed) Stock <- SubOM(Object, "Stock") } if (Class == "Stock") { if (is.null(title)) title <- "Stock Object Plots" Pars <- list() Pars$Stock <- SampleStockPars(Object, nsim, nyears, proyears, SampCpars, msg=FALSE) name <- Object@Name name <- gsub(' ', '_', name) name <- gsub(':', '_', name) Pars$Name <- gsub(" ", "_", name) } else if (Class == "Fleet") { if (is.null(title)) title <- "Fleet Object Plots" if (class(Stock)!="Stock") stop("Must provide object of class 'Stock'", call. = FALSE) StockPars <- SampleStockPars(Stock, nsim, nyears, proyears, SampCpars, msg=FALSE) FleetPars <- SampleFleetPars(Object, StockPars, nsim, nyears, proyears, SampCpars, msg=FALSE) Pars <- list() Pars$Stock <- StockPars Pars$Fleet <- FleetPars Pars$Name <- gsub(" ", "_", Object@Name) Pars$CurrentYr <- Object@CurrentYr Pars$MPA <- Object@MPA } else if (Class == "Obs") { if (is.null(title)) title <- "Obs Object Plots" ObsPars <- SampleObsPars(Object, nsim, cpars=SampCpars, nyears=nyears, proyears=proyears) BMSY_B0bias <- array(rlnorm(nsim, mconv(1, Object@BMSY_B0biascv), sdconv(1, Object@BMSY_B0biascv)), dim = c(nsim)) ObsPars$BMSY_B0bias <- BMSY_B0bias Pars <- list() Pars$Obs <- ObsPars } else if (Class == "Imp") { if (is.null(title)) title <- "Imp Object Plots" ImpPars <- SampleImpPars(Object, nsim, cpars=SampCpars, nyears=nyears, proyears=proyears) Pars <- list() Pars$Imp <- ImpPars } else if (Class == "OM") { if (is.null(title)) title <- "OM Object Plots" message("Sampling Stock, Fleet, Obs, and Imp parameters") if (!parallel) dopar <- FALSE if (nsim>=48 & parallel) dopar <- TRUE if (nsim<48& parallel) dopar <- FALSE message("Running Historical Simulations") Hist <- Simulate(Object, silent=TRUE, parallel = dopar) Pars <- list(Stock=Hist@SampPars$Stock, Fleet=Hist@SampPars$Fleet, Obs=Hist@SampPars$Obs, Imp=Hist@SampPars$Imp) Pars$Hist <- Hist Pars$Name <- "OM" Pars$MPA <- Object@MPA Pars$CurrentYr <- Object@CurrentYr } else if (Class == "Hist") { Pars <- list() Pars$Hist <- Object Pars$CurrentYr <- Object@OMPars$CurrentYr[1] nyears <- length(Object@Data@Year) if (is.null(title)) title <- "Historical Simulations" } else { stop("Object must be class 'Stock', 'Fleet', 'Obs', or 'Imp'", call.=FALSE) } if (Class !="Hist" & Class !="OM") { name <- Object@Name name <- gsub(' ', '_', name) name <- gsub(':', '_', name) Pars$Name <- gsub(" ", "_", name) } its <- sample(1:nsim, nsamp) Params <- list( title = title, Pars = Pars, plotPars=plotPars, tabs = tabs, its = its, nyears=nyears, proyears=proyears, date=NULL ) outname <- paste0("_", RMD, ".html") if (Class !="Hist" & Class !="OM") { if (is.null(output_file)) output_file <- paste0(Pars$Name, outname) } else { if (is.null(output_file)) output_file <- paste0(RMD, ".html") } message("Rendering HTML file") RMD <- paste0(RMD, ".Rmd") if (dev) { input <- file.path('inst/Rmd', Class, RMD) } else { input <- file.path(system.file(package = 'MSEtool'),'Rmd', Class, RMD) } knitr::knit_meta(class=NULL, clean = TRUE) rend <- try(rmarkdown::render(input, params=Params, output_file=output_file, output_dir=output_dir, quiet=quiet), silent=TRUE) if (class(rend) == "try-error") { print(rend) } else { message("Rendered ", output_file, " in ", output_dir) if (open) utils::browseURL(file.path(output_dir, output_file)) } } plot.character <- function(x, Object, ...) { plot.pars(x, Object, ...) } plot.pars <- function(x, Object, Stock=NULL, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars =NULL, html=FALSE, open=TRUE, dev=FALSE, ...) { StockDF <- data.frame(chr=c("M", "Growth", "Maturity", "Recruitment", "Spatial", "Depletion"), Class="Stock", stringsAsFactors = FALSE) FleetDF <- data.frame(chr=c("Effort", "Catchability", "MPA", "Selectivity"), Class="Fleet", stringsAsFactors = FALSE) DF <- dplyr::bind_rows(StockDF, FleetDF) if (!x %in% DF[,1]) stop("Invalid argument. Valid arguments are: ", paste0(DF[,1], sep=" "), call.=FALSE) Class <- DF$Class[match(x, DF[,1])] if (class(Object) !="OM" & class(Object) != Class & class(Object)!="Hist") stop("Incorrect class object for this parameter", call.=FALSE) if (x == "M") x <- "NaturalMortality" if (!html) { fun <- paste0('plot.', x) if (Class=='Stock') do.call(fun, list(Object=Object, nsamp=nsamp, plotPars=plotPars, ...)) if (Class=='Fleet') do.call(fun, list(Object=Object, Stock=Stock, nsamp=nsamp, plotPars=plotPars, ...)) } else { render_plot(Object=Object, Class=Class, Stock=Stock, RMD=x, nsamp=nsamp, nsim=nsim, nyears=nyears, proyears=proyears, output_file=output_file, output_dir=output_dir, quiet=quiet, tabs=tabs, title=title, date=date, plotPars=plotPars, open=open, dev=dev) } } plot.Stock <- function(x, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars =NULL, open=TRUE, dev=FALSE, ...){ render_plot(Object=x, Class="Stock", RMD='Stock', nsamp=nsamp, nsim=nsim, nyears=nyears, proyears=proyears, output_file=output_file, output_dir=output_dir, quiet=quiet, tabs=tabs, title=title, date=date, plotPars=plotPars, open=open, dev=dev) } plot.Fleet <- function(x, Stock=NULL, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars =NULL, open=TRUE, dev=FALSE, ...){ if (class(Stock) !="Stock" & class(x) !="OM") stop("Must provide object of class 'Stock'") render_plot(Object=x, Class="Fleet", Stock=Stock, RMD='Fleet', nsamp=nsamp, nsim=nsim, nyears=nyears, proyears=proyears, output_file=output_file, output_dir=output_dir, quiet=quiet, tabs=tabs, title=title, date=date, plotPars=plotPars, open=open, dev=dev) } plot.Obs <- function(x, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars =NULL, open=TRUE, dev=FALSE, ...){ render_plot(Object=x, Class="Obs", Stock=NULL, RMD='Obs', nsamp=nsamp, nsim=nsim, nyears=nyears, proyears=proyears, output_file=output_file, output_dir=output_dir, quiet=quiet, tabs=tabs, title=title, date=date, plotPars=plotPars, open=open, dev=dev) } plot.Imp <- function(x, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars =NULL, open=TRUE, dev=FALSE, ...){ render_plot(Object=x, Class="Imp", Stock=NULL, RMD='Imp', nsamp=nsamp, nsim=nsim, nyears=nyears, proyears=proyears, output_file=output_file, output_dir=output_dir, quiet=quiet, tabs=tabs, title=title, date=date, plotPars=plotPars, open=open, dev=dev) } plot.Hist <- function(x, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars =NULL, open=TRUE, dev=FALSE, ...) { render_plot(Object=x, Class="Hist", Stock=NULL, RMD='Hist', nsamp=nsamp, nsim=nsim, nyears=nyears, proyears=proyears, output_file=output_file, output_dir=output_dir, quiet=quiet, tabs=tabs, title=title, date=date, plotPars=plotPars, open=open, dev=dev) } plot.OM <- function(x, nsamp=3, nsim=200, nyears=50, proyears=28, output_file=NULL, output_dir=getwd(), quiet=TRUE, tabs=TRUE, title=NULL, date=NULL, plotPars =NULL, open=TRUE, dev=FALSE, ...) { render_plot(Object=x, Class="OM", Stock=NULL, RMD='OM', nsamp=nsamp, nsim=nsim, nyears=nyears, proyears=proyears, output_file=output_file, output_dir=output_dir, quiet=quiet, tabs=tabs, title=title, date=date, plotPars=plotPars, open=open, dev=dev) } hist2 <- function(x, col, axes=FALSE, main="", breaks=10,cex.main=1) { if (mean(x) == x[1]) { plot(mean(x)*c(0.9,1.1),c(0,1000),col="white",axes=F,main=main,xlab="",ylab="") axis(1) abline(v=mean(x),col=col,lwd=2) } else { col="dark grey" hist(x, border='white',xlab="",col=col,axes=axes,main=main,breaks=breaks, ylab="") } }
LOCAL <- identical(Sys.getenv("LOCAL"), "TRUE") knitr::opts_chunk$set(purl = LOCAL) NOT_CRAN <- identical(tolower(Sys.getenv("NOT_CRAN")), "TRUE") knitr::opts_chunk$set(purl = NOT_CRAN) knitr::opts_chunk$set( collapse = TRUE, comment = " ) SAVE_GRAPHS=FALSE
"isMicrosoftRClient" <- function() { returnVal <- FALSE if (identical(.Platform$OS.type, "windows")) { clientRegEntry <- try(utils::readRegistry(file.path("SOFTWARE", "Microsoft", "R Client", fsep="\\"), "HLM"), silent=TRUE) if (!inherits(clientRegEntry, "try-error")) { returnVal <- TRUE } } returnVal }
word_document <- function(toc = FALSE, toc_depth = 3, number_sections = FALSE, fig_width = 5, fig_height = 4, fig_caption = TRUE, df_print = "default", highlight = "default", reference_docx = "default", keep_md = FALSE, md_extensions = NULL, pandoc_args = NULL) { knitr <- knitr_options( opts_chunk = list(dev = 'png', dpi = 96, fig.width = fig_width, fig.height = fig_height) ) args <- c() args <- c(args, pandoc_toc_args(toc, toc_depth)) lua_filters <- pkg_file_lua("pagebreak.lua") if (number_sections) { if (pandoc_available("2.10.1")) { args <- c(args, "--number-sections") } else { lua_filters <- c(lua_filters, pkg_file_lua("number-sections.lua")) } } if (!is.null(highlight)) highlight <- match.arg(highlight, highlighters()) args <- c(args, pandoc_highlight_args(highlight)) args <- c(args, reference_doc_args("docx", reference_docx)) args <- c(args, pandoc_args) saved_files_dir <- NULL pre_processor <- function(metadata, input_file, runtime, knit_meta, files_dir, output_dir) { saved_files_dir <<- files_dir NULL } intermediates_generator <- function(...) { reference_intermediates_generator(saved_files_dir, ..., reference_docx) } output_format( knitr = knitr, pandoc = pandoc_options(to = "docx", from = from_rmarkdown(fig_caption, md_extensions), args = args, lua_filters = lua_filters), keep_md = keep_md, df_print = df_print, pre_processor = pre_processor, intermediates_generator = intermediates_generator ) } reference_doc_args <- function(type, doc) { if (is.null(doc) || identical(doc, "default")) return() c(paste0("--reference-", if (pandoc2.0()) "doc" else { match.arg(type, c("docx", "odt", "doc")) }), pandoc_path_arg(doc)) }
make_tapnet <- function(tree_low, tree_high, networks, abun_low = NULL, abun_high = NULL, traits_low = NULL, traits_high = NULL, npems_lat = NULL, use.all.pems=FALSE ) { if (! (("phylo" %in% class(tree_low)) | "phylo" %in% class(tree_high) )) { stop("'tree_low' and 'tree_high' must be of class 'phylo'. See the documentation of package 'ape' on how to convert phylogenetic trees to this format.") } if (!is.list(networks)) networks <- list(networks) mat_check <- sapply(networks, is.matrix) if (any(mat_check == FALSE)) stop("All elements of 'networks' must be matrices.") for (i in 1:length(networks)) { if (is.null(rownames(networks[[i]])) | is.null(colnames(networks[[i]]))) { stop("All interaction networks must have species identities as row and column names.") } } spec_lower <- sort(unique(unlist(lapply(networks, rownames)))) spec_higher <- sort(unique(unlist(lapply(networks, colnames)))) if (!all(spec_lower %in% tree_low$tip.label) | !all(spec_higher %in% tree_high$tip.label)) { stop("All species in the interaction networks must appear in their respective phylogeny. Please make sure that species names match.") } for (i in 1:length(networks)) { networks[[i]] <- networks[[i]][order(rownames(networks[[i]])), order(colnames(networks[[i]]))] } if (!is.null(abun_low)) { if (!is.list(abun_low)) abun_low <- list(abun_low) num_check <- sapply(abun_low, is.numeric) if (any(num_check == F)) stop("All elements of 'abun_low' must be numeric vectors.") if (length(networks) != length(abun_low)) stop("Some networks have missing lower level abundances.") for (i in 1:length(networks)) { abun_low[[i]] <- abun_low[[i]][order(names(abun_low[[i]]))] if (!all(rownames(networks[[i]]) == names(abun_low[[i]]))) stop("Some lower trophic level species have missing abundances.") } } else { warning("No abundances for lower trophic level were provided. Using marginal totals instead.") } if (!is.null(abun_high)) { if (!is.list(abun_high)) abun_high <- list(abun_high) num_check <- sapply(abun_high, is.numeric) if (any(num_check == F)) stop("All elements of 'abun_high' must be numeric vectors.") if (length(networks) != length(abun_high)) stop("Some networks have missing higher level abundances.") for (i in 1:length(networks)) { abun_high[[i]] <- abun_high[[i]][order(names(abun_high[[i]]))] if (!all(colnames(networks[[i]]) == names(abun_high[[i]]))) stop("Some higher trophic level species have missing abundances.") } } else { warning("No abundances for higher trophic level were provided. Using marginal totals instead.") } if (!is.null(traits_low) | !is.null(traits_high)) { if (is.null(traits_low) | is.null(traits_high)) { stop("Trait data must be supplied for both trophic levels.") } if (!is.matrix(traits_low) | !is.matrix(traits_high)) { stop("'traits_low' and 'traits_high' must be matrices.") } if (ncol(traits_low) != ncol(traits_high)) { stop("Numbers of traits of lower and higher trophic level must be equal.") } if (!all(spec_lower %in% rownames(traits_low))) stop("Some lower level species have missing trait data.") if (!all(spec_higher %in% rownames(traits_high))) stop("Some higher level species have missing trait data.") } trees <- list(low = tree_low, high = tree_high) traits_all <- list(low = traits_low, high = traits_high) if (is.null(abun_low)) { abun_low <- lapply(networks, rowSums) } if (is.null(abun_high)) { abun_high <- lapply(networks, colSums) } webs <- list() for (i in 1:length(networks)) { webs[[i]] <- list() webs[[i]]$web <- networks[[i]] if (use.all.pems == FALSE){ pems_web_low <- select_relevant_pems(tree_low, rownames(networks[[i]])) } else { pems_web_low <- pems_from_tree(tree_low) } pems_web_low <- pems_web_low[order(rownames(pems_web_low)),] if (use.all.pems == FALSE){ pems_web_high <- select_relevant_pems(tree_high, colnames(networks[[i]])) } else { pems_web_high <- pems_from_tree(tree_high) } pems_web_high <- pems_web_high[order(rownames(pems_web_high)),] if (!is.null(npems_lat)) { if (npems_lat > ncol(pems_web_low)) { warning(paste("For web no.", i, ", only", ncol(pems_web_low) , "PEMs will be used for the lower trophic level latent trait,\n since this network only has", nrow(webs[[i]]$web), "lower trophic level species.")) } else { pems_web_low <- pems_web_low[, 1:npems_lat, drop = F] } if (npems_lat > ncol(pems_web_high)) { warning(paste("For web no.", i, ", only", ncol(pems_web_high) , "PEMs will be used for the higher trophic level latent trait,\n since this network only has", ncol(webs[[i]]$web), "higher trophic level species.")) } else { pems_web_high <- pems_web_high[, 1:npems_lat, drop = F] } } webs[[i]]$pems <- list(low = pems_web_low, high = pems_web_high) webs[[i]]$abuns <- list(low = abun_low[[i]], high = abun_high[[i]]) } if (is.null(traits_low)) { for (i in 1:length(networks)) webs[[i]]$traits <- NULL } else { for (i in 1:length(networks)) { traits_web_low <- traits_low[which(rownames(traits_low) %in% rownames(networks[[i]])), , drop = F] traits_web_low <- traits_web_low[order(rownames(traits_web_low)), , drop = F] traits_web_high <- traits_high[which(rownames(traits_high) %in% colnames(networks[[i]])), , drop = F] traits_web_high <- traits_web_high[order(rownames(traits_web_high)), , drop = F] webs[[i]]$traits <- list(low = traits_web_low, high = traits_web_high) } } out <- list(trees = trees, traits_all = traits_all, networks = webs) class(out) <- "tapnet" return(out) }
Fpa <- function(Flim, sigmaF) { Flim * exp(-1.645*sigmaF) }
setMethod("show", signature = "powerLongSurv", definition = function(object){ cat(object@title,"\n", object@subtitle,"\n") cat("Covariance matrix SigmaTheta :\n") print(object@SigmaTheta) cat("Measurement times: ", "t[1:",length(object@t),"]=", object@t, "\n", "Subject proportions: ", "p[1:",length(object@p),"]=",object@p, "\n", "Number of subjects (N): ",object@N, "\n", "Number of events (nevents): ",object@nevents, "\n", "Percent censored (censr): ", object@censr, "\n", "Median survival time (tmedian): ", object@tmedian, "\n", "Mean follow-up time (meantf): ", object@meantf, "\n", "Trajectory effect (beta): ", object@beta, "\n", "Type I Error (alpha): ", object@alpha, "\n", "Power (power): ", object@power, "\n") } )
convertgen <- function(input_geno, type = c("hmp1", "hmp2", "num"), missingrate = 0.05, impute = TRUE) { if (type == "num") { genotype <- as.matrix(input_geno) gen_missingrate <- apply(genotype, 1, function(x) { rate <- length(which(is.na(x)))/ncol(genotype) return(rate) }) num_filter <- which(gen_missingrate <= missingrate) gen_filter <- genotype[num_filter, ] gen <- apply(gen_filter, 2, function(x) { x1 <- as.numeric(x) return(x1) }) if (impute) { gene1 <- apply(gen, 1, function(x) { x[which(is.na(x))] <- mean(x, na.rm = TRUE) return(x) }) } else { gene1 <- t(gen) } } if (type != "num") { input_geno[input_geno == "N"] = NA input_geno[input_geno == "NN"] = NA genotype <- input_geno[, -c(1:11)] gen_missingrate <- apply(genotype, 1, function(x) { rate <- length(which(is.na(x)))/ncol(genotype) return(rate) }) num_filter <- which(gen_missingrate <= missingrate) gen_filter <- genotype[num_filter, ] map <- input_geno[num_filter, c(1:4)] x1 <- substr(map[, 2], 1, 1) x2 <- substr(map[, 2], 3, 3) aa <- paste(x1, x1, sep = "") bb <- paste(x2, x2, sep = "") cc <- paste(x1, x2, sep = "") if (type == "hmp1") { gen <- apply(gen_filter, 2, function(x) { x[x == x1] <- 1 x[x == x2] <- -1 x[x %in% c("R", "Y", "S", "W", "K", "M")] <- 0 x1 <- as.numeric(x) return(x1) }) } if (type == "hmp2") { gen <- apply(gen_filter, 2, function(x) { x[x == aa] <- 1 x[x == bb] <- -1 x[x == cc] <- 0 x1 <- as.numeric(x) return(x1) }) } if (impute) { gene1 <- apply(gen, 1, function(x) { x[which(is.na(x))] <- mean(x, na.rm = TRUE) return(x) }) } else { gene1 <- t(gen) } } return(gene1) }